SalexAI commited on
Commit
9243edd
·
verified ·
1 Parent(s): ce68a7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +235 -883
app.py CHANGED
@@ -1,22 +1,19 @@
1
- from fastapi import FastAPI, Request, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from pydantic import BaseModel, Field
4
- from typing import Optional, List, Dict
5
  import httpx
6
  import json
7
  import logging
8
  import os
9
  import asyncio
10
- import hashlib
11
  from datetime import datetime, timezone
12
- import re
13
- import fastapi
14
- import random
15
 
 
 
 
16
  app = FastAPI()
17
  logging.basicConfig(level=logging.INFO)
18
 
19
- # Enable CORS for all origins
20
  app.add_middleware(
21
  CORSMiddleware,
22
  allow_origins=["*"],
@@ -24,906 +21,261 @@ app.add_middleware(
24
  allow_headers=["*"],
25
  )
26
 
27
- # ---------------------------
28
- # Persistent storage setup
29
- # ---------------------------
30
- PERSISTENT_ROOT = os.environ.get("PERSISTENT_DIR", "/data")
31
- CHAT_DIR = os.path.join(PERSISTENT_ROOT, "chat")
32
- if not os.path.isdir(PERSISTENT_ROOT):
33
- CHAT_DIR = os.path.join(".", "data", "chat")
34
- os.makedirs(CHAT_DIR, exist_ok=True)
35
-
36
- USERS_DIR = os.path.join(PERSISTENT_ROOT, "users")
37
- os.makedirs(USERS_DIR, exist_ok=True)
38
- USERS_FILE = os.path.join(USERS_DIR, "users.jsonl")
39
- SESSIONS_FILE = os.path.join(USERS_DIR, "sessions.json")
40
-
41
- # New storage files
42
- ROOMS_FILE = os.path.join(USERS_DIR, "rooms2025.json")
43
- VOTES_FILE = os.path.join(USERS_DIR, "votes.json")
44
- BADGES_FILE = os.path.join(USERS_DIR, "badges.json")
45
-
46
- ADMIN_KEY = os.environ.get("ADMIN_KEY", "") # set in HF Space secrets
47
-
48
- # Async file locks
49
- app.state.chat_locks = {}
50
- app.state.users_lock = asyncio.Lock()
51
- app.state.sessions_lock = asyncio.Lock()
52
- app.state.rooms_lock = asyncio.Lock()
53
- app.state.votes_lock = asyncio.Lock()
54
- app.state.badges_lock = asyncio.Lock()
55
-
56
- app.state.sessions: Dict[str, str] = {}
57
- app.state.rooms: List[Dict] = []
58
- app.state.votes: Dict[str, Dict] = {} # post_id -> {upvotes: int, downvotes: int, voters: {user_handle: "up"|"down"}}
59
- app.state.badges: Dict[str, str] = {} # user_handle -> badge_type
60
-
61
- def _chat_file_for(video_id: str) -> str:
62
- # Stable filename to avoid path traversal
63
- h = hashlib.sha256(video_id.encode("utf-8")).hexdigest()[:32]
64
- return os.path.join(CHAT_DIR, f"{h}.jsonl")
65
-
66
- def _lock_for(path: str) -> asyncio.Lock:
67
- lock = app.state.chat_locks.get(path)
68
- if lock is None:
69
- lock = asyncio.Lock()
70
- app.state.chat_locks[path] = lock
71
- return lock
72
-
73
- def _now_iso() -> str:
74
- return datetime.now(timezone.utc).isoformat()
75
-
76
- def _valid_author(s: Optional[str]) -> str:
77
- s = (s or "anon").strip()
78
- s = re.sub(r"\s+", " ", s)
79
- return s[:32] or "anon"
80
-
81
- def _valid_text(s: str) -> str:
82
- s = (s or "").rstrip("\n")
83
- return s[:2000]
84
-
85
- async def _append_jsonl(path: str, record: dict) -> None:
86
- line = json.dumps(record, ensure_ascii=False) + "\n"
87
- def _write():
88
- with open(path, "a", encoding="utf-8") as f:
89
- f.write(line)
90
- await asyncio.to_thread(_write)
91
-
92
- async def _read_jsonl(path: str) -> List[dict]:
93
- if not os.path.exists(path):
94
- return []
95
- def _read():
96
- with open(path, "r", encoding="utf-8") as f:
97
- return [json.loads(x) for x in f if x.strip()]
98
- return await asyncio.to_thread(_read)
99
-
100
- # ---------------------------
101
- # Users & Auth helpers
102
- # ---------------------------
103
-
104
- def _safe_handle(s: str) -> str:
105
- s = (s or "").strip()
106
- s = re.sub(r"[^a-zA-Z0-9_.~-]", "_", s)
107
- return s[:24]
108
-
109
- def _hash_pin(pin: str) -> str:
110
- return hashlib.sha256(("tlks|" + pin).encode("utf-8")).hexdigest()
111
-
112
- def _rand_token() -> str:
113
- return hashlib.sha256(os.urandom(32)).hexdigest()
114
-
115
- def _gen_temp_pin(digits: int = 6) -> str:
116
- # numeric temp PIN (easier to convey to students)
117
- lower = 10 ** (digits - 1)
118
- return str(random.randint(lower, 10 ** digits - 1))
119
-
120
- async def _append_user(record: dict) -> None:
121
- line = json.dumps(record, ensure_ascii=False) + "\n"
122
- def _write():
123
- with open(USERS_FILE, "a", encoding="utf-8") as f:
124
- f.write(line)
125
- async with app.state.users_lock:
126
- await asyncio.to_thread(_write)
127
-
128
- async def _read_users() -> List[dict]:
129
- if not os.path.exists(USERS_FILE):
130
- return []
131
- def _read():
132
- with open(USERS_FILE, "r", encoding="utf-8") as f:
133
- return [json.loads(x) for x in f if x.strip()]
134
- async with app.state.users_lock:
135
- return await asyncio.to_thread(_read)
136
-
137
- async def _load_sessions():
138
- if os.path.exists(SESSIONS_FILE):
139
- def _read():
140
- with open(SESSIONS_FILE, "r", encoding="utf-8") as f:
141
- return json.load(f)
142
- app.state.sessions = await asyncio.to_thread(_read)
143
- else:
144
- app.state.sessions = {}
145
-
146
- async def _save_sessions():
147
- def _write(data):
148
- with open(SESSIONS_FILE, "w", encoding="utf-8") as f:
149
- json.dump(data, f)
150
- async with app.state.sessions_lock:
151
- await asyncio.to_thread(_write, app.state.sessions)
152
-
153
- # New storage functions
154
- async def _load_rooms():
155
- if os.path.exists(ROOMS_FILE):
156
- def _read():
157
- with open(ROOMS_FILE, "r", encoding="utf-8") as f:
158
- return json.load(f)
159
- app.state.rooms = await asyncio.to_thread(_read)
160
- else:
161
- # Default rooms
162
- app.state.rooms = [
163
- {"id": "main", "name": "General", "private": False},
164
- ]
165
- await _save_rooms()
166
-
167
- async def _save_rooms():
168
- def _write(data):
169
- with open(ROOMS_FILE, "w", encoding="utf-8") as f:
170
- json.dump(data, f)
171
- async with app.state.rooms_lock:
172
- await asyncio.to_thread(_write, app.state.rooms)
173
-
174
- async def _load_votes():
175
- if os.path.exists(VOTES_FILE):
176
- def _read():
177
- with open(VOTES_FILE, "r", encoding="utf-8") as f:
178
- return json.load(f)
179
- app.state.votes = await asyncio.to_thread(_read)
180
- else:
181
- app.state.votes = {}
182
-
183
- async def _save_votes():
184
- def _write(data):
185
- with open(VOTES_FILE, "w", encoding="utf-8") as f:
186
- json.dump(data, f)
187
- async with app.state.votes_lock:
188
- await asyncio.to_thread(_write, app.state.votes)
189
-
190
- async def _load_badges():
191
- if os.path.exists(BADGES_FILE):
192
- def _read():
193
- with open(BADGES_FILE, "r", encoding="utf-8") as f:
194
- return json.load(f)
195
- app.state.badges = await asyncio.to_thread(_read)
196
- else:
197
- app.state.badges = {}
198
-
199
- async def _save_badges():
200
- def _write(data):
201
- with open(BADGES_FILE, "w", encoding="utf-8") as f:
202
- json.dump(data, f)
203
- async with app.state.badges_lock:
204
- await asyncio.to_thread(_write, app.state.badges)
205
-
206
- @app.on_event("startup")
207
- async def _startup_load_data():
208
- await _load_sessions()
209
- await _load_rooms()
210
- await _load_votes()
211
- await _load_badges()
212
-
213
- def _require_admin(request: Request):
214
- provided = request.headers.get("x-admin-key", "")
215
- if not ADMIN_KEY or provided != ADMIN_KEY:
216
- raise fastapi.HTTPException(status_code=401, detail="Admin key required")
217
-
218
- def _is_verified_staff(handle: str) -> bool:
219
- """Check if user is verified staff (can moderate)"""
220
- VERIFIED_STAFF = {"teacher1", "staff", "alex"} # Configure as needed
221
- return handle in VERIFIED_STAFF
222
-
223
- # ---------------------------
224
- # Chat API (public read, authed write)
225
- # ---------------------------
226
- class NewMessage(BaseModel):
227
- author: Optional[str] = Field(default="anon", max_length=64) # ignored on server write
228
- text: str = Field(..., min_length=1, max_length=5000)
229
-
230
- @app.get("/chat/{video_id}")
231
- async def get_messages(video_id: str, limit: int = 50, since: Optional[str] = None):
232
- """
233
- Fetch messages for a room/video.
234
- - limit: max messages (default 50)
235
- - since: ISO8601 timestamp; return only messages newer than this
236
- """
237
- limit = max(1, min(limit, 200))
238
- path = _chat_file_for(video_id)
239
- items = await _read_jsonl(path)
240
-
241
- if since:
242
- try:
243
- since_dt = datetime.fromisoformat(since.replace("Z", "+00:00"))
244
- items = [
245
- m for m in items
246
- if datetime.fromisoformat(str(m.get("created_at", "")).replace("Z", "+00:00")) > since_dt
247
- ]
248
- except Exception:
249
- pass # Ignore bad since param
250
-
251
- items.sort(key=lambda m: m.get("created_at", ""))
252
- if len(items) > limit:
253
- items = items[-limit:]
254
-
255
- # Add vote counts and badges to messages
256
- for item in items:
257
- post_id = item.get("id")
258
- if post_id and post_id in app.state.votes:
259
- vote_data = app.state.votes[post_id]
260
- item["upvotes"] = vote_data.get("upvotes", 0)
261
- item["downvotes"] = vote_data.get("downvotes", 0)
262
- else:
263
- item["upvotes"] = 0
264
- item["downvotes"] = 0
265
-
266
- # Add badge info
267
- handle = item.get("handle")
268
- if handle and handle in app.state.badges:
269
- item["badge"] = app.state.badges[handle]
270
-
271
- return {"video_id": video_id, "count": len(items), "messages": items}
272
-
273
- @app.delete("/chat/{video_id}/{message_id}")
274
- async def delete_message(video_id: str, message_id: str, request: Request):
275
- """
276
- Delete a message (staff only)
277
- """
278
- user = await _require_user(request)
279
- if not _is_verified_staff(user["handle"]):
280
- raise HTTPException(status_code=403, detail="Staff access required")
281
-
282
- path = _chat_file_for(video_id)
283
- lock = _lock_for(path)
284
-
285
- async with lock:
286
- items = await _read_jsonl(path)
287
- original_count = len(items)
288
- items = [m for m in items if m.get("id") != message_id]
289
-
290
- if len(items) == original_count:
291
- raise HTTPException(status_code=404, detail="Message not found")
292
-
293
- # Rewrite file without the deleted message
294
- def _write_all():
295
- with open(path, "w", encoding="utf-8") as f:
296
- for item in items:
297
- f.write(json.dumps(item, ensure_ascii=False) + "\n")
298
- await asyncio.to_thread(_write_all)
299
-
300
- logging.info(f"Message {message_id} deleted by {user['handle']}")
301
- return {"ok": True}
302
-
303
- # ---------------------------
304
- # Users & Auth API
305
- # ---------------------------
306
- class NewUser(BaseModel):
307
- email: str
308
- first_name: str
309
- last_name: str
310
- handle: str = Field(..., min_length=2, max_length=24)
311
- klass: str = Field(..., max_length=64)
312
- profile_image: Optional[str] = ""
313
- description: Optional[str] = ""
314
- pin: str = Field(..., min_length=3, max_length=32)
315
-
316
- class UpdateUser(BaseModel):
317
- first_name: Optional[str] = None
318
- last_name: Optional[str] = None
319
- klass: Optional[str] = None
320
- profile_image: Optional[str] = None
321
- description: Optional[str] = None
322
- pin: Optional[str] = None
323
- disabled: Optional[bool] = None
324
-
325
- class UpdateProfile(BaseModel):
326
- first_name: Optional[str] = None
327
- last_name: Optional[str] = None
328
- profile_image: Optional[str] = None
329
-
330
- class LoginReq(BaseModel):
331
- handle: str
332
- pin: str
333
-
334
- @app.post("/admin/users")
335
- async def admin_create_user(user: NewUser, request: Request):
336
- _require_admin(request)
337
- users = await _read_users()
338
-
339
- handle = _safe_handle(user.handle.lstrip("@"))
340
- if any(u.get("handle") == handle for u in users):
341
- return {"ok": False, "error": "Handle already exists"}
342
-
343
- rec = {
344
- "email": user.email.strip(),
345
- "first_name": user.first_name.strip(),
346
- "last_name": user.last_name.strip(),
347
- "handle": handle,
348
- "klass": user.klass.strip(),
349
- "profile_image": (user.profile_image or "").strip(),
350
- "description": (user.description or "").strip(),
351
- "pin_hash": _hash_pin(user.pin),
352
- "disabled": False,
353
- "must_change_pin": False,
354
- "created_at": _now_iso(),
355
- }
356
- await _append_user(rec)
357
- pub = {k: v for k, v in rec.items() if k != "pin_hash"}
358
- return {"ok": True, "user": pub}
359
-
360
- @app.get("/admin/users")
361
- async def admin_list_users(request: Request, q: Optional[str] = None, limit: int = 200):
362
- _require_admin(request)
363
- users = await _read_users()
364
- if q:
365
- ql = q.lower()
366
- users = [u for u in users if ql in u.get("email", "").lower() or ql in u.get("handle", "").lower()]
367
- users = users[: max(1, min(limit, 1000))]
368
- for u in users:
369
- u.pop("pin_hash", None)
370
- return {"count": len(users), "users": users}
371
-
372
- @app.get("/admin/users/{handle}")
373
- async def admin_get_user(handle: str, request: Request):
374
- """
375
- Return user details (names, email, class, disabled, must_change_pin, created_at).
376
- NOTE: For security we DO NOT return the existing PIN or pin_hash.
377
- """
378
- _require_admin(request)
379
- handle = _safe_handle(handle)
380
- users = await _read_users()
381
- u = next((x for x in users if x.get("handle") == handle), None)
382
- if not u:
383
- raise fastapi.HTTPException(status_code=404, detail="User not found")
384
- pub = {k: v for k, v in u.items() if k != "pin_hash"}
385
- return {"ok": True, "user": pub}
386
-
387
- @app.put("/admin/users/{handle}")
388
- async def admin_update_user(handle: str, patch: UpdateUser, request: Request):
389
- _require_admin(request)
390
- handle = _safe_handle(handle)
391
- users = await _read_users()
392
- changed = False
393
- for u in users:
394
- if u.get("handle") == handle:
395
- if patch.first_name is not None:
396
- u["first_name"] = patch.first_name.strip()
397
- if patch.last_name is not None:
398
- u["last_name"] = patch.last_name.strip()
399
- if patch.klass is not None:
400
- u["klass"] = patch.klass.strip()
401
- if patch.profile_image is not None:
402
- u["profile_image"] = patch.profile_image.strip()
403
- if patch.description is not None:
404
- u["description"] = patch.description.strip()
405
- if patch.disabled is not None:
406
- u["disabled"] = bool(patch.disabled)
407
- if patch.pin is not None:
408
- u["pin_hash"] = _hash_pin(patch.pin)
409
- u["must_change_pin"] = False
410
- changed = True
411
- break
412
- if not changed:
413
- raise fastapi.HTTPException(status_code=404, detail="User not found")
414
-
415
- # rewrite file
416
- async with app.state.users_lock:
417
- def _write_all():
418
- with open(USERS_FILE, "w", encoding="utf-8") as f:
419
- for rec in users:
420
- f.write(json.dumps(rec, ensure_ascii=False) + "\n")
421
- await asyncio.to_thread(_write_all)
422
- return {"ok": True}
423
-
424
- @app.put("/me/profile")
425
- async def update_my_profile(patch: UpdateProfile, request: Request):
426
- """
427
- Update current user's profile
428
- """
429
- user = await _require_user(request)
430
- handle = user["handle"]
431
-
432
- users = await _read_users()
433
- changed = False
434
- for u in users:
435
- if u.get("handle") == handle:
436
- if patch.first_name is not None:
437
- u["first_name"] = patch.first_name.strip()
438
- if patch.last_name is not None:
439
- u["last_name"] = patch.last_name.strip()
440
- if patch.profile_image is not None:
441
- u["profile_image"] = patch.profile_image.strip()
442
- changed = True
443
- break
444
-
445
- if not changed:
446
- raise HTTPException(status_code=404, detail="User not found")
447
-
448
- # rewrite file
449
- async with app.state.users_lock:
450
- def _write_all():
451
- with open(USERS_FILE, "w", encoding="utf-8") as f:
452
- for rec in users:
453
- f.write(json.dumps(rec, ensure_ascii=False) + "\n")
454
- await asyncio.to_thread(_write_all)
455
-
456
- return {"ok": True}
457
-
458
- @app.post("/admin/users/{handle}/reset_pin")
459
- async def admin_reset_pin(handle: str, body: dict = None, request: Request = None):
460
- """
461
- Admin-only endpoint to reset a user's PIN.
462
- Request body (optional): { "new_pin": "123456" }
463
- If new_pin is not provided, the server will generate a numeric temporary PIN (6 digits)
464
- and set must_change_pin = true on the user record.
465
- The endpoint returns {"ok": True, "new_pin": "..."} so the admin can communicate it.
466
- NOTE: We DO NOT return the user's old PIN for security reasons.
467
- """
468
- _require_admin(request)
469
- handle = _safe_handle(handle)
470
- users = await _read_users()
471
- found = False
472
- new_pin = None
473
- for u in users:
474
- if u.get("handle") == handle:
475
- found = True
476
- new_pin = (body or {}).get("new_pin")
477
- if new_pin:
478
- # basic validation
479
- new_pin = str(new_pin).strip()
480
- if len(new_pin) < 3 or len(new_pin) > 32:
481
- raise fastapi.HTTPException(status_code=400, detail="PIN length invalid")
482
- u["pin_hash"] = _hash_pin(new_pin)
483
- u["must_change_pin"] = False
484
- else:
485
- # generate temporary numeric PIN and flag must_change_pin
486
- new_pin = _gen_temp_pin(6)
487
- u["pin_hash"] = _hash_pin(new_pin)
488
- u["must_change_pin"] = True
489
- break
490
- if not found:
491
- raise fastapi.HTTPException(status_code=404, detail="User not found")
492
-
493
- # rewrite file with updated pin_hash
494
- async with app.state.users_lock:
495
- def _write_all():
496
- with open(USERS_FILE, "w", encoding="utf-8") as f:
497
- for rec in users:
498
- f.write(json.dumps(rec, ensure_ascii=False) + "\n")
499
- await asyncio.to_thread(_write_all)
500
-
501
- logging.info(f"Admin reset PIN for @{handle}")
502
- return {"ok": True, "new_pin": new_pin}
503
-
504
- @app.post("/auth/login")
505
- async def login(req: LoginReq):
506
- users = await _read_users()
507
- handle = _safe_handle(req.handle.lstrip("@"))
508
- u = next((x for x in users if x.get("handle") == handle), None)
509
- if not u or u.get("disabled"):
510
- return {"ok": False, "error": "Invalid user"}
511
- if u.get("pin_hash") != _hash_pin(req.pin):
512
- return {"ok": False, "error": "Invalid PIN"}
513
-
514
- token = _rand_token()
515
- app.state.sessions[token] = handle
516
- await _save_sessions()
517
- # include must_change_pin to allow client to force password change
518
- return {"ok": True, "token": token, "must_change_pin": bool(u.get("must_change_pin", False))}
519
-
520
- async def _require_user(request: Request) -> dict:
521
- auth = request.headers.get("authorization", "")
522
- if not auth.lower().startswith("bearer "):
523
- raise fastapi.HTTPException(status_code=401, detail="Missing bearer token")
524
- token = auth.split(" ", 1)[1].strip()
525
- handle = app.state.sessions.get(token)
526
- if not handle:
527
- raise fastapi.HTTPException(status_code=401, detail="Invalid session")
528
-
529
- users = await _read_users()
530
- user = next((u for u in users if u.get("handle") == handle), None)
531
- if not user or user.get("disabled"):
532
- raise fastapi.HTTPException(status_code=401, detail="User disabled")
533
- return user
534
-
535
- @app.get("/me")
536
- async def me(request: Request):
537
- user = await _require_user(request)
538
- pub = {k: v for k, v in user.items() if k not in ("pin_hash",)}
539
- return {"ok": True, "user": pub}
540
-
541
- # ---------------------------
542
- # Rooms API
543
- # ---------------------------
544
-
545
- class NewRoom(BaseModel):
546
- name: str = Field(..., min_length=1, max_length=64)
547
- room_id: str = Field(..., min_length=1, max_length=32)
548
- private: bool = False
549
- invite_code: Optional[str] = None
550
-
551
- class RoomAccessRequest(BaseModel):
552
- invite_code: str
553
-
554
- @app.get("/rooms")
555
- async def get_rooms():
556
- """
557
- Get all rooms (without invite codes for security)
558
- """
559
- rooms = []
560
- for room in app.state.rooms:
561
- room_data = {
562
- "id": room["id"],
563
- "name": room["name"],
564
- "private": room.get("private", False)
565
- }
566
- rooms.append(room_data)
567
- return {"rooms": rooms}
568
-
569
- @app.post("/rooms")
570
- async def create_room(room_data: NewRoom, request: Request):
571
- """
572
- Create a new room (staff only)
573
- """
574
- user = await _require_user(request)
575
- if not _is_verified_staff(user["handle"]):
576
- raise HTTPException(status_code=403, detail="Staff access required")
577
-
578
- # Validate room_id
579
- room_id = re.sub(r"[^a-zA-Z0-9_.~-]", "_", room_data.room_id.strip())
580
- if not room_id:
581
- raise HTTPException(status_code=400, detail="Invalid room ID")
582
-
583
- # Check if room already exists
584
- if any(r["id"] == room_id for r in app.state.rooms):
585
- raise HTTPException(status_code=400, detail="Room ID already exists")
586
-
587
- # Validate invite code for private rooms
588
- if room_data.private and not room_data.invite_code:
589
- raise HTTPException(status_code=400, detail="Private rooms require an invite code")
590
-
591
- new_room = {
592
- "id": room_id,
593
- "name": room_data.name.strip(),
594
- "private": room_data.private,
595
- "created_by": user["handle"],
596
- "created_at": _now_iso()
597
- }
598
-
599
- if room_data.private and room_data.invite_code:
600
- new_room["invite"] = room_data.invite_code.strip()
601
-
602
- app.state.rooms.append(new_room)
603
- await _save_rooms()
604
-
605
- logging.info(f"Room {room_id} created by {user['handle']}")
606
-
607
- # Return room without invite code
608
- public_room = {k: v for k, v in new_room.items() if k != "invite"}
609
- return {"ok": True, "room": public_room}
610
-
611
- @app.post("/rooms/{room_id}/access")
612
- async def request_room_access(room_id: str, access_req: RoomAccessRequest, request: Request):
613
- """
614
- Request access to a private room with invite code
615
- """
616
- user = await _require_user(request)
617
-
618
- room = next((r for r in app.state.rooms if r["id"] == room_id), None)
619
- if not room:
620
- raise HTTPException(status_code=404, detail="Room not found")
621
-
622
- if not room.get("private"):
623
- return {"ok": True, "access_granted": True} # Public room
624
-
625
- if room.get("invite") == access_req.invite_code.strip():
626
- return {"ok": True, "access_granted": True}
627
- else:
628
- return {"ok": False, "access_granted": False, "error": "Invalid invite code"}
629
-
630
- # ---------------------------
631
- # Voting API
632
- # ---------------------------
633
-
634
- class VoteRequest(BaseModel):
635
- vote_type: str # "up" or "down"
636
-
637
- @app.post("/chat/{video_id}/{message_id}/vote")
638
- async def vote_message(video_id: str, message_id: str, vote_req: VoteRequest, request: Request):
639
- """
640
- Vote on a message
641
- """
642
- user = await _require_user(request)
643
- handle = user["handle"]
644
-
645
- if vote_req.vote_type not in ["up", "down"]:
646
- raise HTTPException(status_code=400, detail="Invalid vote type")
647
-
648
- # Initialize vote data if doesn't exist
649
- if message_id not in app.state.votes:
650
- app.state.votes[message_id] = {
651
- "upvotes": 0,
652
- "downvotes": 0,
653
- "voters": {}
654
- }
655
-
656
- vote_data = app.state.votes[message_id]
657
- current_vote = vote_data["voters"].get(handle)
658
-
659
- # Remove previous vote
660
- if current_vote == "up":
661
- vote_data["upvotes"] = max(0, vote_data["upvotes"] - 1)
662
- elif current_vote == "down":
663
- vote_data["downvotes"] = max(0, vote_data["downvotes"] - 1)
664
-
665
- # Add new vote (or remove if same)
666
- if current_vote == vote_req.vote_type:
667
- # Toggle off - remove vote
668
- del vote_data["voters"][handle]
669
- else:
670
- # Add new vote
671
- vote_data["voters"][handle] = vote_req.vote_type
672
- if vote_req.vote_type == "up":
673
- vote_data["upvotes"] += 1
674
- else:
675
- vote_data["downvotes"] += 1
676
-
677
- await _save_votes()
678
-
679
- return {
680
- "ok": True,
681
- "upvotes": vote_data["upvotes"],
682
- "downvotes": vote_data["downvotes"],
683
- "user_vote": vote_data["voters"].get(handle)
684
- }
685
-
686
- @app.get("/chat/{video_id}/{message_id}/votes")
687
- async def get_message_votes(video_id: str, message_id: str, request: Request):
688
- """
689
- Get vote counts for a message
690
- """
691
- user = await _require_user(request)
692
- handle = user["handle"]
693
-
694
- if message_id not in app.state.votes:
695
- return {
696
- "upvotes": 0,
697
- "downvotes": 0,
698
- "user_vote": None
699
- }
700
-
701
- vote_data = app.state.votes[message_id]
702
- return {
703
- "upvotes": vote_data["upvotes"],
704
- "downvotes": vote_data["downvotes"],
705
- "user_vote": vote_data["voters"].get(handle)
706
- }
707
-
708
- # ---------------------------
709
- # Badge API
710
- # ---------------------------
711
-
712
- class BadgeRequest(BaseModel):
713
- badge_type: str # "gold", "silver", "green", or "none" to remove
714
-
715
- @app.post("/users/{target_handle}/badge")
716
- async def assign_badge(target_handle: str, badge_req: BadgeRequest, request: Request):
717
- """
718
- Assign badge to user (staff only)
719
- """
720
- user = await _require_user(request)
721
- if not _is_verified_staff(user["handle"]):
722
- raise HTTPException(status_code=403, detail="Staff access required")
723
-
724
- target_handle = _safe_handle(target_handle)
725
-
726
- # Verify target user exists
727
- users = await _read_users()
728
- target_user = next((u for u in users if u.get("handle") == target_handle), None)
729
- if not target_user:
730
- raise HTTPException(status_code=404, detail="User not found")
731
-
732
- valid_badges = {"gold", "silver", "green", "none"}
733
- if badge_req.badge_type not in valid_badges:
734
- raise HTTPException(status_code=400, detail="Invalid badge type")
735
-
736
- if badge_req.badge_type == "none":
737
- # Remove badge
738
- if target_handle in app.state.badges:
739
- del app.state.badges[target_handle]
740
- else:
741
- # Assign badge
742
- app.state.badges[target_handle] = badge_req.badge_type
743
-
744
- await _save_badges()
745
-
746
- logging.info(f"Badge {badge_req.badge_type} assigned to {target_handle} by {user['handle']}")
747
- return {"ok": True}
748
-
749
- @app.get("/users/{handle}/badge")
750
- async def get_user_badge(handle: str):
751
- """
752
- Get user's badge
753
- """
754
- handle = _safe_handle(handle)
755
- badge = app.state.badges.get(handle)
756
- return {"badge": badge}
757
-
758
- # ---------------------------
759
- # Enhanced Chat API
760
- # ---------------------------
761
-
762
- @app.post("/chat/{video_id}")
763
- async def post_message(video_id: str, msg: NewMessage, request: Request):
764
- """
765
- Append a message to a room's chat.
766
- Body: { "text": "hello" }
767
- """
768
- path = _chat_file_for(video_id)
769
- lock = _lock_for(path)
770
-
771
- # Require a valid session and take author from the user profile
772
- user = await _require_user(request)
773
- author = _valid_author(f"{user.get('first_name','')} {user.get('last_name','')}".strip() or user["handle"])
774
- handle = user["handle"]
775
- klass = user.get("klass", "")
776
- profile_image = user.get("profile_image", "")
777
-
778
- text = _valid_text(msg.text)
779
- if not text:
780
- return {"ok": False, "error": "Empty message"}
781
-
782
- created = _now_iso()
783
- mid = hashlib.sha1(f"{video_id}|{author}|{created}|{text}".encode("utf-8")).hexdigest()[:16]
784
- ip = request.client.host if request and request.client else None
785
-
786
- record = {
787
- "id": mid,
788
- "video_id": video_id,
789
- "author": author,
790
- "handle": handle,
791
- "klass": klass,
792
- "profile_image": profile_image,
793
- "text": text,
794
- "created_at": created,
795
- "ip": ip,
796
- "ua": request.headers.get("user-agent", "")[:200],
797
- }
798
-
799
- async with lock:
800
- await _append_jsonl(path, record)
801
-
802
- return {"ok": True, "message": record}
803
-
804
- # ---------------------------
805
- # iCloud album endpoints (unchanged)
806
- # ---------------------------
807
- BASE_62_MAP = {c: i for i, c in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")}
808
 
 
 
 
809
  async def get_client() -> httpx.AsyncClient:
810
  if not hasattr(app.state, "client"):
811
- app.state.client = httpx.AsyncClient(timeout=15.0)
812
  return app.state.client
813
 
 
 
 
 
 
 
 
814
  def base62_to_int(token: str) -> int:
815
- result = 0
816
- for ch in token:
817
- result = result * 62 + BASE_62_MAP[ch]
818
- return result
 
 
 
 
 
 
 
 
 
819
 
820
  async def get_base_url(token: str) -> str:
821
- first = token[0]
822
- if first == "A":
823
  n = base62_to_int(token[1])
824
  else:
825
  n = base62_to_int(token[1:3])
826
  return f"https://p{n:02d}-sharedstreams.icloud.com/{token}/sharedstreams/"
827
 
828
- ICLOUD_HEADERS = {
829
- "Origin": "https://www.icloud.com",
830
- "Content-Type": "text/plain",
831
- }
832
- ICLOUD_PAYLOAD = '{"streamCtag":null}'
833
-
834
  async def get_redirected_base_url(base_url: str, token: str) -> str:
835
  client = await get_client()
836
- resp = await client.post(
837
- f"{base_url}webstream", headers=ICLOUD_HEADERS, data=ICLOUD_PAYLOAD, follow_redirects=False
 
 
 
838
  )
839
- if resp.status_code == 330:
840
- try:
841
- body = resp.json()
842
- host = body.get("X-Apple-MMe-Host")
843
- if not host:
844
- raise ValueError("Missing X-Apple-MMe-Host in 330 response")
845
- logging.info(f"Redirected to {host}")
846
- return f"https://{host}/{token}/sharedstreams/"
847
- except Exception as e:
848
- logging.error(f"Redirect parsing failed: {e}")
849
- raise
850
- elif resp.status_code == 200:
851
  return base_url
852
- else:
853
- resp.raise_for_status()
854
 
855
  async def post_json(path: str, base_url: str, payload: str) -> dict:
856
  client = await get_client()
857
- resp = await client.post(f"{base_url}{path}", headers=ICLOUD_HEADERS, data=payload)
858
- resp.raise_for_status()
859
- return resp.json()
 
 
 
 
860
 
861
  async def get_metadata(base_url: str) -> list:
862
- data = await post_json("webstream", base_url, ICLOUD_PAYLOAD)
863
- return data.get("photos", [])
864
 
865
  async def get_asset_urls(base_url: str, guids: list) -> dict:
866
  payload = json.dumps({"photoGuids": guids})
867
- data = await post_json("webasseturls", base_url, payload)
868
- return data.get("items", {})
869
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870
  @app.get("/album/{token}")
871
- async def get_album(token: str):
872
- try:
873
- base_url = await get_base_url(token)
874
- base_url = await get_redirected_base_url(base_url, token)
875
- metadata = await get_metadata(base_url)
876
- guids = [photo["photoGuid"] for photo in metadata]
877
- asset_map = await get_asset_urls(base_url, guids)
878
-
879
- videos = []
880
- for photo in metadata:
881
- if photo.get("mediaAssetType", "").lower() != "video":
882
- continue
883
-
884
- derivatives = photo.get("derivatives", {})
885
- best = max(
886
- (d for k, d in derivatives.items() if k.lower() != "posterframe"),
887
- key=lambda d: int(d.get("fileSize") or 0),
888
- default=None,
889
- )
890
- if not best:
891
- continue
892
-
893
- checksum = best.get("checksum")
894
- info = asset_map.get(checksum)
895
- if not info:
896
- continue
897
- video_url = f"https://{info['url_location']}{info['url_path']}"
898
-
899
- poster = None
900
- pf = derivatives.get("PosterFrame")
901
- if pf:
902
- pf_info = asset_map.get(pf.get("checksum"))
903
- if pf_info:
904
- poster = f"https://{pf_info['url_location']}{pf_info['url_path']}"
905
-
906
- videos.append({
907
- "caption": photo.get("caption", ""),
908
- "url": video_url,
909
- "poster": poster or "",
910
- })
911
-
912
- return {"videos": videos}
913
-
914
- except Exception as e:
915
- logging.exception("Error in get_album")
916
- return {"error": str(e)}
917
 
918
  @app.get("/album/{token}/raw")
919
- async def get_album_raw(token: str):
920
- try:
921
- base_url = await get_base_url(token)
922
- base_url = await get_redirected_base_url(base_url, token)
923
- metadata = await get_metadata(base_url)
924
- guids = [photo["photoGuid"] for photo in metadata]
925
- asset_map = await get_asset_urls(base_url, guids)
926
- return {"metadata": metadata, "asset_urls": asset_map}
927
- except Exception as e:
928
- logging.exception("Error in get_album_raw")
929
- return {"error": str(e)}
 
 
1
+ from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.staticfiles import StaticFiles
 
4
  import httpx
5
  import json
6
  import logging
7
  import os
8
  import asyncio
 
9
  from datetime import datetime, timezone
 
 
 
10
 
11
+ # --------------------------------------------------
12
+ # App setup
13
+ # --------------------------------------------------
14
  app = FastAPI()
15
  logging.basicConfig(level=logging.INFO)
16
 
 
17
  app.add_middleware(
18
  CORSMiddleware,
19
  allow_origins=["*"],
 
21
  allow_headers=["*"],
22
  )
23
 
24
+ # --------------------------------------------------
25
+ # Storage
26
+ # --------------------------------------------------
27
+ DATA_ROOT = os.environ.get("PERSISTENT_DIR", "/data")
28
+ VIDEO_DIR = os.path.join(DATA_ROOT, "videos")
29
+ INDEX_FILE = os.path.join(DATA_ROOT, "index.json")
30
+
31
+ os.makedirs(VIDEO_DIR, exist_ok=True)
32
+
33
+ # --------------------------------------------------
34
+ # Album → Publisher mapping
35
+ # --------------------------------------------------
36
+ ALBUM_PUBLISHERS = {
37
+ "B2c5n8hH4uWRoAW": "Alex Rose",
38
+ "B2c5yeZFhHXzdFg": "Central Space Program",
39
+ "B2cGI9HKKtaAF3T": "Sam Holden",
40
+ "B2c59UlCquMMGkJ": "Alex Rose",
41
+ "B2cJ0DiRHusi12z": "Alex Rose",
42
+ "B2c5ON9t3uz8kT7": "Cole Vandepoll",
43
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # --------------------------------------------------
46
+ # HTTP client
47
+ # --------------------------------------------------
48
  async def get_client() -> httpx.AsyncClient:
49
  if not hasattr(app.state, "client"):
50
+ app.state.client = httpx.AsyncClient(timeout=20.0)
51
  return app.state.client
52
 
53
+ # --------------------------------------------------
54
+ # Base62 helpers
55
+ # --------------------------------------------------
56
+ BASE_62_MAP = {c: i for i, c in enumerate(
57
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
58
+ )}
59
+
60
  def base62_to_int(token: str) -> int:
61
+ n = 0
62
+ for c in token:
63
+ n = n * 62 + BASE_62_MAP[c]
64
+ return n
65
+
66
+ # --------------------------------------------------
67
+ # iCloud helpers
68
+ # --------------------------------------------------
69
+ ICLOUD_HEADERS = {
70
+ "Origin": "https://www.icloud.com",
71
+ "Content-Type": "text/plain",
72
+ }
73
+ ICLOUD_PAYLOAD = '{"streamCtag":null}'
74
 
75
  async def get_base_url(token: str) -> str:
76
+ if token[0] == "A":
 
77
  n = base62_to_int(token[1])
78
  else:
79
  n = base62_to_int(token[1:3])
80
  return f"https://p{n:02d}-sharedstreams.icloud.com/{token}/sharedstreams/"
81
 
 
 
 
 
 
 
82
  async def get_redirected_base_url(base_url: str, token: str) -> str:
83
  client = await get_client()
84
+ r = await client.post(
85
+ f"{base_url}webstream",
86
+ headers=ICLOUD_HEADERS,
87
+ data=ICLOUD_PAYLOAD,
88
+ follow_redirects=False,
89
  )
90
+
91
+ if r.status_code == 330:
92
+ host = r.json().get("X-Apple-MMe-Host")
93
+ if not host:
94
+ raise RuntimeError("Missing redirect host")
95
+ return f"https://{host}/{token}/sharedstreams/"
96
+
97
+ if r.status_code == 200:
 
 
 
 
98
  return base_url
99
+
100
+ r.raise_for_status()
101
 
102
  async def post_json(path: str, base_url: str, payload: str) -> dict:
103
  client = await get_client()
104
+ r = await client.post(
105
+ f"{base_url}{path}",
106
+ headers=ICLOUD_HEADERS,
107
+ data=payload,
108
+ )
109
+ r.raise_for_status()
110
+ return r.json()
111
 
112
  async def get_metadata(base_url: str) -> list:
113
+ return (await post_json("webstream", base_url, ICLOUD_PAYLOAD)).get("photos", [])
 
114
 
115
  async def get_asset_urls(base_url: str, guids: list) -> dict:
116
  payload = json.dumps({"photoGuids": guids})
117
+ return (await post_json("webasseturls", base_url, payload)).get("items", {})
118
+
119
+ # --------------------------------------------------
120
+ # Index helpers
121
+ # --------------------------------------------------
122
+ def load_index() -> dict:
123
+ if not os.path.exists(INDEX_FILE):
124
+ return {"videos": []}
125
+ with open(INDEX_FILE, "r", encoding="utf-8") as f:
126
+ return json.load(f)
127
+
128
+ def save_index(data: dict):
129
+ with open(INDEX_FILE, "w", encoding="utf-8") as f:
130
+ json.dump(data, f, indent=2)
131
+
132
+ # --------------------------------------------------
133
+ # Downloader
134
+ # --------------------------------------------------
135
+ async def download_file(url: str, path: str):
136
+ client = await get_client()
137
+ async with client.stream("GET", url) as r:
138
+ r.raise_for_status()
139
+ with open(path, "wb") as f:
140
+ async for chunk in r.aiter_bytes():
141
+ f.write(chunk)
142
+
143
+ # --------------------------------------------------
144
+ # Poll + ingest album
145
+ # --------------------------------------------------
146
+ async def poll_album(token: str):
147
+ base_url = await get_base_url(token)
148
+ base_url = await get_redirected_base_url(base_url, token)
149
+
150
+ metadata = await get_metadata(base_url)
151
+ guids = [p["photoGuid"] for p in metadata]
152
+ assets = await get_asset_urls(base_url, guids)
153
+
154
+ index = load_index()
155
+ known = {v["id"] for v in index["videos"]}
156
+
157
+ publisher = ALBUM_PUBLISHERS.get(token, "Unknown")
158
+ category = publisher
159
+
160
+ album_dir = os.path.join(VIDEO_DIR, token)
161
+ os.makedirs(album_dir, exist_ok=True)
162
+
163
+ for photo in metadata:
164
+ if photo.get("mediaAssetType", "").lower() != "video":
165
+ continue
166
+
167
+ vid = photo["photoGuid"]
168
+ if vid in known:
169
+ continue
170
+
171
+ derivatives = photo.get("derivatives", {})
172
+ best = max(
173
+ (d for k, d in derivatives.items() if k.lower() != "posterframe"),
174
+ key=lambda d: int(d.get("fileSize") or 0),
175
+ default=None,
176
+ )
177
+ if not best:
178
+ continue
179
+
180
+ asset = assets.get(best["checksum"])
181
+ if not asset:
182
+ continue
183
+
184
+ video_url = f"https://{asset['url_location']}{asset['url_path']}"
185
+ video_path = os.path.join(album_dir, f"{vid}.mp4")
186
+ await download_file(video_url, video_path)
187
+
188
+ thumb_path = ""
189
+ pf = derivatives.get("PosterFrame")
190
+ if pf:
191
+ pf_asset = assets.get(pf.get("checksum"))
192
+ if pf_asset:
193
+ poster_url = f"https://{pf_asset['url_location']}{pf_asset['url_path']}"
194
+ thumb_path = os.path.join(album_dir, f"{vid}.jpg")
195
+ await download_file(poster_url, thumb_path)
196
+
197
+ index["videos"].append({
198
+ "id": vid,
199
+ "name": photo.get("caption") or "Untitled",
200
+ "video_url": f"/media/{token}/{vid}.mp4",
201
+ "thumbnail": f"/media/{token}/{vid}.jpg" if thumb_path else "",
202
+ "upload_date": photo.get("creationDate") or datetime.now(timezone.utc).isoformat(),
203
+ "category": category,
204
+ "publisher": publisher,
205
+ "source_album": token,
206
+ })
207
+
208
+ save_index(index)
209
+
210
+ # --------------------------------------------------
211
+ # Background polling loop
212
+ # --------------------------------------------------
213
+ @app.on_event("startup")
214
+ async def start_polling():
215
+ async def loop():
216
+ while True:
217
+ for token in ALBUM_PUBLISHERS:
218
+ try:
219
+ await poll_album(token)
220
+ except Exception:
221
+ logging.exception(f"Polling failed for {token}")
222
+ await asyncio.sleep(60)
223
+
224
+ asyncio.create_task(loop())
225
+
226
+ # --------------------------------------------------
227
+ # New JSON feed (for new app)
228
+ # --------------------------------------------------
229
+ @app.get("/feed/videos")
230
+ async def get_video_feed():
231
+ return load_index()
232
+
233
+ # --------------------------------------------------
234
+ # Legacy iCloud passthrough (unchanged)
235
+ # --------------------------------------------------
236
  @app.get("/album/{token}")
237
+ async def legacy_album(token: str):
238
+ base_url = await get_base_url(token)
239
+ base_url = await get_redirected_base_url(base_url, token)
240
+ metadata = await get_metadata(base_url)
241
+ guids = [p["photoGuid"] for p in metadata]
242
+ assets = await get_asset_urls(base_url, guids)
243
+
244
+ videos = []
245
+ for photo in metadata:
246
+ if photo.get("mediaAssetType", "").lower() != "video":
247
+ continue
248
+
249
+ derivatives = photo.get("derivatives", {})
250
+ best = max(
251
+ (d for k, d in derivatives.items() if k.lower() != "posterframe"),
252
+ key=lambda d: int(d.get("fileSize") or 0),
253
+ default=None,
254
+ )
255
+ if not best:
256
+ continue
257
+
258
+ asset = assets.get(best["checksum"])
259
+ if not asset:
260
+ continue
261
+
262
+ videos.append({
263
+ "caption": photo.get("caption", ""),
264
+ "url": f"https://{asset['url_location']}{asset['url_path']}",
265
+ })
266
+
267
+ return {"videos": videos}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
  @app.get("/album/{token}/raw")
270
+ async def legacy_album_raw(token: str):
271
+ base_url = await get_base_url(token)
272
+ base_url = await get_redirected_base_url(base_url, token)
273
+ metadata = await get_metadata(base_url)
274
+ guids = [p["photoGuid"] for p in metadata]
275
+ assets = await get_asset_urls(base_url, guids)
276
+ return {"metadata": metadata, "asset_urls": assets}
277
+
278
+ # --------------------------------------------------
279
+ # Static media
280
+ # --------------------------------------------------
281
+ app.mount("/media", StaticFiles(directory=VIDEO_DIR), name="media")