Sindbad~EG File Manager

Current Path : /home/numerotech/conference.numerotech.com/food_kit_scan_badges/core/model/
Upload File :
Current File : //home/numerotech/conference.numerotech.com/food_kit_scan_badges/core/model/FirebaseModel.py

from flask import session
from flask import request, Blueprint, jsonify
from sqlalchemy import create_engine, select, MetaData, Table,text
from sqlalchemy.sql import and_, or_
# import sqlite3

from core import app

engine      = create_engine(app.config['DATABASE_URI'],pool_size=5000,pool_pre_ping=True,pool_recycle=3600)
engine_fk   = create_engine(app.config['DATABASE_URI_FK'],pool_size=5000,pool_pre_ping=True,pool_recycle=3600)
engine_conf = create_engine(app.config['DATABASE_URI_CONF'],pool_size=5000,pool_pre_ping=True,pool_recycle=3600)

class FirebaseModel():  
	def __init__(self):
		try:
			self.meta = MetaData()
			self.fb_users        = Table("fb_users",self.meta, autoload_with= engine_conf)
			self.fb_notification   = Table("fb_notification", self.meta,autoload_with=engine_conf)
			self.notification_logs = Table("notification_logs", self.meta,autoload_with=engine_conf)
			self.fb_reports        = Table("fb_reports",self.meta, autoload_with= engine_conf)
			
			
			
		except Exception as e:
			print(e)

	def GetConfFirebaseModel(self,conf_id):
		with engine.connect() as conn:
			stmt   = text("select * from conference  where conf_id = "+str(conf_id)+"  limit 1;")
			result = conn.execute(stmt)
			result = result.one_or_none()
			return dict(result._mapping) if result else None


	def insertFCMData(self,data):
		return_data = {}
		try:
			with engine_conf.connect() as conn:
				# result = conn.execute(self.fcm_master.insert(data))
				result = conn.execute(self.fb_users.insert(), data)
				conn.commit()
				pk_id     = [r for r in result.inserted_primary_key] if result.inserted_primary_key else None
				# return pk_id[0]
				return_data["fb_user_id"] = pk_id[0]
				return_data["msg"]    = "success"
		except Exception as e:
			return_data["msg"]    = str(e)

		return return_data	
			
	def UpdateFCMData(self,data,fb_user_id):
		return_data = {}
		try:
			with engine_conf.connect() as conn:
				stmt = self.fb_users.update().where(self.fb_users.c.fb_user_id.in_([fb_user_id])).values(data)
				conn.execute(stmt) 
				conn.commit()
				return_data["fb_user_id"] = fb_user_id
				return_data["msg"]    = "success"
		except Exception as e:
			return_data["msg"]    = str(e)

		return return_data	

	def getUserDataByToken(self,conf_id,fcm_token):	
		with engine_conf.connect() as conn:
			stmt = text( "SELECT * FROM fb_users where fcm_token = '"+fcm_token+"' and conf_id = "+str(conf_id)+" limit 1 ")
			result = conn.execute(stmt)
			result = result.fetchone()
			return dict(result._mapping) if result else None


	def insert_fb_notification(self,insert_data):
		with engine_conf.connect() as conn:
			result = conn.execute(self.fb_notification.insert(),insert_data)
			conn.commit()
			return result
					

	# Dec 30, 2023
