veltrixcode commited on
Commit
b115dae
Β·
verified Β·
1 Parent(s): 6f9ad71

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +918 -0
main.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FinderX File Manager API
3
+ ========================
4
+ A comprehensive file management API backed by HuggingFace Buckets.
5
+ Bucket: FinderX File Upload (configure BUCKET_ID in .env)
6
+ """
7
+
8
+ import os
9
+ import io
10
+ import json
11
+ import math
12
+ import time
13
+ import uuid
14
+ import shutil
15
+ import hashlib
16
+ import asyncio
17
+ import mimetypes
18
+ import tempfile
19
+ from pathlib import Path
20
+ from datetime import datetime, timezone
21
+ from typing import Optional, List, Dict, Any
22
+
23
+ import aiofiles
24
+ from fastapi import (
25
+ FastAPI, HTTPException, UploadFile, File, Form,
26
+ Query, BackgroundTasks, Request, Depends
27
+ )
28
+ from fastapi.responses import StreamingResponse, JSONResponse, Response
29
+ from fastapi.middleware.cors import CORSMiddleware
30
+ from pydantic import BaseModel, Field
31
+ from huggingface_hub import HfApi, list_bucket_tree, batch_bucket_files, download_bucket_files, get_bucket_paths_info, bucket_info
32
+
33
+ # ──────────────────────────── Config ────────────────────────────
34
+
35
+ BUCKET_ID = os.getenv("BUCKET_ID", "YOUR_HF_USERNAME/FinderX")
36
+ HF_TOKEN = os.getenv("HF_TOKEN", "") # hf_xxxx token
37
+ CHUNK_DIR = Path(tempfile.gettempdir()) / "finderx_chunks"
38
+ CACHE_DIR = Path(tempfile.gettempdir()) / "finderx_cache"
39
+ MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "5120")) # 5 GB default
40
+ API_VERSION = "1.0.0"
41
+
42
+ CHUNK_DIR.mkdir(parents=True, exist_ok=True)
43
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
44
+
45
+ # ──────────────────────────── HF Client ─────────────────────────
46
+
47
+ api = HfApi(token=HF_TOKEN or None)
48
+
49
+ # ──────────────────────────── In-Memory Stores ──────────────────
50
+ # (In production swap these with a Redis / SQLite store)
51
+
52
+ _recent_files: List[Dict] = [] # last 50 accessed paths
53
+ _favorites: Dict[str, bool] = {} # path -> True
54
+ _trash: Dict[str, Dict] = {} # path -> {original, deleted_at, data}
55
+ _activity_log: List[Dict] = [] # append-only log
56
+ _versions: Dict[str, List] = {} # path -> [{version_id, uploaded_at, size}]
57
+ _chunk_sessions: Dict[str, Dict] = {} # session_id -> {filename, total, received, parts[]}
58
+
59
+ # ──────────────────────────── Helpers ───────────────────────────
60
+
61
+ def _now() -> str:
62
+ return datetime.now(timezone.utc).isoformat()
63
+
64
+
65
+ def _log(action: str, path: str, extra: Dict = None):
66
+ entry = {"action": action, "path": path, "timestamp": _now(), **(extra or {})}
67
+ _activity_log.append(entry)
68
+ if len(_activity_log) > 1000:
69
+ _activity_log.pop(0)
70
+
71
+
72
+ def _add_recent(path: str):
73
+ global _recent_files
74
+ _recent_files = [r for r in _recent_files if r["path"] != path]
75
+ _recent_files.insert(0, {"path": path, "accessed_at": _now()})
76
+ _recent_files = _recent_files[:50]
77
+
78
+
79
+ def _detect_mime(filename: str) -> str:
80
+ mime, _ = mimetypes.guess_type(filename)
81
+ return mime or "application/octet-stream"
82
+
83
+
84
+ def _hf_path(virtual_path: str) -> str:
85
+ """Clean and normalise a virtual path for bucket storage."""
86
+ p = virtual_path.strip("/")
87
+ return p
88
+
89
+
90
+ def _list_tree(prefix: str = "", recursive: bool = True) -> List[Dict]:
91
+ items = []
92
+ for item in list_bucket_tree(BUCKET_ID, prefix=prefix or None, recursive=recursive):
93
+ items.append({
94
+ "path": item.path,
95
+ "type": item.type, # "file" | "directory"
96
+ "size": getattr(item, "size", None),
97
+ "last_modified": getattr(item, "last_modified", None),
98
+ "mime_type": _detect_mime(item.path) if item.type == "file" else None,
99
+ })
100
+ return items
101
+
102
+
103
+ def _upload_bytes(data: bytes, remote_path: str):
104
+ batch_bucket_files(BUCKET_ID, add=[(data, remote_path)], token=HF_TOKEN or None)
105
+
106
+
107
+ def _download_bytes(remote_path: str) -> bytes:
108
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
109
+ tmp_path = tmp.name
110
+ try:
111
+ download_bucket_files(
112
+ BUCKET_ID,
113
+ files=[(remote_path, tmp_path)],
114
+ token=HF_TOKEN or None,
115
+ )
116
+ with open(tmp_path, "rb") as f:
117
+ return f.read()
118
+ finally:
119
+ if os.path.exists(tmp_path):
120
+ os.remove(tmp_path)
121
+
122
+
123
+ def _file_exists(remote_path: str) -> bool:
124
+ try:
125
+ results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None))
126
+ return len(results) > 0
127
+ except Exception:
128
+ return False
129
+
130
+
131
+ def _get_file_meta(remote_path: str) -> Optional[Dict]:
132
+ try:
133
+ results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None))
134
+ if not results:
135
+ return None
136
+ r = results[0]
137
+ return {
138
+ "path": r.path,
139
+ "size": getattr(r, "size", None),
140
+ "xet_hash": getattr(r, "xet_hash", None),
141
+ "mime_type": _detect_mime(r.path),
142
+ "last_modified": getattr(r, "last_modified", _now()),
143
+ }
144
+ except Exception:
145
+ return None
146
+
147
+
148
+ # ──────────────────────────── App ───────────────────────────────
149
+
150
+ app = FastAPI(
151
+ title="FinderX File Manager API",
152
+ description="Full-featured file management API backed by HuggingFace Buckets",
153
+ version=API_VERSION,
154
+ docs_url="/docs",
155
+ redoc_url="/redoc",
156
+ )
157
+
158
+ app.add_middleware(
159
+ CORSMiddleware,
160
+ allow_origins=["*"],
161
+ allow_methods=["*"],
162
+ allow_headers=["*"],
163
+ )
164
+
165
+ # ════════════════════════════════════════════════════════════════
166
+ # HEALTH
167
+ # ════════════════════════════════════════════════════════════════
168
+
169
+ @app.get("/", tags=["Health"])
170
+ def root():
171
+ return {"service": "FinderX API", "version": API_VERSION, "status": "ok"}
172
+
173
+
174
+ @app.get("/health", tags=["Health"])
175
+ def health():
176
+ try:
177
+ info = bucket_info(BUCKET_ID, token=HF_TOKEN or None)
178
+ return {"status": "ok", "bucket": BUCKET_ID, "size": info.size, "files": info.total_files}
179
+ except Exception as e:
180
+ raise HTTPException(500, f"Bucket unreachable: {e}")
181
+
182
+
183
+ # ════════════════════════════════════════════════════════════════
184
+ # FILE LISTING & SEARCH
185
+ # ════════════════════════════════════════════════════════════════
186
+
187
+ @app.get("/files", tags=["Browse"])
188
+ def list_files(
189
+ path: str = Query("", description="Folder prefix to list"),
190
+ recursive: bool = Query(False, description="Recurse into sub-folders"),
191
+ sort_by: str = Query("name", description="Sort by: name | size | date"),
192
+ order: str = Query("asc", description="asc | desc"),
193
+ page: int = Query(1, ge=1),
194
+ per_page: int = Query(50, ge=1, le=500),
195
+ ):
196
+ """List files and folders. Supports pagination, sorting."""
197
+ items = _list_tree(prefix=path, recursive=recursive)
198
+ # sort
199
+ reverse = order.lower() == "desc"
200
+ if sort_by == "size":
201
+ items.sort(key=lambda x: x["size"] or 0, reverse=reverse)
202
+ elif sort_by == "date":
203
+ items.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse)
204
+ else:
205
+ items.sort(key=lambda x: x["path"], reverse=reverse)
206
+ # paginate
207
+ total = len(items)
208
+ start = (page - 1) * per_page
209
+ end = start + per_page
210
+ return {
211
+ "path": path,
212
+ "total": total,
213
+ "page": page,
214
+ "per_page": per_page,
215
+ "pages": math.ceil(total / per_page),
216
+ "items": items[start:end],
217
+ }
218
+
219
+
220
+ @app.get("/search", tags=["Browse"])
221
+ def search_files(
222
+ q: str = Query(..., description="Search term (matches path/filename)"),
223
+ path: str = Query("", description="Scope search to a folder prefix"),
224
+ sort_by: str = Query("name"),
225
+ order: str = Query("asc"),
226
+ page: int = Query(1, ge=1),
227
+ per_page: int = Query(50, ge=1, le=500),
228
+ ):
229
+ """Full-text search across all file paths."""
230
+ all_items = _list_tree(prefix=path, recursive=True)
231
+ term = q.lower()
232
+ matched = [i for i in all_items if term in i["path"].lower()]
233
+ reverse = order.lower() == "desc"
234
+ if sort_by == "size":
235
+ matched.sort(key=lambda x: x["size"] or 0, reverse=reverse)
236
+ elif sort_by == "date":
237
+ matched.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse)
238
+ else:
239
+ matched.sort(key=lambda x: x["path"], reverse=reverse)
240
+ total = len(matched)
241
+ start = (page - 1) * per_page
242
+ return {
243
+ "query": q, "total": total, "page": page,
244
+ "per_page": per_page, "pages": math.ceil(total / per_page) if total else 0,
245
+ "items": matched[start: start + per_page],
246
+ }
247
+
248
+
249
+ # ════════════════════════════════════════════════════════════════
250
+ # FILE METADATA
251
+ # ════════════════════════════════════════════════════════════════
252
+
253
+ @app.get("/files/meta", tags=["Metadata"])
254
+ def file_metadata(path: str = Query(..., description="Remote file path")):
255
+ """Get metadata: size, MIME type, hash, modified date."""
256
+ meta = _get_file_meta(_hf_path(path))
257
+ if not meta:
258
+ raise HTTPException(404, f"File not found: {path}")
259
+ meta["favorites"] = _favorites.get(path, False)
260
+ meta["in_trash"] = path in _trash
261
+ meta["versions"] = _versions.get(path, [])
262
+ return meta
263
+
264
+
265
+ @app.post("/files/hash", tags=["Metadata"])
266
+ def hash_file(path: str = Query(..., description="Remote file path")):
267
+ """Compute SHA-256 hash of a file (duplicate / corruption detection)."""
268
+ data = _download_bytes(_hf_path(path))
269
+ sha256 = hashlib.sha256(data).hexdigest()
270
+ md5 = hashlib.md5(data).hexdigest()
271
+ _log("hash", path)
272
+ return {"path": path, "sha256": sha256, "md5": md5, "size": len(data)}
273
+
274
+
275
+ # ════════════════════════════════════════════════════════════════
276
+ # UPLOAD
277
+ # ════════════════════════════════════════════════════════════════
278
+
279
+ @app.post("/upload", tags=["Upload"], status_code=201)
280
+ async def upload_file(
281
+ file: UploadFile = File(...),
282
+ destination_path: str = Form("", description="Remote folder path (e.g. photos/2024)"),
283
+ overwrite: bool = Form(True),
284
+ ):
285
+ """
286
+ Upload a single file. The remote path is: `destination_path/filename`.
287
+ Saves a version snapshot if the file already exists.
288
+ """
289
+ if file.size and file.size > MAX_UPLOAD_MB * 1024 * 1024:
290
+ raise HTTPException(413, f"File exceeds {MAX_UPLOAD_MB} MB limit")
291
+
292
+ remote_dir = destination_path.strip("/")
293
+ remote_path = f"{remote_dir}/{file.filename}".strip("/")
294
+
295
+ # version snapshot
296
+ if _file_exists(remote_path):
297
+ if not overwrite:
298
+ raise HTTPException(409, f"File already exists: {remote_path}")
299
+ _versions.setdefault(remote_path, [])
300
+ _versions[remote_path].append({
301
+ "version_id": str(uuid.uuid4()),
302
+ "uploaded_at": _now(),
303
+ "size": (_get_file_meta(remote_path) or {}).get("size"),
304
+ })
305
+
306
+ data = await file.read()
307
+ _upload_bytes(data, remote_path)
308
+ _log("upload", remote_path, {"size": len(data)})
309
+ _add_recent(remote_path)
310
+
311
+ return {
312
+ "status": "uploaded",
313
+ "path": remote_path,
314
+ "size": len(data),
315
+ "mime_type": _detect_mime(file.filename),
316
+ "uploaded_at": _now(),
317
+ }
318
+
319
+
320
+ # ════════════════════════════════════════════════════════════════
321
+ # CHUNKED / RESUMABLE UPLOAD
322
+ # ════════════════════════════════════════════════════════════════
323
+
324
+ class ChunkInitRequest(BaseModel):
325
+ filename: str
326
+ total_size: int
327
+ total_chunks: int
328
+ destination_path: str = ""
329
+
330
+ @app.post("/upload/chunked/init", tags=["Upload"])
331
+ def init_chunked_upload(req: ChunkInitRequest):
332
+ """Initialise a chunked upload session. Returns a session_id."""
333
+ session_id = str(uuid.uuid4())
334
+ session_dir = CHUNK_DIR / session_id
335
+ session_dir.mkdir(parents=True, exist_ok=True)
336
+ _chunk_sessions[session_id] = {
337
+ "filename": req.filename,
338
+ "total_size": req.total_size,
339
+ "total_chunks": req.total_chunks,
340
+ "destination_path": req.destination_path,
341
+ "received": [],
342
+ "created_at": _now(),
343
+ }
344
+ return {"session_id": session_id, "total_chunks": req.total_chunks}
345
+
346
+
347
+ @app.post("/upload/chunked/{session_id}/{chunk_index}", tags=["Upload"])
348
+ async def upload_chunk(session_id: str, chunk_index: int, file: UploadFile = File(...)):
349
+ """Upload a single chunk. chunk_index is 0-based."""
350
+ if session_id not in _chunk_sessions:
351
+ raise HTTPException(404, "Session not found. Call /upload/chunked/init first.")
352
+ session = _chunk_sessions[session_id]
353
+ chunk_data = await file.read()
354
+ chunk_path = CHUNK_DIR / session_id / f"chunk_{chunk_index:06d}"
355
+ async with aiofiles.open(chunk_path, "wb") as f:
356
+ await f.write(chunk_data)
357
+ if chunk_index not in session["received"]:
358
+ session["received"].append(chunk_index)
359
+ progress = len(session["received"]) / session["total_chunks"] * 100
360
+ return {
361
+ "session_id": session_id,
362
+ "chunk_index": chunk_index,
363
+ "received": len(session["received"]),
364
+ "total_chunks": session["total_chunks"],
365
+ "progress": round(progress, 2),
366
+ }
367
+
368
+
369
+ @app.post("/upload/chunked/{session_id}/complete", tags=["Upload"])
370
+ def complete_chunked_upload(session_id: str):
371
+ """Assemble all chunks and push the completed file to the bucket."""
372
+ if session_id not in _chunk_sessions:
373
+ raise HTTPException(404, "Session not found.")
374
+ session = _chunk_sessions[session_id]
375
+ total_chunks = session["total_chunks"]
376
+ received = sorted(session["received"])
377
+ if len(received) != total_chunks or received != list(range(total_chunks)):
378
+ missing = [i for i in range(total_chunks) if i not in received]
379
+ raise HTTPException(400, f"Missing chunks: {missing}")
380
+
381
+ session_dir = CHUNK_DIR / session_id
382
+ assembled = b""
383
+ for i in range(total_chunks):
384
+ chunk_path = session_dir / f"chunk_{i:06d}"
385
+ with open(chunk_path, "rb") as f:
386
+ assembled += f.read()
387
+
388
+ remote_dir = session["destination_path"].strip("/")
389
+ remote_path = f"{remote_dir}/{session['filename']}".strip("/")
390
+ _upload_bytes(assembled, remote_path)
391
+
392
+ shutil.rmtree(session_dir, ignore_errors=True)
393
+ del _chunk_sessions[session_id]
394
+ _log("chunked_upload", remote_path, {"size": len(assembled)})
395
+ _add_recent(remote_path)
396
+
397
+ return {
398
+ "status": "assembled",
399
+ "path": remote_path,
400
+ "size": len(assembled),
401
+ "uploaded_at": _now(),
402
+ }
403
+
404
+
405
+ @app.get("/upload/chunked/{session_id}/status", tags=["Upload"])
406
+ def chunked_upload_status(session_id: str):
407
+ """Check status / progress of a chunked upload session."""
408
+ if session_id not in _chunk_sessions:
409
+ raise HTTPException(404, "Session not found.")
410
+ session = _chunk_sessions[session_id]
411
+ received = len(session["received"])
412
+ total = session["total_chunks"]
413
+ return {
414
+ "session_id": session_id,
415
+ "filename": session["filename"],
416
+ "received": received,
417
+ "total_chunks": total,
418
+ "progress": round(received / total * 100, 2),
419
+ "missing": [i for i in range(total) if i not in session["received"]],
420
+ }
421
+
422
+
423
+ # ════════════════════════════════════════════════════════════════
424
+ # DOWNLOAD & STREAM
425
+ # ════════════════════════════════════════════════════════════════
426
+
427
+ @app.get("/download", tags=["Download"])
428
+ def download_file(path: str = Query(..., description="Remote file path")):
429
+ """Download a file as an attachment (triggers browser save dialog)."""
430
+ remote_path = _hf_path(path)
431
+ data = _download_bytes(remote_path)
432
+ _add_recent(path)
433
+ _log("download", path)
434
+ filename = Path(remote_path).name
435
+ mime = _detect_mime(filename)
436
+ return Response(
437
+ content=data,
438
+ media_type=mime,
439
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
440
+ )
441
+
442
+
443
+ @app.get("/stream", tags=["Download"])
444
+ def stream_file(path: str = Query(..., description="Remote file path")):
445
+ """
446
+ Stream a file inline (for direct open in browser/player).
447
+ Supports partial Range requests for video seeking.
448
+ """
449
+ remote_path = _hf_path(path)
450
+ data = _download_bytes(remote_path)
451
+ filename = Path(remote_path).name
452
+ mime = _detect_mime(filename)
453
+ _add_recent(path)
454
+ _log("stream", path)
455
+
456
+ def _gen():
457
+ chunk = 65536
458
+ for i in range(0, len(data), chunk):
459
+ yield data[i: i + chunk]
460
+
461
+ return StreamingResponse(
462
+ _gen(),
463
+ media_type=mime,
464
+ headers={
465
+ "Content-Disposition": f'inline; filename="{filename}"',
466
+ "Content-Length": str(len(data)),
467
+ "Accept-Ranges": "bytes",
468
+ "Cache-Control": "public, max-age=3600",
469
+ },
470
+ )
471
+
472
+
473
+ # ════════════════════════════════════════════════════════════════
474
+ # FILE OPERATIONS
475
+ # ════════════════════════════════════════════════════════════════
476
+
477
+ class RenameRequest(BaseModel):
478
+ path: str = Field(..., description="Current path")
479
+ new_name: str = Field(..., description="New filename (not full path)")
480
+
481
+ @app.post("/files/rename", tags=["File Operations"])
482
+ def rename_file(req: RenameRequest):
483
+ """Rename a file (keeps it in the same folder)."""
484
+ old_path = _hf_path(req.path)
485
+ parent = str(Path(old_path).parent).rstrip(".")
486
+ new_path = f"{parent}/{req.new_name}".strip("/")
487
+ data = _download_bytes(old_path)
488
+ _upload_bytes(data, new_path)
489
+ batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
490
+ _log("rename", old_path, {"new_path": new_path})
491
+ return {"status": "renamed", "old_path": old_path, "new_path": new_path}
492
+
493
+
494
+ class MoveRequest(BaseModel):
495
+ path: str = Field(..., description="Source path")
496
+ destination_dir: str = Field(..., description="Target folder path")
497
+
498
+ @app.post("/files/move", tags=["File Operations"])
499
+ def move_file(req: MoveRequest):
500
+ """Move a file to a different folder."""
501
+ old_path = _hf_path(req.path)
502
+ filename = Path(old_path).name
503
+ new_path = f"{req.destination_dir.strip('/')}/{filename}"
504
+ data = _download_bytes(old_path)
505
+ _upload_bytes(data, new_path)
506
+ batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
507
+ _log("move", old_path, {"new_path": new_path})
508
+ return {"status": "moved", "old_path": old_path, "new_path": new_path}
509
+
510
+
511
+ class CopyRequest(BaseModel):
512
+ path: str = Field(..., description="Source path")
513
+ destination_dir: str = Field(..., description="Target folder path")
514
+ new_name: Optional[str] = Field(None, description="Override filename")
515
+
516
+ @app.post("/files/copy", tags=["File Operations"])
517
+ def copy_file(req: CopyRequest):
518
+ """Copy a file to another folder (optionally rename)."""
519
+ src_path = _hf_path(req.path)
520
+ filename = req.new_name or Path(src_path).name
521
+ dest_path = f"{req.destination_dir.strip('/')}/{filename}"
522
+ data = _download_bytes(src_path)
523
+ _upload_bytes(data, dest_path)
524
+ _log("copy", src_path, {"dest_path": dest_path})
525
+ return {"status": "copied", "source": src_path, "destination": dest_path}
526
+
527
+
528
+ @app.delete("/files", tags=["File Operations"])
529
+ def delete_file(
530
+ path: str = Query(..., description="File path to delete"),
531
+ permanent: bool = Query(False, description="Skip trash and permanently delete"),
532
+ ):
533
+ """
534
+ Move a file to trash (recoverable) or permanently delete it.
535
+ """
536
+ remote_path = _hf_path(path)
537
+ if permanent:
538
+ batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
539
+ _log("permanent_delete", path)
540
+ return {"status": "permanently_deleted", "path": path}
541
+ else:
542
+ # soft delete β†’ store data in trash
543
+ data = _download_bytes(remote_path)
544
+ _trash[path] = {
545
+ "original_path": path,
546
+ "deleted_at": _now(),
547
+ "data": data,
548
+ "size": len(data),
549
+ "mime_type": _detect_mime(Path(path).name),
550
+ }
551
+ batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
552
+ _log("trash", path)
553
+ return {"status": "moved_to_trash", "path": path}
554
+
555
+
556
+ # ════════════════════════════════════════════════════════════════
557
+ # BATCH OPERATIONS
558
+ # ════════════════════════════════════════════════════════════════
559
+
560
+ class BatchDeleteRequest(BaseModel):
561
+ paths: List[str]
562
+ permanent: bool = False
563
+
564
+ @app.post("/batch/delete", tags=["Batch"])
565
+ def batch_delete(req: BatchDeleteRequest):
566
+ """Delete multiple files at once."""
567
+ results = []
568
+ for path in req.paths:
569
+ remote_path = _hf_path(path)
570
+ try:
571
+ if req.permanent:
572
+ batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
573
+ results.append({"path": path, "status": "permanently_deleted"})
574
+ else:
575
+ data = _download_bytes(remote_path)
576
+ _trash[path] = {
577
+ "original_path": path,
578
+ "deleted_at": _now(),
579
+ "data": data,
580
+ "size": len(data),
581
+ "mime_type": _detect_mime(Path(path).name),
582
+ }
583
+ batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
584
+ results.append({"path": path, "status": "trashed"})
585
+ _log("batch_delete", path)
586
+ except Exception as e:
587
+ results.append({"path": path, "status": "error", "error": str(e)})
588
+ return {"results": results}
589
+
590
+
591
+ class BatchMoveRequest(BaseModel):
592
+ paths: List[str]
593
+ destination_dir: str
594
+
595
+ @app.post("/batch/move", tags=["Batch"])
596
+ def batch_move(req: BatchMoveRequest):
597
+ """Move multiple files to the same destination folder."""
598
+ results = []
599
+ for path in req.paths:
600
+ try:
601
+ old_path = _hf_path(path)
602
+ filename = Path(old_path).name
603
+ new_path = f"{req.destination_dir.strip('/')}/{filename}"
604
+ data = _download_bytes(old_path)
605
+ _upload_bytes(data, new_path)
606
+ batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
607
+ results.append({"path": path, "new_path": new_path, "status": "moved"})
608
+ _log("batch_move", path, {"new_path": new_path})
609
+ except Exception as e:
610
+ results.append({"path": path, "status": "error", "error": str(e)})
611
+ return {"results": results}
612
+
613
+
614
+ class BatchCopyRequest(BaseModel):
615
+ paths: List[str]
616
+ destination_dir: str
617
+
618
+ @app.post("/batch/copy", tags=["Batch"])
619
+ def batch_copy(req: BatchCopyRequest):
620
+ """Copy multiple files to the same destination folder."""
621
+ results = []
622
+ for path in req.paths:
623
+ try:
624
+ src = _hf_path(path)
625
+ dest = f"{req.destination_dir.strip('/')}/{Path(src).name}"
626
+ data = _download_bytes(src)
627
+ _upload_bytes(data, dest)
628
+ results.append({"path": path, "dest": dest, "status": "copied"})
629
+ _log("batch_copy", path, {"dest": dest})
630
+ except Exception as e:
631
+ results.append({"path": path, "status": "error", "error": str(e)})
632
+ return {"results": results}
633
+
634
+
635
+ # ════════════════════════════════════════════════════════════════
636
+ # FOLDER OPERATIONS
637
+ # ════════════════════════════════════════════════════════════════
638
+
639
+ class FolderCreateRequest(BaseModel):
640
+ path: str = Field(..., description="Full path for the new folder (e.g. docs/work)")
641
+
642
+ @app.post("/folders", tags=["Folders"], status_code=201)
643
+ def create_folder(req: FolderCreateRequest):
644
+ """
645
+ Create a folder by uploading a hidden placeholder file.
646
+ HF Buckets use virtual folders (path prefixes) β€” this ensures
647
+ the folder appears in listings.
648
+ """
649
+ folder_path = req.path.strip("/")
650
+ placeholder = f"{folder_path}/.finderx_folder"
651
+ _upload_bytes(b"", placeholder)
652
+ _log("create_folder", folder_path)
653
+ return {"status": "created", "path": folder_path}
654
+
655
+
656
+ class FolderRenameRequest(BaseModel):
657
+ path: str = Field(..., description="Current folder path")
658
+ new_name: str = Field(..., description="New folder name (last segment)")
659
+
660
+ @app.post("/folders/rename", tags=["Folders"])
661
+ def rename_folder(req: FolderRenameRequest):
662
+ """Rename a folder by moving all its contents to the new path."""
663
+ old_prefix = req.path.strip("/")
664
+ parent = str(Path(old_prefix).parent).rstrip(".")
665
+ new_prefix = f"{parent}/{req.new_name}".strip("/")
666
+
667
+ items = [i for i in _list_tree(prefix=old_prefix, recursive=True) if i["type"] == "file"]
668
+ moved = []
669
+ for item in items:
670
+ old_p = item["path"]
671
+ suffix = old_p[len(old_prefix):]
672
+ new_p = new_prefix + suffix
673
+ data = _download_bytes(old_p)
674
+ _upload_bytes(data, new_p)
675
+ batch_bucket_files(BUCKET_ID, delete=[old_p], token=HF_TOKEN or None)
676
+ moved.append({"old": old_p, "new": new_p})
677
+
678
+ _log("rename_folder", old_prefix, {"new_prefix": new_prefix})
679
+ return {"status": "renamed", "old_path": old_prefix, "new_path": new_prefix, "files_moved": len(moved)}
680
+
681
+
682
+ @app.delete("/folders", tags=["Folders"])
683
+ def delete_folder(
684
+ path: str = Query(..., description="Folder path to delete"),
685
+ permanent: bool = Query(False),
686
+ ):
687
+ """Delete a folder and all its contents (recursive)."""
688
+ folder_path = path.strip("/")
689
+ items = [i for i in _list_tree(prefix=folder_path, recursive=True) if i["type"] == "file"]
690
+ paths = [i["path"] for i in items]
691
+
692
+ if permanent:
693
+ if paths:
694
+ batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None)
695
+ _log("permanent_delete_folder", folder_path, {"count": len(paths)})
696
+ else:
697
+ for p in paths:
698
+ data = _download_bytes(p)
699
+ _trash[p] = {
700
+ "original_path": p, "deleted_at": _now(),
701
+ "data": data, "size": len(data),
702
+ "mime_type": _detect_mime(Path(p).name),
703
+ }
704
+ if paths:
705
+ batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None)
706
+ _log("trash_folder", folder_path, {"count": len(paths)})
707
+
708
+ return {"status": "deleted" if permanent else "trashed", "path": folder_path, "files_affected": len(paths)}
709
+
710
+
711
+ # ════════════════════════════════════════════════════════════════
712
+ # TRASH BIN
713
+ # ════════════════════════════════════════════════════════════════
714
+
715
+ @app.get("/trash", tags=["Trash"])
716
+ def list_trash():
717
+ """List all files in the trash bin."""
718
+ items = [
719
+ {"path": p, "original_path": v["original_path"],
720
+ "deleted_at": v["deleted_at"], "size": v["size"], "mime_type": v["mime_type"]}
721
+ for p, v in _trash.items()
722
+ ]
723
+ return {"total": len(items), "items": items}
724
+
725
+
726
+ @app.post("/trash/restore", tags=["Trash"])
727
+ def restore_from_trash(path: str = Query(..., description="Path to restore")):
728
+ """Restore a file from trash to its original location."""
729
+ if path not in _trash:
730
+ raise HTTPException(404, f"Not found in trash: {path}")
731
+ item = _trash.pop(path)
732
+ original = item["original_path"]
733
+ _upload_bytes(item["data"], _hf_path(original))
734
+ _log("restore", original)
735
+ return {"status": "restored", "path": original}
736
+
737
+
738
+ @app.delete("/trash", tags=["Trash"])
739
+ def empty_trash():
740
+ """Permanently delete everything in the trash bin."""
741
+ count = len(_trash)
742
+ _trash.clear()
743
+ _log("empty_trash", "*", {"count": count})
744
+ return {"status": "emptied", "files_removed": count}
745
+
746
+
747
+ @app.delete("/trash/item", tags=["Trash"])
748
+ def permanent_delete_from_trash(path: str = Query(...)):
749
+ """Permanently delete a single item from trash."""
750
+ if path not in _trash:
751
+ raise HTTPException(404, f"Not found in trash: {path}")
752
+ del _trash[path]
753
+ _log("permanent_delete", path)
754
+ return {"status": "permanently_deleted", "path": path}
755
+
756
+
757
+ # ════════════════════════════════════════════════════════════════
758
+ # FAVORITES
759
+ # ════════════════════════════════════════════════════════════════
760
+
761
+ @app.get("/favorites", tags=["Favorites"])
762
+ def list_favorites():
763
+ return {"total": len(_favorites), "items": list(_favorites.keys())}
764
+
765
+ @app.post("/favorites", tags=["Favorites"])
766
+ def add_favorite(path: str = Query(...)):
767
+ _favorites[path] = True
768
+ _log("favorite_add", path)
769
+ return {"status": "added", "path": path}
770
+
771
+ @app.delete("/favorites", tags=["Favorites"])
772
+ def remove_favorite(path: str = Query(...)):
773
+ _favorites.pop(path, None)
774
+ return {"status": "removed", "path": path}
775
+
776
+
777
+ # ════════════════════════════════════════════════════════════════
778
+ # RECENT FILES
779
+ # ════════════════════════════════════════════════════════════════
780
+
781
+ @app.get("/recent", tags=["Recent"])
782
+ def recent_files(limit: int = Query(20, ge=1, le=50)):
783
+ return {"items": _recent_files[:limit]}
784
+
785
+
786
+ # ════════════════════════════════════════════════════════════════
787
+ # VERSIONING
788
+ # ════════════════════════════════════════════════════════════════
789
+
790
+ @app.get("/versions", tags=["Versions"])
791
+ def list_versions(path: str = Query(...)):
792
+ return {"path": path, "versions": _versions.get(path, [])}
793
+
794
+
795
+ # ════════════════════════════════════════════════════════════════
796
+ # THUMBNAILS & PREVIEW
797
+ # ════════════════════════════════════════════════════════════════
798
+
799
+ @app.get("/preview", tags=["Preview"])
800
+ def preview_file(path: str = Query(..., description="Remote image or PDF path")):
801
+ """
802
+ Return raw bytes for inline preview (images and PDFs).
803
+ Images: returned as-is. PDFs: returned as application/pdf.
804
+ """
805
+ remote_path = _hf_path(path)
806
+ mime = _detect_mime(Path(remote_path).name)
807
+ allowed = ("image/", "application/pdf")
808
+ if not any(mime.startswith(p) for p in allowed):
809
+ raise HTTPException(415, f"Preview not supported for MIME type: {mime}")
810
+ data = _download_bytes(remote_path)
811
+ _add_recent(path)
812
+ return Response(content=data, media_type=mime)
813
+
814
+
815
+ @app.get("/thumbnail", tags=["Preview"])
816
+ def thumbnail(
817
+ path: str = Query(...),
818
+ width: int = Query(256, ge=32, le=1024),
819
+ height: int = Query(256, ge=32, le=1024),
820
+ ):
821
+ """
822
+ Generate a thumbnail for image files.
823
+ Requires Pillow (`pip install Pillow`).
824
+ Falls back to the original image if Pillow is unavailable.
825
+ """
826
+ remote_path = _hf_path(path)
827
+ mime = _detect_mime(Path(remote_path).name)
828
+ if not mime.startswith("image/"):
829
+ raise HTTPException(415, "Thumbnails are only supported for images")
830
+
831
+ data = _download_bytes(remote_path)
832
+ try:
833
+ from PIL import Image
834
+ img = Image.open(io.BytesIO(data))
835
+ img.thumbnail((width, height), Image.LANCZOS)
836
+ buf = io.BytesIO()
837
+ fmt = img.format or "JPEG"
838
+ img.save(buf, format=fmt)
839
+ return Response(content=buf.getvalue(), media_type=mime)
840
+ except ImportError:
841
+ # Pillow not installed β†’ return original
842
+ return Response(content=data, media_type=mime)
843
+
844
+
845
+ # ════════════════════════════════════════════════════════════════
846
+ # STORAGE USAGE
847
+ # ════════════════════════════════════════════════════════════════
848
+
849
+ @app.get("/storage/usage", tags=["Storage"])
850
+ def storage_usage():
851
+ """Total bucket usage: size in bytes and file count."""
852
+ info = bucket_info(BUCKET_ID, token=HF_TOKEN or None)
853
+ return {
854
+ "bucket_id": BUCKET_ID,
855
+ "total_bytes": info.size,
856
+ "total_files": info.total_files,
857
+ "total_mb": round(info.size / 1024 / 1024, 2),
858
+ "total_gb": round(info.size / 1024 / 1024 / 1024, 4),
859
+ }
860
+
861
+
862
+ # ════════════════════════════════════════════════════════════════
863
+ # ACTIVITY LOGS
864
+ # ════════════════════════════════════════════════════════════════
865
+
866
+ @app.get("/activity", tags=["Activity"])
867
+ def activity_log(
868
+ limit: int = Query(50, ge=1, le=500),
869
+ action: Optional[str] = Query(None, description="Filter by action type"),
870
+ ):
871
+ """Return recent activity log entries."""
872
+ entries = list(reversed(_activity_log))
873
+ if action:
874
+ entries = [e for e in entries if e["action"] == action]
875
+ return {"total": len(entries), "items": entries[:limit]}
876
+
877
+
878
+ # ════════════════════════════════════════════════════════════════
879
+ # CACHE MANAGEMENT
880
+ # ════════════════════════════════════════════════════════════════
881
+
882
+ @app.delete("/cache", tags=["Cache"])
883
+ def clear_cache():
884
+ """Clear all locally cached temporary files."""
885
+ removed = 0
886
+ for f in CACHE_DIR.iterdir():
887
+ try:
888
+ f.unlink() if f.is_file() else shutil.rmtree(f)
889
+ removed += 1
890
+ except Exception:
891
+ pass
892
+ return {"status": "cleared", "files_removed": removed}
893
+
894
+
895
+ @app.get("/cache/stats", tags=["Cache"])
896
+ def cache_stats():
897
+ files = list(CACHE_DIR.iterdir())
898
+ size = sum(f.stat().st_size for f in files if f.is_file())
899
+ return {"files": len(files), "size_bytes": size, "size_mb": round(size / 1024 / 1024, 2)}
900
+
901
+
902
+ # ════════════════════════════════════════════════════════════════
903
+ # PATH UTILITIES
904
+ # ════════════════════════════════════════════════════════════════
905
+
906
+ @app.get("/path/info", tags=["Utilities"])
907
+ def path_info(path: str = Query(...)):
908
+ """Return structured path components."""
909
+ p = Path(path)
910
+ return {
911
+ "full": str(p),
912
+ "parent": str(p.parent),
913
+ "name": p.name,
914
+ "stem": p.stem,
915
+ "suffix": p.suffix,
916
+ "parts": list(p.parts),
917
+ "mime_type": _detect_mime(p.name),
918
+ }