m8chaa commited on
Commit
b797528
·
verified ·
1 Parent(s): 541dec4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -120
app.py CHANGED
@@ -52,14 +52,13 @@ request_timeout = Timeout(1000.0, connect=600.0)
52
  with open('/app/secrets/fb_secret.json', 'r') as f:
53
  firebase_configuration = json.load(f)
54
 
55
- logging.info("firebase: " + firebase_configuration)
56
  firebase_credentials = credentials.Certificate(firebase_configuration)
57
  firebase_admin.initialize_app(firebase_credentials, {
58
  'projectId': firebase_configuration['project_id'],
59
  })
60
  firestore_db = firestore.client()
61
  users_collection_ref = firestore_db.collection('users')
62
- logging.info(users_collection_ref)
63
  transactions_collection_ref = firestore_db.collection('transactions')
64
 
65
  SCOPES = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']
@@ -902,124 +901,124 @@ async def sync_data(data_json: str = Form(...), user_id: str = Form(...)):
902
 
903
 
904
 
905
- # Global variables
906
- gDrive_watch_list = {
907
- "7A5bxxijved7Du4G7xXo1916hIU2": "1ZfvMPZ_R8j4g0JCVU4dWFerVOlFWG6w1"
908
- }
909
- watch_list_channels = {}
910
-
911
- def create_channel(service, folder_id):
912
- body = {
913
- 'id': f'channel-{folder_id}-{int(time.time())}',
914
- 'type': 'web_hook',
915
- 'address': 'https://m8chaa-re-sheet-develop.hf.space/notifications',
916
- }
917
- response = service.files().watch(fileId=folder_id, body=body).execute()
918
- return response
919
-
920
- def close_channel(channel_id, resource_id):
921
- request_body = {
922
- 'id': channel_id,
923
- 'resourceId': resource_id,
924
- }
925
- drive_service.channels().stop(body=request_body).execute()
926
-
927
- def update_watch_list():
928
- global gDrive_watch_list, watch_list_channels
929
-
930
- # Close all existing channels
931
- for channel_id, channel_info in watch_list_channels.items():
932
- close_channel(channel_id, channel_info['resourceId'])
933
-
934
- watch_list_channels.clear()
935
-
936
- # Create new channels for all folders in the watch list
937
- for user_id, folder_id in gDrive_watch_list.items():
938
- try:
939
- response = create_channel(drive_service, folder_id)
940
- logging.info("create channel: " + response)
941
- watch_list_channels[response['id']] = {
942
- 'resourceId': response['resourceId'],
943
- 'user_id': user_id,
944
- 'folder_id': folder_id
945
- }
946
- logging.info("watch list: " + watch_list_channels)
947
- except Exception as e:
948
- print(f"Error creating channel for user {user_id}: {str(e)}")
949
-
950
- def on_snapshot(doc_snapshot, changes, read_time):
951
- global gDrive_watch_list, watch_list_channels
952
-
953
- for change in changes:
954
- user_id = change.document.id
955
- user_data = change.document.to_dict()
956
-
957
- if change.type.name == 'ADDED' or change.type.name == 'MODIFIED':
958
- if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
959
- folder_id = user_data['gDrive_metadata']['uploaded']
960
- gDrive_watch_list[user_id] = folder_id
961
-
962
- # Create a new channel for this folder
963
- try:
964
- response = create_channel(drive_service, folder_id)
965
- watch_list_channels[response['id']] = {
966
- 'resourceId': response['resourceId'],
967
- 'user_id': user_id,
968
- 'folder_id': folder_id
969
- }
970
- except Exception as e:
971
- print(f"Error creating channel for user {user_id}: {str(e)}")
972
-
973
- elif change.type.name == 'REMOVED':
974
- if user_id in gDrive_watch_list:
975
- folder_id = gDrive_watch_list.pop(user_id)
976
 
977
- # Find and close the channel for this user
978
- for channel_id, channel_info in list(watch_list_channels.items()):
979
- if channel_info['user_id'] == user_id:
980
- close_channel(channel_id, channel_info['resourceId'])
981
- del watch_list_channels[channel_id]
982
- break
983
-
984
- @app.post("/notifications")
985
- async def notifications(request: Request):
986
- try:
987
- body = await request.body()
988
- print("Notification received:", body)
989
- return {"message": "Notification received"}
990
- except Exception as e:
991
- raise HTTPException(status_code=500, detail=str(e))
992
-
993
- # Set up the Firebase listener
994
- users_watch = users_collection_ref.on_snapshot(on_snapshot)
995
-
996
- # Set up the scheduler to update watch list every 24 hours
997
- scheduler = BackgroundScheduler()
998
- scheduler.add_job(update_watch_list, 'interval', hours=24)
999
- scheduler.start()
1000
-
1001
- # Startup event to initialize the watch list
1002
- @app.on_event("startup")
1003
- async def startup_event():
1004
- global gDrive_watch_list
1005
- # Fetch all users and initialize the watch list
1006
- users = users_collection_ref.get()
1007
- for user in users:
1008
- user_data = user.to_dict()
1009
- if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
1010
- gDrive_watch_list[user.id] = user_data['gDrive_metadata']['uploaded']
1011
 
1012
- # Initial update of watch list channels
1013
- update_watch_list()
1014
-
1015
- # Shutdown event to clean up resources
1016
- @app.on_event("shutdown")
1017
- async def shutdown_event():
1018
- global watch_list_channels
1019
- # Close all channels
1020
- for channel_id, channel_info in watch_list_channels.items():
1021
- close_channel(channel_id, channel_info['resourceId'])
1022
 
1023
- # Stop the Firebase listener and the scheduler
1024
- users_watch.unsubscribe()
1025
- scheduler.shutdown()
 
52
  with open('/app/secrets/fb_secret.json', 'r') as f:
