File size: 2,836 Bytes
289daab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | import os
import sys
import json
import urllib.parse
import subprocess
import threading
import asyncio
from aiohttp import web
import folder_paths
import struct
from .utils import require_filename, resolve_within
async def api_get_notebooks(request):
script_dir = os.path.dirname(os.path.abspath(__file__))
nb_dir = os.path.join(script_dir, "notebooks")
if not os.path.exists(nb_dir):
os.makedirs(nb_dir)
notebooks = []
for f in os.listdir(nb_dir):
if f.endswith('.json'):
try:
with open(os.path.join(nb_dir, f), 'r', encoding='utf-8') as file:
data = json.load(file)
notebooks.append({
"filename": f,
"name": data.get("name", f.replace('.json', '')),
"data": data
})
except Exception:
pass
return web.json_response({"notebooks": notebooks})
async def api_save_notebook(request):
try:
data = await request.json()
filename = data.get("filename", "")
if not filename.endswith('.json'):
filename += '.json'
try:
filename = require_filename(filename)
except ValueError:
return web.json_response({"status": "error", "message": "Invalid filename"}, status=400)
script_dir = os.path.dirname(os.path.abspath(__file__))
nb_dir = os.path.join(script_dir, "notebooks")
if not os.path.exists(nb_dir):
os.makedirs(nb_dir)
file_path = resolve_within(nb_dir, filename)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data.get("data", {}), f, indent=4, ensure_ascii=False)
return web.json_response({"status": "success"})
except Exception as e:
return web.json_response({"status": "error", "message": str(e)})
async def api_delete_notebook(request):
try:
data = await request.json()
filename = data.get("filename", "")
try:
filename = require_filename(filename)
except ValueError:
return web.json_response({"status": "error", "message": "Invalid filename"}, status=400)
script_dir = os.path.dirname(os.path.abspath(__file__))
nb_dir = os.path.join(script_dir, "notebooks")
file_path = resolve_within(nb_dir, filename)
if os.path.exists(file_path):
os.remove(file_path)
return web.json_response({"status": "success"})
return web.json_response({"status": "error", "message": "File not found"})
except Exception as e:
return web.json_response({"status": "error", "message": str(e)})
|