# 	def getFBUserData(self,conf_id,device_type,is_all_user,is_loggedin_user,is_commitment_user ):
# 		with engine_conf.connect() as conn:
# 			get_stmt  = text(" SELECT fb_user_id,conf_id,user_id,app_name,device_type,fcm_token from fb_users where conf_id = "+str(conf_id)+"  order by fb_user_id desc")
# 			results = conn.execute(get_stmt).all()
# 			results = [dict(r._mapping) for r in results] if results else None
# 			return results	
	
	def getFBUserData(self,conf_id,device_type,is_all_user,is_loggedin_user,is_commitment_user ):
		with engine_conf.connect() as conn:
			if is_loggedin_user and is_loggedin_user > 0 :
				get_stmt  = text(" SELECT f.fb_user_id,u.prefix,u.full_name,u.email,u.mobile,u.membership_no,u.user_id,f.conf_id,"
				+" f.user_id,f.app_name,f.device_type,f.fcm_token from fb_users f "
				+ " inner join numerotech_primary_db.users u  on u.user_id = f.user_id " 
				+ " where f.conf_id = "+str(conf_id)+" and f.is_test_user  = 1 order by fb_user_id desc ;")

				# get_stmt  = text(" SELECT fb_user_id,conf_id,user_id,app_name,device_type,fcm_token from fb_users where conf_id = "+str(conf_id)+"  and user_id is not null and user_id > 0 order by fb_user_id desc")
			else :
				get_stmt  = text(" SELECT fb_user_id,conf_id,user_id,app_name,device_type,fcm_token from fb_users where conf_id = "+str(conf_id)+" and is_test_user = 1  order by fb_user_id desc")
			results = conn.execute(get_stmt).all()
			results = [dict(r._mapping) for r in results] if results else None
			return results

	# notification_id	
	
	def getFBNotificationByID(self,conf_id,notification_id):	
		with engine_conf.connect() as conn:
			stmt = text( "SELECT * FROM fb_notification where notification_id = "+str(notification_id)+" and conf_id = "+str(conf_id)+" limit 1 ")
			result = conn.execute(stmt)
			result = result.fetchone()
			return dict(result._mapping) if result else None	

	def insert_demo_del_sqlite(self, data):
		with sqlite3.connect('fc_sessions_v1.db') as sqlite_conn:
			sqlite_cursor     = sqlite_conn.cursor()
			delete_query      = "DELETE FROM notification_logs"
			try:
				sqlite_cursor.execute(delete_query)
				sqlite_conn.commit()
				head_query = 'insert into notification_logs ( fb_user_id,notification_id, fcm_token, conf_id, notification_title, notification_content, send_user, device_type, send_at, fb_message, created_at) values'
				item_query = []
				for row in data:
					item_query.append(f"('{row['fb_user_id']}','{row['notification_id']}','{row['fcm_token']}','{row['conf_id']}','{row['notification_title']}','{row['notification_content']}','{row['send_user']}','{row['device_type']}','{row['send_at']}','{row['fb_message']}','{row['created_at']}')");
				stmt = head_query + (',').join(item_query) + ';' 

				
				results = sqlite_cursor.execute(stmt)
				sqlite_conn.commit()
				sqlite_cursor.close()
				if results : 
					return "success"
				else:
					return "failed"
			
			except sqlite3.Error as e:
				print(f"SQLite error: {e}")
				sqlite_conn.rollback()
				return f"SQLite error: {e}"

	# Ramya Source Code

	def get_fb_notification(self,conf_id):
		with engine_conf.connect() as conn:
			stmt = text("select *  from fb_notification where conf_id = "+str(conf_id)+";")
			result = conn.execute(stmt).all()
			return [dict(r._mapping) for r in result] if result else None



	def get_fb_notification_by_id(self,notification_id):
		with engine_conf.connect() as conn:
			try:
				stmt    = text("select notification_id, notification_type, notification_title, notification_content, image, send_user, sent_at, schedule_at from fb_notification where notification_id = "+str(notification_id)+";")
				result 	= conn.execute(stmt).one_or_none()
				return dict(result._mapping) if result else None

			except Exception as e:
				return str(e)

	def update_fb_notification(self,notification_id,update_data):
		with engine_conf.connect() as conn:
			stmt 	= self.fb_notification.update().where(self.fb_notification.c.notification_id.in_([notification_id])).values(update_data)
			result  = conn.execute(stmt)
			conn.commit()
			return 'success' if result else 'fail'


	def insert_notification_logs(self,insert_logs_data):
		with engine_conf.connect() as conn:
			result = conn.execute(self.notification_logs.insert(),insert_logs_data)
			conn.commit()
			return result

	def get_notification_logs(self,conf_id,fcm_token):
		with engine_conf.connect() as conn:
			where_con = ""
			if fcm_token :
				where_con = " and fcm_token = '"+str(fcm_token)+"' "
			else :
				where_con = ""
			stmt     = "select *  from notification_logs where conf_id = "+str(conf_id)+" "
			get_stmt = text( stmt + where_con )
			
			result = conn.execute(get_stmt).all()
			return [dict(r._mapping) for r in result] if result else None		
			

# 	def get_del_data_in_sqlite(self, conf_id):
# 		with sqlite3.connect('fc_sessions_v1.db') as sqlite_conn:
# 			c = sqlite_conn.cursor()
# 			stmt =  "SELECT fb_user_id, notification_id, fcm_token, conf_id, notification_title, notification_content, send_user, device_type, send_at, fb_message, created_at, updated_at FROM notification_logs where conf_id = "+str(conf_id)+" ; "  
# 			# stmt = f"SELECT fb_user_id, notification_id, fcm_token, conf_id, notification_title, notification_content, send_user, device_type, send_at, fb_message, created_at, updated_at FROM notification_logs where conf_id = {conf_id} ;"

# 			c.execute(stmt)
# 			columns = [col[0] for col in c.description]  # Get column names

