m8chaa commited on
Commit
71b6206
·
verified ·
1 Parent(s): 6ee09e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -1
app.py CHANGED
@@ -16,6 +16,11 @@ from typing import List, Optional, Dict
16
  from google.oauth2 import service_account
17
  from googleapiclient.discovery import build
18
 
 
 
 
 
 
19
  # start application
20
  app = FastAPI()
21
 
@@ -882,4 +887,52 @@ async def sync_data(data_json: str = Form(...), user_id: str = Form(...)):
882
  raise he
883
  except Exception as e:
884
  logging.error(f"Unexpected error in sync_data for user {user_id}: {str(e)}")
885
- raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  from google.oauth2 import service_account
17
  from googleapiclient.discovery import build
18
 
19
+ from watchdog.observers import Observer
20
+ from watchdog.events import FileSystemEventHandler
21
+ import os
22
+ from threading import Thread
23
+
24
  # start application
25
  app = FastAPI()
26
 
 
887
  raise he
888
  except Exception as e:
889
  logging.error(f"Unexpected error in sync_data for user {user_id}: {str(e)}")
890
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
891
+
892
+
893
+
894
+ observers = {}
895
+
896
+ class WatchdogHandler(FileSystemEventHandler):
897
+ def __init__(self, folder_id):
898
+ self.folder_id = folder_id
899
+
900
+ def on_modified(self, event):
901
+ logging.info(f"Modification detected: {event.src_path}")
902
+
903
+ def on_created(self, event):
904
+ logging.info(f"Creation detected: {event.src_path}")
905
+
906
+ def on_deleted(self, event):
907
+ logging.info(f"Deletion detected: {event.src_path}")
908
+
909
+ def on_moved(self, event):
910
+ logging.info(f"Move detected: from {event.src_path} to {event.dest_path}")
911
+
912
+ def watch_folder(folder_path, folder_id):
913
+ event_handler = WatchdogHandler(folder_id)
914
+ observer = Observer()
915
+ observer.schedule(event_handler, path=folder_path, recursive=True)
916
+ observer.start()
917
+ observers[folder_id] = observer
918
+
919
+ @app.post("/watch/{folder_id}")
920
+ async def watch_folder_endpoint(folder_id: str):
921
+ # Construct a folder path from the folder_id
922
+ folder_path = f"./{folder_id}"
923
+
924
+ # Check if the folder exists
925
+ if not os.path.exists(folder_path):
926
+ raise HTTPException(status_code=404, detail="Folder not found")
927
+
928
+ # Start watching the folder in a separate thread
929
+ thread = Thread(target=watch_folder, args=(folder_path, folder_id))
930
+ thread.start()
931
+
932
+ return {"message": f"Started watching folder: {folder_id}"}
933
+
934
+ @app.on_event("shutdown")
935
+ def shutdown_event():
936
+ for observer in observers.values():
937
+ observer.stop()
938
+ observer.join()