Starchik1 commited on
Commit
c15c343
·
verified ·
1 Parent(s): 1bda23f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +687 -76
main.py CHANGED
@@ -1,81 +1,692 @@
1
- import socket
2
- import threading
3
- import select
4
- import sys
5
-
6
- # Конфигурация
7
- PROXY_HOST = '0.0.0.0'
8
- PROXY_PORT = 8888
9
- BUFFER_SIZE = 4096
10
-
11
- def handle_client(client_socket):
12
- # Получаем первый пакет (заголовки)
13
- data = client_socket.recv(BUFFER_SIZE)
14
-
15
- # Анализ запроса (HTTP или HTTPS)
16
- try:
17
- if data.startswith(b'CONNECT'):
18
- # HTTPS CONNECT запрос
19
- target = data.split(b' ')[1].split(b':')[0].decode()
20
- port = int(data.split(b':')[2].split(b' ')[0])
21
- else:
22
- # HTTP запрос
23
- target = data.split(b'Host: ')[1].split(b'\r\n')[0].decode()
24
- port = 80
25
- except Exception:
26
- client_socket.close()
27
- return
28
-
29
- # Подключаемся к целевому серверу
30
- try:
31
- remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
32
- remote_socket.connect((target, port))
33
-
34
- # Для HTTPS отправляем подтверждение
35
- if data.startswith(b'CONNECT'):
36
- client_socket.send(b'HTTP/1.1 200 Connection Established\r\n\r\n')
37
- else:
38
- remote_socket.send(data)
39
- except Exception as e:
40
- client_socket.close()
41
- return
42
-
43
- # Туннелируем данные в обоих направлениях
44
- sockets = [client_socket, remote_socket]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  while True:
46
- try:
47
- read_sockets, _, _ = select.select(sockets, [], [])
48
- for sock in read_sockets:
49
- data = sock.recv(BUFFER_SIZE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  if not data:
51
  break
52
- if sock is client_socket:
53
- remote_socket.send(data)
54
- else:
55
- client_socket.send(data)
56
- except Exception:
57
- break
58
-
59
- client_socket.close()
60
- remote_socket.close()
61
-
62
- def start_proxy():
63
- proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
64
- proxy_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
65
- proxy_socket.bind((PROXY_HOST, PROXY_PORT))
66
- proxy_socket.listen(50)
67
-
68
- print(f"[*] Прокси запущен на {PROXY_HOST}:{PROXY_PORT}")
69
-
70
- while True:
71
- client_socket, addr = proxy_socket.accept()
72
- print(f"[>] Подключено: {addr[0]}:{addr[1]}")
73
- proxy_thread = threading.Thread(
74
- target=handle_client,
75
- args=(client_socket,)
76
- )
77
- proxy_thread.daemon = True
78
- proxy_thread.start()
79
 
 
80
  if __name__ == "__main__":
81
- start_proxy()
 
1
+ import os
2
+ import shutil
3
+ import uuid
4
+ import string
5
+ import random
6
+ import zipfile
7
+ import io
8
+ from datetime import datetime, timedelta
9
+ from pathlib import Path
10
+ from contextlib import asynccontextmanager
11
+
12
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Request, Form
13
+ from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse
14
+ import aiofiles
15
+ from apscheduler.schedulers.background import BackgroundScheduler
16
+ import uvicorn
17
+
18
+ # ------------------- Configuration -------------------
19
+ BASE_DIR = Path(__file__).resolve().parent
20
+ UPLOAD_DIR = BASE_DIR / "uploads"
21
+ CHUNK_DIR = BASE_DIR / "chunks"
22
+ SQLITE_DB = BASE_DIR / "database.db"
23
+ CHUNK_SIZE = 5 * 1024 * 1024 # 5 MB per chunk
24
+ MAX_FILE_SIZE = 50 * 1024 * 1024 * 1024 # 50 GB per file
25
+
26
+ UPLOAD_DIR.mkdir(exist_ok=True)
27
+ CHUNK_DIR.mkdir(exist_ok=True)
28
+
29
+ # ------------------- Database (SQLite) -------------------
30
+ import sqlite3
31
+
32
+ def init_db():
33
+ conn = sqlite3.connect(str(SQLITE_DB))
34
+ conn.execute("""
35
+ CREATE TABLE IF NOT EXISTS uploads (
36
+ id TEXT PRIMARY KEY,
37
+ short_code TEXT UNIQUE,
38
+ delete_token TEXT UNIQUE,
39
+ total_size INTEGER DEFAULT 0,
40
+ file_count INTEGER DEFAULT 0,
41
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
42
+ expires_at TIMESTAMP DEFAULT (datetime('now', '+7 days')),
43
+ is_complete INTEGER DEFAULT 0,
44
+ is_deleted INTEGER DEFAULT 0
45
+ )
46
+ """)
47
+ conn.execute("""
48
+ CREATE TABLE IF NOT EXISTS files (
49
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
50
+ upload_id TEXT,
51
+ original_name TEXT,
52
+ stored_name TEXT,
53
+ size INTEGER,
54
+ FOREIGN KEY(upload_id) REFERENCES uploads(id)
55
+ )
56
+ """)
57
+ conn.commit()
58
+ conn.close()
59
+
60
+ def get_conn():
61
+ conn = sqlite3.connect(str(SQLITE_DB))
62
+ conn.row_factory = sqlite3.Row
63
+ return conn
64
+
65
+ def generate_short_code(length=6):
66
+ chars = string.ascii_lowercase + string.digits
67
  while True:
68
+ code = ''.join(random.choices(chars, k=length))
69
+ if not get_conn().execute("SELECT 1 FROM uploads WHERE short_code=?", (code,)).fetchone():
70
+ return code
71
+
72
+ # ------------------- Helper functions -------------------
73
+ async def cleanup_expired():
74
+ conn = get_conn()
75
+ expired = conn.execute(
76
+ "SELECT id FROM uploads WHERE expires_at < datetime('now') AND is_deleted=0"
77
+ ).fetchall()
78
+ for row in expired:
79
+ await delete_upload(row['id'], conn=conn, manual=False)
80
+ conn.close()
81
+
82
+ async def delete_upload(upload_id: str, conn=None, manual: bool = True):
83
+ if conn is None:
84
+ conn = get_conn()
85
+ own_conn = True
86
+ else:
87
+ own_conn = False
88
+ try:
89
+ upload_path = UPLOAD_DIR / upload_id
90
+ chunk_path = CHUNK_DIR / upload_id
91
+ for path in (upload_path, chunk_path):
92
+ if path.exists():
93
+ shutil.rmtree(path, ignore_errors=True)
94
+ conn.execute("UPDATE uploads SET is_deleted=1 WHERE id=?", (upload_id,))
95
+ conn.execute("DELETE FROM files WHERE upload_id=?", (upload_id,))
96
+ conn.commit()
97
+ finally:
98
+ if own_conn:
99
+ conn.close()
100
+
101
+ # ------------------- FastAPI with lifespan -------------------
102
+ @asynccontextmanager
103
+ async def lifespan(app: FastAPI):
104
+ init_db()
105
+ scheduler = BackgroundScheduler()
106
+ scheduler.add_job(cleanup_expired, 'interval', hours=1)
107
+ scheduler.start()
108
+ app.state.scheduler = scheduler
109
+ yield
110
+ scheduler.shutdown()
111
+
112
+ app = FastAPI(title="Free File Sharing", lifespan=lifespan)
113
+
114
+ # ------------------- Web Interface -------------------
115
+ @app.get("/", response_class=HTMLResponse)
116
+ async def index():
117
+ return HTMLResponse("""
118
+ <!DOCTYPE html>
119
+ <html lang="en">
120
+ <head>
121
+ <meta charset="UTF-8">
122
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
123
+ <title>Free File Sharing</title>
124
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
125
+ <style>
126
+ * { box-sizing: border-box; margin: 0; padding: 0; }
127
+ body {
128
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
129
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
130
+ min-height: 100vh;
131
+ display: flex;
132
+ justify-content: center;
133
+ align-items: center;
134
+ padding: 20px;
135
+ }
136
+ .container {
137
+ width: 100%;
138
+ max-width: 560px;
139
+ }
140
+ .card {
141
+ background: white;
142
+ border-radius: 20px;
143
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
144
+ padding: 40px 30px;
145
+ transition: transform 0.3s;
146
+ }
147
+ h1 {
148
+ text-align: center;
149
+ color: #333;
150
+ margin-bottom: 15px;
151
+ font-size: 2em;
152
+ }
153
+ .logo {
154
+ display: block;
155
+ margin: 0 auto 20px;
156
+ width: 80px;
157
+ height: 80px;
158
+ background: linear-gradient(135deg, #667eea, #764ba2);
159
+ border-radius: 20px;
160
+ display: flex;
161
+ align-items: center;
162
+ justify-content: center;
163
+ font-size: 2.5em;
164
+ color: white;
165
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2);
166
+ }
167
+ .drop-zone {
168
+ border: 2px dashed #ccc;
169
+ border-radius: 15px;
170
+ padding: 30px;
171
+ text-align: center;
172
+ background: #f9f9ff;
173
+ margin: 25px 0;
174
+ transition: all 0.3s;
175
+ cursor: pointer;
176
+ }
177
+ .drop-zone.dragover {
178
+ border-color: #667eea;
179
+ background: #eef0ff;
180
+ transform: scale(1.02);
181
+ }
182
+ .drop-zone p {
183
+ color: #555;
184
+ font-size: 0.95em;
185
+ }
186
+ .drop-zone label {
187
+ color: #667eea;
188
+ font-weight: bold;
189
+ cursor: pointer;
190
+ text-decoration: underline;
191
+ }
192
+ .progress-container {
193
+ margin: 20px 0;
194
+ }
195
+ .progress-bar-wrapper {
196
+ background: #e0e0e0;
197
+ border-radius: 20px;
198
+ overflow: hidden;
199
+ height: 25px;
200
+ margin: 10px 0;
201
+ }
202
+ .progress-fill {
203
+ width: 0%;
204
+ height: 100%;
205
+ background: linear-gradient(90deg, #667eea, #764ba2);
206
+ border-radius: 20px;
207
+ transition: width 0.2s;
208
+ position: relative;
209
+ }
210
+ .progress-text {
211
+ display: flex;
212
+ justify-content: space-between;
213
+ font-size: 0.9em;
214
+ color: #555;
215
+ }
216
+ .btn {
217
+ display: inline-block;
218
+ padding: 12px 25px;
219
+ border: none;
220
+ border-radius: 30px;
221
+ font-weight: bold;
222
+ cursor: pointer;
223
+ transition: all 0.2s;
224
+ background: #f0f0f0;
225
+ color: #333;
226
+ }
227
+ .btn-primary {
228
+ background: linear-gradient(135deg, #667eea, #764ba2);
229
+ color: white;
230
+ box-shadow: 0 4px 10px rgba(102,126,234,0.4);
231
+ }
232
+ .btn-primary:hover {
233
+ transform: translateY(-2px);
234
+ box-shadow: 0 6px 15px rgba(102,126,234,0.6);
235
+ }
236
+ .btn-danger {
237
+ background: #ff5252;
238
+ color: white;
239
+ }
240
+ .btn-danger:hover {
241
+ background: #ff1744;
242
+ }
243
+ .result-box {
244
+ background: #f0fff0;
245
+ border-radius: 15px;
246
+ padding: 20px;
247
+ margin: 20px 0;
248
+ border: 1px solid #b8e6b8;
249
+ }
250
+ .share-link {
251
+ display: flex;
252
+ align-items: center;
253
+ justify-content: space-between;
254
+ background: white;
255
+ border-radius: 30px;
256
+ padding: 8px 20px;
257
+ margin: 10px 0;
258
+ border: 1px solid #ccc;
259
+ }
260
+ .share-link a {
261
+ color: #333;
262
+ text-decoration: none;
263
+ font-weight: 500;
264
+ word-break: break-all;
265
+ }
266
+ .copy-btn {
267
+ background: none;
268
+ border: none;
269
+ color: #667eea;
270
+ cursor: pointer;
271
+ font-size: 1.2em;
272
+ margin-left: 10px;
273
+ }
274
+ .copy-btn:hover { color: #764ba2; }
275
+ .hidden { display: none; }
276
+ .error-message { color: #ff5252; text-align: center; margin-top: 10px; }
277
+ .success-message { color: #2e7d32; text-align: center; margin-top: 10px; }
278
+
279
+ @media (max-width: 600px) {
280
+ .card { padding: 25px 20px; }
281
+ h1 { font-size: 1.5em; }
282
+ .logo { width: 60px; height: 60px; font-size: 2em; }
283
+ }
284
+ </style>
285
+ </head>
286
+ <body>
287
+ <div class="container">
288
+ <div class="card">
289
+ <div class="logo">📦</div>
290
+ <h1>File Sharing</h1>
291
+ <p style="text-align:center; color:#666;">Free, no registration, up to 50 GB</p>
292
+
293
+ <div class="drop-zone" id="drop-zone">
294
+ <p>📂 Drag & drop files or folders here</p>
295
+ <p>or <label for="file-input">choose files</label></p>
296
+ <input type="file" id="file-input" multiple hidden />
297
+ </div>
298
+
299
+ <div id="progress-container" class="progress-container hidden">
300
+ <div class="progress-text">
301
+ <span id="progress-label">Uploading...</span>
302
+ <span id="progress-percent">0%</span>
303
+ </div>
304
+ <div class="progress-bar-wrapper">
305
+ <div id="progress-fill" class="progress-fill" style="width:0%"></div>
306
+ </div>
307
+ <button id="cancel-btn" class="btn" style="margin-top:10px;">Cancel</button>
308
+ </div>
309
+
310
+ <div id="result" class="result-box hidden">
311
+ <p style="color:#2e7d32; font-weight:bold;">✅ Link ready:</p>
312
+ <div class="share-link">
313
+ <a id="share-link" href="#" target="_blank"></a>
314
+ <button class="copy-btn" id="copy-btn" title="Copy link">📋</button>
315
+ </div>
316
+ <p style="margin-top:15px; font-size:0.9em; color:#555;">Files available for 7 days</p>
317
+ <button id="delete-btn" class="btn btn-danger" style="margin-top:10px;">🗑 Delete now</button>
318
+ </div>
319
+
320
+ <div id="message"></div>
321
+ </div>
322
+ </div>
323
+
324
+ <script>
325
+ let currentUploadId = null;
326
+ let deleteToken = null;
327
+ let abortController = null;
328
+
329
+ const dropZone = document.getElementById('drop-zone');
330
+ const fileInput = document.getElementById('file-input');
331
+ const progressContainer = document.getElementById('progress-container');
332
+ const progressFill = document.getElementById('progress-fill');
333
+ const progressPercent = document.getElementById('progress-percent');
334
+ const progressLabel = document.getElementById('progress-label');
335
+ const cancelBtn = document.getElementById('cancel-btn');
336
+ const resultDiv = document.getElementById('result');
337
+ const shareLink = document.getElementById('share-link');
338
+ const copyBtn = document.getElementById('copy-btn');
339
+ const deleteBtn = document.getElementById('delete-btn');
340
+ const messageDiv = document.getElementById('message');
341
+
342
+ // Drag & Drop
343
+ dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
344
+ dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
345
+ dropZone.addEventListener('drop', (e) => {
346
+ e.preventDefault();
347
+ dropZone.classList.remove('dragover');
348
+ const items = e.dataTransfer.items;
349
+ if (items) handleItems(items);
350
+ });
351
+ dropZone.addEventListener('click', () => fileInput.click());
352
+
353
+ fileInput.addEventListener('change', (e) => {
354
+ if (e.target.files.length > 0) handleFileList(e.target.files);
355
+ });
356
+
357
+ async function handleItems(items) {
358
+ let files = [];
359
+ for (let i = 0; i < items.length; i++) {
360
+ const item = items[i].webkitGetAsEntry();
361
+ if (item) await traverseEntry(item, '', files);
362
+ }
363
+ if (files.length > 0) handleFileList(files);
364
+ }
365
+
366
+ function traverseEntry(entry, path, files) {
367
+ return new Promise((resolve) => {
368
+ if (entry.isFile) {
369
+ entry.file((file) => {
370
+ file.relativePath = path + file.name;
371
+ files.push(file);
372
+ resolve();
373
+ });
374
+ } else if (entry.isDirectory) {
375
+ const dirReader = entry.createReader();
376
+ dirReader.readEntries(async (entries) => {
377
+ for (const ent of entries) {
378
+ await traverseEntry(ent, path + entry.name + '/', files);
379
+ }
380
+ resolve();
381
+ });
382
+ }
383
+ });
384
+ }
385
+
386
+ function handleFileList(fileList) {
387
+ const files = Array.from(fileList);
388
+ if (files.length === 0) return;
389
+ if (files.length === 1) {
390
+ uploadSingleFile(files[0]);
391
+ } else {
392
+ uploadAsZip(files);
393
+ }
394
+ }
395
+
396
+ async function uploadSingleFile(file) {
397
+ if (file.size > 50 * 1024 * 1024 * 1024) {
398
+ showError(`File "${file.name}" is too large (>50 GB)`);
399
+ return;
400
+ }
401
+ const initRes = await fetch('/upload/init', {
402
+ method: 'POST',
403
+ headers: {'Content-Type': 'application/json'},
404
+ body: JSON.stringify({ file_count: 1, total_size: file.size })
405
+ });
406
+ if (!initRes.ok) { showError('Initialization error'); return; }
407
+ const { upload_id, short_code, delete_token } = await initRes.json();
408
+ prepareUI(upload_id, short_code, delete_token);
409
+ await uploadFileInChunks(file, file.relativePath || file.name, file.size);
410
+ await finishUpload();
411
+ }
412
+
413
+ async function uploadAsZip(files) {
414
+ const zip = new JSZip();
415
+ let totalSize = 0;
416
+ for (const file of files) {
417
+ if (file.size > 50 * 1024 * 1024 * 1024) {
418
+ showError(`File "${file.name}" is too large (>50 GB)`);
419
+ return;
420
+ }
421
+ totalSize += file.size;
422
+ zip.file(file.relativePath || file.name, file);
423
+ }
424
+ let zipBlob;
425
+ try {
426
+ zipBlob = await zip.generateAsync({type: "blob"});
427
+ } catch (e) {
428
+ showError('Error creating archive');
429
+ return;
430
+ }
431
+ const initRes = await fetch('/upload/init', {
432
+ method: 'POST',
433
+ headers: {'Content-Type': 'application/json'},
434
+ body: JSON.stringify({ file_count: 1, total_size: zipBlob.size })
435
+ });
436
+ if (!initRes.ok) { showError('Initialization error'); return; }
437
+ const { upload_id, short_code, delete_token } = await initRes.json();
438
+ prepareUI(upload_id, short_code, delete_token);
439
+ const zipFile = new File([zipBlob], "archive.zip", {type: "application/zip"});
440
+ await uploadFileInChunks(zipFile, "archive.zip", zipBlob.size);
441
+ await finishUpload();
442
+ }
443
+
444
+ function prepareUI(upload_id, short_code, delete_token) {
445
+ currentUploadId = upload_id;
446
+ deleteToken = delete_token;
447
+ shareLink.href = '/' + short_code;
448
+ shareLink.textContent = window.location.origin + '/' + short_code;
449
+ resultDiv.classList.remove('hidden');
450
+ progressContainer.classList.remove('hidden');
451
+ progressFill.style.width = '0%';
452
+ progressPercent.textContent = '0%';
453
+ progressLabel.textContent = 'Uploading...';
454
+ }
455
+
456
+ async function uploadFileInChunks(file, fileName, fileSize) {
457
+ const chunkCount = Math.ceil(fileSize / (5 * 1024 * 1024));
458
+ abortController = new AbortController();
459
+ let uploaded = 0;
460
+ try {
461
+ for (let i = 0; i < chunkCount; i++) {
462
+ if (abortController.signal.aborted) throw new Error('Cancelled');
463
+ const start = i * 5 * 1024 * 1024;
464
+ const end = Math.min(start + 5 * 1024 * 1024, fileSize);
465
+ const blob = file.slice(start, end);
466
+ const formData = new FormData();
467
+ formData.append('chunk', blob, fileName);
468
+ formData.append('file_name', fileName);
469
+ formData.append('file_size', fileSize);
470
+ formData.append('chunk_index', i);
471
+ formData.append('total_chunks', chunkCount);
472
+
473
+ const res = await fetch(`/upload/${currentUploadId}/${i}`, {
474
+ method: 'PUT',
475
+ body: formData,
476
+ signal: abortController.signal
477
+ });
478
+ if (!res.ok) throw new Error('Error');
479
+ uploaded += (end - start);
480
+ const percent = Math.round((uploaded / fileSize) * 100);
481
+ progressFill.style.width = percent + '%';
482
+ progressPercent.textContent = percent + '%';
483
+ progressLabel.textContent = `Uploaded ${percent}%`;
484
+ }
485
+ } catch (err) {
486
+ if (err.message !== 'Cancelled') showError(err.message);
487
+ progressContainer.classList.add('hidden');
488
+ abortController = null;
489
+ throw err;
490
+ }
491
+ abortController = null;
492
+ }
493
+
494
+ async function finishUpload() {
495
+ try {
496
+ await fetch(`/upload/${currentUploadId}/complete`, {method: 'POST'});
497
+ progressContainer.classList.add('hidden');
498
+ showSuccess('Upload complete!');
499
+ } catch (e) {
500
+ showError('Error completing upload');
501
+ }
502
+ }
503
+
504
+ cancelBtn.addEventListener('click', () => {
505
+ if (abortController) {
506
+ abortController.abort();
507
+ showError('Upload cancelled');
508
+ progressContainer.classList.add('hidden');
509
+ abortController = null;
510
+ }
511
+ });
512
+
513
+ deleteBtn.addEventListener('click', async () => {
514
+ if (!deleteToken) return;
515
+ if (confirm('Are you sure you want to delete all files?')) {
516
+ const res = await fetch('/delete/' + deleteToken, {method: 'DELETE'});
517
+ if (res.ok) {
518
+ resultDiv.classList.add('hidden');
519
+ showSuccess('Files deleted');
520
+ } else {
521
+ showError('Deletion error');
522
+ }
523
+ }
524
+ });
525
+
526
+ copyBtn.addEventListener('click', () => {
527
+ const link = shareLink.textContent;
528
+ navigator.clipboard.writeText(link).then(() => {
529
+ copyBtn.textContent = '✅';
530
+ setTimeout(() => { copyBtn.textContent = '📋'; }, 2000);
531
+ }).catch(() => {
532
+ alert('Could not copy');
533
+ });
534
+ });
535
+
536
+ function showMessage(msg, isError = false) {
537
+ messageDiv.innerHTML = `<p class="${isError ? 'error-message' : 'success-message'}">${msg}</p>`;
538
+ }
539
+ function showError(msg) { showMessage(msg, true); }
540
+ function showSuccess(msg) { showMessage(msg, false); }
541
+ </script>
542
+ </body>
543
+ </html>
544
+ """)
545
+
546
+ # ------------------- API Endpoints -------------------
547
+ @app.post("/upload/init")
548
+ async def init_upload(data: dict):
549
+ file_count = data.get("file_count", 1)
550
+ upload_id = str(uuid.uuid4())
551
+ short_code = generate_short_code()
552
+ delete_token = str(uuid.uuid4())
553
+ conn = get_conn()
554
+ conn.execute(
555
+ "INSERT INTO uploads (id, short_code, delete_token, file_count, created_at, expires_at) VALUES (?,?,?,?, datetime('now'), datetime('now', '+7 days'))",
556
+ (upload_id, short_code, delete_token, file_count)
557
+ )
558
+ conn.commit()
559
+ conn.close()
560
+ (CHUNK_DIR / upload_id).mkdir(exist_ok=True)
561
+ return {"upload_id": upload_id, "short_code": short_code, "delete_token": delete_token}
562
+
563
+ @app.put("/upload/{upload_id}/{chunk_index}")
564
+ async def upload_chunk(
565
+ upload_id: str,
566
+ chunk_index: int,
567
+ chunk: UploadFile = File(...),
568
+ file_name: str = Form(...),
569
+ file_size: int = Form(...),
570
+ total_chunks: int = Form(...)
571
+ ):
572
+ conn = get_conn()
573
+ upload = conn.execute("SELECT id FROM uploads WHERE id=? AND is_complete=0 AND is_deleted=0", (upload_id,)).fetchone()
574
+ conn.close()
575
+ if not upload:
576
+ raise HTTPException(status_code=404, detail="Upload not found or already completed")
577
+
578
+ chunk_dir = CHUNK_DIR / upload_id
579
+ chunk_path = chunk_dir / f"{file_name}.part{chunk_index}"
580
+ async with aiofiles.open(chunk_path, 'wb') as out_file:
581
+ content = await chunk.read()
582
+ await out_file.write(content)
583
+
584
+ if chunk_index == 0:
585
+ conn = get_conn()
586
+ conn.execute(
587
+ "INSERT OR REPLACE INTO files (upload_id, original_name, stored_name, size) VALUES (?,?,?,?)",
588
+ (upload_id, file_name, file_name, file_size)
589
+ )
590
+ conn.commit()
591
+ conn.close()
592
+ return {"status": "chunk_uploaded"}
593
+
594
+ @app.post("/upload/{upload_id}/complete")
595
+ async def complete_upload(upload_id: str):
596
+ conn = get_conn()
597
+ upload = conn.execute("SELECT id, short_code FROM uploads WHERE id=? AND is_complete=0 AND is_deleted=0", (upload_id,)).fetchone()
598
+ if not upload:
599
+ conn.close()
600
+ raise HTTPException(status_code=404, detail="Upload not found")
601
+
602
+ chunk_dir = CHUNK_DIR / upload_id
603
+ target_dir = UPLOAD_DIR / upload_id
604
+ target_dir.mkdir(exist_ok=True)
605
+
606
+ chunks = {}
607
+ for chunk_file in chunk_dir.iterdir():
608
+ parts = chunk_file.name.rsplit('.part', 1)
609
+ if len(parts) != 2:
610
+ continue
611
+ orig_name = parts[0]
612
+ idx = int(parts[1])
613
+ chunks.setdefault(orig_name, {})[idx] = chunk_file
614
+
615
+ for orig_name, parts_dict in chunks.items():
616
+ sorted_indices = sorted(parts_dict.keys())
617
+ target_path = target_dir / orig_name
618
+ async with aiofiles.open(target_path, 'wb') as outfile:
619
+ for i in sorted_indices:
620
+ part_path = parts_dict[i]
621
+ async with aiofiles.open(part_path, 'rb') as infile:
622
+ while True:
623
+ data = await infile.read(1024*1024)
624
+ if not data:
625
+ break
626
+ await outfile.write(data)
627
+ for part_path in parts_dict.values():
628
+ part_path.unlink(missing_ok=True)
629
+
630
+ conn.execute("UPDATE uploads SET is_complete=1 WHERE id=?", (upload_id,))
631
+ conn.commit()
632
+ conn.close()
633
+ shutil.rmtree(chunk_dir, ignore_errors=True)
634
+ return {"status": "completed", "short_code": upload['short_code']}
635
+
636
+ @app.delete("/delete/{delete_token}")
637
+ async def delete_by_token(delete_token: str):
638
+ conn = get_conn()
639
+ upload = conn.execute("SELECT id FROM uploads WHERE delete_token=? AND is_deleted=0", (delete_token,)).fetchone()
640
+ conn.close()
641
+ if not upload:
642
+ raise HTTPException(status_code=404, detail="Invalid token or files already deleted")
643
+ await delete_upload(upload['id'])
644
+ return {"status": "deleted"}
645
+
646
+ @app.get("/{short_code}")
647
+ async def download(short_code: str, request: Request):
648
+ conn = get_conn()
649
+ upload = conn.execute(
650
+ "SELECT id, is_complete, is_deleted FROM uploads WHERE short_code=?",
651
+ (short_code,)
652
+ ).fetchone()
653
+ if not upload or upload['is_deleted']:
654
+ conn.close()
655
+ raise HTTPException(status_code=404, detail="Link not found or files deleted")
656
+ if not upload['is_complete']:
657
+ conn.close()
658
+ return HTMLResponse("<h3>Files are still uploading, please try later</h3>", status_code=202)
659
+
660
+ files = conn.execute("SELECT original_name, stored_name FROM files WHERE upload_id=?", (upload['id'],)).fetchall()
661
+ conn.close()
662
+ upload_dir = UPLOAD_DIR / upload['id']
663
+ if not upload_dir.exists():
664
+ raise HTTPException(status_code=404, detail="Files not found on disk")
665
+
666
+ if len(files) == 1:
667
+ file_path = upload_dir / files[0]['original_name']
668
+ if not file_path.exists():
669
+ raise HTTPException(status_code=404, detail="File missing")
670
+ return FileResponse(file_path, filename=files[0]['original_name'])
671
+ else:
672
+ zip_filename = f"files_{short_code}.zip"
673
+ async def zip_stream():
674
+ zip_buffer = io.BytesIO()
675
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
676
+ for f in files:
677
+ file_path = upload_dir / f['original_name']
678
+ if file_path.exists():
679
+ zf.write(file_path, f['original_name'])
680
+ zip_buffer.seek(0)
681
+ while True:
682
+ data = zip_buffer.read(8192)
683
  if not data:
684
  break
685
+ yield data
686
+ return StreamingResponse(zip_stream(), media_type="application/zip", headers={
687
+ "Content-Disposition": f'attachment; filename="{zip_filename}"'
688
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689
 
690
+ # ------------------- Run -------------------
691
  if __name__ == "__main__":
692
+ uvicorn.run("12:app", host="0.0.0.0", port=8000, reload=True)