-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
305 lines (257 loc) · 12.7 KB
/
server.py
File metadata and controls
305 lines (257 loc) · 12.7 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
import http.server
import socketserver
import json
import os
import mimetypes
import argparse
from urllib.parse import urlparse
from io import BytesIO
UNREAD_FILENAME = 'unread_papers.json'
USEFUL_LINKS_FILENAME = 'useful_links.json'
DATASETS_FILENAME = 'datasets.json'
TOPICS_FILENAME = 'topics.json'
TOPICS_DIR = 'topics'
class ReusableTCPServer(socketserver.TCPServer):
allow_reuse_address = True
class PaperServerHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
# Add CORS headers for all responses
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')
super().end_headers()
def do_OPTIONS(self):
self.send_response(200)
self.end_headers()
def do_GET(self):
parsed_path = urlparse(self.path)
# Dynamic papers list endpoint
if parsed_path.path == '/list-papers':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# Dynamically scan papers directory
papers_dir = os.path.join(os.getcwd(), 'papers')
paper_files = []
try:
if os.path.exists(papers_dir) and os.path.isdir(papers_dir):
for filename in os.listdir(papers_dir):
if filename.endswith('.json'):
paper_files.append(f'papers/{filename}')
# Sort the files for consistent ordering
paper_files.sort()
print(f"Dynamically found {len(paper_files)} papers")
except Exception as e:
print(f"Error scanning papers directory: {e}")
# Return the paper files as JSON
response = {'paperFiles': paper_files}
self.wfile.write(json.dumps(response).encode())
# Unread list persistence
elif parsed_path.path == '/unread-list':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
unread_path = os.path.join(os.getcwd(), UNREAD_FILENAME)
legacy_path = os.path.join(os.getcwd(), 'unread-list.json')
data = {"items": []}
try:
path_to_use = unread_path if os.path.exists(unread_path) else (legacy_path if os.path.exists(legacy_path) else None)
if path_to_use:
with open(path_to_use, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
print(f"Error reading unread list: {e}")
self.wfile.write(json.dumps(data).encode())
# Useful links persistence
elif parsed_path.path == '/useful-links':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
links_path = os.path.join(os.getcwd(), USEFUL_LINKS_FILENAME)
data = {"items": []}
try:
if os.path.exists(links_path):
with open(links_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
print(f"Error reading useful links: {e}")
self.wfile.write(json.dumps(data).encode())
# Datasets persistence
elif parsed_path.path == '/datasets':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
datasets_path = os.path.join(os.getcwd(), DATASETS_FILENAME)
data = {"items": []}
try:
if os.path.exists(datasets_path):
with open(datasets_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
print(f"Error reading datasets: {e}")
self.wfile.write(json.dumps(data).encode())
# Topics persistence
elif parsed_path.path == '/topics':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
topics_path = os.path.join(os.getcwd(), TOPICS_FILENAME)
data = {"items": []}
try:
if os.path.exists(topics_path):
with open(topics_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
print(f"Error reading topics: {e}")
self.wfile.write(json.dumps(data).encode())
# Get topic markdown file
elif parsed_path.path.startswith('/topics/') and len(parsed_path.path.split('/')) == 3:
slug = parsed_path.path.split('/')[2]
topics_dir = os.path.join(os.getcwd(), TOPICS_DIR)
markdown_path = os.path.join(topics_dir, f"{slug}.md")
if os.path.exists(markdown_path):
self.send_response(200)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
try:
with open(markdown_path, 'r', encoding='utf-8') as f:
content = f.read()
self.wfile.write(content.encode('utf-8'))
except Exception as e:
print(f"Error reading markdown: {e}")
self.wfile.write(b'')
else:
self.send_response(200)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
self.wfile.write(b'')
# Handle other requests normally (serve static files)
else:
super().do_GET()
def do_POST(self):
parsed_path = urlparse(self.path)
if parsed_path.path == '/unread-list':
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
try:
payload = json.loads(body.decode('utf-8'))
items = payload.get('items', [])
if not isinstance(items, list):
raise ValueError("items must be a list")
unread_path = os.path.join(os.getcwd(), UNREAD_FILENAME)
with open(unread_path, 'w', encoding='utf-8') as f:
json.dump({"items": items}, f, ensure_ascii=False, indent=2)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
print(f"Error saving unread list: {e}")
self.send_response(400)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
elif parsed_path.path == '/useful-links':
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
try:
payload = json.loads(body.decode('utf-8'))
items = payload.get('items', [])
if not isinstance(items, list):
raise ValueError("items must be a list")
links_path = os.path.join(os.getcwd(), USEFUL_LINKS_FILENAME)
with open(links_path, 'w', encoding='utf-8') as f:
json.dump({"items": items}, f, ensure_ascii=False, indent=2)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
print(f"Error saving useful links: {e}")
self.send_response(400)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
elif parsed_path.path == '/datasets':
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
try:
payload = json.loads(body.decode('utf-8'))
items = payload.get('items', [])
if not isinstance(items, list):
raise ValueError("items must be a list")
datasets_path = os.path.join(os.getcwd(), DATASETS_FILENAME)
with open(datasets_path, 'w', encoding='utf-8') as f:
json.dump({"items": items}, f, ensure_ascii=False, indent=2)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
print(f"Error saving datasets: {e}")
self.send_response(400)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
elif parsed_path.path == '/topics':
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
try:
payload = json.loads(body.decode('utf-8'))
items = payload.get('items', [])
if not isinstance(items, list):
raise ValueError("items must be a list")
topics_path = os.path.join(os.getcwd(), TOPICS_FILENAME)
with open(topics_path, 'w', encoding='utf-8') as f:
json.dump({"items": items}, f, ensure_ascii=False, indent=2)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
print(f"Error saving topics: {e}")
self.send_response(400)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
# Save topic markdown file
elif parsed_path.path.startswith('/topics/') and len(parsed_path.path.split('/')) == 3:
slug = parsed_path.path.split('/')[2]
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
try:
topics_dir = os.path.join(os.getcwd(), TOPICS_DIR)
os.makedirs(topics_dir, exist_ok=True)
markdown_path = os.path.join(topics_dir, f"{slug}.md")
content = body.decode('utf-8')
with open(markdown_path, 'w', encoding='utf-8') as f:
f.write(content)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
print(f"Error saving topic markdown: {e}")
self.send_response(400)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
else:
self.send_response(404)
self.end_headers()
def run_server(port=8000):
with ReusableTCPServer(("", port), PaperServerHandler) as httpd:
print(f"Server running at http://localhost:{port}")
print(f"Papers list endpoint: http://localhost:{port}/list-papers")
print(f"Main page: http://localhost:{port}")
print("\nPress Ctrl+C to stop the server")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nServer stopped.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Run a simple HTTP server for paper management')
parser.add_argument('--port', type=int, default=9000, help='Port to run the server on')
args = parser.parse_args()
run_server(args.port)