Spaces:
Running
Running
Download database.py from Nrighton233j/Api-cache: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/Nrighton233j/Api-cache/resolve/main/database.py
- Command line
-
hf download hf://spaces/Nrighton233j/Api-cache/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Nrighton233j/Api-cache/resolve/main/database.py
13.1 kB
| """ | |
| database.py — SQLite metadata + on-disk blob storage for the B24 Downloads | |
| service. Actual file bytes live on the mounted bucket at /data/files/, | |
| named by checksum (content-addressed, natural dedup). SQLite only stores | |
| metadata + the relative path. | |
| """ | |
| import sqlite3 | |
| import os | |
| import time | |
| import hashlib | |
| DB_PATH = os.environ.get("DB_PATH", "/data/b24_files.db") | |
| DATA_DIR = os.path.dirname(DB_PATH) | |
| FILES_DIR = os.path.join(DATA_DIR, "files") | |
| from huggingface_hub import HfApi | |
| FILES_DATASET_REPO = os.environ.get("FILES_DATASET_REPO", "Nrighton233j/Storage-downld") | |
| AVATAR_DATASET_REPO = os.environ.get("AVATAR_DATASET_REPO", "Nrighton233j/Avatar") | |
| MOVIES_DATASET_REPO = os.environ.get("MOVIES_DATASET_REPO", "Nrighton233j/Movies") | |
| PLAYART_DATASET_REPO = os.environ.get("PLAYART_DATASET_REPO", "Nrighton233j/playart_1") | |
| _hf_api = HfApi(token=os.environ.get("HF_TOKEN")) | |
| # --- ownership/retrieval migration --- | |
| def _migrate_ownership_columns(conn): | |
| cols_to_add = [ | |
| ("recipient_user_id", "INTEGER"), | |
| ("retrieved_at", "INTEGER"), | |
| ("retrieved_by", "INTEGER"), | |
| ] | |
| existing = {row[1] for row in conn.execute("PRAGMA table_info(files)").fetchall()} | |
| for col, coltype in cols_to_add: | |
| if col not in existing: | |
| conn.execute(f"ALTER TABLE files ADD COLUMN {col} {coltype}") | |
| conn.commit() | |
| def get_conn(): | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| conn = sqlite3.connect(DB_PATH, check_same_thread=False) | |
| conn.row_factory = sqlite3.Row | |
| conn.execute("PRAGMA foreign_keys = ON") | |
| return conn | |
| def init_db(): | |
| os.makedirs(FILES_DIR, exist_ok=True) | |
| conn = get_conn() | |
| conn.execute(""" | |
| CREATE TABLE IF NOT EXISTS files ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| app_id TEXT NOT NULL, | |
| category TEXT NOT NULL, | |
| owner_user_id INTEGER, | |
| ref_id INTEGER, | |
| filename TEXT NOT NULL, | |
| content_type TEXT NOT NULL, | |
| size_bytes INTEGER NOT NULL, | |
| checksum TEXT NOT NULL, | |
| storage_path TEXT NOT NULL, | |
| is_public INTEGER NOT NULL DEFAULT 0, | |
| created_at INTEGER NOT NULL, | |
| expires_at INTEGER, | |
| deleted_at INTEGER, | |
| recipient_user_id INTEGER, | |
| retrieved_at INTEGER, | |
| retrieved_by INTEGER | |
| ) | |
| """) | |
| conn.execute(""" | |
| CREATE INDEX IF NOT EXISTS idx_files_lookup | |
| ON files (app_id, category, owner_user_id) | |
| """) | |
| conn.execute(""" | |
| CREATE INDEX IF NOT EXISTS idx_files_checksum | |
| ON files (checksum) | |
| """) | |
| _migrate_ownership_columns(conn) | |
| conn.commit() | |
| conn.close() | |
| def _repo_path_for(app_id, category, checksum, filename): | |
| ext = os.path.splitext(filename)[1] | |
| return f"{app_id}/{category}/{checksum}{ext}" | |
| # ---------- CREATE ---------- | |
| def save_file(app_id, category, filename, content_type, file_bytes, | |
| owner_user_id=None, ref_id=None, is_public=False, expires_at=None, recipient_user_id=None): | |
| size_bytes = len(file_bytes) | |
| checksum = hashlib.sha256(file_bytes).hexdigest() | |
| now = int(time.time()) | |
| path_in_repo = _repo_path_for(app_id, category, checksum, filename) | |
| if category == "avatar": | |
| target_repo = AVATAR_DATASET_REPO | |
| is_public = True | |
| elif category == "playlist_art": | |
| target_repo = PLAYART_DATASET_REPO | |
| is_public = True | |
| try: | |
| _hf_api.create_repo(PLAYART_DATASET_REPO, repo_type="dataset", exist_ok=True) | |
| except Exception as e: | |
| print("[playart] create_repo failed:", e) | |
| elif category in ("movie", "poster"): | |
| target_repo = MOVIES_DATASET_REPO | |
| is_public = True | |
| else: | |
| target_repo = FILES_DATASET_REPO | |
| url = f"https://huggingface.co/datasets/{target_repo}/resolve/main/{path_in_repo}" | |
| existing = find_by_checksum(checksum, app_id) | |
| if not existing: | |
| _hf_api.upload_file( | |
| path_or_fileobj=file_bytes, | |
| path_in_repo=path_in_repo, | |
| repo_id=target_repo, | |
| repo_type="dataset", | |
| ) | |
| conn = get_conn() | |
| cur = conn.execute( | |
| """INSERT INTO files (app_id, category, owner_user_id, ref_id, filename, content_type, | |
| size_bytes, checksum, storage_path, is_public, created_at, expires_at, deleted_at, | |
| recipient_user_id) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, | |
| ?)""", | |
| (app_id, category, owner_user_id, ref_id, filename, content_type, | |
| size_bytes, checksum, url, 1 if is_public else 0, now, expires_at, | |
| recipient_user_id) | |
| ) | |
| file_id = cur.lastrowid | |
| conn.commit() | |
| conn.close() | |
| return {"id": file_id, "checksum": checksum, "size_bytes": size_bytes, "url": url} | |
| # ---------- READ ---------- | |
| def get_file(file_id, include_data=True): | |
| conn = get_conn() | |
| row = conn.execute( | |
| "SELECT * FROM files WHERE id = ? AND deleted_at IS NULL", (file_id,) | |
| ).fetchone() | |
| conn.close() | |
| if not row: | |
| return None | |
| record = dict(row) | |
| record["url"] = record.pop("storage_path", None) | |
| return record | |
| def get_file_meta(file_id): | |
| return get_file(file_id, include_data=False) | |
| def find_by_checksum(checksum, app_id=None): | |
| conn = get_conn() | |
| if app_id: | |
| row = conn.execute( | |
| "SELECT id, filename, content_type, size_bytes FROM files " | |
| "WHERE checksum = ? AND app_id = ? AND deleted_at IS NULL LIMIT 1", | |
| (checksum, app_id) | |
| ).fetchone() | |
| else: | |
| row = conn.execute( | |
| "SELECT id, filename, content_type, size_bytes FROM files " | |
| "WHERE checksum = ? AND deleted_at IS NULL LIMIT 1", | |
| (checksum,) | |
| ).fetchone() | |
| conn.close() | |
| return dict(row) if row else None | |
| def list_files(app_id, category=None, owner_user_id=None, ref_id=None, limit=100, offset=0): | |
| conn = get_conn() | |
| query = ("SELECT id, app_id, category, owner_user_id, ref_id, filename, content_type, " | |
| "size_bytes, checksum, is_public, created_at, expires_at, storage_path " | |
| "FROM files WHERE app_id = ? AND deleted_at IS NULL") | |
| params = [app_id] | |
| if category: | |
| query += " AND category = ?" | |
| params.append(category) | |
| if owner_user_id is not None: | |
| query += " AND owner_user_id = ?" | |
| params.append(owner_user_id) | |
| if ref_id is not None: | |
| query += " AND ref_id = ?" | |
| params.append(ref_id) | |
| query += " ORDER BY created_at DESC LIMIT ? OFFSET ?" | |
| params.extend([limit, offset]) | |
| rows = conn.execute(query, params).fetchall() | |
| conn.close() | |
| results = [] | |
| for r in rows: | |
| d = dict(r) | |
| path = d.pop("storage_path", None) | |
| if d.get("is_public"): | |
| d["url"] = path | |
| results.append(d) | |
| return results | |
| # ---------- DELETE ---------- | |
| def soft_delete_file(file_id): | |
| conn = get_conn() | |
| conn.execute( | |
| "UPDATE files SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL", | |
| (int(time.time()), file_id) | |
| ) | |
| changed = conn.total_changes | |
| conn.commit() | |
| conn.close() | |
| return changed > 0 | |
| def hard_delete_expired(older_than_seconds=0): | |
| """Permanently removes rows that were soft-deleted more than | |
| older_than_seconds ago, or past expires_at. Only unlinks the on-disk | |
| file if no other row still references the same storage_path (dedup-safe).""" | |
| now = int(time.time()) | |
| conn = get_conn() | |
| rows = conn.execute( | |
| "SELECT id, storage_path FROM files WHERE " | |
| "(deleted_at IS NOT NULL AND deleted_at <= ?) " | |
| "OR (expires_at IS NOT NULL AND expires_at <= ?)", | |
| (now - older_than_seconds, now) | |
| ).fetchall() | |
| deleted = 0 | |
| for row in rows: | |
| conn.execute("DELETE FROM files WHERE id = ?", (row["id"],)) | |
| deleted += 1 | |
| still_referenced = conn.execute( | |
| "SELECT 1 FROM files WHERE storage_path = ? LIMIT 1", (row["storage_path"],) | |
| ).fetchone() | |
| if not still_referenced: | |
| try: | |
| os.remove(row["storage_path"]) | |
| except OSError: | |
| pass | |
| conn.commit() | |
| conn.close() | |
| return deleted | |
| # ---------- ADMIN / STATS ---------- | |
| def count_files(app_id=None): | |
| conn = get_conn() | |
| if app_id: | |
| row = conn.execute( | |
| "SELECT COUNT(*) AS c FROM files WHERE app_id = ? AND deleted_at IS NULL", (app_id,) | |
| ).fetchone() | |
| else: | |
| row = conn.execute("SELECT COUNT(*) AS c FROM files WHERE deleted_at IS NULL").fetchone() | |
| conn.close() | |
| return row["c"] | |
| def total_size_bytes(app_id=None): | |
| conn = get_conn() | |
| if app_id: | |
| row = conn.execute( | |
| "SELECT COALESCE(SUM(size_bytes), 0) AS s FROM files " | |
| "WHERE app_id = ? AND deleted_at IS NULL", (app_id,) | |
| ).fetchone() | |
| else: | |
| row = conn.execute( | |
| "SELECT COALESCE(SUM(size_bytes), 0) AS s FROM files WHERE deleted_at IS NULL" | |
| ).fetchone() | |
| conn.close() | |
| return row["s"] | |
| def db_file_size_bytes(): | |
| try: | |
| return os.path.getsize(DB_PATH) | |
| except OSError: | |
| return 0 | |
| def mark_retrieved(file_id, user_id): | |
| import time | |
| conn = get_conn() | |
| row = conn.execute("SELECT retrieved_at FROM files WHERE id = ?", (file_id,)).fetchone() | |
| if row is None: | |
| return {"ok": False, "error": "File not found"}, 404 | |
| if row[0] is None: | |
| conn.execute( | |
| "UPDATE files SET retrieved_at = ?, retrieved_by = ? WHERE id = ?", | |
| (int(time.time()), user_id, file_id) | |
| ) | |
| conn.commit() | |
| return {"ok": True, "file_id": file_id, "retrieved_by": user_id} | |
| # ---------- PLAYLIST TRACKING ---------- | |
| def init_playlist_tracks(): | |
| conn = get_conn() | |
| conn.execute(""" | |
| CREATE TABLE IF NOT EXISTS playlist_tracks ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| owner_user_id INTEGER NOT NULL, | |
| playlist_id TEXT NOT NULL, | |
| playlist_title TEXT, | |
| playlist_art TEXT, | |
| spotify_track_id TEXT NOT NULL, | |
| title TEXT, | |
| artist TEXT, | |
| status TEXT NOT NULL DEFAULT 'pending', | |
| file_id INTEGER, | |
| error TEXT, | |
| created_at INTEGER NOT NULL, | |
| updated_at INTEGER NOT NULL, | |
| UNIQUE(owner_user_id, playlist_id, spotify_track_id) | |
| ) | |
| """) | |
| conn.execute(""" | |
| CREATE INDEX IF NOT EXISTS idx_playlist_lookup | |
| ON playlist_tracks (owner_user_id, playlist_id) | |
| """) | |
| try: | |
| conn.execute("ALTER TABLE playlist_tracks ADD COLUMN art_url TEXT") | |
| except Exception: | |
| pass # column already exists | |
| conn.commit() | |
| conn.close() | |
| def upsert_playlist_track(owner_user_id, playlist_id, playlist_title, playlist_art, | |
| spotify_track_id, title, artist): | |
| """Idempotent: re-pasting the same playlist won't reset an already- | |
| 'done' track back to pending - it only inserts genuinely new tracks.""" | |
| now = int(time.time()) | |
| conn = get_conn() | |
| existing = conn.execute( | |
| "SELECT * FROM playlist_tracks WHERE owner_user_id=? AND playlist_id=? AND spotify_track_id=?", | |
| (owner_user_id, playlist_id, spotify_track_id) | |
| ).fetchone() | |
| if existing: | |
| conn.close() | |
| return dict(existing) | |
| cur = conn.execute( | |
| """INSERT INTO playlist_tracks | |
| (owner_user_id, playlist_id, playlist_title, playlist_art, spotify_track_id, | |
| title, artist, status, created_at, updated_at) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)""", | |
| (owner_user_id, playlist_id, playlist_title, playlist_art, spotify_track_id, | |
| title, artist, now, now) | |
| ) | |
| row_id = cur.lastrowid | |
| conn.commit() | |
| row = conn.execute("SELECT * FROM playlist_tracks WHERE id=?", (row_id,)).fetchone() | |
| conn.close() | |
| return dict(row) | |
| def set_playlist_track_status(track_id, status, file_id=None, error=None): | |
| conn = get_conn() | |
| conn.execute( | |
| "UPDATE playlist_tracks SET status=?, file_id=?, error=?, updated_at=? WHERE id=?", | |
| (status, file_id, error, int(time.time()), track_id) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| def get_playlist_tracks(owner_user_id, playlist_id): | |
| conn = get_conn() | |
| rows = conn.execute( | |
| "SELECT * FROM playlist_tracks WHERE owner_user_id=? AND playlist_id=? ORDER BY created_at", | |
| (owner_user_id, playlist_id) | |
| ).fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |
| def get_playlist_tracks_by_ids(track_ids): | |
| if not track_ids: | |
| return [] | |
| conn = get_conn() | |
| placeholders = ",".join("?" * len(track_ids)) | |
| rows = conn.execute( | |
| f"SELECT * FROM playlist_tracks WHERE id IN ({placeholders})", track_ids | |
| ).fetchall() | |
| conn.close() | |
| return [dict(r) for r in rows] | |