-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave-plugin.py
More file actions
100 lines (83 loc) · 3.62 KB
/
save-plugin.py
File metadata and controls
100 lines (83 loc) · 3.62 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
#!/usr/bin/env python3
"""
Simple file saving API for plugin development
Handles POST requests to save plugin files to disk
"""
import json
import os
import sys
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
class FileSaveHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
"""Handle CORS preflight requests"""
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
def do_POST(self):
"""Handle plugin file save requests"""
try:
# CORS headers
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-Type', 'application/json')
self.end_headers()
# Parse request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
# Extract parameters
file_path = data.get('filePath')
content = data.get('content')
backup = data.get('backup', True)
if not file_path or content is None:
raise ValueError("Missing filePath or content")
# Security check: ensure file is within project directory
project_root = os.path.abspath('.')
full_path = os.path.abspath(file_path)
if not full_path.startswith(project_root):
raise ValueError("File path outside project directory")
# Create backup if requested
if backup and os.path.exists(full_path):
backup_path = f"{full_path}.backup"
with open(full_path, 'r', encoding='utf-8') as f:
backup_content = f.read()
with open(backup_path, 'w', encoding='utf-8') as f:
f.write(backup_content)
# Ensure directory exists
os.makedirs(os.path.dirname(full_path), exist_ok=True)
# Write file
with open(full_path, 'w', encoding='utf-8') as f:
f.write(content)
# Success response
response = {
'success': True,
'message': f'File saved successfully: {file_path}',
'filePath': file_path,
'size': len(content)
}
self.wfile.write(json.dumps(response).encode('utf-8'))
print(f"✅ Saved file: {file_path} ({len(content)} bytes)")
except Exception as e:
# Error response
response = {
'success': False,
'error': str(e),
'message': f'Failed to save file: {str(e)}'
}
self.wfile.write(json.dumps(response).encode('utf-8'))
print(f"❌ Error saving file: {str(e)}")
def log_message(self, format, *args):
"""Suppress default logging"""
pass
if __name__ == '__main__':
port = 10001 # Different port from main server
server = HTTPServer(('', port), FileSaveHandler)
print(f"🚀 File saving API server running on port {port}")
print(f"💾 Ready to save plugin files via POST requests")
try:
server.serve_forever()
except KeyboardInterrupt:
print(f"\n🛑 File saving API server stopped")