Repository navigation
Expand file tree
/
Copy pathserver_routes.py
More file actions
68 lines (60 loc) · 2.64 KB
/
Copy pathserver_routes.py
File metadata and controls
68 lines (60 loc) · 2.64 KB
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
# -*- coding: utf-8 -*-
"""PerfectLab's own userdata write API.
The stock ComfyUI userdata routes are read-only on some installations
(this machine's 0.11.1 build answers 405 to POST and DELETE on
/api/userdata/{file} while the code on disk registers them -- whatever
the cause, the panel's custom libraries could never persist). PerfectLab
ships its own read/write/delete endpoints scoped to the same user
directory, built on the UserManager's own path validation, so the
panel's writes work on any build.
Registered under /perfectlab/userdata (and /api/perfectlab/userdata via
the automatic /api prefix mirror).
"""
import os
from aiohttp import web
def add_routes(routes, user_manager):
def resolve(request, f, create_dir=False):
"""user-scoped path, or None when the name escapes it. The stock
validator raises on cross-drive absolute names (Windows) and on
unknown multi-user ids -- both read as a plain rejection here."""
try:
return user_manager.get_request_user_filepath(request, f, create_dir=create_dir)
except (ValueError, KeyError, OSError):
return None
@routes.get("/perfectlab/userdata")
async def read_userdata(request):
f = request.query.get("file", "")
if not f:
return web.Response(status=400, text="file query parameter required")
path = resolve(request, f)
if not path or not os.path.exists(path):
return web.Response(status=404, text="not found")
return web.FileResponse(path)
@routes.post("/perfectlab/userdata")
async def write_userdata(request):
f = request.query.get("file", "")
if not f:
return web.Response(status=400, text="file query parameter required")
path = resolve(request, f, create_dir=True)
if not path:
return web.Response(status=403, text="path rejected")
body = await request.read()
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as fh:
fh.write(body)
except OSError:
return web.Response(status=400, text="invalid filename")
return web.json_response(f)
@routes.delete("/perfectlab/userdata")
async def delete_userdata(request):
f = request.query.get("file", "")
if not f:
return web.Response(status=400, text="file query parameter required")
path = resolve(request, f)
if path and os.path.exists(path):
try:
os.remove(path)
except OSError:
return web.Response(status=400, text="could not remove")
return web.json_response(f)