File size: 20,486 Bytes
8f16c3d
 
 
 
3b5901f
4b4c033
8f16c3d
99e48df
 
8f16c3d
 
afb618b
7a29f73
99e48df
7a29f73
8f16c3d
4b4c033
 
 
 
3b5901f
 
bcf954e
 
 
 
de711f2
 
 
 
 
 
 
 
 
 
99e48df
bcf954e
99e48df
bcf954e
4b4c033
99e48df
4b4c033
 
c727649
99e48df
c727649
7a29f73
 
 
99e48df
7a29f73
c727649
 
 
99e48df
afb618b
a6dbd9e
99e48df
197e4fa
99e48df
 
 
 
c727649
99e48df
7a29f73
99e48df
 
7a29f73
 
99e48df
 
7a29f73
 
4b4c033
 
7a29f73
4b4c033
7a29f73
 
99e48df
7a29f73
 
99e48df
 
7a29f73
4b4c033
 
99e48df
 
4b4c033
99e48df
8f16c3d
 
 
99e48df
8f16c3d
78e2e6b
 
 
0fae7dc
 
 
 
 
 
 
 
 
 
 
 
 
 
afb618b
0fae7dc
 
 
 
 
 
afb618b
0fae7dc
 
 
 
afb618b
0fae7dc
 
afb618b
0fae7dc
 
afb618b
0fae7dc
afb618b
 
0fae7dc
 
 
 
 
 
 
 
 
afb618b
 
 
 
0fae7dc
afb618b
78e2e6b
 
 
 
 
 
afb618b
78e2e6b
afb618b
78e2e6b
 
afb618b
 
78e2e6b
 
 
 
45689cf
99e48df
45689cf
197e4fa
45689cf
99e48df
 
afb618b
99e48df
45689cf
197e4fa
45689cf
197e4fa
 
 
45689cf
 
197e4fa
99e48df
 
 
 
45689cf
 
197e4fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e48df
45689cf
afb618b
 
 
 
78e2e6b
afb618b
 
 
 
78e2e6b
afb618b
 
 
99e48df
afb618b
99e48df
 
afb618b
 
 
 
 
 
78e2e6b
99e48df
 
 
 
 
 
 
45689cf
99e48df
 
 
78e2e6b
99e48df
 
afb618b
78e2e6b
 
 
 
 
 
99e48df
78e2e6b
 
 
 
 
 
99e48df
 
8f16c3d
bcf954e
78e2e6b
bcf954e
 
99e48df
 
 
 
 
 
78e2e6b
 
 
99e48df
 
 
bcf954e
99e48df
 
78e2e6b
99e48df
 
 
 
 
 
 
8f16c3d
9885cf3
 
 
 
 
 
 
 
 
 
 
b45ad87
9885cf3
 
 
 
 
 
 
0851add
 
 
 
 
 
 
afb618b
0851add
 
 
 
 
 
9885cf3
 
0851add
afb618b
0851add
afb618b
0851add
 
 
afb618b
9885cf3
 
 
 
 
0851add
 
 
9885cf3
 
 
 
 
 
 
 
 
0851add
 
 
 
 
 
 
 
afb618b
0851add
 
9885cf3
0851add
a6dbd9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f16c3d
 
99e48df
 
7a29f73
 
99e48df
8f16c3d
 
 
 
 
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
import os
import shutil
import time
import uuid
import asyncio
from contextlib import asynccontextmanager
from typing import List, Optional
from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request, Query
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from config import UPLOAD_DIR, BASE_URL
from db import get_metadata, delete_metadata, set_metadata

# Bot status tracking
bot_status = {"running": False, "error": None, "started_at": None}

# --- CLEANUP TASK ---
async def cleanup_old_files():
    while True:
        try:
            now = time.time()
            if os.path.exists(UPLOAD_DIR):
                for root, dirs, files in os.walk(UPLOAD_DIR):
                    for filename in files:
                        file_path = os.path.join(root, filename)
                        try:
                            # Check metadata for custom expiration
                            meta = get_metadata(filename)
                            expire_hours = meta.get("expire_hours", 24) if meta else 24
                            
                            # If expire_hours is 0, it's 'Never Delete'
                            if expire_hours > 0:
                                if now - os.path.getmtime(file_path) > (expire_hours * 3600):
                                    os.remove(file_path)
                                    delete_metadata(filename)
                                    print(f"πŸ—‘οΈ Cleaned up expired file: {filename} ({expire_hours}h)")
                        except: pass
                    if root != UPLOAD_DIR and not os.listdir(root):
                        try: os.rmdir(root)
                        except: pass
        except Exception as e:
            print(f"Cleanup error: {e}")
        await asyncio.sleep(3600)

from pyrogram.types import BotCommand
from pyrogram import idle

async def start_bot_safe():
    try:
        from bot import bot as telegram_bot
        if telegram_bot is None: return None
        await asyncio.wait_for(telegram_bot.start(), timeout=30)
        try:
            await telegram_bot.set_bot_commands([
                BotCommand("start", "Start the bot"),
                BotCommand("zip", "Create ZIP"),
                BotCommand("unzip", "Extract ZIP"),
                BotCommand("torrent", "Download via magnet/hash/.torrent"),
                BotCommand("pdf_merge", "Merge PDFs"),
                BotCommand("vcompress", "Compress Video"),
                BotCommand("search", "Search your files"),
                BotCommand("settings", "Bot settings"),
                BotCommand("files", "My files"),
                BotCommand("help", "Usage guide")
            ])
        except: pass
        me = await telegram_bot.get_me()
        bot_status.update({"running": True, "started_at": time.time()})
        print(f"πŸš€ Bot: @{me.username}")
        return telegram_bot
    except Exception as e:
        bot_status["error"] = str(e)
        print(f"❌ Bot failed: {e}")
        return None

@asynccontextmanager
async def lifespan(app: FastAPI):
    os.makedirs(UPLOAD_DIR, exist_ok=True)
    cleanup_task = asyncio.create_task(cleanup_old_files())
    telegram_bot = await start_bot_safe()
    bot_keep_alive_task = None
    if telegram_bot:
        async def keep_bot_alive():
            while True:
                try: await asyncio.sleep(10)
                except asyncio.CancelledError: break
        bot_keep_alive_task = asyncio.create_task(keep_bot_alive())
    yield
    cleanup_task.cancel()
    if bot_keep_alive_task: bot_keep_alive_task.cancel()
    if telegram_bot: await telegram_bot.stop()

app = FastAPI(title="NexusShare Pro", lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
async def read_index(): return FileResponse("static/index.html")

# --- PROFESSIONAL UI TEMPLATES ---
UI_STYLE = """
<style>
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');
    :root { --primary: #6366f1; --bg: #030712; --card: #0f172a; --text: #f8fafc; --text-dim: #94a3b8; --border: #334155; }
    body { 
        font-family: 'Plus Jakarta Sans', sans-serif; 
        background: var(--bg); 
        background-image: radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.15) 0px, transparent 50%);
        color: var(--text); 
        margin: 0; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem;
    }
    .container { width: 100%; max-width: 800px; animation: fadeIn 0.6s ease-out; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    .card { background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(12px); padding: 40px; border-radius: 28px; box-shadow: 0 20px 50px rgba(0,0,0,0.5); border: 1px solid var(--border); }
    h2 { font-size: 2rem; font-weight: 800; text-align: center; margin-bottom: 0.5rem; letter-spacing: -1px; }
    p.subtitle { text-align: center; color: var(--text-dim); margin-bottom: 2.5rem; font-weight: 500; }
    
    .file-list { display: grid; gap: 12px; }
    .file-item { 
        background: rgba(30, 41, 59, 0.5); padding: 16px; border-radius: 20px; border: 1px solid var(--border);
        display: flex; justify-content: space-between; align-items: center; transition: 0.3s;
    }
    .file-item:hover { border-color: var(--primary); background: rgba(99, 102, 241, 0.05); transform: translateX(5px); }
    
    .file-icon { 
        width: 48px; height: 48px; background: var(--bg); border-radius: 14px; 
        display: flex; align-items: center; justify-content: center; font-size: 0.8rem; font-weight: 800; color: var(--primary); 
    }
    .file-details { flex: 1; margin-left: 15px; overflow: hidden; }
    .file-name { font-weight: 700; color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .file-meta { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
    
    .actions { display: flex; gap: 8px; }
    .btn-sm { padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 700; text-decoration: none; transition: 0.2s; }
    .btn-get { background: var(--primary); color: #fff; }
    .btn-watch { background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); }
    
    .password-form { text-align: center; }
    input[type="password"] { 
        background: var(--bg); border: 2px solid var(--border); color: #fff; 
        padding: 16px; border-radius: 16px; width: 100%; max-width: 320px; outline: none; transition: 0.3s; font-size: 1rem; margin-bottom: 20px; 
    }
    input[type="password"]:focus { border-color: var(--primary); }
    .btn-main { 
        background: var(--primary); color: white; border: none; padding: 16px 40px; border-radius: 16px; 
        cursor: pointer; font-weight: 800; font-size: 1rem; transition: 0.3s; box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
    }

    @media (max-width: 600px) {
        .file-item { flex-direction: column; align-items: flex-start; gap: 15px; }
        .actions { width: 100%; }
        .btn-sm { flex: 1; text-align: center; }
    }
</style>
"""

def get_password_wall(target_name: str, error: bool = False):
    return f"""
    <html><head><meta name="viewport" content="width=device-width, initial-scale=1">{UI_STYLE}</head>
    <body><div class="container"><div class="card password-form">
        <h2>πŸ” Restricted Access</h2>
        <p class="subtitle">'{target_name}' is protected by a secure access code.</p>
        <form method="get">
            <input type="password" name="password" placeholder="Enter Access Code" autofocus required>
            {f'<p style="color:#ff5252;font-size:14px;margin-top:-10px;margin-bottom:15px;">Incorrect password. Please try again.</p>' if error else ''}
            <div><button type="submit" class="btn-main">Unlock Content</button></div>
        </form>
    </div></div></body></html>
    """

@app.get("/view/{user_id}/{batch_id}")
async def view_batch(user_id: str, batch_id: str, password: Optional[str] = Query(None)):
    user_dir = os.path.join(UPLOAD_DIR, user_id)
    if not os.path.exists(user_dir): raise HTTPException(404, "User directory not found")
    
    meta = get_metadata(batch_id)
    if meta and meta.get("password") and meta.get("password") != password:
        return HTMLResponse(get_password_wall(f"Archive: {batch_id}", error=password is not None))

    files_data = []
    # Search for files belonging to this batch
    for f in os.listdir(user_dir):
        if f.startswith(f"{batch_id}_"):
            if f.endswith(".zip") or f.endswith(".pdf"): continue
            
            fpath = os.path.join(user_dir, f)
            files_data.append({
                "name": "_".join(f.split("_")[2:]) if len(f.split("_")) > 2 else "_".join(f.split("_")[1:]),
                "url": f"/download/{user_id}/{f}?password={password or ''}",
                "stream": f"/player/{user_id}/{f}?password={password or ''}" if f.lower().endswith(('.mp4', '.mkv', '.webm')) else None,
                "size": round(os.path.getsize(fpath)/1024/1024, 2),
                "raw": f
            })
    
    # Fallback: If no batch files found, maybe batch_id is a single filename
    if not files_data:
        target_file = None
        for f in os.listdir(user_dir):
            if f.startswith(batch_id):
                target_file = f
                break
        
        if target_file:
            fpath = os.path.join(user_dir, target_file)
            files_data.append({
                "name": "_".join(target_file.split("_")[1:]),
                "url": f"/download/{user_id}/{target_file}?password={password or ''}",
                "stream": f"/player/{user_id}/{target_file}?password={password or ''}" if target_file.lower().endswith(('.mp4', '.mkv', '.webm')) else None,
                "size": round(os.path.getsize(fpath)/1024/1024, 2),
                "raw": target_file
            })

    if not files_data: raise HTTPException(404, "No files found for this batch")
    files_data.sort(key=lambda x: x["raw"])
    
    items_html = ""
    for f in files_data:
        ext = f['name'].split('.')[-1].upper() if '.' in f['name'] else 'FILE'
        items_html += f"""
        <div class="file-item">
            <div class="file-icon">{ext[:4]}</div>
            <div class="file-details">
                <div class="file-name">{f['name']}</div>
                <div class="file-meta">{f['size']} MB β€’ {ext}</div>
            </div>
            <div class="actions">
                {f'<a href="{f["stream"]}" class="btn-sm btn-watch">Watch</a>' if f['stream'] else ''}
                <a href="{f['url']}" class="btn-sm btn-get">Download</a>
            </div>
        </div>"""

    return HTMLResponse(f"""
    <html><head><title>NexusShare - File Viewer</title><meta name="viewport" content="width=device-width, initial-scale=1">{UI_STYLE}</head>
    <body><div class="container"><div class="card">
        <h2>πŸ“¦ Archive Contents</h2>
        <p class="subtitle">Viewing {len(files_data)} items from batch <b>{batch_id}</b></p>
        <div class="file-list">{items_html}</div>
        <div style="text-align:center;margin-top:30px;color:#444;font-size:12px;">Powered by NexusShare Professional</div>
    </div></div></body></html>
    """)

@app.get("/player/{filepath:path}")
async def video_player(filepath: str, password: Optional[str] = Query(None)):
    safe_path = os.path.normpath(filepath).lstrip(os.sep)
    path = os.path.join(UPLOAD_DIR, safe_path)
    if not os.path.exists(path): raise HTTPException(404)
    
    fname = os.path.basename(path)
    meta = get_metadata(fname) or get_metadata(fname.split('_')[0])
    if meta and meta.get("password") and meta.get("password") != password:
        return HTMLResponse(get_password_wall(fname, error=password is not None))

    return HTMLResponse(f"""
    <html><head><title>NexusShare Player</title><meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body{{margin:0;background:#000;display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;}}
        .player-container {{ width:100%; max-width:1000px; height: auto; aspect-ratio: 16/9; position: relative; }}
        video {{ width:100%; height:100%; border-radius: 12px; box-shadow: 0 0 50px rgba(0,0,0,0.8); }}
        .header {{ position:absolute; top:20px; left:20px; z-index:10; background:rgba(0,0,0,0.5); padding:10px 20px; border-radius:30px; backdrop-filter:blur(10px); color:white; font-size:14px; }}
    </style>
    </head><body>
        <div class="player-container">
            <div class="header">🎬 Playing: {"_".join(fname.split("_")[1:])}</div>
            <video controls autoplay>
                <source src="/download/{filepath}?password={password or ''}" type="video/mp4">
            </video>
        </div>
    </body></html>
    """)

@app.get("/download/{filepath:path}")
async def download_file(filepath: str, request: Request, password: Optional[str] = Query(None)):
    safe_path = os.path.normpath(filepath).lstrip(os.sep)
    path = os.path.join(UPLOAD_DIR, safe_path)
    if not os.path.exists(path): raise HTTPException(404)
    
    fname = os.path.basename(path)
    meta = get_metadata(fname) or get_metadata(fname.split('_')[0])
    
    if meta and meta.get("password") and meta.get("password") != password:
        accept = request.headers.get("accept", "")
        if "text/html" in accept:
            return HTMLResponse(get_password_wall(fname, error=password is not None))
        raise HTTPException(403, "Password required.")

    resp = FileResponse(path, filename="_".join(fname.split("_")[1:]))
    
    if meta and meta.get("self_destruct"):
        async def delete_after():
            await asyncio.sleep(10) # Safety delay
            try: 
                os.remove(path)
                delete_metadata(fname)
            except: pass
        asyncio.create_task(delete_after())

    return resp

@app.get("/files")
async def list_files(x_user_id: str = Header(None)):
    if not x_user_id: return []
    user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}")
    if not os.path.exists(user_dir): return []
    
    files = []
    for f in os.listdir(user_dir):
        path = os.path.join(user_dir, f)
        if os.path.isfile(path):
            files.append({
                "name": f"user_{x_user_id}/{f}",
                "display_name": "_".join(f.split("_")[1:]) if "_" in f else f,
                "size": os.path.getsize(path),
                "mtime": os.path.getmtime(path)
            })
    files.sort(key=lambda x: x["mtime"], reverse=True)
    return files

@app.api_route("/upload/{filename}", methods=["PUT", "POST"])
@app.api_route("/upload", methods=["PUT", "POST"])
async def upload_files(
    filename: Optional[str] = None,
    files: Optional[List[UploadFile]] = File(None),
    file: Optional[UploadFile] = File(None),
    x_user_id: str = Header(None),
    x_password: str = Header(None),
    request: Request = None
):
    user_id = x_user_id or "cli-anonymous"
    user_dir = os.path.join(UPLOAD_DIR, f"user_{user_id}")
    os.makedirs(user_dir, exist_ok=True)

    # Binary Upload (curl -T style)
    if request.method == "PUT" or (not files and not file and request.headers.get("content-type") != "application/x-www-form-urlencoded"):
        content = await request.body()
        if not content: raise HTTPException(status_code=400, detail="Empty file body.")
        fname = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}"
        fname = os.path.basename(fname)
        safe_name = f"{str(uuid.uuid4())[:8]}_{fname}"
        with open(os.path.join(user_dir, safe_name), "wb") as b:
            b.write(content)
        if x_password: set_metadata(safe_name, {"password": x_password})
        
        # Return plain text for terminal, JSON for web
        if "curl" in request.headers.get("user-agent", "").lower():
            return f"{BASE_URL}/download/user_{user_id}/{safe_name}\n"
        return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"}

    # Multipart Upload
    target = (files or []) + ([file] if file else [])
    if not target: 
        # Check if it was meant to be a binary upload but failed content-type check
        content = await request.body()
        if content:
             fname = filename or f"upload_{int(time.time())}"
             safe_name = f"{str(uuid.uuid4())[:8]}_{fname}"
             with open(os.path.join(user_dir, safe_name), "wb") as b: b.write(content)
             return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"}
        raise HTTPException(status_code=400, detail="No files provided.")

    urls = []
    for f in target:
        fname = os.path.basename(f.filename or f"file_{int(time.time())}")
        name = f"{str(uuid.uuid4())[:8]}_{fname}"
        dest = os.path.join(user_dir, name)
        with open(dest, "wb") as b:
            shutil.copyfileobj(f.file, b)
        if x_password: set_metadata(name, {"password": x_password})
        urls.append(f"{BASE_URL}/download/user_{user_id}/{name}")

    return {"urls": urls} if len(urls) > 1 or x_user_id else urls[0]

