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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -17
app.py CHANGED
@@ -916,6 +916,7 @@ class DriveWatcher:
916
  'id': f'channel-{folder_id}-{int(time.time())}',
917
  'type': 'web_hook',
918
  'address': 'https://m8chaa-re-sheet-develop.hf.space/notifications',
 
919
  }
920
  response = app.state.drive_service.files().watch(fileId=folder_id, body=body).execute()
921
  return response
@@ -931,23 +932,28 @@ class DriveWatcher:
931
  logging.error(f"Error closing channel {channel_id}: {str(e)}")
932
 
933
  def update_watch_list(self):
 
934
  for channel_id, channel_info in list(self.channels.items()):
935
- self.close_channel(channel_id, channel_info['resourceId'])
936
- del self.channels[channel_id]
 
937
 
938
  for user_id, folder_id in self.watch_list.items():
939
- try:
940
- response = self.create_channel(folder_id)
941
- self.channels[response['id']] = {
942
- 'resourceId': response['resourceId'],
943
- 'user_id': user_id,
944
- 'folder_id': folder_id
945
- }
946
- logging.info(f"Created new channel for user {user_id}, folder {folder_id}")
947
- except Exception as e:
948
- logging.error(f"Error creating channel for user {user_id}: {str(e)}")
 
 
949
 
950
  def on_user_change(self, snapshot, changes, read_time):
 
951
  for change in changes:
952
  user_id = change.document.id
953
  user_data = change.document.to_dict()
@@ -955,13 +961,17 @@ class DriveWatcher:
955
  if change.type.name in ['ADDED', 'MODIFIED']:
956
  if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
957
  folder_id = user_data['gDrive_metadata']['uploaded']
958
- self.watch_list[user_id] = folder_id
959
- self.update_watch_list()
 
960
 
961
  elif change.type.name == 'REMOVED':
962
  if user_id in self.watch_list:
963
  del self.watch_list[user_id]
964
- self.update_watch_list()
 
 
 
965
 
966
  @app.on_event("startup")
967
  def startup_event():
@@ -1010,11 +1020,11 @@ async def notifications(request: Request, background_tasks: BackgroundTasks):
1010
 
1011
  logging.info(f"Notification is for user: {user_id}, folder: {folder_id}")
1012
 
1013
- if resource_state in ['changes']:
1014
  try:
1015
  # List files in the folder that have been recently modified
1016
  results = app.state.drive_service.files().list(
1017
- q=f"'{folder_id}' in parents and mimeType contains 'image/' and modifiedTime > '-1d'",
1018
  fields="files(id, mimeType)"
1019
  ).execute()
1020
  files = results.get('files', [])
@@ -1036,6 +1046,8 @@ async def notifications(request: Request, background_tasks: BackgroundTasks):
1036
  logging.error(f"Error processing notification: {str(e)}")
1037
  raise HTTPException(status_code=500, detail=str(e))
1038
 
 
 
1039
  def stop_channel(channel_id, resource_id):
1040
  request_body = {
1041
  'id': channel_id,
 
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
 
932
  logging.error(f"Error closing channel {channel_id}: {str(e)}")
933
 
934
  def update_watch_list(self):
935
+ current_time = int(time.time())
936
  for channel_id, channel_info in list(self.channels.items()):
937
+ if current_time >= channel_info['expiration'] // 1000:
938
+ self.close_channel(channel_id, channel_info['resourceId'])
939
+ del self.channels[channel_id]
940
 
941
  for user_id, folder_id in self.watch_list.items():
942
+ if not any(info['folder_id'] == folder_id for info in self.channels.values()):
943
+ try:
944
+ response = self.create_channel(folder_id)
945
+ self.channels[response['id']] = {
946
+ 'resourceId': response['resourceId'],
947
+ 'user_id': user_id,
948
+ 'folder_id': folder_id,
949
+ 'expiration': int(response['expiration'])
950
+ }
951
+ logging.info(f"Created new channel for user {user_id}, folder {folder_id}")
952
+ except Exception as e:
953
+ logging.error(f"Error creating channel for user {user_id}: {str(e)}")
954
 
955
  def on_user_change(self, snapshot, changes, read_time):
956
+ update_required = False
957
  for change in changes:
958
  user_id = change.document.id
959
  user_data = change.document.to_dict()
 
961
  if change.type.name in ['ADDED', 'MODIFIED']:
962
  if 'gDrive_metadata' in user_data and 'uploaded' in user_data['gDrive_metadata']:
963
  folder_id = user_data['gDrive_metadata']['uploaded']
964
+ if user_id not in self.watch_list or self.watch_list[user_id] != folder_id:
965
+ self.watch_list[user_id] = folder_id
966
+ update_required = True
967
 
968
  elif change.type.name == 'REMOVED':
969
  if user_id in self.watch_list:
970
  del self.watch_list[user_id]
971
+ update_required = True
972
+
973
+ if update_required:
974
+ self.update_watch_list()
975
 
976
  @app.on_event("startup")
977
  def startup_event():
 
1020
 
1021
  logging.info(f"Notification is for user: {user_id}, folder: {folder_id}")
1022
 
1023
+ if resource_state == 'change' and changed == 'content':
1024
  try:
1025
  # List files in the folder that have been recently modified
1026
  results = app.state.drive_service.files().list(
1027
+ q=f"'{folder_id}' in parents and mimeType contains 'image/' and modifiedTime > '-5m'",
1028
  fields="files(id, mimeType)"
1029
  ).execute()
1030
  files = results.get('files', [])
 
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,