"""Room-aware history. Scope is derived on the server, never supplied as a storage key.""" import json from contextlib import contextmanager from media_accounts import open_database, require_admin, assigned_rooms, session_user, AccountError from datetime import datetime import library_index as li KINDS=('tube','movies','tv') MODES=('shared','group','room','user','off') DEFAULT={k:'shared' for k in KINDS} def validate(data): if not isinstance(data,dict) or any(k not in KINDS or v not in MODES for k,v in data.items()): raise AccountError(400,'Invalid history settings') return {**DEFAULT,**data} def init(db): db.execute('CREATE TABLE IF NOT EXISTS room_history_settings (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, settings TEXT NOT NULL)') def settings(db,rid): init(db) row=db.execute('SELECT settings FROM room_history_settings WHERE room_id=?',(rid,)).fetchone() return {**DEFAULT,**(json.loads(row[0]) if row else {})} def put(db,rid,data): init(db) db.execute('INSERT INTO room_history_settings VALUES(?,?) ON CONFLICT(room_id) DO UPDATE SET settings=excluded.settings',(rid,json.dumps(validate(data)))) def admin_get(token,rid): require_admin(token) with open_database() as db: if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') return settings(db,rid) def admin_save(token,data): require_admin(token) rid=data.get('room_id') if type(rid) is not int: raise AccountError(400,'Invalid room') with open_database() as db: if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') put(db,rid,data.get('history')) return {'ok':True} def resolve(token,room_header,kind): user=session_user(token) if not room_header or not str(room_header).isdigit(): raise AccountError(400,'Select a room and refresh the page to use media history') rid=int(room_header) if rid not in {r['id'] for r in assigned_rooms(token)}: raise AccountError(403,'Room history access denied') with open_database() as db: mode=settings(db,rid)[kind] if mode=='shared': return 'shared' if mode=='off': return None if mode=='room': return f'room:{rid}' if mode=='user': return f'user:{user["id"]}' group=db.execute('SELECT group_id FROM managed_rooms WHERE id=?',(rid,)).fetchone() if not group: raise AccountError(403,'Room history unavailable') return f'group:{group[0]}' @contextmanager def connect(): db=li.get_db() db.execute('CREATE TABLE IF NOT EXISTS scoped_progress (scope TEXT NOT NULL, kind TEXT NOT NULL, item TEXT NOT NULL, position_seconds REAL NOT NULL, duration_seconds REAL, completed INTEGER NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(scope,kind,item))') db.execute('CREATE TABLE IF NOT EXISTS scoped_tube_history (scope TEXT NOT NULL, video_id TEXT NOT NULL, title TEXT NOT NULL, channel_name TEXT, thumbnail_url TEXT, duration_seconds REAL, first_played_at TEXT NOT NULL, last_played_at TEXT NOT NULL, watch_count INTEGER NOT NULL, PRIMARY KEY(scope,video_id))') try: with db: yield db finally: db.close() def get_progress(scope,kind,item): if scope=='shared': return li.get_youtube_playback_progress(item) if kind=='tube' else li.get_playback_progress(item) result={'position_seconds':0.0,'duration_seconds':None,'completed':False,'updated_at':None} if scope is None: return result with connect() as db: row=db.execute('SELECT position_seconds,duration_seconds,completed,updated_at FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item))).fetchone() if row: result.update(dict(row));result['completed']=bool(result['completed']) return result def save_progress(scope,kind,item,position,duration=None,completed=False): if scope is None: return if scope=='shared': return (li.save_youtube_playback_progress if kind=='tube' else li.save_playback_progress)(item,position,duration,completed) position=max(0.,float(position or 0));duration=max(0.,float(duration)) if duration not in (None,'') else None with connect() as db: db.execute('''INSERT INTO scoped_progress VALUES(?,?,?,?,?,?,?) ON CONFLICT(scope,kind,item) DO UPDATE SET position_seconds=excluded.position_seconds,duration_seconds=COALESCE(excluded.duration_seconds,scoped_progress.duration_seconds),completed=excluded.completed,updated_at=excluded.updated_at''',(scope,kind,str(item),position,duration,int(bool(completed)),datetime.now().isoformat())) def reset_progress(scope,kind,item): if scope is None: return if scope=='shared': return (li.reset_youtube_playback_progress if kind=='tube' else li.reset_playback_progress)(item) with connect() as db: db.execute('DELETE FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item))) def record_watch(scope,video_id,title,channel_name=None,thumbnail_url=None,duration_seconds=None): if scope is None: return if scope=='shared': return li.record_youtube_watch(video_id,title,channel_name,thumbnail_url,duration_seconds) try: duration=float(duration_seconds) if duration_seconds not in (None,'') else None except (ValueError,TypeError): duration=None now=datetime.now().isoformat() with connect() as db: db.execute('''INSERT INTO scoped_tube_history VALUES(?,?,?,?,?,?,?,?,1) ON CONFLICT(scope,video_id) DO UPDATE SET title=excluded.title,channel_name=COALESCE(excluded.channel_name,scoped_tube_history.channel_name),thumbnail_url=COALESCE(excluded.thumbnail_url,scoped_tube_history.thumbnail_url),duration_seconds=COALESCE(excluded.duration_seconds,scoped_tube_history.duration_seconds),last_played_at=excluded.last_played_at,watch_count=scoped_tube_history.watch_count+1''',(scope,video_id,title or video_id,channel_name,thumbnail_url,duration,now,now)) def history(scope,limit=50): if scope is None: return [] if scope=='shared': return li.get_youtube_history(limit) with connect() as db: rows=db.execute('''SELECT h.video_id,h.title,h.channel_name,h.thumbnail_url,COALESCE(p.duration_seconds,h.duration_seconds) duration_seconds,h.first_played_at,h.last_played_at,h.watch_count,COALESCE(p.position_seconds,0) position_seconds,COALESCE(p.completed,0) completed,c.video_id IS NOT NULL cached,c.size_bytes cache_size_bytes FROM scoped_tube_history h LEFT JOIN scoped_progress p ON p.scope=h.scope AND p.kind='tube' AND p.item=h.video_id LEFT JOIN youtube_video_cache c ON c.video_id=h.video_id WHERE h.scope=? ORDER BY h.last_played_at DESC LIMIT ?''',(scope,max(1,min(int(limit),500)))).fetchall() return [{**dict(r),'completed':bool(r['completed']),'cached':bool(r['cached'])} for r in rows]