import os import threading import subprocess import traceback from datetime import datetime from rclone_installer import check_and_install_rclone, RCLONE_EXE # Rclone configuration REMOTE_NAME = "gdrive" REMOTE_FOLDER = "Guardians_Workspace/Aizen_Forge" def _sync_task(filename: str, content: str): """ Background worker thread to save the file locally and then sync it to Google Drive using Rclone. """ temp_path = None try: # 1. Rclone 설치/경로 확인 if not os.path.exists(RCLONE_EXE): return # 2. 임시 파일 생성 (rclone은 파일 단위 전송이 기본) temp_dir = os.path.join(os.path.expanduser("~"), ".jarvis_rclone_temp") os.makedirs(temp_dir, exist_ok=True) temp_path = os.path.join(temp_dir, filename) with open(temp_path, "w", encoding="utf-8") as f: f.write(content) # 3. Rclone copyto 실행 (gdrive:폴더/파일명) # copyto는 대상 파일이 있으면 덮어씌웁니다 (n8n처럼 중복 생성 안 됨) remote_path = f"{REMOTE_NAME}:{REMOTE_FOLDER}/{filename}" cmd = [RCLONE_EXE, "copyto", temp_path, remote_path, "--quiet"] # Subprocess 실행 (비동기 스레드 내부이므로 wait 해도 메인 서버는 안 멈춤) result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace') if result.returncode == 0: print(f"[{datetime.now().strftime('%H:%M:%S')}] ☁️ [Rclone] '{filename}' 동기화 성공! -> Google Drive") else: print(f"[{datetime.now().strftime('%H:%M:%S')}] ⚠️ [Rclone] '{filename}' 동기화 실패: {result.stderr}") except Exception as e: print(f"[{datetime.now().strftime('%H:%M:%S')}] ❌ [Rclone] '{filename}' 동기화 중 에러: {e}") finally: # 임시 파일 삭제 if temp_path and os.path.exists(temp_path): try: os.remove(temp_path) except: pass def sync_to_gdrive(filename: str, content: str): """ Spawns a background thread to sync file content to Google Drive via Rclone. """ # Exclude files that do not need to be synced ignored_prefixes = ["JARVIS_TERMINAL", "JARVISRUN_STATUS"] for prefix in ignored_prefixes: if filename.startswith(prefix): return thread = threading.Thread(target=_sync_task, args=(filename, content)) thread.daemon = True thread.start() if __name__ == "__main__": # Test execution print("🚀 Testing Rclone Google Drive Sync Module...") check_and_install_rclone() test_content = f"# Rclone Test\nLast updated: {datetime.now()}" sync_to_gdrive("rclone_test.md", test_content) import time time.sleep(5) # 스레드 완료 대기 print("Test finished.")