-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
114 lines (95 loc) · 4.87 KB
/
Copy pathserver.py
File metadata and controls
114 lines (95 loc) · 4.87 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import http.server
import json
import os
import urllib.parse
PORT = 8000
DIRECTORY = os.path.dirname(os.path.abspath(__file__))
class ConciergeRequestHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
def do_POST(self):
parsed_url = urllib.parse.urlparse(self.path)
# 1. API: List Files in subdirectory
if parsed_url.path == '/api/list-files':
try:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
path_array = data.get('pathArray', [])
target_dir = os.path.join(DIRECTORY, 'data', *path_array)
files = []
if os.path.exists(target_dir):
for name in os.listdir(target_dir):
if os.path.isfile(os.path.join(target_dir, name)) and name.endswith('.md'):
files.append(name)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({'files': files}).encode('utf-8'))
except Exception as e:
self.send_error_response(e)
# 2. API: Write file inside data subdirectory
elif parsed_url.path == '/api/write-file':
try:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
path_array = data.get('pathArray', [])
filename = data.get('filename', '')
content = data.get('content', '')
target_dir = os.path.join(DIRECTORY, 'data', *path_array)
os.makedirs(target_dir, exist_ok=True)
target_file = os.path.join(target_dir, filename)
with open(target_file, 'w', encoding='utf-8') as f:
f.write(content)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({'status': 'success'}).encode('utf-8'))
except Exception as e:
self.send_error_response(e)
# 3. API: Delete file inside data subdirectory
elif parsed_url.path == '/api/delete-file':
try:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
path_array = data.get('pathArray', [])
filename = data.get('filename', '')
target_file = os.path.join(DIRECTORY, 'data', *path_array, filename)
if os.path.exists(target_file):
os.remove(target_file)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({'status': 'success'}).encode('utf-8'))
except Exception as e:
self.send_error_response(e)
else:
self.send_response(404)
self.end_headers()
def send_error_response(self, exception):
try:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({'error': str(exception)}).encode('utf-8'))
except Exception as e:
print("Failed to send error response:", e)
def do_OPTIONS(self):
# Support CORS preflight
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
if __name__ == '__main__':
print(f"Starting Concierge Local Server on http://localhost:{PORT}...")
# ThreadingHTTPServer: browsers hold idle keep-alive/preconnect sockets open,
# which deadlocks the single-threaded HTTPServer (all requests queue behind them).
server = http.server.ThreadingHTTPServer(('localhost', PORT), ConciergeRequestHandler)
server.serve_forever()