# 			results = [dict(zip(columns, row)) for row in c.fetchall()]  # Convert rows to dictionaries
# 			sqlite_conn.commit()
# 			if results : 
# 				return results
# 			else:
# 				return None	

	def saveNotificationLogsMysql(self,conf_id,data):
		with engine_conf.connect() as conn:
			result = conn.execute(self.notification_logs.insert(),data)
			conn.commit()
			# stmt = text(" SELECT * FROM notification_logs where conf_id = "+str(conf_id)+" ")
			# result = conn.execute(stmt).all()
			# return [dict(r._mapping) for r in result] if result else None


	def GetNotificationLogsMysql(self,conf_id,fcm_token):
		with engine_conf.connect() as conn:
			if fcm_token :
				stmt = text(" SELECT * FROM notification_logs where conf_id = "+str(conf_id)+" and fcm_token = '"+fcm_token+"' order by send_at DESC")
			else :
				stmt = text(" SELECT * FROM notification_logs where conf_id = "+str(conf_id)+" order by send_at DESC")
			result = conn.execute(stmt).all()
			return [dict(r._mapping) for r in result] if result else None		


# 	def deleteSqliteNotificationLogs(self,conf_id):
# 		with sqlite3.connect('fc_sessions_v1.db') as sqlite_conn:
# 			sqlite_cursor     = sqlite_conn.cursor()
# 			delete_query      = "DELETE FROM notification_logs where conf_id = "+str(conf_id)+"  ;"
# 			try:
# 				sqlite_cursor.execute(delete_query)
# 				sqlite_conn.commit()
# 			except sqlite3.Error as e:
# 				print(f"SQLite error: {e}")
# 				sqlite_conn.rollback()
# 				return f"SQLite error: {e}"	
		
	def checkFBUser(self,fb_user_id,user_id ,conf_id) :
		with engine_conf.connect() as conn:
			stmt = text(" SELECT * FROM fb_users where fb_user_id = "+str(fb_user_id)+" and user_id = "+str(user_id)+" and conf_id = "+str(conf_id)+" limit 1 ")
			result = conn.execute(stmt).fetchone()
			return dict(result._mapping) if result else None	
			
	
	# getFirebase Commitment USER
	def getFBCommitmentUser(self,conf_id):
		with engine_conf.connect() as conn:
			stmt = text("select c.user_id,fbu.fb_user_id,concat( ifnull(u.prefix,''), ' ' ,u.full_name) as full_name ,c.fb_commitments as notification_content, "
				+ " c.conf_id,fbu.device_type,fbu.fcm_token from fb_commitments c "
				+ " inner join  numerotech_primary_db.users u on u.user_id = c.user_id "
				+ " inner join  fb_users fbu on fbu.user_id = c.user_id "
				+ " where c.conf_id = "+str(conf_id)+" and c.fb_commitments is not null;")	

			result = conn.execute(stmt).all()
			return [dict(r._mapping) for r in result] if result else None		


	def saveNotificationReports(self,conf_id,data):
		with engine_conf.connect() as conn:
			result = conn.execute(self.fb_reports.insert(),data)
			conn.commit()		
			return "success"		

	# Purpose : To Get firebase notification data for index
	def get_usp_notification_index(self,conf_id,notification_id,fb_user_id):
		sets = []
		try:
			connection = engine_conf.raw_connection()
			cursor = connection.cursor()
			cursor.callproc("usp_firebase_notification_index",[(conf_id or None),(notification_id or None),(fb_user_id or None)])
			while 1:
				#(column_name, type_, ignore_, ignore_, ignore_, null_ok, column_flags)
				names = [c[0] for c in cursor.description]
				set_ = []
				while 1:
					row_raw = cursor.fetchone()
					if row_raw is None:
						break
						
					row = dict(zip(names, row_raw))
					set_.append(row)
	 
				sets.append(list(set_))
	 
				if cursor.nextset() is None:
					break
	 
				# nextset() doesn't seem to be sufficiant to tell the end.
				if cursor.description is None:
					break
		finally:
			# Return the connection to the pool (won't actually close).
			connection.commit()
			connection.close()
			
		return sets

	# Purpose : To Update Full name in fb_users table
	def update_fbuser_name(self,conf_id,curr_dt):
		try:
			with engine_conf.connect() as conn:
				safe_update = text("SET SQL_SAFE_UPDATES = 0 ")
				result      = conn.execute(safe_update)

				stmt = text("Update fb_users fb inner join numerotech_primary_db.users u on u.user_id = fb.user_id "
							+" set fb.full_name = concat(u.prefix,' ', u.full_name) , fb.name_updated_at ='"+curr_dt+"' ,fb.updated_at ='"+curr_dt+"' "
							+" where fb.full_name is null and fb.user_id is not null and fb.conf_id = "+str(conf_id)+" ")
				result = conn.execute(stmt)
				conn.commit()
				
				
				get_stmt = text("select count(fb.fb_user_id) as total_updated_count from fb_users fb "
							+" where fb.user_id is not null and fb.conf_id = "+str(conf_id)+" and fb.name_updated_at= '"+curr_dt+"'")
				result = conn.execute(get_stmt).fetchone()
				return dict(result._mapping) if result else None
		except Exception as e:
			return str(e)


Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists