-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
283 lines (242 loc) · 10.8 KB
/
server.py
File metadata and controls
283 lines (242 loc) · 10.8 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
import os
import socket
import json
import mimetypes
import urllib.parse
from http.server import BaseHTTPRequestHandler
from socketserver import ThreadingMixIn, TCPServer
from pathlib import Path
import threading
import webbrowser
import gzip
# Configuration
UPLOAD_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "shared_files")
os.makedirs(UPLOAD_DIR, exist_ok=True)
PORT = 8080
def generate_qr_svg(data, box_size=6):
"""Generate QR code as SVG string using pure Python (no dependencies)."""
# We'll generate the QR code on the client side with JS instead
pass
CHUNK_SIZE = 262144 # 256KB chunks for fast transfer
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
def format_size(size_bytes):
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.1f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes / (1024 * 1024):.1f} MB"
else:
return f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"
def get_file_type(filename):
ext = Path(filename).suffix.lower()
types = {
".pdf": "pdf", ".doc": "doc", ".docx": "doc", ".txt": "text",
".jpg": "image", ".jpeg": "image", ".png": "image", ".gif": "image",
".webp": "image", ".svg": "image", ".bmp": "image", ".ico": "image",
".mp4": "video", ".mov": "video", ".avi": "video", ".mkv": "video", ".webm": "video",
".mp3": "audio", ".wav": "audio", ".flac": "audio", ".aac": "audio", ".ogg": "audio",
".zip": "archive", ".rar": "archive", ".7z": "archive", ".tar": "archive", ".gz": "archive",
".py": "code", ".js": "code", ".html": "code", ".css": "code", ".java": "code",
".cpp": "code", ".c": "code", ".ts": "code", ".dart": "code", ".json": "code",
".xlsx": "spreadsheet", ".xls": "spreadsheet", ".csv": "spreadsheet",
".pptx": "presentation", ".ppt": "presentation",
".apk": "android", ".ipa": "ios",
".exe": "app", ".msi": "app", ".dmg": "app",
}
return types.get(ext, "file")
# Cache HTML in memory on startup for instant serving
HTML_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html")
HTML_CACHE = b""
HTML_CACHE_GZIP = b""
def load_html_cache():
global HTML_CACHE, HTML_CACHE_GZIP
with open(HTML_PATH, "r", encoding="utf-8") as f:
HTML_CACHE = f.read().encode("utf-8")
HTML_CACHE_GZIP = gzip.compress(HTML_CACHE, compresslevel=6)
class ThreadingHTTPServer(ThreadingMixIn, TCPServer):
allow_reuse_address = True
daemon_threads = True
request_queue_size = 64
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1048576)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1048576)
except Exception:
pass
super().server_bind()
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass # Quiet logging for speed
def do_OPTIONS(self):
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.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
p = self.path.split("?")[0]
if p in ("/", "/index.html"):
self.serve_html()
elif p == "/api/files":
self.list_files()
elif p.startswith("/api/download/"):
self.download_file()
elif p == "/api/info":
self.send_json({"ip": get_local_ip(), "port": PORT, "hostname": socket.gethostname()})
else:
self.send_error(404)
def do_POST(self):
p = self.path.split("?")[0]
if p == "/api/upload":
self.upload_file()
elif p.startswith("/api/delete/"):
self.delete_file()
else:
self.send_error(404)
def serve_html(self):
ae = self.headers.get("Accept-Encoding", "")
if "gzip" in ae and HTML_CACHE_GZIP:
body = HTML_CACHE_GZIP
self.send_response(200)
self.send_header("Content-Encoding", "gzip")
else:
body = HTML_CACHE
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Connection", "keep-alive")
self.end_headers()
self.wfile.write(body)
def list_files(self):
files = []
try:
for f in sorted(os.listdir(UPLOAD_DIR)):
fp = os.path.join(UPLOAD_DIR, f)
if os.path.isfile(fp):
st = os.stat(fp)
files.append({
"name": f,
"size": st.st_size,
"size_fmt": format_size(st.st_size),
"modified": st.st_mtime,
"type": get_file_type(f),
})
except Exception as e:
print(f" Error: {e}")
self.send_json(files)
def download_file(self):
filename = urllib.parse.unquote(self.path.split("?")[0][len("/api/download/"):])
filepath = os.path.join(UPLOAD_DIR, filename)
if not os.path.abspath(filepath).startswith(os.path.abspath(UPLOAD_DIR)):
self.send_error(403); return
if not os.path.isfile(filepath):
self.send_error(404); return
mime, _ = mimetypes.guess_type(filepath)
fsize = os.path.getsize(filepath)
self.send_response(200)
self.send_header("Content-Type", mime or "application/octet-stream")
self.send_header("Content-Length", str(fsize))
self.send_header("Content-Disposition", f'attachment; filename="{urllib.parse.quote(filename)}"')
self.send_header("Connection", "keep-alive")
self.end_headers()
with open(filepath, "rb") as f:
while True:
chunk = f.read(CHUNK_SIZE)
if not chunk: break
try:
self.wfile.write(chunk)
except (BrokenPipeError, ConnectionResetError):
break
def upload_file(self):
ct = self.headers.get("Content-Type", "")
if "multipart/form-data" not in ct:
self.send_json({"error": "Invalid"}, 400); return
boundary = ct.split("boundary=")[1].strip().strip('"')
cl = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(cl)
parts = body.split(b"--" + boundary.encode())
uploaded = []
for part in parts:
if b"Content-Disposition" not in part: continue
he = part.find(b"\r\n\r\n")
if he == -1: continue
hdr = part[:he].decode("utf-8", errors="replace")
content = part[he + 4:]
if content.endswith(b"\r\n"): content = content[:-2]
if content.endswith(b"--"): content = content[:-2]
if content.endswith(b"\r\n"): content = content[:-2]
if 'filename="' in hdr:
fn = hdr.split('filename="')[1].split('"')[0]
if not fn: continue
fn = os.path.basename(fn)
fp = os.path.join(UPLOAD_DIR, fn)
if os.path.exists(fp):
nm, ext = os.path.splitext(fn)
c = 1
while os.path.exists(fp):
fn = f"{nm} ({c}){ext}"; fp = os.path.join(UPLOAD_DIR, fn); c += 1
with open(fp, "wb") as f:
f.write(content)
uploaded.append({"name": fn, "size": len(content), "size_fmt": format_size(len(content))})
print(f" ✅ Uploaded: {fn} ({format_size(len(content))})")
self.send_json({"files": uploaded, "count": len(uploaded)})
def delete_file(self):
fn = urllib.parse.unquote(self.path.split("?")[0][len("/api/delete/"):])
fp = os.path.join(UPLOAD_DIR, fn)
if not os.path.abspath(fp).startswith(os.path.abspath(UPLOAD_DIR)):
self.send_json({"error": "Denied"}, 403); return
if os.path.isfile(fp):
os.remove(fp); print(f" 🗑️ Deleted: {fn}")
self.send_json({"success": True})
else:
self.send_json({"error": "Not found"}, 404)
def send_json(self, data, status=200):
body = json.dumps(data, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Connection", "keep-alive")
self.end_headers()
self.wfile.write(body)
def main():
load_html_cache()
local_ip = get_local_ip()
url = f"http://{local_ip}:{PORT}"
print()
print(" ╔══════════════════════════════════════════════════════╗")
print(" ║ 📡 AirBridge File Transfer ║")
print(" ╠══════════════════════════════════════════════════════╣")
print(f" ║ Server running at: ║")
print(f" ║ 👉 {url:<43s} ║")
print(" ║ ║")
print(" ║ Open this URL in Safari on your iPhone ║")
print(" ║ (Make sure both devices are on the same Wi-Fi) ║")
print(" ╠══════════════════════════════════════════════════════╣")
print(f" ║ Shared folder: shared_files/ ║")
print(" ╚══════════════════════════════════════════════════════╝")
print()
print(" Waiting for connections... (Press Ctrl+C to stop)")
print()
server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
threading.Timer(0.5, lambda: webbrowser.open(url)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n 👋 Server stopped. Goodbye!")
server.server_close()
if __name__ == "__main__":
main()