import os import json import aiohttp from aiohttp import web import server import folder_paths # <--- USE COMFTYUI PATH MANAGER # --- Improved Path Configuration --- # This attempts to save where ComfyUI looks for workflows by default base_path = folder_paths.base_path # Try the modern 'user/default/workflows' path first SAVE_DIR = os.path.join(base_path, "user", "default", "workflows") # If that folder structure doesn't exist (older comfy), fallback to 'output' if not os.path.exists(os.path.dirname(SAVE_DIR)): SAVE_DIR = folder_paths.get_output_directory() if not os.path.exists(SAVE_DIR): os.makedirs(SAVE_DIR) class NetworkSync: pass # 1. RECEIVE Endpoint @server.PromptServer.instance.routes.post("/network-sync/receive") async def receive_workflow(request): try: data = await request.json() filename = data.get("name", "synced_workflow") workflow = data.get("workflow") # Basic security: prevent saving outside the folder filename = os.path.basename(filename) if not filename.endswith(".json"): filename += ".json" save_path = os.path.join(SAVE_DIR, filename) # Write the file with open(save_path, "w", encoding="utf-8") as f: json.dump(workflow, f, indent=2) print(f"✅ [NetworkSync] Received and updated: {filename}") return web.json_response({"status": "success", "message": f"Saved to {save_path}"}) except Exception as e: print(f"❌ [NetworkSync] Error: {e}") return web.json_response({"status": "error", "message": str(e)}, status=500) # 2. PUSH Endpoint @server.PromptServer.instance.routes.post("/network-sync/push") async def push_workflow(request): try: data = await request.json() target_ip = data.get("target_ip") # Auto-correct IP formatting if "http" not in target_ip: target_ip = "http://" + target_ip # Ensure port is present if missing (assume default 8188) if ":" not in target_ip.replace("http://", "").replace("https://", ""): target_ip += ":8188" target_url = f"{target_ip}/network-sync/receive" payload = { "name": data.get("name"), "workflow": data.get("workflow") } # Timeout added so ComfyUI doesn't freeze if target is offline timeout = aiohttp.ClientTimeout(total=5) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(target_url, json=payload) as resp: if resp.status == 200: return web.json_response({"status": "success"}) else: return web.json_response({"status": "error", "message": f"Target error: {resp.status}"}) except Exception as e: return web.json_response({"status": "error", "message": str(e)}, status=500) NODE_CLASS_MAPPINGS = {} WEB_DIRECTORY = "./web"