mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* docs(api): document error responses for roms routes Describe every 4xx and 5xx the rom routes and their helpers raise in each decorator's responses=, so the OpenAPI schema lists them. A hidden rom, platform or file is described like a missing one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for saves routes Describe every 4xx/5xx the saves, states, screenshots, snapshots, play-sessions and sync routes raise in their responses=, and rewrite the states identifiers docstring that carried Args/Returns blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for devices routes Describe the 4xx/5xx statuses that the device, device auth, install, client token, notification, notification channel, sync channel and heartbeat routes raise, and fill the empty install route entries. Rewrite the setup and heartbeat docstrings that published Args and Returns blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for streaming routes Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for admin routes Describe the 4xx and 5xx statuses the config, permissions, user, auth, tasks, logs, activity and export routes raise, and rewrite their Args/Returns docstrings as plain operation descriptions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for library routes Describe the 400/403/404/409/500 statuses the collection, feed, firmware, platform, music, playlist and search routes raise, and replace route docstrings that carried Args/Returns blocks with plain sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): describe private collections and playlists as missing Matches #5686, where another user's private collection or playlist answers 404 and a play session on a hidden rom answers like a missing one. The read routes drop their 403, and the write 403 now covers only a public resource another user owns. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): address Greptile review on route error docs Fold the nine multi-paragraph route docstrings into one line, and keep the device-scope 403 descriptions in utils/auth.py next to resolve_device, which raises them, instead of in both saves.py and states.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): plain-prose pass on route error descriptions Spell out clipped error descriptions, replace internal slang (picked, taken, live, moved past), name the parameter an ID comes from, and split the long save conversion 400s into sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1074 lines
37 KiB
Python
1074 lines
37 KiB
Python
import csv
|
|
import io
|
|
import re
|
|
from collections import Counter
|
|
from collections.abc import Sequence
|
|
from datetime import datetime
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Query, Request, status
|
|
from fastapi.responses import JSONResponse, Response
|
|
from starlette.datastructures import URLPath
|
|
|
|
from config import (
|
|
DISABLE_DOWNLOAD_ENDPOINT_AUTH,
|
|
TINFOIL_WELCOME_MESSAGE,
|
|
)
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.feeds import (
|
|
WEBRCADE_SLUG_TO_TYPE_MAP,
|
|
WEBRCADE_SUPPORTED_PLATFORM_SLUGS,
|
|
FPKGiFeedItemSchema,
|
|
KekatsuDSItemSchema,
|
|
PKGiFeedPS3ItemSchema,
|
|
PKGiFeedPSPItemSchema,
|
|
PKGiFeedPSVitaItemSchema,
|
|
PkgjPSPDlcsItemSchema,
|
|
PkgjPSPGamesItemSchema,
|
|
PkgjPSVDlcsItemSchema,
|
|
PkgjPSVGamesItemSchema,
|
|
PkgjPSXGamesItemSchema,
|
|
TinfoilFeedFileSchema,
|
|
TinfoilFeedSchema,
|
|
TinfoilFeedTitleDBSchema,
|
|
WebrcadeFeedCategorySchema,
|
|
WebrcadeFeedItemPropsSchema,
|
|
WebrcadeFeedItemSchema,
|
|
WebrcadeFeedSchema,
|
|
)
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import get_rom_visibility_filter
|
|
from handler.database import db_platform_handler, db_rom_handler
|
|
from handler.filesystem import fs_rom_handler
|
|
from handler.metadata import meta_igdb_handler
|
|
from handler.metadata.base_handler import (
|
|
SONY_SERIAL_REGEX,
|
|
SWITCH_TITLEDB_REGEX,
|
|
)
|
|
from models.platform import Platform
|
|
from models.rom import (
|
|
HAS_FILE_ON_DISK_FILTERS,
|
|
Rom,
|
|
RomFile,
|
|
RomFileCategory,
|
|
)
|
|
from utils.archives import is_compressed_file
|
|
from utils.datetime import format_utc
|
|
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
|
from utils.router import APIRouter
|
|
from utils.urls import rom_content_url, romfile_content_url
|
|
|
|
router = APIRouter(
|
|
prefix="/feeds",
|
|
tags=["feeds"],
|
|
)
|
|
|
|
|
|
PKGI_CONTENT_TYPE_400 = "The content type is not one this feed supports."
|
|
PLATFORM_SLUG_404 = "No platform the caller can see has this slug."
|
|
|
|
|
|
def _visible_platform_by_slug(request: Request, slug: str) -> Platform | None:
|
|
"""A platform with `slug` the caller can see, or None."""
|
|
return db_platform_handler.get_platform_by_slug(
|
|
slug, visibility=get_rom_visibility_filter(request)
|
|
)
|
|
|
|
|
|
def _platform_roms(
|
|
request: Request, platform_id: int, *, include_files: bool = False
|
|
) -> Sequence[Rom]:
|
|
"""Roms of a platform a feed can serve: nothing hidden from the caller, and
|
|
nothing file-less (every feed entry carries a download URL)."""
|
|
return db_rom_handler.get_roms_scalar(
|
|
platform_ids=[platform_id],
|
|
include_files=include_files,
|
|
visibility=get_rom_visibility_filter(request),
|
|
**HAS_FILE_ON_DISK_FILTERS,
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/webrcade",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
)
|
|
def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
|
"""Get the webRcade feed of the library, in the format described at https://docs.webrcade.com/feeds/format/."""
|
|
|
|
visibility = get_rom_visibility_filter(request)
|
|
platforms = db_platform_handler.get_platforms(visibility=visibility)
|
|
|
|
categories = []
|
|
for p in platforms:
|
|
if p.slug not in WEBRCADE_SUPPORTED_PLATFORM_SLUGS:
|
|
continue
|
|
|
|
category_items = []
|
|
roms = db_rom_handler.get_roms_scalar(
|
|
platform_ids=[p.id],
|
|
visibility=visibility,
|
|
**HAS_FILE_ON_DISK_FILTERS,
|
|
)
|
|
for rom in roms:
|
|
download_url = rom_content_url(request, rom)
|
|
category_item = WebrcadeFeedItemSchema(
|
|
title=rom.name or rom.fs_name_no_tags,
|
|
description=rom.summary or "",
|
|
type=WEBRCADE_SLUG_TO_TYPE_MAP.get(p.slug, p.slug),
|
|
props=WebrcadeFeedItemPropsSchema(
|
|
rom=download_url,
|
|
),
|
|
)
|
|
if rom.path_cover_small:
|
|
category_item["thumbnail"] = str(
|
|
URLPath(rom.path_cover_small).make_absolute_url(request.base_url)
|
|
)
|
|
if rom.path_cover_large:
|
|
category_item["background"] = str(
|
|
URLPath(rom.path_cover_large).make_absolute_url(request.base_url)
|
|
)
|
|
category_items.append(category_item)
|
|
|
|
categories.append(
|
|
WebrcadeFeedCategorySchema(
|
|
title=p.name,
|
|
longTitle=f"{p.name} Games",
|
|
background=str(
|
|
URLPath(
|
|
f"/assets/webrcade/feed/{p.slug.lower()}-background.png"
|
|
).make_absolute_url(request.base_url)
|
|
),
|
|
thumbnail=str(
|
|
URLPath(
|
|
f"/assets/webrcade/feed/{p.slug.lower()}-thumb.png"
|
|
).make_absolute_url(request.base_url)
|
|
),
|
|
items=category_items,
|
|
)
|
|
)
|
|
|
|
return WebrcadeFeedSchema(
|
|
title="RomM Feed",
|
|
longTitle="Custom RomM Feed",
|
|
description="Custom feed from your RomM library",
|
|
thumbnail="https://raw.githubusercontent.com/rommapp/romm/release/.github/resources/isotipo.svg",
|
|
background="https://raw.githubusercontent.com/rommapp/romm/release/.github/resources/screenshots/gallery.png",
|
|
categories=categories,
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/tinfoil",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
)
|
|
async def tinfoil_index_feed(
|
|
request: Request,
|
|
slug: str = "switch",
|
|
) -> TinfoilFeedSchema:
|
|
"""Get the Tinfoil custom index (https://blawar.github.io/tinfoil/custom_index/) of a Nintendo Switch platform. When the caller can see no platform with `slug`, the index has no files and an error message."""
|
|
switch = _visible_platform_by_slug(request, slug)
|
|
if not switch:
|
|
return TinfoilFeedSchema(
|
|
files=[],
|
|
directories=[],
|
|
error="Nintendo Switch platform not found",
|
|
)
|
|
|
|
async def extract_titledb(
|
|
roms: Sequence[Rom],
|
|
) -> dict[str, dict[str, Any]]:
|
|
titledb: dict[str, dict[str, Any]] = {}
|
|
for rom in roms:
|
|
tdb_match = SWITCH_TITLEDB_REGEX.search(rom.fs_name)
|
|
if tdb_match:
|
|
(
|
|
_search_term,
|
|
index_entry,
|
|
) = await meta_igdb_handler._switch_titledb_format(
|
|
tdb_match, rom.fs_name
|
|
)
|
|
else:
|
|
(
|
|
_search_term,
|
|
index_entry,
|
|
) = await meta_igdb_handler._switch_productid_format(
|
|
rom, rom.fs_name, rom.fs_name
|
|
)
|
|
|
|
if not index_entry:
|
|
continue
|
|
|
|
# Tinfoil keys the index by nsuId, so an entry without one has no home.
|
|
nsu_id = index_entry.get("nsuId")
|
|
if nsu_id is not None:
|
|
titledb[str(nsu_id)] = TinfoilFeedTitleDBSchema(
|
|
**index_entry
|
|
).model_dump()
|
|
|
|
return titledb
|
|
|
|
roms = db_rom_handler.get_roms_scalar(
|
|
platform_ids=[switch.id],
|
|
include_files=True,
|
|
visibility=get_rom_visibility_filter(request),
|
|
**HAS_FILE_ON_DISK_FILTERS,
|
|
)
|
|
|
|
return TinfoilFeedSchema(
|
|
files=[
|
|
TinfoilFeedFileSchema(
|
|
url=romfile_content_url(request, rom_file),
|
|
size=rom_file.file_size_bytes,
|
|
)
|
|
for rom in roms
|
|
for rom_file in rom.files
|
|
if rom_file.file_extension.lower() in ["xci", "nsp", "nsz", "xcz", "nro"]
|
|
],
|
|
directories=[],
|
|
success=TINFOIL_WELCOME_MESSAGE,
|
|
titledb=await extract_titledb(roms),
|
|
)
|
|
|
|
|
|
CONTENT_TYPE_MAP: dict[RomFileCategory, int] = {
|
|
RomFileCategory.GAME: 1,
|
|
RomFileCategory.DLC: 2,
|
|
RomFileCategory.DEMO: 5,
|
|
RomFileCategory.UPDATE: 6,
|
|
RomFileCategory.PATCH: 6,
|
|
}
|
|
|
|
|
|
def validate_pkgi_file(file: RomFile, content_type: RomFileCategory) -> bool:
|
|
# Match content type by file category
|
|
if content_type != RomFileCategory.GAME and file.category != content_type:
|
|
return False
|
|
|
|
# Only consider top-level files as games
|
|
if content_type == RomFileCategory.GAME and not file.is_top_level:
|
|
return False
|
|
|
|
# Compressed files get a free pass
|
|
full_path = fs_rom_handler.validate_path(file.full_path)
|
|
if content_type == RomFileCategory.GAME and is_compressed_file(str(full_path)):
|
|
return True
|
|
|
|
# PKGi only supports PKG files
|
|
if file.file_extension.lower() != "pkg":
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def generate_content_id(file: RomFile) -> str:
|
|
"""Generate content ID for a rom file"""
|
|
titleid_match = SONY_SERIAL_REGEX.search(file.file_name)
|
|
if titleid_match:
|
|
# UP9644 is our custom Publisher ID
|
|
return f"UP9644-{titleid_match.group(1).replace('-', '')}_00-0000000000000000"
|
|
return f"UP9644-{file.id:09d}_00-0000000000000000"
|
|
|
|
|
|
def get_rap_data(request: Request, rom: Rom) -> tuple[str, str]:
|
|
"""Helper to find the .rap file for a given rom"""
|
|
for file in rom.files:
|
|
if file.file_extension.lower() == "rap":
|
|
rap_hash = file.sha1_hash or ""
|
|
rap_download_url = romfile_content_url(request, file)
|
|
return rap_hash, rap_download_url
|
|
|
|
return "", ""
|
|
|
|
|
|
def format_pkgj_datetime(value: datetime | None) -> str:
|
|
if isinstance(value, datetime):
|
|
return value.strftime("%Y-%m-%d %H:%M:%S")
|
|
return ""
|
|
|
|
|
|
def text_response(lines: list[str], filename: str) -> Response:
|
|
return Response(
|
|
content="\n".join(lines),
|
|
media_type="text/plain",
|
|
headers={
|
|
"Content-Disposition": f"filename={filename}",
|
|
"Cache-Control": "no-cache",
|
|
},
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgi/ps3/{content_type}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {"description": PKGI_CONTENT_TYPE_400},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation 3 platform."
|
|
},
|
|
},
|
|
)
|
|
def pkgi_ps3_feed(
|
|
request: Request,
|
|
content_type: Annotated[str, PathVar(description="Content type")],
|
|
) -> Response:
|
|
"""Get the PKGi PS3 database (https://github.com/bucanero/pkgi-ps3) of the PlayStation 3 files of one content type (`game`, `dlc`, `demo`, `update` or `patch`), as text."""
|
|
ps3_platform = _visible_platform_by_slug(request, UPS.PS3)
|
|
if not ps3_platform:
|
|
raise HTTPException(status_code=404, detail="PlayStation 3 platform not found")
|
|
|
|
try:
|
|
content_type_enum = RomFileCategory(content_type)
|
|
content_type_int = CONTENT_TYPE_MAP[content_type_enum]
|
|
except (ValueError, KeyError) as e:
|
|
raise HTTPException(
|
|
status_code=400, detail=f"Invalid content type: {content_type}"
|
|
) from e
|
|
|
|
roms = _platform_roms(request, ps3_platform.id, include_files=True)
|
|
txt_lines = []
|
|
|
|
for rom in roms:
|
|
rap_hash, _ = get_rap_data(request, rom)
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, content_type_enum):
|
|
continue
|
|
|
|
content_id = generate_content_id(file)
|
|
download_url = romfile_content_url(request, file)
|
|
|
|
# Validate the item schema
|
|
pkgi_item = PKGiFeedPS3ItemSchema(
|
|
contentid=content_id,
|
|
type=content_type_int,
|
|
name=file.file_name_no_tags,
|
|
description="",
|
|
rap=rap_hash,
|
|
url=download_url,
|
|
size=file.file_size_bytes,
|
|
checksum=file.sha1_hash or "",
|
|
)
|
|
|
|
# Format: contentid,type,name,description,rap,url,size,checksum
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgi_item.contentid,
|
|
str(pkgi_item.type),
|
|
pkgi_item.name,
|
|
pkgi_item.description,
|
|
pkgi_item.rap,
|
|
pkgi_item.url,
|
|
str(pkgi_item.size),
|
|
pkgi_item.checksum,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, f"pkgi_{content_type_enum.value}.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgi/psvita/{content_type}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {"description": PKGI_CONTENT_TYPE_400},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Vita platform."
|
|
},
|
|
},
|
|
)
|
|
def pkgi_psvita_feed(
|
|
request: Request,
|
|
content_type: Annotated[str, PathVar(description="Content type")],
|
|
) -> Response:
|
|
"""Get the PKGi database (https://github.com/mmozeiko/pkgi) of the PlayStation Vita files of one content type, such as `game` or `dlc`, as text."""
|
|
psvita_platform = _visible_platform_by_slug(request, UPS.PSVITA)
|
|
if not psvita_platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Vita platform not found"
|
|
)
|
|
|
|
try:
|
|
content_type_enum = RomFileCategory(content_type)
|
|
except ValueError as e:
|
|
raise HTTPException(
|
|
status_code=400, detail=f"Invalid content type: {content_type}"
|
|
) from e
|
|
|
|
roms = _platform_roms(request, psvita_platform.id, include_files=True)
|
|
txt_lines = []
|
|
|
|
for rom in roms:
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, content_type_enum):
|
|
continue
|
|
|
|
content_id = generate_content_id(file)
|
|
download_url = romfile_content_url(request, file)
|
|
|
|
pkgi_item = PKGiFeedPSVitaItemSchema(
|
|
contentid=content_id,
|
|
flags=0,
|
|
name=file.file_name_no_tags,
|
|
name2="",
|
|
zrif="",
|
|
url=download_url,
|
|
size=file.file_size_bytes,
|
|
checksum=file.sha1_hash or "",
|
|
)
|
|
|
|
# Format: contentid,flags,name,name2,zrif,url,size,checksum
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgi_item.contentid,
|
|
str(pkgi_item.flags),
|
|
pkgi_item.name,
|
|
pkgi_item.name2,
|
|
pkgi_item.zrif,
|
|
pkgi_item.url,
|
|
str(pkgi_item.size),
|
|
pkgi_item.checksum,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, f"pkgi_{content_type_enum.value}.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgi/psp/{content_type}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {"description": PKGI_CONTENT_TYPE_400},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Portable platform."
|
|
},
|
|
},
|
|
)
|
|
def pkgi_psp_feed(
|
|
request: Request,
|
|
content_type: Annotated[str, PathVar(description="Content type")],
|
|
) -> Response:
|
|
"""Get the PKGi PSP database (https://github.com/bucanero/pkgi-psp) of the PlayStation Portable files of one content type (`game`, `dlc`, `demo`, `update` or `patch`), as text."""
|
|
psp_platform = _visible_platform_by_slug(request, UPS.PSP)
|
|
if not psp_platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Portable platform not found"
|
|
)
|
|
|
|
try:
|
|
content_type_enum = RomFileCategory(content_type)
|
|
content_type_int = CONTENT_TYPE_MAP[content_type_enum]
|
|
except (ValueError, KeyError) as e:
|
|
raise HTTPException(
|
|
status_code=400, detail=f"Invalid content type: {content_type}"
|
|
) from e
|
|
|
|
roms = _platform_roms(request, psp_platform.id, include_files=True)
|
|
txt_lines = []
|
|
|
|
for rom in roms:
|
|
rap_hash, _ = get_rap_data(request, rom)
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, content_type_enum):
|
|
continue
|
|
|
|
content_id = generate_content_id(file)
|
|
download_url = romfile_content_url(request, file)
|
|
|
|
# Validate the item schema
|
|
pkgi_item = PKGiFeedPSPItemSchema(
|
|
contentid=content_id,
|
|
type=content_type_int,
|
|
name=file.file_name_no_tags,
|
|
description="",
|
|
rap=rap_hash,
|
|
url=download_url,
|
|
size=file.file_size_bytes,
|
|
checksum=file.sha1_hash or "",
|
|
)
|
|
|
|
# Format: contentid,type,name,description,rap,url,size,checksum
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgi_item.contentid,
|
|
str(pkgi_item.type),
|
|
pkgi_item.name,
|
|
pkgi_item.description,
|
|
pkgi_item.rap,
|
|
pkgi_item.url,
|
|
str(pkgi_item.size),
|
|
pkgi_item.checksum,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, f"pkgi_{content_type_enum.value}.txt")
|
|
|
|
|
|
def format_release_date(timestamp: int | None) -> str | None:
|
|
"""Format release date to MM-DD-YYYY format"""
|
|
if not timestamp:
|
|
return None
|
|
|
|
return format_utc(timestamp, "%m-%d-%Y")
|
|
|
|
|
|
FPKGI_CATEGORY_LABELS: dict[RomFileCategory, str] = {
|
|
RomFileCategory.GAME: "Game",
|
|
RomFileCategory.DLC: "DLC",
|
|
RomFileCategory.UPDATE: "Update",
|
|
RomFileCategory.PATCH: "Patch",
|
|
RomFileCategory.DEMO: "Demo",
|
|
}
|
|
|
|
|
|
# PS4/PS5 title ids as they appear in package file names, e.g. CUSA12345
|
|
FPKGI_TITLE_ID_REGEX = re.compile(r"(?:CUSA|PPSA)\d{5}", re.IGNORECASE)
|
|
|
|
|
|
def fpkgi_name_candidates(rom_name: str, file: RomFile) -> list[str]:
|
|
"""Names for a package, from the most readable to the most specific."""
|
|
label = FPKGI_CATEGORY_LABELS.get(file.category) if file.category else None
|
|
stem = file.file_name_no_ext
|
|
|
|
candidates = []
|
|
if label:
|
|
candidates.append(f"{rom_name} - {label}")
|
|
candidates.append(f"{rom_name} - {stem}")
|
|
if label:
|
|
candidates.append(f"{rom_name} - {label} - {stem}")
|
|
# Last resort: two categories can hold packages with the same file name
|
|
candidates.append(f"{rom_name} - {stem} ({file.id})")
|
|
return candidates
|
|
|
|
|
|
def fpkgi_item_names(rom: Rom, files: list[RomFile]) -> dict[int, str]:
|
|
"""Name shown in FPKGi per package, keyed by rom file id.
|
|
|
|
FPKGi downloads to `[<title_id>] <name>.pkg`, and packages of a rom share a
|
|
title id, so two of them sharing a name overwrite each other on the console.
|
|
Each package therefore takes the first of its candidate names that no other
|
|
package in the rom lays claim to.
|
|
"""
|
|
rom_name = rom.name or rom.fs_name
|
|
if len(files) == 1:
|
|
return {files[0].id: rom_name}
|
|
|
|
candidates = {f.id: fpkgi_name_candidates(rom_name, f) for f in files}
|
|
claimed = Counter(name for names in candidates.values() for name in names)
|
|
return {
|
|
file_id: next(name for name in names if claimed[name] == 1)
|
|
for file_id, names in candidates.items()
|
|
}
|
|
|
|
|
|
def fpkgi_title_id(rom: Rom, files: list[RomFile]) -> str:
|
|
"""The game's real title id when a file name carries one, else a RomM one.
|
|
|
|
Resolved per rom so a base game and its updates/DLC stay grouped, the way
|
|
FPKGi searches and sorts content.
|
|
"""
|
|
for name in (rom.fs_name, *(file.file_name for file in files)):
|
|
match = FPKGI_TITLE_ID_REGEX.search(name)
|
|
if match:
|
|
return match.group(0).upper()
|
|
|
|
return f"ROMM{str(rom.id)[-5:].zfill(5)}"
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/fpkgi/{platform_slug}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "The content type is not a known file category."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {"description": PLATFORM_SLUG_404},
|
|
},
|
|
)
|
|
def fpkgi_feed(
|
|
request: Request,
|
|
platform_slug: str,
|
|
content_type: Annotated[
|
|
str | None,
|
|
Query(
|
|
description="Only list packages of this category (game, dlc, update, patch, demo)"
|
|
),
|
|
] = None,
|
|
) -> Response:
|
|
"""Get the FPKGi feed (https://github.com/ItsJokerZz/FPKGi) of a platform's `.pkg` files as JSON, usually for `ps4` or `ps5`."""
|
|
platform = _visible_platform_by_slug(request, platform_slug)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail=f"Platform {platform_slug} not found"
|
|
)
|
|
|
|
try:
|
|
category_filter = RomFileCategory(content_type) if content_type else None
|
|
except ValueError as e:
|
|
raise HTTPException(
|
|
status_code=400, detail=f"Invalid content type: {content_type}"
|
|
) from e
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
response_data = {}
|
|
|
|
for rom in roms:
|
|
# FPKGi installs one package per entry, so each .pkg is listed on its own
|
|
pkg_files = [
|
|
f
|
|
for f in rom.files
|
|
if f.file_extension.lower() == "pkg" and not f.missing_from_fs
|
|
]
|
|
title_id = fpkgi_title_id(rom, pkg_files)
|
|
# Named over every package of the rom, not just the filtered ones, so a
|
|
# name means the same thing whichever CONTENT_URLS slot serves it
|
|
item_names = fpkgi_item_names(rom, pkg_files)
|
|
cover_url = (
|
|
str(URLPath(rom.path_cover_large).make_absolute_url(request.base_url))
|
|
if rom.path_cover_large
|
|
else None
|
|
)
|
|
|
|
for file in pkg_files:
|
|
# Files without a category folder are treated as the base game
|
|
category = file.category or RomFileCategory.GAME
|
|
if category_filter and category != category_filter:
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
response_data[download_url] = FPKGiFeedItemSchema(
|
|
name=item_names[file.id],
|
|
size=file.file_size_bytes,
|
|
title_id=title_id,
|
|
region=rom.regions[0] if rom.regions else None,
|
|
version=rom.revision or None,
|
|
release=format_release_date(rom.metadatum.first_release_date),
|
|
min_fw=None,
|
|
cover_url=cover_url,
|
|
).model_dump()
|
|
|
|
return JSONResponse(
|
|
content={"DATA": response_data},
|
|
headers={"Cache-Control": "no-cache"},
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/kekatsu/{platform_slug}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {"description": PLATFORM_SLUG_404}},
|
|
)
|
|
def kekatsu_ds_feed(
|
|
request: Request,
|
|
platform_slug: str,
|
|
) -> Response:
|
|
"""Get the Kekatsu DS database of a platform's roms as tab-separated text, as described at https://github.com/cavv-dev/Kekatsu-DS."""
|
|
platform = _visible_platform_by_slug(request, platform_slug)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail=f"Platform {platform_slug} not found"
|
|
)
|
|
|
|
roms = _platform_roms(request, platform.id)
|
|
|
|
txt_lines = []
|
|
txt_lines.append("1") # Database version
|
|
# Delimiter (cannot use csv (coma) as kekatsu does not support " (double quotes) as a text delimiter)
|
|
txt_lines.append("\t")
|
|
|
|
for rom in roms:
|
|
download_url = rom_content_url(request, rom)
|
|
|
|
# Generate box art URL if cover exists
|
|
box_art_url = ""
|
|
if rom.path_cover_small:
|
|
box_art_url = str(
|
|
URLPath(rom.path_cover_small).make_absolute_url(request.base_url)
|
|
)
|
|
|
|
# Create Kekatsu DS item
|
|
kekatsu_item = KekatsuDSItemSchema(
|
|
title=rom.name or rom.fs_name_no_tags,
|
|
platform=platform.slug,
|
|
region=rom.regions[0] if rom.regions else "ANY",
|
|
version=rom.revision or "1.0.0",
|
|
author="RomM",
|
|
download_url=download_url,
|
|
filename=rom.fs_name,
|
|
size=rom.fs_size_bytes,
|
|
box_art_url=box_art_url,
|
|
)
|
|
|
|
# Format: title platform region version author download_url filename size box_art_url
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
kekatsu_item.title,
|
|
kekatsu_item.platform,
|
|
kekatsu_item.region,
|
|
kekatsu_item.version,
|
|
kekatsu_item.author,
|
|
kekatsu_item.download_url,
|
|
kekatsu_item.filename,
|
|
str(kekatsu_item.size),
|
|
kekatsu_item.box_art_url,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, f"kekatsu_{platform_slug}.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgj/psp/games",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Portable platform."
|
|
}
|
|
},
|
|
)
|
|
def pkgj_psp_games_feed(request: Request) -> Response:
|
|
"""Get the PKGj feed of PlayStation Portable games as tab-separated text."""
|
|
platform = _visible_platform_by_slug(request, UPS.PSP)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Portable platform not found"
|
|
)
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
txt_lines = []
|
|
txt_lines.append(
|
|
"Title ID\tRegion\tType\tName\tPKG direct link\tContent ID\tLast Modification Date\tRAP\tDownload .RAP file\tFile Size\tSHA256"
|
|
)
|
|
|
|
for rom in roms:
|
|
rap_hash, rap_download_url = get_rap_data(request, rom)
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
content_id = generate_content_id(file)
|
|
last_modified = format_pkgj_datetime(file.updated_at)
|
|
|
|
pkgj_item = PkgjPSPGamesItemSchema(
|
|
title_id="",
|
|
region=rom.regions[0] if rom.regions else "",
|
|
type="PSP",
|
|
name=(file.file_name_no_tags).strip(),
|
|
download_link=download_url,
|
|
content_id=content_id,
|
|
last_modified=last_modified,
|
|
rap=rap_hash,
|
|
download_rap_file=rap_download_url,
|
|
file_size=file.file_size_bytes,
|
|
sha_256=file.sha1_hash or "",
|
|
)
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgj_item.title_id,
|
|
pkgj_item.region,
|
|
pkgj_item.type,
|
|
pkgj_item.name,
|
|
pkgj_item.download_link,
|
|
pkgj_item.content_id,
|
|
pkgj_item.last_modified,
|
|
pkgj_item.rap,
|
|
pkgj_item.download_rap_file,
|
|
str(pkgj_item.file_size),
|
|
pkgj_item.sha_256,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, "pkgj_psp_games.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgj/psp/dlc",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Portable platform."
|
|
}
|
|
},
|
|
)
|
|
def pkgj_psp_dlcs_feed(request: Request) -> Response:
|
|
"""Get the PKGj feed of PlayStation Portable DLC as tab-separated text."""
|
|
platform = _visible_platform_by_slug(request, UPS.PSP)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Portable platform not found"
|
|
)
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
txt_lines = []
|
|
txt_lines.append(
|
|
"Title ID\tRegion\tName\tPKG direct link\tContent ID\tLast Modification Date\tRAP\tDownload .RAP file\tFile Size\tSHA256"
|
|
)
|
|
|
|
for rom in roms:
|
|
rap_hash, rap_download_url = get_rap_data(request, rom)
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, RomFileCategory.DLC):
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
content_id = generate_content_id(file)
|
|
last_modified = format_pkgj_datetime(file.updated_at)
|
|
|
|
pkgj_item = PkgjPSPDlcsItemSchema(
|
|
title_id="",
|
|
region=rom.regions[0] if rom.regions else "",
|
|
name=(file.file_name_no_tags).strip(),
|
|
download_link=download_url,
|
|
content_id=content_id,
|
|
last_modified=last_modified,
|
|
rap=rap_hash,
|
|
download_rap_file=rap_download_url,
|
|
file_size=file.file_size_bytes,
|
|
sha_256=file.sha1_hash or "",
|
|
)
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgj_item.title_id,
|
|
pkgj_item.region,
|
|
pkgj_item.name,
|
|
pkgj_item.download_link,
|
|
pkgj_item.content_id,
|
|
pkgj_item.last_modified,
|
|
pkgj_item.rap,
|
|
pkgj_item.download_rap_file,
|
|
str(pkgj_item.file_size),
|
|
pkgj_item.sha_256,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, "pkgj_psp_dlc.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgj/psvita/games",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Vita platform."
|
|
}
|
|
},
|
|
)
|
|
def pkgj_psv_games_feed(request: Request) -> Response:
|
|
"""Get the PKGj feed of PlayStation Vita games as tab-separated text."""
|
|
platform = _visible_platform_by_slug(request, UPS.PSVITA)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Vita platform not found"
|
|
)
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
txt_lines = []
|
|
txt_lines.append(
|
|
"Title ID\tRegion\tName\tPKG direct link\tzRIF\tContent ID\tLast Modification Date\tOriginal Name\tFile Size\tSHA256\tRequired FW\tApp Version"
|
|
)
|
|
|
|
for rom in roms:
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
content_id = generate_content_id(file)
|
|
last_modified = format_pkgj_datetime(file.updated_at)
|
|
|
|
pkgj_item = PkgjPSVGamesItemSchema(
|
|
title_id="",
|
|
region=rom.regions[0] if rom.regions else "",
|
|
name=(file.file_name_no_tags).strip(),
|
|
download_link=download_url,
|
|
zrif="",
|
|
content_id=content_id,
|
|
last_modified=last_modified,
|
|
original_name="",
|
|
file_size=file.file_size_bytes,
|
|
sha_256=file.sha1_hash or "",
|
|
required_fw="",
|
|
app_version="",
|
|
)
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgj_item.title_id,
|
|
pkgj_item.region,
|
|
pkgj_item.name,
|
|
pkgj_item.download_link,
|
|
pkgj_item.zrif,
|
|
pkgj_item.content_id,
|
|
pkgj_item.last_modified,
|
|
pkgj_item.original_name,
|
|
str(pkgj_item.file_size),
|
|
pkgj_item.sha_256,
|
|
pkgj_item.required_fw,
|
|
pkgj_item.app_version,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, "pkgj_psvita_games.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgj/psvita/dlc",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation Vita platform."
|
|
}
|
|
},
|
|
)
|
|
def pkgj_psv_dlcs_feed(request: Request) -> Response:
|
|
"""Get the PKGj feed of PlayStation Vita DLC as tab-separated text."""
|
|
platform = _visible_platform_by_slug(request, UPS.PSVITA)
|
|
if not platform:
|
|
raise HTTPException(
|
|
status_code=404, detail="PlayStation Vita platform not found"
|
|
)
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
txt_lines = []
|
|
txt_lines.append(
|
|
"Title ID\tRegion\tName\tPKG direct link\tzRIF\tContent ID\tLast Modification Date\tFile Size\tSHA256"
|
|
)
|
|
|
|
for rom in roms:
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, RomFileCategory.DLC):
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
content_id = generate_content_id(file)
|
|
last_modified = format_pkgj_datetime(file.updated_at)
|
|
|
|
pkgj_item = PkgjPSVDlcsItemSchema(
|
|
title_id="",
|
|
region=rom.regions[0] if rom.regions else "",
|
|
name=(file.file_name_no_tags).strip(),
|
|
download_link=download_url,
|
|
zrif="",
|
|
content_id=content_id,
|
|
last_modified=last_modified,
|
|
file_size=file.file_size_bytes,
|
|
sha_256=file.sha1_hash or "",
|
|
)
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgj_item.title_id,
|
|
pkgj_item.region,
|
|
pkgj_item.name,
|
|
pkgj_item.download_link,
|
|
pkgj_item.zrif,
|
|
pkgj_item.content_id,
|
|
pkgj_item.last_modified,
|
|
str(pkgj_item.file_size),
|
|
pkgj_item.sha_256,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, "pkgj_psvita_dlc.txt")
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/pkgj/psx/games",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The library has no PlayStation platform."
|
|
}
|
|
},
|
|
)
|
|
def pkgj_psx_games_feed(request: Request) -> Response:
|
|
"""Get the PKGj feed of PlayStation games as tab-separated text."""
|
|
platform = _visible_platform_by_slug(request, UPS.PSX)
|
|
if not platform:
|
|
raise HTTPException(status_code=404, detail="PlayStation platform not found")
|
|
|
|
roms = _platform_roms(request, platform.id, include_files=True)
|
|
txt_lines = []
|
|
txt_lines.append(
|
|
"Title ID\tRegion\tName\tPKG direct link\tContent ID\tLast Modification Date\tOriginal Name\tFile Size\tSHA256"
|
|
)
|
|
|
|
for rom in roms:
|
|
for file in rom.files:
|
|
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
|
continue
|
|
|
|
download_url = romfile_content_url(request, file)
|
|
content_id = generate_content_id(file)
|
|
last_modified = format_pkgj_datetime(file.updated_at)
|
|
|
|
pkgj_item = PkgjPSXGamesItemSchema(
|
|
title_id="",
|
|
region=rom.regions[0] if rom.regions else "",
|
|
name=(file.file_name_no_tags).strip(),
|
|
download_link=download_url,
|
|
content_id=content_id,
|
|
last_modified=last_modified,
|
|
original_name="",
|
|
file_size=file.file_size_bytes,
|
|
sha_256=file.sha1_hash or "",
|
|
)
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter="\t", quoting=csv.QUOTE_MINIMAL)
|
|
writer.writerow(
|
|
[
|
|
pkgj_item.title_id,
|
|
pkgj_item.region,
|
|
pkgj_item.name,
|
|
pkgj_item.download_link,
|
|
pkgj_item.content_id,
|
|
pkgj_item.last_modified,
|
|
pkgj_item.original_name,
|
|
str(pkgj_item.file_size),
|
|
pkgj_item.sha_256,
|
|
]
|
|
)
|
|
txt_lines.append(output.getvalue().strip())
|
|
|
|
return text_response(txt_lines, "pkgj_psx_games.txt")
|