Spaces:
Running
Running
File size: 38,507 Bytes
b115dae eaeb5bb b115dae | 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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 | """
FinderX File Manager API
========================
A comprehensive file management API backed by HuggingFace Buckets.
Bucket: FinderX File Upload (configure BUCKET_ID in .env)
"""
import os
import io
import json
import math
import time
import uuid
import shutil
import hashlib
import asyncio
import mimetypes
import tempfile
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional, List, Dict, Any
import aiofiles
from fastapi import (
FastAPI, HTTPException, UploadFile, File, Form,
Query, BackgroundTasks, Request, Depends
)
from fastapi.responses import StreamingResponse, JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from huggingface_hub import HfApi, list_bucket_tree, batch_bucket_files, download_bucket_files, get_bucket_paths_info, bucket_info
# ββββββββββββββββββββββββββββ Config ββββββββββββββββββββββββββββ
BUCKET_ID = os.getenv("BUCKET_ID", "veltrixcode/FinderX")
HF_TOKEN = os.getenv("HF_TOKEN", "") # hf_xxxx token
CHUNK_DIR = Path(tempfile.gettempdir()) / "finderx_chunks"
CACHE_DIR = Path(tempfile.gettempdir()) / "finderx_cache"
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "5120")) # 5 GB default
API_VERSION = "1.0.0"
CHUNK_DIR.mkdir(parents=True, exist_ok=True)
CACHE_DIR.mkdir(parents=True, exist_ok=True)
# ββββββββββββββββββββββββββββ HF Client βββββββββββββββββββββββββ
api = HfApi(token=HF_TOKEN or None)
# ββββββββββββββββββββββββββββ In-Memory Stores ββββββββββββββββββ
# (In production swap these with a Redis / SQLite store)
_recent_files: List[Dict] = [] # last 50 accessed paths
_favorites: Dict[str, bool] = {} # path -> True
_trash: Dict[str, Dict] = {} # path -> {original, deleted_at, data}
_activity_log: List[Dict] = [] # append-only log
_versions: Dict[str, List] = {} # path -> [{version_id, uploaded_at, size}]
_chunk_sessions: Dict[str, Dict] = {} # session_id -> {filename, total, received, parts[]}
# ββββββββββββββββββββββββββββ Helpers βββββββββββββββββββββββββββ
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
def _log(action: str, path: str, extra: Dict = None):
entry = {"action": action, "path": path, "timestamp": _now(), **(extra or {})}
_activity_log.append(entry)
if len(_activity_log) > 1000:
_activity_log.pop(0)
def _add_recent(path: str):
global _recent_files
_recent_files = [r for r in _recent_files if r["path"] != path]
_recent_files.insert(0, {"path": path, "accessed_at": _now()})
_recent_files = _recent_files[:50]
def _detect_mime(filename: str) -> str:
mime, _ = mimetypes.guess_type(filename)
return mime or "application/octet-stream"
def _hf_path(virtual_path: str) -> str:
"""Clean and normalise a virtual path for bucket storage."""
p = virtual_path.strip("/")
return p
def _list_tree(prefix: str = "", recursive: bool = True) -> List[Dict]:
items = []
for item in list_bucket_tree(BUCKET_ID, prefix=prefix or None, recursive=recursive):
items.append({
"path": item.path,
"type": item.type, # "file" | "directory"
"size": getattr(item, "size", None),
"last_modified": getattr(item, "last_modified", None),
"mime_type": _detect_mime(item.path) if item.type == "file" else None,
})
return items
def _upload_bytes(data: bytes, remote_path: str):
batch_bucket_files(BUCKET_ID, add=[(data, remote_path)], token=HF_TOKEN or None)
def _download_bytes(remote_path: str) -> bytes:
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp_path = tmp.name
try:
download_bucket_files(
BUCKET_ID,
files=[(remote_path, tmp_path)],
token=HF_TOKEN or None,
)
with open(tmp_path, "rb") as f:
return f.read()
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
def _file_exists(remote_path: str) -> bool:
try:
results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None))
return len(results) > 0
except Exception:
return False
def _get_file_meta(remote_path: str) -> Optional[Dict]:
try:
results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None))
if not results:
return None
r = results[0]
return {
"path": r.path,
"size": getattr(r, "size", None),
"xet_hash": getattr(r, "xet_hash", None),
"mime_type": _detect_mime(r.path),
"last_modified": getattr(r, "last_modified", _now()),
}
except Exception:
return None
# ββββββββββββββββββββββββββββ App βββββββββββββββββββββββββββββββ
app = FastAPI(
title="FinderX File Manager API",
description="Full-featured file management API backed by HuggingFace Buckets",
version=API_VERSION,
docs_url="/docs",
redoc_url="/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HEALTH
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/", tags=["Health"])
def root():
return {"service": "FinderX API", "version": API_VERSION, "status": "ok"}
@app.get("/health", tags=["Health"])
def health():
try:
info = bucket_info(BUCKET_ID, token=HF_TOKEN or None)
return {"status": "ok", "bucket": BUCKET_ID, "size": info.size, "files": info.total_files}
except Exception as e:
raise HTTPException(500, f"Bucket unreachable: {e}")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FILE LISTING & SEARCH
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/files", tags=["Browse"])
def list_files(
path: str = Query("", description="Folder prefix to list"),
recursive: bool = Query(False, description="Recurse into sub-folders"),
sort_by: str = Query("name", description="Sort by: name | size | date"),
order: str = Query("asc", description="asc | desc"),
page: int = Query(1, ge=1),
per_page: int = Query(50, ge=1, le=500),
):
"""List files and folders. Supports pagination, sorting."""
items = _list_tree(prefix=path, recursive=recursive)
# sort
reverse = order.lower() == "desc"
if sort_by == "size":
items.sort(key=lambda x: x["size"] or 0, reverse=reverse)
elif sort_by == "date":
items.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse)
else:
items.sort(key=lambda x: x["path"], reverse=reverse)
# paginate
total = len(items)
start = (page - 1) * per_page
end = start + per_page
return {
"path": path,
"total": total,
"page": page,
"per_page": per_page,
"pages": math.ceil(total / per_page),
"items": items[start:end],
}
@app.get("/search", tags=["Browse"])
def search_files(
q: str = Query(..., description="Search term (matches path/filename)"),
path: str = Query("", description="Scope search to a folder prefix"),
sort_by: str = Query("name"),
order: str = Query("asc"),
page: int = Query(1, ge=1),
per_page: int = Query(50, ge=1, le=500),
):
"""Full-text search across all file paths."""
all_items = _list_tree(prefix=path, recursive=True)
term = q.lower()
matched = [i for i in all_items if term in i["path"].lower()]
reverse = order.lower() == "desc"
if sort_by == "size":
matched.sort(key=lambda x: x["size"] or 0, reverse=reverse)
elif sort_by == "date":
matched.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse)
else:
matched.sort(key=lambda x: x["path"], reverse=reverse)
total = len(matched)
start = (page - 1) * per_page
return {
"query": q, "total": total, "page": page,
"per_page": per_page, "pages": math.ceil(total / per_page) if total else 0,
"items": matched[start: start + per_page],
}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FILE METADATA
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/files/meta", tags=["Metadata"])
def file_metadata(path: str = Query(..., description="Remote file path")):
"""Get metadata: size, MIME type, hash, modified date."""
meta = _get_file_meta(_hf_path(path))
if not meta:
raise HTTPException(404, f"File not found: {path}")
meta["favorites"] = _favorites.get(path, False)
meta["in_trash"] = path in _trash
meta["versions"] = _versions.get(path, [])
return meta
@app.post("/files/hash", tags=["Metadata"])
def hash_file(path: str = Query(..., description="Remote file path")):
"""Compute SHA-256 hash of a file (duplicate / corruption detection)."""
data = _download_bytes(_hf_path(path))
sha256 = hashlib.sha256(data).hexdigest()
md5 = hashlib.md5(data).hexdigest()
_log("hash", path)
return {"path": path, "sha256": sha256, "md5": md5, "size": len(data)}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# UPLOAD
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/upload", tags=["Upload"], status_code=201)
async def upload_file(
file: UploadFile = File(...),
destination_path: str = Form("", description="Remote folder path (e.g. photos/2024)"),
overwrite: bool = Form(True),
):
"""
Upload a single file. The remote path is: `destination_path/filename`.
Saves a version snapshot if the file already exists.
"""
if file.size and file.size > MAX_UPLOAD_MB * 1024 * 1024:
raise HTTPException(413, f"File exceeds {MAX_UPLOAD_MB} MB limit")
remote_dir = destination_path.strip("/")
remote_path = f"{remote_dir}/{file.filename}".strip("/")
# version snapshot
if _file_exists(remote_path):
if not overwrite:
raise HTTPException(409, f"File already exists: {remote_path}")
_versions.setdefault(remote_path, [])
_versions[remote_path].append({
"version_id": str(uuid.uuid4()),
"uploaded_at": _now(),
"size": (_get_file_meta(remote_path) or {}).get("size"),
})
data = await file.read()
_upload_bytes(data, remote_path)
_log("upload", remote_path, {"size": len(data)})
_add_recent(remote_path)
return {
"status": "uploaded",
"path": remote_path,
"size": len(data),
"mime_type": _detect_mime(file.filename),
"uploaded_at": _now(),
}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CHUNKED / RESUMABLE UPLOAD
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ChunkInitRequest(BaseModel):
filename: str
total_size: int
total_chunks: int
destination_path: str = ""
@app.post("/upload/chunked/init", tags=["Upload"])
def init_chunked_upload(req: ChunkInitRequest):
"""Initialise a chunked upload session. Returns a session_id."""
session_id = str(uuid.uuid4())
session_dir = CHUNK_DIR / session_id
session_dir.mkdir(parents=True, exist_ok=True)
_chunk_sessions[session_id] = {
"filename": req.filename,
"total_size": req.total_size,
"total_chunks": req.total_chunks,
"destination_path": req.destination_path,
"received": [],
"created_at": _now(),
}
return {"session_id": session_id, "total_chunks": req.total_chunks}
@app.post("/upload/chunked/{session_id}/{chunk_index}", tags=["Upload"])
async def upload_chunk(session_id: str, chunk_index: int, file: UploadFile = File(...)):
"""Upload a single chunk. chunk_index is 0-based."""
if session_id not in _chunk_sessions:
raise HTTPException(404, "Session not found. Call /upload/chunked/init first.")
session = _chunk_sessions[session_id]
chunk_data = await file.read()
chunk_path = CHUNK_DIR / session_id / f"chunk_{chunk_index:06d}"
async with aiofiles.open(chunk_path, "wb") as f:
await f.write(chunk_data)
if chunk_index not in session["received"]:
session["received"].append(chunk_index)
progress = len(session["received"]) / session["total_chunks"] * 100
return {
"session_id": session_id,
"chunk_index": chunk_index,
"received": len(session["received"]),
"total_chunks": session["total_chunks"],
"progress": round(progress, 2),
}
@app.post("/upload/chunked/{session_id}/complete", tags=["Upload"])
def complete_chunked_upload(session_id: str):
"""Assemble all chunks and push the completed file to the bucket."""
if session_id not in _chunk_sessions:
raise HTTPException(404, "Session not found.")
session = _chunk_sessions[session_id]
total_chunks = session["total_chunks"]
received = sorted(session["received"])
if len(received) != total_chunks or received != list(range(total_chunks)):
missing = [i for i in range(total_chunks) if i not in received]
raise HTTPException(400, f"Missing chunks: {missing}")
session_dir = CHUNK_DIR / session_id
assembled = b""
for i in range(total_chunks):
chunk_path = session_dir / f"chunk_{i:06d}"
with open(chunk_path, "rb") as f:
assembled += f.read()
remote_dir = session["destination_path"].strip("/")
remote_path = f"{remote_dir}/{session['filename']}".strip("/")
_upload_bytes(assembled, remote_path)
shutil.rmtree(session_dir, ignore_errors=True)
del _chunk_sessions[session_id]
_log("chunked_upload", remote_path, {"size": len(assembled)})
_add_recent(remote_path)
return {
"status": "assembled",
"path": remote_path,
"size": len(assembled),
"uploaded_at": _now(),
}
@app.get("/upload/chunked/{session_id}/status", tags=["Upload"])
def chunked_upload_status(session_id: str):
"""Check status / progress of a chunked upload session."""
if session_id not in _chunk_sessions:
raise HTTPException(404, "Session not found.")
session = _chunk_sessions[session_id]
received = len(session["received"])
total = session["total_chunks"]
return {
"session_id": session_id,
"filename": session["filename"],
"received": received,
"total_chunks": total,
"progress": round(received / total * 100, 2),
"missing": [i for i in range(total) if i not in session["received"]],
}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DOWNLOAD & STREAM
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/download", tags=["Download"])
def download_file(path: str = Query(..., description="Remote file path")):
"""Download a file as an attachment (triggers browser save dialog)."""
remote_path = _hf_path(path)
data = _download_bytes(remote_path)
_add_recent(path)
_log("download", path)
filename = Path(remote_path).name
mime = _detect_mime(filename)
return Response(
content=data,
media_type=mime,
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@app.get("/stream", tags=["Download"])
def stream_file(path: str = Query(..., description="Remote file path")):
"""
Stream a file inline (for direct open in browser/player).
Supports partial Range requests for video seeking.
"""
remote_path = _hf_path(path)
data = _download_bytes(remote_path)
filename = Path(remote_path).name
mime = _detect_mime(filename)
_add_recent(path)
_log("stream", path)
def _gen():
chunk = 65536
for i in range(0, len(data), chunk):
yield data[i: i + chunk]
return StreamingResponse(
_gen(),
media_type=mime,
headers={
"Content-Disposition": f'inline; filename="{filename}"',
"Content-Length": str(len(data)),
"Accept-Ranges": "bytes",
"Cache-Control": "public, max-age=3600",
},
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FILE OPERATIONS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class RenameRequest(BaseModel):
path: str = Field(..., description="Current path")
new_name: str = Field(..., description="New filename (not full path)")
@app.post("/files/rename", tags=["File Operations"])
def rename_file(req: RenameRequest):
"""Rename a file (keeps it in the same folder)."""
old_path = _hf_path(req.path)
parent = str(Path(old_path).parent).rstrip(".")
new_path = f"{parent}/{req.new_name}".strip("/")
data = _download_bytes(old_path)
_upload_bytes(data, new_path)
batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
_log("rename", old_path, {"new_path": new_path})
return {"status": "renamed", "old_path": old_path, "new_path": new_path}
class MoveRequest(BaseModel):
path: str = Field(..., description="Source path")
destination_dir: str = Field(..., description="Target folder path")
@app.post("/files/move", tags=["File Operations"])
def move_file(req: MoveRequest):
"""Move a file to a different folder."""
old_path = _hf_path(req.path)
filename = Path(old_path).name
new_path = f"{req.destination_dir.strip('/')}/{filename}"
data = _download_bytes(old_path)
_upload_bytes(data, new_path)
batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
_log("move", old_path, {"new_path": new_path})
return {"status": "moved", "old_path": old_path, "new_path": new_path}
class CopyRequest(BaseModel):
path: str = Field(..., description="Source path")
destination_dir: str = Field(..., description="Target folder path")
new_name: Optional[str] = Field(None, description="Override filename")
@app.post("/files/copy", tags=["File Operations"])
def copy_file(req: CopyRequest):
"""Copy a file to another folder (optionally rename)."""
src_path = _hf_path(req.path)
filename = req.new_name or Path(src_path).name
dest_path = f"{req.destination_dir.strip('/')}/{filename}"
data = _download_bytes(src_path)
_upload_bytes(data, dest_path)
_log("copy", src_path, {"dest_path": dest_path})
return {"status": "copied", "source": src_path, "destination": dest_path}
@app.delete("/files", tags=["File Operations"])
def delete_file(
path: str = Query(..., description="File path to delete"),
permanent: bool = Query(False, description="Skip trash and permanently delete"),
):
"""
Move a file to trash (recoverable) or permanently delete it.
"""
remote_path = _hf_path(path)
if permanent:
batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
_log("permanent_delete", path)
return {"status": "permanently_deleted", "path": path}
else:
# soft delete β store data in trash
data = _download_bytes(remote_path)
_trash[path] = {
"original_path": path,
"deleted_at": _now(),
"data": data,
"size": len(data),
"mime_type": _detect_mime(Path(path).name),
}
batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
_log("trash", path)
return {"status": "moved_to_trash", "path": path}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BATCH OPERATIONS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class BatchDeleteRequest(BaseModel):
paths: List[str]
permanent: bool = False
@app.post("/batch/delete", tags=["Batch"])
def batch_delete(req: BatchDeleteRequest):
"""Delete multiple files at once."""
results = []
for path in req.paths:
remote_path = _hf_path(path)
try:
if req.permanent:
batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
results.append({"path": path, "status": "permanently_deleted"})
else:
data = _download_bytes(remote_path)
_trash[path] = {
"original_path": path,
"deleted_at": _now(),
"data": data,
"size": len(data),
"mime_type": _detect_mime(Path(path).name),
}
batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None)
results.append({"path": path, "status": "trashed"})
_log("batch_delete", path)
except Exception as e:
results.append({"path": path, "status": "error", "error": str(e)})
return {"results": results}
class BatchMoveRequest(BaseModel):
paths: List[str]
destination_dir: str
@app.post("/batch/move", tags=["Batch"])
def batch_move(req: BatchMoveRequest):
"""Move multiple files to the same destination folder."""
results = []
for path in req.paths:
try:
old_path = _hf_path(path)
filename = Path(old_path).name
new_path = f"{req.destination_dir.strip('/')}/{filename}"
data = _download_bytes(old_path)
_upload_bytes(data, new_path)
batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None)
results.append({"path": path, "new_path": new_path, "status": "moved"})
_log("batch_move", path, {"new_path": new_path})
except Exception as e:
results.append({"path": path, "status": "error", "error": str(e)})
return {"results": results}
class BatchCopyRequest(BaseModel):
paths: List[str]
destination_dir: str
@app.post("/batch/copy", tags=["Batch"])
def batch_copy(req: BatchCopyRequest):
"""Copy multiple files to the same destination folder."""
results = []
for path in req.paths:
try:
src = _hf_path(path)
dest = f"{req.destination_dir.strip('/')}/{Path(src).name}"
data = _download_bytes(src)
_upload_bytes(data, dest)
results.append({"path": path, "dest": dest, "status": "copied"})
_log("batch_copy", path, {"dest": dest})
except Exception as e:
results.append({"path": path, "status": "error", "error": str(e)})
return {"results": results}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FOLDER OPERATIONS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class FolderCreateRequest(BaseModel):
path: str = Field(..., description="Full path for the new folder (e.g. docs/work)")
@app.post("/folders", tags=["Folders"], status_code=201)
def create_folder(req: FolderCreateRequest):
"""
Create a folder by uploading a hidden placeholder file.
HF Buckets use virtual folders (path prefixes) β this ensures
the folder appears in listings.
"""
folder_path = req.path.strip("/")
placeholder = f"{folder_path}/.finderx_folder"
_upload_bytes(b"", placeholder)
_log("create_folder", folder_path)
return {"status": "created", "path": folder_path}
class FolderRenameRequest(BaseModel):
path: str = Field(..., description="Current folder path")
new_name: str = Field(..., description="New folder name (last segment)")
@app.post("/folders/rename", tags=["Folders"])
def rename_folder(req: FolderRenameRequest):
"""Rename a folder by moving all its contents to the new path."""
old_prefix = req.path.strip("/")
parent = str(Path(old_prefix).parent).rstrip(".")
new_prefix = f"{parent}/{req.new_name}".strip("/")
items = [i for i in _list_tree(prefix=old_prefix, recursive=True) if i["type"] == "file"]
moved = []
for item in items:
old_p = item["path"]
suffix = old_p[len(old_prefix):]
new_p = new_prefix + suffix
data = _download_bytes(old_p)
_upload_bytes(data, new_p)
batch_bucket_files(BUCKET_ID, delete=[old_p], token=HF_TOKEN or None)
moved.append({"old": old_p, "new": new_p})
_log("rename_folder", old_prefix, {"new_prefix": new_prefix})
return {"status": "renamed", "old_path": old_prefix, "new_path": new_prefix, "files_moved": len(moved)}
@app.delete("/folders", tags=["Folders"])
def delete_folder(
path: str = Query(..., description="Folder path to delete"),
permanent: bool = Query(False),
):
"""Delete a folder and all its contents (recursive)."""
folder_path = path.strip("/")
items = [i for i in _list_tree(prefix=folder_path, recursive=True) if i["type"] == "file"]
paths = [i["path"] for i in items]
if permanent:
if paths:
batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None)
_log("permanent_delete_folder", folder_path, {"count": len(paths)})
else:
for p in paths:
data = _download_bytes(p)
_trash[p] = {
"original_path": p, "deleted_at": _now(),
"data": data, "size": len(data),
"mime_type": _detect_mime(Path(p).name),
}
if paths:
batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None)
_log("trash_folder", folder_path, {"count": len(paths)})
return {"status": "deleted" if permanent else "trashed", "path": folder_path, "files_affected": len(paths)}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# TRASH BIN
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/trash", tags=["Trash"])
def list_trash():
"""List all files in the trash bin."""
items = [
{"path": p, "original_path": v["original_path"],
"deleted_at": v["deleted_at"], "size": v["size"], "mime_type": v["mime_type"]}
for p, v in _trash.items()
]
return {"total": len(items), "items": items}
@app.post("/trash/restore", tags=["Trash"])
def restore_from_trash(path: str = Query(..., description="Path to restore")):
"""Restore a file from trash to its original location."""
if path not in _trash:
raise HTTPException(404, f"Not found in trash: {path}")
item = _trash.pop(path)
original = item["original_path"]
_upload_bytes(item["data"], _hf_path(original))
_log("restore", original)
return {"status": "restored", "path": original}
@app.delete("/trash", tags=["Trash"])
def empty_trash():
"""Permanently delete everything in the trash bin."""
count = len(_trash)
_trash.clear()
_log("empty_trash", "*", {"count": count})
return {"status": "emptied", "files_removed": count}
@app.delete("/trash/item", tags=["Trash"])
def permanent_delete_from_trash(path: str = Query(...)):
"""Permanently delete a single item from trash."""
if path not in _trash:
raise HTTPException(404, f"Not found in trash: {path}")
del _trash[path]
_log("permanent_delete", path)
return {"status": "permanently_deleted", "path": path}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FAVORITES
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/favorites", tags=["Favorites"])
def list_favorites():
return {"total": len(_favorites), "items": list(_favorites.keys())}
@app.post("/favorites", tags=["Favorites"])
def add_favorite(path: str = Query(...)):
_favorites[path] = True
_log("favorite_add", path)
return {"status": "added", "path": path}
@app.delete("/favorites", tags=["Favorites"])
def remove_favorite(path: str = Query(...)):
_favorites.pop(path, None)
return {"status": "removed", "path": path}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# RECENT FILES
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/recent", tags=["Recent"])
def recent_files(limit: int = Query(20, ge=1, le=50)):
return {"items": _recent_files[:limit]}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# VERSIONING
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/versions", tags=["Versions"])
def list_versions(path: str = Query(...)):
return {"path": path, "versions": _versions.get(path, [])}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# THUMBNAILS & PREVIEW
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/preview", tags=["Preview"])
def preview_file(path: str = Query(..., description="Remote image or PDF path")):
"""
Return raw bytes for inline preview (images and PDFs).
Images: returned as-is. PDFs: returned as application/pdf.
"""
remote_path = _hf_path(path)
mime = _detect_mime(Path(remote_path).name)
allowed = ("image/", "application/pdf")
if not any(mime.startswith(p) for p in allowed):
raise HTTPException(415, f"Preview not supported for MIME type: {mime}")
data = _download_bytes(remote_path)
_add_recent(path)
return Response(content=data, media_type=mime)
@app.get("/thumbnail", tags=["Preview"])
def thumbnail(
path: str = Query(...),
width: int = Query(256, ge=32, le=1024),
height: int = Query(256, ge=32, le=1024),
):
"""
Generate a thumbnail for image files.
Requires Pillow (`pip install Pillow`).
Falls back to the original image if Pillow is unavailable.
"""
remote_path = _hf_path(path)
mime = _detect_mime(Path(remote_path).name)
if not mime.startswith("image/"):
raise HTTPException(415, "Thumbnails are only supported for images")
data = _download_bytes(remote_path)
try:
from PIL import Image
img = Image.open(io.BytesIO(data))
img.thumbnail((width, height), Image.LANCZOS)
buf = io.BytesIO()
fmt = img.format or "JPEG"
img.save(buf, format=fmt)
return Response(content=buf.getvalue(), media_type=mime)
except ImportError:
# Pillow not installed β return original
return Response(content=data, media_type=mime)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STORAGE USAGE
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/storage/usage", tags=["Storage"])
def storage_usage():
"""Total bucket usage: size in bytes and file count."""
info = bucket_info(BUCKET_ID, token=HF_TOKEN or None)
return {
"bucket_id": BUCKET_ID,
"total_bytes": info.size,
"total_files": info.total_files,
"total_mb": round(info.size / 1024 / 1024, 2),
"total_gb": round(info.size / 1024 / 1024 / 1024, 4),
}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ACTIVITY LOGS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/activity", tags=["Activity"])
def activity_log(
limit: int = Query(50, ge=1, le=500),
action: Optional[str] = Query(None, description="Filter by action type"),
):
"""Return recent activity log entries."""
entries = list(reversed(_activity_log))
if action:
entries = [e for e in entries if e["action"] == action]
return {"total": len(entries), "items": entries[:limit]}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CACHE MANAGEMENT
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.delete("/cache", tags=["Cache"])
def clear_cache():
"""Clear all locally cached temporary files."""
removed = 0
for f in CACHE_DIR.iterdir():
try:
f.unlink() if f.is_file() else shutil.rmtree(f)
removed += 1
except Exception:
pass
return {"status": "cleared", "files_removed": removed}
@app.get("/cache/stats", tags=["Cache"])
def cache_stats():
files = list(CACHE_DIR.iterdir())
size = sum(f.stat().st_size for f in files if f.is_file())
return {"files": len(files), "size_bytes": size, "size_mb": round(size / 1024 / 1024, 2)}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PATH UTILITIES
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/path/info", tags=["Utilities"])
def path_info(path: str = Query(...)):
"""Return structured path components."""
p = Path(path)
return {
"full": str(p),
"parent": str(p.parent),
"name": p.name,
"stem": p.stem,
"suffix": p.suffix,
"parts": list(p.parts),
"mime_type": _detect_mime(p.name),
} |