Files
romm/backend/handler/database/screenshots_handler.py
Sam Dornan 5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00

227 lines
7.3 KiB
Python

from collections.abc import Collection, Sequence
from functools import partial
from typing import Any
import pydash
from sqlalchemy import case, delete, func, or_, select, update
from sqlalchemy.orm import Session
from sqlalchemy.sql import Delete, Select, Update
from decorators.database import begin_session
from models.assets import Save, Screenshot, State
from models.base import with_file_name_parts
from .base_handler import DBBaseHandler
class DBScreenshotsHandler(DBBaseHandler):
def filter[QueryT: (Select[tuple[Screenshot]], Update, Delete)](
self,
query: QueryT,
*,
rom_id: int,
user_id: int,
filenames: Sequence[str] = (),
exclude_filenames: Sequence[str] = (),
) -> QueryT:
query = query.filter(
Screenshot.rom_id == rom_id,
Screenshot.user_id == user_id,
)
if filenames:
query = query.filter(
or_(
Screenshot.file_name.in_(filenames),
Screenshot.file_name_no_ext.in_(filenames),
)
)
if exclude_filenames:
query = query.filter(
Screenshot.file_name.not_in(exclude_filenames),
Screenshot.file_name_no_ext.not_in(exclude_filenames),
)
return query
@begin_session
def add_screenshot(
self,
screenshot: Screenshot,
session: Session = None, # type: ignore[assignment]
) -> Screenshot:
return session.merge(screenshot)
@begin_session
def get_screenshots(
self,
*,
user_id: int,
rom_ids: Collection[int],
session: Session = None, # type: ignore[assignment]
) -> Sequence[Screenshot]:
return session.scalars(
select(Screenshot).filter(
Screenshot.user_id == user_id, Screenshot.rom_id.in_(rom_ids)
)
).all()
@begin_session
def get_screenshot(
self,
*,
rom_id: int,
user_id: int,
file_name: str,
file_name_no_ext: str | None = None,
session: Session = None, # type: ignore[assignment]
) -> Screenshot | None:
query = self.filter(
select(Screenshot),
rom_id=rom_id,
user_id=user_id,
filenames=pydash.compact([file_name, file_name_no_ext]),
)
# Prefer exact stem matches first
query = query.order_by(
case((Screenshot.file_name_no_ext == file_name, 0), else_=1),
Screenshot.id.desc(),
)
return session.scalars(query.limit(1)).first()
@begin_session
def get_screenshot_by_id(
self,
id: int,
session: Session = None, # type: ignore[assignment]
) -> Screenshot | None:
return session.get(Screenshot, id)
@begin_session
def is_bound(
self,
screenshot: Screenshot,
ignoring: Save | State | None = None,
session: Session = None, # type: ignore[assignment]
) -> bool:
"""Whether a save or state other than `ignoring` shows the screenshot
as its thumbnail."""
names = pydash.compact([screenshot.file_name, screenshot.file_name_no_ext])
for model in (Save, State):
query = select(model.file_name, model.file_name_no_ext).filter(
model.rom_id == screenshot.rom_id,
model.user_id == screenshot.user_id,
or_(model.file_name.in_(names), model.file_name_no_ext.in_(names)),
)
if isinstance(ignoring, model):
query = query.filter(model.id != ignoring.id)
# A name can match several screenshots, and the asset shows only
# the one its lookup prefers.
for file_name, file_name_no_ext in session.execute(query):
shown = self.get_screenshot(
rom_id=screenshot.rom_id,
user_id=screenshot.user_id,
file_name=file_name,
file_name_no_ext=file_name_no_ext,
session=session,
)
if shown is not None and shown.id == screenshot.id:
return True
return False
@begin_session
def get_name_variants(
self,
screenshot: Screenshot,
session: Session = None, # type: ignore[assignment]
) -> Sequence[Screenshot]:
"""Other screenshots in the same folder whose name differs only in case."""
query = self.filter(
select(Screenshot), rom_id=screenshot.rom_id, user_id=screenshot.user_id
).filter(
Screenshot.id != screenshot.id,
Screenshot.file_path == screenshot.file_path,
func.lower(Screenshot.file_name) == screenshot.file_name.lower(),
)
return session.scalars(query).all()
@begin_session
def get_rom_gallery_screenshots(
self,
rom_id: int,
user_id: int,
public_only: bool = False,
session: Session = None, # type: ignore[assignment]
) -> Sequence[Screenshot]:
"""Gallery (intentionally-uploaded) screenshots for a ROM, visible to
the requesting user. Mirrors `db_rom_handler.get_rom_notes`: own
screenshots (public + private) plus other users' public ones. Excludes
the auto-captured save/state thumbnails (`is_gallery == False`)."""
query = select(Screenshot).filter(
Screenshot.rom_id == rom_id,
Screenshot.is_gallery,
)
if public_only:
query = query.filter(Screenshot.is_public)
else:
query = query.filter(
or_(Screenshot.user_id == user_id, Screenshot.is_public)
)
query = query.order_by(Screenshot.created_at.desc())
return session.scalars(query).all()
@begin_session
def update_screenshot(
self,
id: int,
data: dict[str, Any],
session: Session = None, # type: ignore[assignment]
) -> Screenshot:
session.execute(
update(Screenshot)
.where(Screenshot.id == id)
.values(**with_file_name_parts(data))
.execution_options(synchronize_session="evaluate")
)
return session.scalars(select(Screenshot).filter_by(id=id)).one()
@begin_session
def delete_screenshot(
self,
id: int,
session: Session = None, # type: ignore[assignment]
) -> None:
session.execute(
delete(Screenshot)
.where(Screenshot.id == id)
.execution_options(synchronize_session="evaluate")
)
@begin_session
def mark_missing_screenshots(
self,
rom_id: int,
user_id: int,
screenshots_to_keep: list[str],
session: Session = None, # type: ignore[assignment]
) -> Sequence[Screenshot]:
query_fn = partial(
self.filter,
rom_id=rom_id,
user_id=user_id,
exclude_filenames=screenshots_to_keep,
)
missing_screenshots = session.scalars(query_fn(query=select(Screenshot))).all()
session.execute(
query_fn(query=update(Screenshot))
.values(**{"missing_from_fs": True})
.execution_options(synchronize_session="evaluate")
)
return missing_screenshots