Spaces:
Running

File size: 13,082 Bytes
12dd2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
045e6c0
12dd2bf
 
3cd865c
12dd2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd865c
 
 
 
 
 
 
12dd2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8389cb2
 
 
 
12dd2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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]