"""Per-device self-service: przejęcie legacy stanu usera. Po migracji device-scopingu (0022) stare wiersze mają `device_id='legacy-shared'`. `POST /me/adopt-legacy` przepina WSZYSTKIE legacy wiersze (favorites/progress/blacklisty) na device wołającego. Robi to JEDEN raz właściciel instancji po update apki — kolejne wywołania nic nie znajdą (legacy już puste). Jeśli na keep-device istnieje już wiersz dla tej samej encji, legacy duplikat jest pomijany (ON CONFLICT DO NOTHING → potem kasujemy resztki legacy). """ from __future__ import annotations from typing import Annotated from fastapi import APIRouter, Depends from pydantic import BaseModel from sqlalchemy import text from sqlalchemy.orm import Session from app.api.device import LEGACY_DEVICE, get_device_id from app.auth import require_api_key from app.db import get_session router = APIRouter(prefix="/me", tags=["me"], dependencies=[Depends(require_api_key)]) # (tabela, kolumna-encji) — wszystkie tabele device-scoped (migracja 0022). _TABLES: list[tuple[str, str]] = [ ("favorite_performers", "performer_id"), ("favorite_studios", "studio_id"), ("favorite_scenes", "scene_id"), ("favorite_movies", "movie_id"), ("scene_play_progress", "scene_id"), ("movie_play_progress", "movie_id"), ("blacklisted_performers", "performer_id"), ("blacklisted_studios", "studio_id"), ("blacklisted_tags", "tag_id"), ] class AdoptLegacyOut(BaseModel): device_id: str moved: dict[str, int] class ImportOut(BaseModel): device_id: str imported: dict[str, int] # Tabele do przeniesienia przy transferze między urządzeniami + kolumna-encji do dedupu. # saved_searches ma własne `id` PK (nie (device_id,encja)), więc dedup po `query`. _COPY_TABLES: list[tuple[str, str]] = _TABLES + [("saved_searches", "query")] @router.post("/import/{source_device}", response_model=ImportOut) def import_from_device( source_device: str, session: Annotated[Session, Depends(get_session)], device_id: Annotated[str, Depends(get_device_id)], ) -> ImportOut: """Backup/transfer stanu (ulubione/blacklisty/progres/zapisane wyszukiwania) z innego urządzenia na wołające. `source_device` to device_id starego telefonu (pełni rolę kodu transferu — jest losowym UUID, więc jego znajomość == autoryzacja; instancja bez kont). KOPIUJE (nie przenosi): stary telefon zachowuje swoje. Dedup: pomija encje które urządzenie już ma. Idempotentne. `id`-PK (saved_searches) dostaje nowy gen_random_uuid().""" imported: dict[str, int] = {} source = (source_device or "").strip()[:64] if not source or source == device_id or source == LEGACY_DEVICE: return ImportOut(device_id=device_id, imported={}) for table, dedup_col in _COPY_TABLES: cols = [ r[0] for r in session.execute( text( "SELECT column_name FROM information_schema.columns " "WHERE table_name = :t ORDER BY ordinal_position" ).bindparams(t=table) ).all() ] if not cols: continue select_exprs = ", ".join( ":dev" if c == "device_id" else ("gen_random_uuid()" if c == "id" else f"src.{c}") for c in cols ) sql = ( f"INSERT INTO {table} ({', '.join(cols)}) " f"SELECT {select_exprs} FROM {table} src " f"WHERE src.device_id = :src AND NOT EXISTS (" f" SELECT 1 FROM {table} t WHERE t.device_id = :dev AND t.{dedup_col} = src.{dedup_col})" ) res = session.execute(text(sql).bindparams(dev=device_id, src=source)) imported[table] = res.rowcount or 0 session.commit() return ImportOut(device_id=device_id, imported=imported) @router.post("/adopt-legacy", response_model=AdoptLegacyOut) def adopt_legacy( session: Annotated[Session, Depends(get_session)], device_id: Annotated[str, Depends(get_device_id)], ) -> AdoptLegacyOut: moved: dict[str, int] = {} if device_id == LEGACY_DEVICE: # Wołający bez X-Device-Id == legacy → nie ma czego przepinać. return AdoptLegacyOut(device_id=device_id, moved={}) for table, entity in _TABLES: # Przepnij legacy → device dla encji których device JESZCZE nie ma. res = session.execute( text( f"UPDATE {table} SET device_id = :dev " f"WHERE device_id = :legacy AND {entity} NOT IN " f"(SELECT {entity} FROM {table} WHERE device_id = :dev)" ).bindparams(dev=device_id, legacy=LEGACY_DEVICE) ) moved[table] = res.rowcount or 0 # Resztki legacy (encje które device już miał) — skasuj, żeby nie wisiały. session.execute( text(f"DELETE FROM {table} WHERE device_id = :legacy").bindparams(legacy=LEGACY_DEVICE) ) session.commit() return AdoptLegacyOut(device_id=device_id, moved=moved)