-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·493 lines (410 loc) · 18.5 KB
/
server.py
File metadata and controls
executable file
·493 lines (410 loc) · 18.5 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!/usr/bin/env python3
"""
Markdown Editor Server
A minimal HTTP server with API endpoints for the Markdown Editor application.
Uses only Python standard library - no external dependencies.
"""
import http.server
import socketserver
import json
import os
import sys
import urllib.parse
import sqlite3
import hashlib
import subprocess
from pathlib import Path
from http import HTTPStatus
# Configuration (read from environment or use defaults)
PORT = int(os.environ.get('PORT', 3000))
HOST = os.environ.get('HOST', '0.0.0.0')
DB_PATH = os.environ.get('DB_PATH', './data/markdown_editor.db')
DOCS_DIR = os.environ.get('DOCS_DIR', './data/docs')
PUBLIC_DIR = './public'
class MarkdownEditorRequestHandler(http.server.SimpleHTTPRequestHandler):
"""Custom request handler for the Markdown Editor application."""
def __init__(self, *args, **kwargs):
# Set the directory to serve files from
super().__init__(*args, directory=PUBLIC_DIR, **kwargs)
def log_request(self, code='-', size='-'):
"""Log each request to console."""
print(f"{self.command} {self.path} - {code}")
def do_GET(self):
"""Handle GET requests: static files and API endpoints."""
# API requests
if self.path.startswith('/api/'):
self.handle_api_request()
return
# Default: serve static files
super().do_GET()
def do_POST(self):
"""Handle POST requests: API endpoints."""
# API requests
if self.path.startswith('/api/'):
self.handle_api_request()
return
# Default: method not allowed
self.send_error(HTTPStatus.METHOD_NOT_ALLOWED)
def handle_api_request(self):
"""Route API requests to the appropriate handler."""
# Parse the URL path
parsed_url = urllib.parse.urlparse(self.path)
path = parsed_url.path
# Handle different API endpoints
if path == '/api/login' and self.command == 'POST':
self.handle_login()
elif path == '/api/signup' and self.command == 'POST':
self.handle_signup()
elif path.startswith('/api/documents'):
if self.command == 'GET':
self.handle_documents_get()
elif self.command == 'POST':
self.handle_documents_post()
else:
self.send_error(HTTPStatus.METHOD_NOT_ALLOWED)
else:
self.send_error(HTTPStatus.NOT_FOUND, 'API endpoint not found')
def handle_login(self):
"""Handle user login."""
# Read request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
try:
# Parse JSON data
data = json.loads(post_data)
email = data.get('email', '')
password = data.get('password', '')
if not email or not password:
self.send_error(HTTPStatus.BAD_REQUEST, 'Missing email or password')
return
# Connect to the database
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Check if user exists and password matches
cursor.execute('SELECT id, password_hash FROM users WHERE username = ?', (email,))
user = cursor.fetchone()
if user:
user_id, stored_hash = user
calculated_hash = hashlib.sha256(password.encode()).hexdigest()
if calculated_hash == stored_hash:
# Success
response = {
'success': True,
'userId': user_id,
'id': user_id,
'username': email,
'name': email,
'email': email
}
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode())
else:
# Wrong password
self.send_error(HTTPStatus.UNAUTHORIZED, 'Invalid credentials')
else:
# User not found
self.send_error(HTTPStatus.UNAUTHORIZED, 'Invalid credentials')
conn.close()
except json.JSONDecodeError:
self.send_error(HTTPStatus.BAD_REQUEST, 'Invalid JSON')
except Exception as e:
print(f"Login error: {e}")
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
def handle_signup(self):
"""Handle user registration."""
# Read request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
try:
# Parse JSON data
data = json.loads(post_data)
name = data.get('name', '')
email = data.get('email', '')
password = data.get('password', '')
if not email or not password:
self.send_error(HTTPStatus.BAD_REQUEST, 'Missing email or password')
return
# Connect to the database
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Check if username already exists
cursor.execute('SELECT id FROM users WHERE username = ?', (email,))
if cursor.fetchone():
self.send_error(HTTPStatus.CONFLICT, 'Email already registered')
conn.close()
return
# Hash the password
password_hash = hashlib.sha256(password.encode()).hexdigest()
# Create the user
cursor.execute(
'INSERT INTO users (username, password_hash) VALUES (?, ?)',
(email, password_hash)
)
conn.commit()
# Get the new user's ID
user_id = cursor.lastrowid
# Create the user's document directory
user_dir = os.path.join(DOCS_DIR, f"user_{user_id}")
os.makedirs(user_dir, exist_ok=True)
# Initialize a Git repository for the user
try:
# Init the repo
subprocess.run(['git', 'init'], cwd=user_dir, check=True)
# Create a welcome document
welcome_file = os.path.join(user_dir, 'welcome.md')
with open(welcome_file, 'w') as f:
f.write("# Welcome to the Markdown Editor\n\n")
f.write("This is your first document. You can edit it or create new ones.\n\n")
f.write("## Features\n\n")
f.write("- Write in Markdown\n")
f.write("- Edit and save documents\n")
f.write("- Version control\n")
f.write("- Light and dark mode\n")
# Add the user's Git config (optional)
subprocess.run(['git', 'config', 'user.name', name], cwd=user_dir, check=False)
subprocess.run(['git', 'config', 'user.email', email], cwd=user_dir, check=False)
# Commit the welcome document
subprocess.run(['git', 'add', '.'], cwd=user_dir, check=True)
subprocess.run(['git', 'commit', '-m', 'Initial commit: Welcome document'], cwd=user_dir, check=True)
# Get the commit hash
result = subprocess.run(
['git', 'rev-parse', 'HEAD'],
cwd=user_dir,
capture_output=True,
check=True,
text=True
)
commit_hash = result.stdout.strip()
# Add welcome document to database
cursor.execute(
'INSERT INTO documents (user_id, title, filename) VALUES (?, ?, ?)',
(user_id, 'Welcome', 'welcome.md')
)
# Get the document ID
doc_id = cursor.lastrowid
# Add version to database
cursor.execute(
'INSERT INTO document_versions (document_id, commit_hash, message) VALUES (?, ?, ?)',
(doc_id, commit_hash, 'Initial commit: Welcome document')
)
conn.commit()
except Exception as e:
print(f"Git error: {e}")
# Continue even if Git operations fail
# Send success response
response = {
'success': True,
'userId': user_id,
'id': user_id,
'username': email,
'name': name,
'email': email
}
self.send_response(HTTPStatus.CREATED)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode())
conn.close()
except json.JSONDecodeError:
self.send_error(HTTPStatus.BAD_REQUEST, 'Invalid JSON')
except Exception as e:
print(f"Signup error: {e}")
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
def handle_documents_get(self):
"""Handle document retrieval."""
# Parse query parameters
parsed_url = urllib.parse.urlparse(self.path)
query_params = urllib.parse.parse_qs(parsed_url.query)
# Get user ID
user_id = query_params.get('userId', [''])[0]
if not user_id:
self.send_error(HTTPStatus.BAD_REQUEST, 'Missing userId parameter')
return
# Parse path to check if a specific document is requested
path_parts = parsed_url.path.split('/')
doc_name = None
if len(path_parts) > 3 and path_parts[3]:
doc_name = urllib.parse.unquote(path_parts[3].split('?')[0])
if doc_name:
# Get a specific document
doc_path = os.path.join(DOCS_DIR, f"user_{user_id}", doc_name)
if os.path.exists(doc_path) and os.path.isfile(doc_path):
# Read the document
with open(doc_path, 'r') as f:
content = f.read()
# Send the document content
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'text/markdown')
self.end_headers()
self.wfile.write(content.encode())
else:
self.send_error(HTTPStatus.NOT_FOUND, 'Document not found')
else:
# List all documents for the user
try:
# Connect to the database
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Get all documents for the user
cursor.execute(
'SELECT id, title, filename, created_at, updated_at FROM documents WHERE user_id = ? ORDER BY updated_at DESC',
(user_id,)
)
# Format the document list
documents = []
for doc in cursor.fetchall():
documents.append({
'id': doc[0],
'title': doc[1],
'filename': doc[2],
'createdAt': doc[3],
'updatedAt': doc[4]
})
# Send the document list
response = {
'success': True,
'documents': documents
}
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode())
conn.close()
except Exception as e:
print(f"Document list error: {e}")
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
def handle_documents_post(self):
"""Handle document creation/update."""
# Parse query parameters
parsed_url = urllib.parse.urlparse(self.path)
query_params = urllib.parse.parse_qs(parsed_url.query)
# Get user ID
user_id = query_params.get('userId', [''])[0]
if not user_id:
self.send_error(HTTPStatus.BAD_REQUEST, 'Missing userId parameter')
return
# Read request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
try:
# Parse JSON data
data = json.loads(post_data)
title = data.get('title', data.get('filename', '')) # Try title first, then filename
content = data.get('content', '')
filename = data.get('filename', '')
commit_msg = data.get('commitMsg', 'Update document') # Get commit message if available
if not content:
self.send_error(HTTPStatus.BAD_REQUEST, 'Missing content')
return
# Generate title from filename if not provided
if not title and filename:
title = os.path.splitext(filename)[0]
# Generate filename from title if not provided
if not filename and title:
# Convert spaces to underscores and remove special characters
filename = ''.join(c if c.isalnum() or c in [' ', '_', '-'] else '' for c in title.lower())
filename = filename.replace(' ', '_')
filename += '.md'
# Ensure filename has .md extension
if not filename.endswith('.md'):
filename += '.md'
# Connect to the database
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Check if document exists
cursor.execute(
'SELECT id FROM documents WHERE user_id = ? AND filename = ?',
(user_id, filename)
)
existing_doc = cursor.fetchone()
if existing_doc:
# Update existing document
doc_id = existing_doc[0]
cursor.execute(
'UPDATE documents SET title = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(title or filename, doc_id)
)
is_new = False
else:
# Insert new document
cursor.execute(
'INSERT INTO documents (user_id, title, filename) VALUES (?, ?, ?)',
(user_id, title or filename, filename)
)
doc_id = cursor.lastrowid
is_new = True
conn.commit()
# Save the document content
user_dir = os.path.join(DOCS_DIR, f"user_{user_id}")
os.makedirs(user_dir, exist_ok=True)
doc_path = os.path.join(user_dir, filename)
with open(doc_path, 'w') as f:
f.write(content)
# Update Git repository
try:
# Initialize Git repository if it doesn't exist
git_dir = os.path.join(user_dir, '.git')
if not os.path.exists(git_dir):
subprocess.run(['git', 'init'], cwd=user_dir, check=True)
# Stage the file
subprocess.run(['git', 'add', filename], cwd=user_dir, check=True)
# Commit the changes
commit_message = commit_msg or f"{'Created' if is_new else 'Updated'} {title or filename}"
subprocess.run(['git', 'commit', '-m', commit_message], cwd=user_dir, check=True)
# Get the commit hash
result = subprocess.run(
['git', 'rev-parse', 'HEAD'],
cwd=user_dir,
capture_output=True,
check=True,
text=True
)
commit_hash = result.stdout.strip()
# Add version to database
cursor.execute(
'INSERT INTO document_versions (document_id, commit_hash, message) VALUES (?, ?, ?)',
(doc_id, commit_hash, commit_message)
)
conn.commit()
except Exception as e:
print(f"Git error: {e}")
# Continue even if Git operations fail
# Send success response
response = {
'success': True,
'documentId': doc_id,
'filename': filename,
'isNew': is_new
}
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response).encode())
conn.close()
except json.JSONDecodeError:
self.send_error(HTTPStatus.BAD_REQUEST, 'Invalid JSON')
except Exception as e:
print(f"Document save error: {e}")
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
def main():
"""Start the server."""
# Create server with threading support
class ThreadedHTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
# Create and configure the server
server = ThreadedHTTPServer((HOST, PORT), MarkdownEditorRequestHandler)
# Print server information
print(f"Starting Markdown Editor server at http://{HOST}:{PORT}")
print("Press Ctrl+C to stop")
try:
# Start the server
server.serve_forever()
except KeyboardInterrupt:
# Handle server shutdown
print("\nShutting down server...")
server.server_close()
print("Server stopped")
if __name__ == "__main__":
main()