m8chaa commited on
Commit
f0e73a6
·
verified ·
1 Parent(s): fdf5a82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -15
app.py CHANGED
@@ -9,7 +9,7 @@ import firebase_admin
9
  from firebase_admin import credentials
10
  from firebase_admin import firestore
11
  import json
12
- from datetime import datetime
13
  import pytz
14
 
15
  from typing import List, Optional, Dict
@@ -912,14 +912,22 @@ class DriveWatcher:
912
  self.channels: Dict[str, Dict[str, Any]] = {}
913
 
914
  def create_channel(self, folder_id: str) -> Dict[str, Any]:
915
- body = {
916
- 'id': f'channel-{folder_id}-{int(time.time())}',
917
- 'type': 'web_hook',
918
- 'address': 'https://m8chaa-re-sheet-develop.hf.space/notifications',
919
- 'expiration': int((datetime.now() + timedelta(days=7)).timestamp() * 1000) # Set expiration to 7 days
920
- }
921
- response = app.state.drive_service.files().watch(fileId=folder_id, body=body).execute()
922
- return response
 
 
 
 
 
 
 
 
923
 
924
  def close_channel(self, channel_id: str, resource_id: str):
925
  try:
@@ -928,8 +936,10 @@ class DriveWatcher:
928
  'resourceId': resource_id,
929
  }).execute()
930
  logging.info(f"Closed channel: {channel_id}")
 
 
931
  except Exception as e:
932
- logging.error(f"Error closing channel {channel_id}: {str(e)}")
933
 
934
  def update_watch_list(self):
935
  current_time = int(time.time())
@@ -974,9 +984,10 @@ class DriveWatcher:
974
  self.update_watch_list()
975
 
976
  @app.on_event("startup")
977
- def startup_event():
978
  app.state.drive_watcher = DriveWatcher()
979
  app.state.drive_service = build('drive', 'v3', credentials=APICredential)
 
980
  # Fetch all users and initialize the watch list
981
  users = users_collection_ref.get()
982
  for user in users:
@@ -992,7 +1003,6 @@ def startup_event():
992
 
993
  logging.info("Application startup completed")
994
 
995
-
996
  @app.on_event("shutdown")
997
  async def shutdown_event():
998
  # Close all channels
@@ -1002,6 +1012,8 @@ async def shutdown_event():
1002
  # Stop the Firebase listener
1003
  app.state.users_watch.unsubscribe()
1004
 
 
 
1005
  @app.post("/notifications")
1006
  async def notifications(request: Request, background_tasks: BackgroundTasks):
1007
  try:
@@ -1034,8 +1046,10 @@ async def notifications(request: Request, background_tasks: BackgroundTasks):
1034
  logging.info(f"Processing new image: {file['id']}")
1035
  await process_image(user_id, file['id'], background_tasks)
1036
 
 
 
1037
  except Exception as e:
1038
- logging.error(f"Error processing folder changes: {str(e)}")
1039
 
1040
  else:
1041
  logging.warning(f"Received notification for unknown channel: {channel_id}")
@@ -1046,8 +1060,6 @@ async def notifications(request: Request, background_tasks: BackgroundTasks):
1046
  logging.error(f"Error processing notification: {str(e)}")
1047
  raise HTTPException(status_code=500, detail=str(e))
1048
 
1049
- # ... (keep the rest o
1050
-
1051
  def stop_channel(channel_id, resource_id):
1052
  request_body = {
1053
  'id': channel_id,
 
9
  from firebase_admin import credentials
10
  from firebase_admin import firestore
11
  import json
12
+ from datetime import datetime, timedelta
13
  import pytz
14
 
15
  from typing import List, Optional, Dict
 
912
  self.channels: Dict[str, Dict[str, Any]] = {}
913
 
914
  def create_channel(self, folder_id: str) -> Dict[str, Any]:
915
+ try:
916
+ body = {
917
+ 'id': f'channel-{folder_id}-{int(time.time())}',
918
+ 'type': 'web_hook',
919
+ 'address': 'https://m8chaa-re-sheet-develop.hf.space/notifications',
920
+ 'expiration': int((datetime.now() + timedelta(days=7)).timestamp() * 1000) # Set expiration to 7 days
921
+ }
922
+ response = app.state.drive_service.files().watch(fileId=folder_id, body=body).execute()
923
+ logging.info(f"Created channel for folder {folder_id}: {response['id']}")
924
+ return response
925
+ except HttpError as e:
926
+ logging.error(f"HttpError creating channel for folder {folder_id}: {e}")
927
+ raise
928
+ except Exception as e:
929
+ logging.error(f"Unexpected error creating channel for folder {folder_id}: {e}")
930
+ raise
931
 
932
  def close_channel(self, channel_id: str, resource_id: str):
933
  try:
 
936
  'resourceId': resource_id,
937
  }).execute()
938
  logging.info(f"Closed channel: {channel_id}")
939
+ except HttpError as e:
940
+ logging.error(f"HttpError closing channel {channel_id}: {e}")
941
  except Exception as e:
942
+ logging.error(f"Unexpected error closing channel {channel_id}: {e}")
943
 
944
  def update_watch_list(self):
945
  current_time = int(time.time())
 
984
  self.update_watch_list()
985
 
986
  @app.on_event("startup")
987
+ async def startup_event():
988
  app.state.drive_watcher = DriveWatcher()
989
  app.state.drive_service = build('drive', 'v3', credentials=APICredential)
990
+
991
  # Fetch all users and initialize the watch list
992
  users = users_collection_ref.get()
993
  for user in users:
 
1003
 
1004
  logging.info("Application startup completed")
1005
 
 
1006
  @app.on_event("shutdown")
1007
  async def shutdown_event():
1008
  # Close all channels
 
1012
  # Stop the Firebase listener
1013
  app.state.users_watch.unsubscribe()
1014
 
1015
+ logging.info("Application shutdown completed")
1016
+
1017
  @app.post("/notifications")
1018
  async def notifications(request: Request, background_tasks: BackgroundTasks):
1019
  try:
 
1046
  logging.info(f"Processing new image: {file['id']}")
1047
  await process_image(user_id, file['id'], background_tasks)
1048
 
1049
+ except HttpError as e:
1050
+ logging.error(f"HttpError processing folder changes: {e}")
1051
  except Exception as e:
1052
+ logging.error(f"Unexpected error processing folder changes: {e}")
1053
 
1054
  else:
1055
  logging.warning(f"Received notification for unknown channel: {channel_id}")
 
1060
  logging.error(f"Error processing notification: {str(e)}")
1061
  raise HTTPException(status_code=500, detail=str(e))
1062
 
 
 
1063
  def stop_channel(channel_id, resource_id):
1064
  request_body = {
1065
  'id': channel_id,