@app.post("/api/zip")
async def api_zip_files(request: Request, x_user_id: str = Header(None)):
    if not x_user_id: raise HTTPException(401, "Missing user id")
    body = await request.json()
    names = body.get("files") or []
    archive_name = (body.get("name") or "").strip()
    if not names: raise HTTPException(400, "No files selected")

    user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}")
    safe_files = []
    for n in names:
        n = os.path.basename(n)
        fpath = os.path.join(user_dir, n)
        if os.path.isfile(fpath): safe_files.append(n)
    if not safe_files: raise HTTPException(404, "No valid files found")

    archive_name = "".join(c for c in archive_name if c.isalnum() or c in "._-") or f"archive_{int(time.time())}"
    oname = f"{str(uuid.uuid4())[:8]}_{archive_name}.zip"
    opath = os.path.join(user_dir, oname)

    cmd = ["7z", "a", "-mx=5", "-mmt=on", opath] + safe_files
    p = await asyncio.create_subprocess_exec(*cmd, cwd=user_dir, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    await p.communicate()
    if p.returncode != 0 or not os.path.exists(opath):
        raise HTTPException(500, "Zip creation failed")

    return {"url": f"{BASE_URL}/download/user_{x_user_id}/{oname}", "name": oname}

@app.post("/api/unzip")
async def api_unzip_file(request: Request, x_user_id: str = Header(None)):
    if not x_user_id: raise HTTPException(401, "Missing user id")
    body = await request.json()
    name = os.path.basename(body.get("file") or "")
    if not name: raise HTTPException(400, "No file specified")

    user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}")
    fpath = os.path.join(user_dir, name)
    if not os.path.exists(fpath): raise HTTPException(404, "File not found")

    bid = str(uuid.uuid4())[:8]
    extract_dir = os.path.join(user_dir, f"unzip_{bid}")
    os.makedirs(extract_dir, exist_ok=True)

    cmd = ["7z", "x", fpath, f"-o{extract_dir}", "-y"]
    p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    await p.communicate()

    count = 0
    new_files = []
    for root, dirs, files in os.walk(extract_dir):
        for f in files:
            count += 1
            new_name = f"{bid}_{count:03d}_{f.replace(' ', '_')}"
            os.rename(os.path.join(root, f), os.path.join(user_dir, new_name))
            new_files.append(new_name)

    try: shutil.rmtree(extract_dir)
    except Exception: pass

    if count == 0: raise HTTPException(500, "No files extracted (not a valid archive?)")
    return {"view_url": f"{BASE_URL}/view/user_{x_user_id}/{bid}", "files": new_files, "count": count}

@app.delete("/delete/{filename}")
async def delete_file(filename: str, x_user_id: str = Header(None)):
    if not x_user_id: raise HTTPException(401)
    p = os.path.join(UPLOAD_DIR, f"user_{x_user_id}", filename)
    if os.path.exists(p):
        os.remove(p)
        delete_metadata(filename)
    return {"status": "ok"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)