53
  firebase_configuration = json.load(f)
54
 
 
55
  firebase_credentials = credentials.Certificate(firebase_configuration)
56
  firebase_admin.initialize_app(firebase_credentials, {
57
  'projectId': firebase_configuration['project_id'],
58
  })
59
  firestore_db = firestore.client()
60
  users_collection_ref = firestore_db.collection('users')
61
+
62
  transactions_collection_ref = firestore_db.collection('transactions')
63
 
64
  SCOPES = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']
 
901
 
902
 
903
 
904
+ # # Global variables
905
+ # gDrive_watch_list = {
906
+ # "7A5bxxijved7Du4G7xXo1916hIU2": "1ZfvMPZ_R8j4g0JCVU4dWFerVOlFWG6w1"
907
+ # }
908
+ # watch_list_channels = {}
909
+
910
+ # def create_channel(service, folder_id):
911
+ # body = {
912
+ # 'id': f'channel-{folder_id}-{int(time.time())}',
913
+ # 'type': 'web_hook',
914
+ # 'address': 'https://m8chaa-re-sheet-develop.hf.space/notifications',
915
+ # }
916
+ # response = service.files().watch(fileId=folder_id, body=body).execute()
917
+ # return response
918
+
919
+ # def close_channel(channel_id, resource_id):
920
+ # request_body = {
921
+ # 'id': channel_id,
922
+ # 'resourceId': resource_id,
923
+ # }
924
+ # drive_service.channels().stop(body=request_body).execute()
925
+
926
+ # def update_watch_list():
927
+ # global gDrive_watch_list, watch_list_channels
928
+
929
+ # # Close all existing channels
930
+ # for channel_id, channel_info in watch_list_channels.items():
931
+ # close_channel(channel_id, channel_info['resourceId'])
932
+
933
+ # watch_list_channels.clear()
934
+
935
+ # # Create new channels for all folders in the watch list
936
+ # for user_id, folder_id in gDrive_watch_list.items():
937
+ # try:
938
+ # response = create_channel(drive_service, folder_id)
939
+ # logging.info("create channel: " + response)
940
+ # watch_list_channels[response['id']] = {
941
+ # 'resourceId': response['resourceId'],
942
+ # 'user_id': user_id,
943
+ # 'folder_id': folder_id
944
+ # }
945
+ # logging.info("watch list: " + watch_list_channels)
946
+ # except Exception as e:
947
+ # print(f"Error creating channel for user {user_id}: {str(e)}")
948
+
949
+ # def on_snapshot(doc_snapshot, changes, read_time):
950
+ # global gDrive_watch_list, watch_list_channels
951
+
952
+ # for change in changes:
953
+ # user_id = change.document.id
954
+ # user_data = change.document.to_dict()
955
+
956
+ # if change.type.name == 'ADDED' or change.type.name == 'MODIFIED':
957
+ # if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
958
+ # folder_id = user_data['gDrive_metadata']['uploaded']
959
+ # gDrive_watch_list[user_id] = folder_id
960
+
961
+ # # Create a new channel for this folder
962
+ # try:
963
+ # response = create_channel(drive_service, folder_id)
964
+ # watch_list_channels[response['id']] = {
965
+ # 'resourceId': response['resourceId'],
966
+ # 'user_id': user_id,
967
+ # 'folder_id': folder_id
968
+ # }
969
+ # except Exception as e:
970
+ # print(f"Error creating channel for user {user_id}: {str(e)}")
971
+
972
+ # elif change.type.name == 'REMOVED':
973
+ # if user_id in gDrive_watch_list:
974
+ # folder_id = gDrive_watch_list.pop(user_id)
975
 
976
+ # # Find and close the channel for this user
977
+ # for channel_id, channel_info in list(watch_list_channels.items()):
978
+ # if channel_info['user_id'] == user_id:
979
+ # close_channel(channel_id, channel_info['resourceId'])
980
+ # del watch_list_channels[channel_id]
981
+ # break
982
+
983
+ # @app.post("/notifications")
984
+ # async def notifications(request: Request):
985
+ # try:
986
+ # body = await request.body()
987
+ # print("Notification received:", body)
988
+ # return {"message": "Notification received"}
989
+ # except Exception as e:
990
+ # raise HTTPException(status_code=500, detail=str(e))
991
+
992
+ # # Set up the Firebase listener
993
+ # users_watch = users_collection_ref.on_snapshot(on_snapshot)
994
+
995
+ # # Set up the scheduler to update watch list every 24 hours
996
+ # scheduler = BackgroundScheduler()
997
+ # scheduler.add_job(update_watch_list, 'interval', hours=24)
998
+ # scheduler.start()
999
+
1000
+ # # Startup event to initialize the watch list
1001
+ # @app.on_event("startup")
1002
+ # async def startup_event():
1003
+ # global gDrive_watch_list
1004
+ # # Fetch all users and initialize the watch list
1005
+ # users = users_collection_ref.get()
1006
+ # for user in users:
1007
+ # user_data = user.to_dict()
1008
+ # if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
1009
+ # gDrive_watch_list[user.id] = user_data['gDrive_metadata']['uploaded']
1010
 
1011
+ # # Initial update of watch list channels
1012
+ # update_watch_list()
1013
+
1014
+ # # Shutdown event to clean up resources
1015
+ # @app.on_event("shutdown")
1016
+ # async def shutdown_event():
1017
+ # global watch_list_channels
1018
+ # # Close all channels
1019
+ # for channel_id, channel_info in watch_list_channels.items():
1020
+ # close_channel(channel_id, channel_info['resourceId'])
1021
 
1022
+ # # Stop the Firebase listener and the scheduler
1023
+ # users_watch.unsubscribe()
1024
+ # scheduler.shutdown()