mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 21:02:21 +01:00
Merge pull request #1369 from rommapp/rom-hashing-background-task
Rom file and hashing refactor
This commit is contained in:
@@ -2,41 +2,41 @@
|
||||
# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml
|
||||
version: 0.1
|
||||
cli:
|
||||
version: 1.22.8
|
||||
version: 1.22.9
|
||||
# Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins)
|
||||
plugins:
|
||||
sources:
|
||||
- id: trunk
|
||||
ref: v1.6.5
|
||||
ref: v1.6.6
|
||||
uri: https://github.com/trunk-io/plugins
|
||||
# Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes)
|
||||
runtimes:
|
||||
enabled:
|
||||
- go@1.21.0
|
||||
- node@18.12.1
|
||||
- node@18.20.5
|
||||
- python@3.12.2
|
||||
# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration)
|
||||
lint:
|
||||
enabled:
|
||||
- markdownlint@0.43.0
|
||||
- eslint@9.16.0
|
||||
- actionlint@1.7.4
|
||||
- bandit@1.8.0
|
||||
- eslint@9.18.0
|
||||
- actionlint@1.7.7
|
||||
- bandit@1.8.2
|
||||
- black@24.10.0
|
||||
- checkov@3.2.332
|
||||
- checkov@3.2.357
|
||||
- git-diff-check
|
||||
- isort@5.13.2
|
||||
- mypy@1.13.0
|
||||
- osv-scanner@1.9.1
|
||||
- mypy@1.14.1
|
||||
- osv-scanner@1.9.2
|
||||
- oxipng@9.1.3
|
||||
- prettier@3.4.2
|
||||
- ruff@0.8.2
|
||||
- ruff@0.9.3
|
||||
- shellcheck@0.10.0
|
||||
- shfmt@3.6.0
|
||||
- svgo@3.3.2
|
||||
- taplo@0.9.3
|
||||
- trivy@0.56.2
|
||||
- trufflehog@3.85.0
|
||||
- trivy@0.58.2
|
||||
- trufflehog@3.88.2
|
||||
- yamllint@1.35.1
|
||||
ignore:
|
||||
- linters: [ALL]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""platforms_custom_name
|
||||
|
||||
Revision ID: fc3783d35bdb
|
||||
Revision ID: 0029_platforms_custom_name
|
||||
Revises: 0028_user_email
|
||||
Create Date: 2024-12-24 01:32:57.121432
|
||||
|
||||
|
||||
208
backend/alembic/versions/0033_rom_file_and_hashes.py
Normal file
208
backend/alembic/versions/0033_rom_file_and_hashes.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0033_rom_file_and_hashes
|
||||
Revises: 0032_longer_fs_fields
|
||||
Create Date: 2024-12-19 23:16:11.053536
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from config import IS_PYTEST_RUN, SCAN_TIMEOUT
|
||||
from endpoints.sockets.scan import scan_platforms
|
||||
from handler.redis_handler import high_prio_queue
|
||||
from handler.scan_handler import ScanType
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0033_rom_file_and_hashes"
|
||||
down_revision = "0032_longer_fs_fields"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"rom_files",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("rom_id", sa.Integer(), nullable=False),
|
||||
sa.Column("file_name", sa.String(length=450), nullable=False),
|
||||
sa.Column("file_path", sa.String(length=1000), nullable=False),
|
||||
sa.Column("file_size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("last_modified", sa.Float(), nullable=True),
|
||||
sa.Column("crc_hash", sa.String(length=100), nullable=True),
|
||||
sa.Column("md5_hash", sa.String(length=100), nullable=True),
|
||||
sa.Column("sha1_hash", sa.String(length=100), nullable=True),
|
||||
sa.Column(
|
||||
"category",
|
||||
sa.Enum(
|
||||
"DLC",
|
||||
"HACK",
|
||||
"MANUAL",
|
||||
"PATCH",
|
||||
"UPDATE",
|
||||
"MOD",
|
||||
"DEMO",
|
||||
"TRANSLATION",
|
||||
"PROTOTYPE",
|
||||
name="romfilecategory",
|
||||
),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO rom_files (
|
||||
rom_id,
|
||||
file_name,
|
||||
file_path,
|
||||
file_size_bytes,
|
||||
last_modified,
|
||||
crc_hash,
|
||||
md5_hash,
|
||||
sha1_hash
|
||||
)
|
||||
SELECT
|
||||
r.id AS rom_id,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.filename')) AS file_name,
|
||||
CASE WHEN r.multi = 0 THEN r.file_path ELSE CONCAT(r.file_path, r.file_name) END AS file_path,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.size')) AS file_size_bytes,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.last_modified')) AS last_modified,
|
||||
CASE WHEN r.multi = 0 THEN r.crc_hash ELSE NULL END AS crc_hash,
|
||||
CASE WHEN r.multi = 0 THEN r.md5_hash ELSE NULL END AS md5_hash,
|
||||
CASE WHEN r.multi = 0 THEN r.sha1_hash ELSE NULL END AS sha1_hash
|
||||
FROM roms r,
|
||||
JSON_TABLE(r.files, '$[*]'
|
||||
COLUMNS (
|
||||
file_data JSON PATH '$'
|
||||
)
|
||||
) AS extracted_files;
|
||||
"""
|
||||
)
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"file_name", new_column_name="fs_name", existing_type=sa.String(length=450)
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"file_name_no_tags",
|
||||
new_column_name="fs_name_no_tags",
|
||||
existing_type=sa.String(length=450),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"file_name_no_ext",
|
||||
new_column_name="fs_name_no_ext",
|
||||
existing_type=sa.String(length=450),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"file_extension",
|
||||
new_column_name="fs_extension",
|
||||
existing_type=sa.String(length=100),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"file_path", new_column_name="fs_path", existing_type=sa.String(length=1000)
|
||||
)
|
||||
batch_op.drop_column("files")
|
||||
batch_op.drop_column("multi")
|
||||
batch_op.drop_column("file_size_bytes")
|
||||
|
||||
# Run a no-scan in the background on migrate
|
||||
if not IS_PYTEST_RUN:
|
||||
high_prio_queue.enqueue(
|
||||
scan_platforms, [], ScanType.QUICK, [], [], job_timeout=SCAN_TIMEOUT
|
||||
)
|
||||
|
||||
high_prio_queue.enqueue(
|
||||
scan_platforms, [], ScanType.HASHES, [], [], job_timeout=SCAN_TIMEOUT
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"multi",
|
||||
mysql.TINYINT(display_width=1),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
)
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"files",
|
||||
mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"file_size_bytes",
|
||||
mysql.BIGINT(display_width=20),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
)
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_path", new_column_name="file_path", existing_type=sa.String(length=1000)
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_extension",
|
||||
new_column_name="file_extension",
|
||||
existing_type=sa.String(length=100),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_ext",
|
||||
new_column_name="file_name_no_ext",
|
||||
existing_type=sa.String(length=450),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_tags",
|
||||
new_column_name="file_name_no_tags",
|
||||
existing_type=sa.String(length=450),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name", new_column_name="file_name", existing_type=sa.String(length=450)
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE roms
|
||||
JOIN (
|
||||
SELECT
|
||||
rom_id,
|
||||
JSON_ARRAYAGG(
|
||||
JSON_OBJECT(
|
||||
'filename', file_name,
|
||||
'size', file_size_bytes,
|
||||
'last_modified', last_modified
|
||||
)
|
||||
) AS files,
|
||||
COUNT(*) > 1 AS multi,
|
||||
COALESCE(SUM(file_size_bytes), 0) AS total_size
|
||||
FROM rom_files
|
||||
GROUP BY rom_id
|
||||
) AS aggregated_data
|
||||
ON roms.id = aggregated_data.rom_id
|
||||
SET
|
||||
roms.files = aggregated_data.files,
|
||||
roms.multi = aggregated_data.multi,
|
||||
roms.file_size_bytes = aggregated_data.total_size;
|
||||
"""
|
||||
)
|
||||
|
||||
op.drop_table("rom_files")
|
||||
@@ -109,15 +109,14 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Missing refresh token"
|
||||
)
|
||||
|
||||
potential_user = await oauth_handler.get_current_active_user_from_bearer_token(
|
||||
user, claims = await oauth_handler.get_current_active_user_from_bearer_token(
|
||||
token
|
||||
)
|
||||
if not potential_user:
|
||||
if not user or not claims:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
|
||||
)
|
||||
|
||||
user, claims = potential_user
|
||||
if claims.get("type") != "refresh":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
|
||||
|
||||
@@ -57,7 +57,7 @@ async def add_collection(
|
||||
|
||||
_added_collection = db_collection_handler.add_collection(Collection(**cleaned_data))
|
||||
|
||||
if artwork is not None:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
(
|
||||
path_cover_l,
|
||||
@@ -82,8 +82,9 @@ async def add_collection(
|
||||
|
||||
_added_collection.path_cover_s = path_cover_s
|
||||
_added_collection.path_cover_l = path_cover_l
|
||||
|
||||
# Update the collection with the cover path and update database
|
||||
return db_collection_handler.update_collection(
|
||||
created_collection = db_collection_handler.update_collection(
|
||||
_added_collection.id,
|
||||
{
|
||||
c: getattr(_added_collection, c)
|
||||
@@ -91,6 +92,8 @@ async def add_collection(
|
||||
},
|
||||
)
|
||||
|
||||
return CollectionSchema.model_validate(created_collection)
|
||||
|
||||
|
||||
@protected_route(router.get, "/collections", [Scope.COLLECTIONS_READ])
|
||||
def get_collections(request: Request) -> list[CollectionSchema]:
|
||||
@@ -105,7 +108,7 @@ def get_collections(request: Request) -> list[CollectionSchema]:
|
||||
"""
|
||||
|
||||
collections = db_collection_handler.get_collections()
|
||||
return CollectionSchema.for_user(request.user.id, collections)
|
||||
return CollectionSchema.for_user(request.user.id, [c for c in collections])
|
||||
|
||||
|
||||
@protected_route(router.get, "/collections/{id}", [Scope.COLLECTIONS_READ])
|
||||
@@ -125,7 +128,7 @@ def get_collection(request: Request, id: int) -> CollectionSchema:
|
||||
if not collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
return collection
|
||||
return CollectionSchema.model_validate(collection)
|
||||
|
||||
|
||||
@protected_route(router.put, "/collections/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
@@ -148,6 +151,8 @@ async def update_collection(
|
||||
data = await request.form()
|
||||
|
||||
collection = db_collection_handler.get_collection(id)
|
||||
if not collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
if collection.user_id != request.user.id:
|
||||
raise CollectionPermissionError(id)
|
||||
@@ -156,7 +161,7 @@ async def update_collection(
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
try:
|
||||
roms = json.loads(data["roms"])
|
||||
roms = json.loads(data["roms"]) # type: ignore
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError("Invalid list for roms field in update collection") from e
|
||||
except KeyError:
|
||||
@@ -174,7 +179,7 @@ async def update_collection(
|
||||
cleaned_data.update(fs_resource_handler.remove_cover(collection))
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
else:
|
||||
if artwork is not None:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
(
|
||||
path_cover_l,
|
||||
@@ -205,13 +210,15 @@ async def update_collection(
|
||||
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
||||
overwrite=True,
|
||||
entity=collection,
|
||||
url_cover=data.get("url_cover", ""),
|
||||
url_cover=data.get("url_cover", ""), # type: ignore
|
||||
)
|
||||
cleaned_data.update(
|
||||
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
|
||||
)
|
||||
|
||||
return db_collection_handler.update_collection(id, cleaned_data)
|
||||
updated_collection = db_collection_handler.update_collection(id, cleaned_data)
|
||||
|
||||
return CollectionSchema.model_validate(updated_collection)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/collections/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Sequence
|
||||
|
||||
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.feeds import (
|
||||
@@ -57,7 +59,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
request.url_for(
|
||||
"get_rom_content",
|
||||
id=rom.id,
|
||||
file_name=rom.file_name,
|
||||
file_name=rom.fs_name,
|
||||
)
|
||||
),
|
||||
),
|
||||
@@ -130,15 +132,17 @@ async def tinfoil_index_feed(
|
||||
error="Nintendo Switch platform not found",
|
||||
)
|
||||
|
||||
roms: list[Rom] = db_rom_handler.get_roms(platform_id=switch.id)
|
||||
roms = db_rom_handler.get_roms(platform_id=switch.id)
|
||||
|
||||
async def extract_titledb(roms: list[Rom]) -> dict[str, TinfoilFeedTitleDBSchema]:
|
||||
async def extract_titledb(
|
||||
roms: Sequence[Rom],
|
||||
) -> dict[str, TinfoilFeedTitleDBSchema]:
|
||||
titledb = {}
|
||||
for rom in roms:
|
||||
match = SWITCH_TITLEDB_REGEX.search(rom.file_name)
|
||||
match = SWITCH_TITLEDB_REGEX.search(rom.fs_name)
|
||||
if match:
|
||||
_search_term, index_entry = (
|
||||
await meta_igdb_handler._switch_titledb_format(match, rom.file_name)
|
||||
await meta_igdb_handler._switch_titledb_format(match, rom.fs_name)
|
||||
)
|
||||
if index_entry:
|
||||
titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema(
|
||||
@@ -160,11 +164,9 @@ async def tinfoil_index_feed(
|
||||
files=[
|
||||
TinfoilFeedFileSchema(
|
||||
url=str(
|
||||
request.url_for(
|
||||
"get_rom_content", id=rom.id, file_name=rom.file_name
|
||||
)
|
||||
request.url_for("get_rom_content", id=rom.id, file_name=rom.fs_name)
|
||||
),
|
||||
size=rom.file_size_bytes,
|
||||
size=rom.fs_size_bytes,
|
||||
)
|
||||
for rom in roms
|
||||
],
|
||||
|
||||
@@ -28,25 +28,28 @@ def add_firmware(
|
||||
files (list[UploadFile], optional): List of files to upload
|
||||
|
||||
Raises:
|
||||
HTTPException: No files were uploaded
|
||||
HTTPException
|
||||
|
||||
Returns:
|
||||
AddFirmwareResponse: Standard message response
|
||||
"""
|
||||
|
||||
db_platform = db_platform_handler.get_platform(platform_id)
|
||||
if not db_platform:
|
||||
error = f"Platform with ID {platform_id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
log.info(f"Uploading firmware to {db_platform.fs_slug}")
|
||||
if files is None:
|
||||
log.error("No files were uploaded")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="No files were uploaded",
|
||||
)
|
||||
|
||||
uploaded_firmware = []
|
||||
firmware_path = fs_firmware_handler.build_upload_file_path(db_platform.fs_slug)
|
||||
|
||||
for file in files:
|
||||
if not file.filename:
|
||||
log.warning("Empty filename, skipping")
|
||||
continue
|
||||
|
||||
fs_firmware_handler.write_file(file=file, path=firmware_path)
|
||||
|
||||
db_firmware = db_firmware_handler.get_firmware_by_filename(
|
||||
@@ -69,11 +72,12 @@ def add_firmware(
|
||||
db_firmware_handler.add_firmware(scanned_firmware)
|
||||
uploaded_firmware.append(scanned_firmware)
|
||||
|
||||
db_platform = db_platform_handler.get_platform(platform_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(files),
|
||||
"firmware": db_platform.firmware,
|
||||
"firmware": [
|
||||
FirmwareSchema.model_validate(f)
|
||||
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +94,10 @@ def get_platform_firmware(
|
||||
Returns:
|
||||
list[FirmwareSchema]: Firmware stored in the database
|
||||
"""
|
||||
return db_firmware_handler.list_firmware(platform_id=platform_id)
|
||||
return [
|
||||
FirmwareSchema.model_validate(f)
|
||||
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
|
||||
]
|
||||
|
||||
|
||||
@protected_route(
|
||||
@@ -108,7 +115,13 @@ def get_firmware(request: Request, id: int) -> FirmwareSchema:
|
||||
Returns:
|
||||
FirmwareSchema: Firmware stored in the database
|
||||
"""
|
||||
return FirmwareSchema(**db_firmware_handler.get_firmware(id))
|
||||
firmware = db_firmware_handler.get_firmware(id)
|
||||
if not firmware:
|
||||
error = f"Firmware with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
return FirmwareSchema.model_validate(firmware)
|
||||
|
||||
|
||||
@protected_route(
|
||||
@@ -129,6 +142,11 @@ def head_firmware_content(request: Request, id: int, file_name: str):
|
||||
"""
|
||||
|
||||
firmware = db_firmware_handler.get_firmware(id)
|
||||
if not firmware:
|
||||
error = f"Firmware with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
|
||||
|
||||
return FileResponse(
|
||||
@@ -162,6 +180,11 @@ def get_firmware_content(
|
||||
"""
|
||||
|
||||
firmware = db_firmware_handler.get_firmware(id)
|
||||
if not firmware:
|
||||
error = f"Firmware with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
|
||||
|
||||
return FileResponse(path=firmware_path, filename=firmware.file_name)
|
||||
|
||||
@@ -12,7 +12,6 @@ from handler.filesystem import fs_platform_handler
|
||||
from handler.metadata.igdb_handler import IGDB_PLATFORM_LIST
|
||||
from handler.scan_handler import scan_platform
|
||||
from logger.logger import log
|
||||
from models.platform import Platform
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
@@ -36,7 +35,9 @@ async def add_platforms(request: Request) -> PlatformSchema:
|
||||
except PlatformAlreadyExistsException:
|
||||
log.info(f"Detected platform: {fs_slug}")
|
||||
scanned_platform = await scan_platform(fs_slug, [fs_slug])
|
||||
return db_platform_handler.add_platform(scanned_platform)
|
||||
return PlatformSchema.model_validate(
|
||||
db_platform_handler.add_platform(scanned_platform)
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/platforms", [Scope.PLATFORMS_READ])
|
||||
@@ -51,7 +52,9 @@ def get_platforms(request: Request) -> list[PlatformSchema]:
|
||||
list[PlatformSchema]: List of platforms
|
||||
"""
|
||||
|
||||
return db_platform_handler.get_platforms()
|
||||
return [
|
||||
PlatformSchema.model_validate(p) for p in db_platform_handler.get_platforms()
|
||||
]
|
||||
|
||||
|
||||
@protected_route(router.get, "/platforms/supported", [Scope.PLATFORMS_READ])
|
||||
@@ -66,7 +69,7 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
|
||||
"""
|
||||
|
||||
supported_platforms = []
|
||||
db_platforms: list[Platform] = db_platform_handler.get_platforms()
|
||||
db_platforms = db_platform_handler.get_platforms()
|
||||
db_platforms_map = {p.name: p.id for p in db_platforms}
|
||||
|
||||
for platform in IGDB_PLATFORM_LIST:
|
||||
@@ -108,7 +111,7 @@ def get_platform(request: Request, id: int) -> PlatformSchema:
|
||||
if not platform:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
|
||||
return platform
|
||||
return PlatformSchema.model_validate(platform)
|
||||
|
||||
|
||||
@protected_route(router.put, "/platforms/{id}", [Scope.PLATFORMS_WRITE])
|
||||
@@ -132,7 +135,7 @@ async def update_platform(request: Request, id: int) -> PlatformSchema:
|
||||
platform_db.custom_name = data.get("custom_name", platform_db.custom_name)
|
||||
platform_db = db_platform_handler.add_platform(platform_db)
|
||||
|
||||
return platform_db
|
||||
return PlatformSchema.model_validate(platform_db)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/platforms/{id}", [Scope.PLATFORMS_WRITE])
|
||||
|
||||
@@ -9,7 +9,7 @@ from endpoints.responses.collection import CollectionSchema
|
||||
from fastapi import Request
|
||||
from handler.metadata.igdb_handler import IGDBMetadata
|
||||
from handler.metadata.moby_handler import MobyMetadata
|
||||
from models.rom import Rom, RomFile, RomUserStatus
|
||||
from models.rom import Rom, RomFileCategory, RomUserStatus
|
||||
from pydantic import computed_field
|
||||
|
||||
from .base import BaseModel
|
||||
@@ -18,12 +18,12 @@ SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s")
|
||||
|
||||
RomIGDBMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomIGDBMetadata",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(IGDBMetadata).items()},
|
||||
dict((k, NotRequired[v]) for k, v in get_type_hints(IGDBMetadata).items()),
|
||||
total=False,
|
||||
)
|
||||
RomMobyMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomMobyMetadata",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(MobyMetadata).items()},
|
||||
dict((k, NotRequired[v]) for k, v in get_type_hints(MobyMetadata).items()),
|
||||
total=False,
|
||||
)
|
||||
|
||||
@@ -96,6 +96,25 @@ class RomUserSchema(BaseModel):
|
||||
]
|
||||
|
||||
|
||||
class RomFileSchema(BaseModel):
|
||||
id: int
|
||||
rom_id: int
|
||||
file_name: str
|
||||
file_path: str
|
||||
file_size_bytes: int
|
||||
full_path: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
last_modified: datetime
|
||||
crc_hash: str | None
|
||||
md5_hash: str | None
|
||||
sha1_hash: str | None
|
||||
category: RomFileCategory | None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RomSchema(BaseModel):
|
||||
id: int
|
||||
igdb_id: int | None
|
||||
@@ -109,12 +128,12 @@ class RomSchema(BaseModel):
|
||||
platform_custom_name: str | None
|
||||
platform_display_name: str
|
||||
|
||||
file_name: str
|
||||
file_name_no_tags: str
|
||||
file_name_no_ext: str
|
||||
file_extension: str
|
||||
file_path: str
|
||||
file_size_bytes: int
|
||||
fs_name: str
|
||||
fs_name_no_tags: str
|
||||
fs_name_no_ext: str
|
||||
fs_extension: str
|
||||
fs_path: str
|
||||
fs_size_bytes: int
|
||||
|
||||
name: str | None
|
||||
slug: str | None
|
||||
@@ -144,11 +163,12 @@ class RomSchema(BaseModel):
|
||||
languages: list[str]
|
||||
tags: list[str]
|
||||
|
||||
multi: bool
|
||||
files: list[RomFile]
|
||||
crc_hash: str | None
|
||||
md5_hash: str | None
|
||||
sha1_hash: str | None
|
||||
|
||||
multi: bool
|
||||
files: list[RomFileSchema]
|
||||
full_path: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
@@ -162,7 +182,7 @@ class RomSchema(BaseModel):
|
||||
return (
|
||||
SORT_COMPARE_REGEX.sub(
|
||||
"",
|
||||
self.name or self.file_name_no_tags,
|
||||
self.name or self.fs_name_no_tags,
|
||||
)
|
||||
.strip()
|
||||
.lower()
|
||||
@@ -176,15 +196,12 @@ class SimpleRomSchema(RomSchema):
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> SimpleRomSchema:
|
||||
user_id = request.user.id
|
||||
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
|
||||
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # type: ignore
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_factory(cls, db_rom: Rom) -> SimpleRomSchema:
|
||||
db_rom.rom_user = rom_user_schema_factory()
|
||||
|
||||
db_rom.rom_user = rom_user_schema_factory() # type: ignore
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
|
||||
@@ -202,21 +219,21 @@ class DetailedRomSchema(RomSchema):
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
|
||||
user_id = request.user.id
|
||||
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
|
||||
db_rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom)
|
||||
db_rom.user_saves = [
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # type: ignore
|
||||
db_rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom) # type: ignore
|
||||
db_rom.user_saves = [ # type: ignore
|
||||
SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id
|
||||
]
|
||||
db_rom.user_states = [
|
||||
db_rom.user_states = [ # type: ignore
|
||||
StateSchema.model_validate(s) for s in db_rom.states if s.user_id == user_id
|
||||
]
|
||||
db_rom.user_screenshots = [
|
||||
db_rom.user_screenshots = [ # type: ignore
|
||||
ScreenshotSchema.model_validate(s)
|
||||
for s in db_rom.screenshots
|
||||
if s.user_id == user_id
|
||||
]
|
||||
db_rom.user_collections = CollectionSchema.for_user(
|
||||
user_id, db_rom.get_collections()
|
||||
db_rom.user_collections = CollectionSchema.for_user( # type: ignore
|
||||
user_id, [c for c in db_rom.get_collections()]
|
||||
)
|
||||
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@@ -3,7 +3,7 @@ from base64 import b64encode
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
from shutil import rmtree
|
||||
from typing import Annotated
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from anyio import Path
|
||||
@@ -18,7 +18,7 @@ from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.rom import DetailedRomSchema, RomUserSchema, SimpleRomSchema
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from fastapi import HTTPException, Query, Request, UploadFile, status
|
||||
from fastapi import HTTPException, Request, UploadFile, status
|
||||
from fastapi.responses import Response
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_collection_handler, db_platform_handler, db_rom_handler
|
||||
@@ -66,7 +66,7 @@ async def add_rom(request: Request):
|
||||
) from None
|
||||
|
||||
platform_fs_slug = db_platform.fs_slug
|
||||
roms_path = fs_rom_handler.build_upload_file_path(platform_fs_slug)
|
||||
roms_path = fs_rom_handler.build_upload_fs_path(platform_fs_slug)
|
||||
log.info(f"Uploading file to {platform_fs_slug}")
|
||||
|
||||
file_location = Path(f"{roms_path}/{filename}")
|
||||
@@ -194,14 +194,15 @@ async def head_rom_content(
|
||||
request: Request,
|
||||
id: int,
|
||||
file_name: str,
|
||||
files: Annotated[list[str] | None, Query()] = None,
|
||||
file_ids: list[int] | None = None,
|
||||
):
|
||||
"""Head rom content endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Rom internal id
|
||||
file_name (str): Required due to a bug in emulatorjs
|
||||
file_name (str): File name to download
|
||||
file_ids (list[int]): List of file ids to download for multi-part roms
|
||||
|
||||
Returns:
|
||||
FileResponse: Returns the response with headers
|
||||
@@ -212,30 +213,32 @@ async def head_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
|
||||
files_to_check = files or [r["filename"] for r in rom.files]
|
||||
file_ids = file_ids or []
|
||||
files = db_rom_handler.get_rom_files(rom.id)
|
||||
files = [f for f in files if f.id in file_ids or not file_ids]
|
||||
|
||||
if not rom.multi:
|
||||
# Serve the file directly in development mode for emulatorjs
|
||||
if DEV_MODE:
|
||||
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
|
||||
return FileResponse(
|
||||
path=rom_path,
|
||||
filename=rom.file_name,
|
||||
filename=rom.fs_name,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"',
|
||||
"Content-Disposition": f'attachment; filename="{quote(rom.fs_name)}"',
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Length": str(rom.file_size_bytes),
|
||||
"Content-Length": str(rom.fs_size_bytes),
|
||||
},
|
||||
)
|
||||
|
||||
return FileRedirectResponse(
|
||||
download_path=Path(f"/library/{rom.full_path}"),
|
||||
filename=rom.file_name,
|
||||
filename=rom.fs_name,
|
||||
)
|
||||
|
||||
if len(files_to_check) == 1:
|
||||
if len(files) == 1:
|
||||
return FileRedirectResponse(
|
||||
download_path=Path(f"/library/{rom.full_path}/{files_to_check[0]}"),
|
||||
download_path=Path(f"/library/{files[0].full_path}"),
|
||||
)
|
||||
|
||||
return Response(
|
||||
@@ -255,14 +258,15 @@ async def get_rom_content(
|
||||
request: Request,
|
||||
id: int,
|
||||
file_name: str,
|
||||
files: Annotated[list[str] | None, Query()] = None,
|
||||
file_ids: list[int] | None = None,
|
||||
):
|
||||
"""Download rom endpoint (one single file or multiple zipped files for multi-part roms)
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Rom internal id
|
||||
files (Annotated[list[str] | None, Query, optional): List of files to download for multi-part roms. Defaults to None.
|
||||
file_name: Zip file output name
|
||||
file_ids (list[int]): List of file ids to download for multi-part roms
|
||||
|
||||
Returns:
|
||||
FileResponse: Returns one file for single file roms
|
||||
@@ -277,46 +281,49 @@ async def get_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
|
||||
files_to_download = sorted(files or [r["filename"] for r in rom.files])
|
||||
file_ids = file_ids or []
|
||||
files = db_rom_handler.get_rom_files(rom.id)
|
||||
files = [f for f in files if f.id in file_ids or not file_ids]
|
||||
|
||||
log.info(f"User {current_username} is downloading {rom.file_name}")
|
||||
log.info(f"User {current_username} is downloading {rom.fs_name}")
|
||||
|
||||
if not rom.multi:
|
||||
# Serve the file directly in development mode for emulatorjs
|
||||
if DEV_MODE:
|
||||
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
|
||||
return FileResponse(
|
||||
path=rom_path,
|
||||
filename=rom.file_name,
|
||||
filename=rom.fs_name,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"',
|
||||
"Content-Disposition": f'attachment; filename="{quote(rom.fs_name)}"',
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Length": str(rom.file_size_bytes),
|
||||
"Content-Length": str(rom.fs_size_bytes),
|
||||
},
|
||||
)
|
||||
|
||||
return FileRedirectResponse(
|
||||
download_path=Path(f"/library/{rom.full_path}"),
|
||||
filename=rom.file_name,
|
||||
filename=rom.fs_name,
|
||||
)
|
||||
|
||||
if len(files_to_download) == 1:
|
||||
if len(files) == 1:
|
||||
return FileRedirectResponse(
|
||||
download_path=Path(f"/library/{rom.full_path}/{files_to_download[0]}"),
|
||||
download_path=Path(f"/library/{files[0].full_path}"),
|
||||
)
|
||||
|
||||
content_lines = [
|
||||
ZipContentLine(
|
||||
# TODO: Use calculated CRC-32 if available.
|
||||
crc32=None,
|
||||
size_bytes=(await Path(f"{rom_path}/{f}").stat()).st_size,
|
||||
encoded_location=quote(f"/library-zip/{rom.full_path}/{f}"),
|
||||
filename=f,
|
||||
crc32=f.crc_hash,
|
||||
size_bytes=(await Path(LIBRARY_BASE_PATH, f.full_path).stat()).st_size,
|
||||
encoded_location=quote(f"/library-zip/{f.full_path}"),
|
||||
filename=f.full_path.replace(rom.full_path, ""),
|
||||
)
|
||||
for f in files_to_download
|
||||
for f in files
|
||||
]
|
||||
|
||||
m3u_encoded_content = "\n".join([f for f in files_to_download]).encode()
|
||||
m3u_encoded_content = "\n".join(
|
||||
[f.full_path.replace(rom.full_path, "") for f in files]
|
||||
).encode()
|
||||
m3u_base64_content = b64encode(m3u_encoded_content).decode()
|
||||
m3u_line = ZipContentLine(
|
||||
crc32=crc32_to_hex(binascii.crc32(m3u_encoded_content)),
|
||||
@@ -370,7 +377,7 @@ async def update_rom(
|
||||
"igdb_id": None,
|
||||
"sgdb_id": None,
|
||||
"moby_id": None,
|
||||
"name": rom.file_name,
|
||||
"name": rom.fs_name,
|
||||
"summary": "",
|
||||
"url_screenshots": [],
|
||||
"path_screenshots": [],
|
||||
@@ -384,20 +391,20 @@ async def update_rom(
|
||||
},
|
||||
)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(
|
||||
db_rom_handler.get_rom(id), request
|
||||
)
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
cleaned_data = {
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
cleaned_data: dict[str, Any] = {
|
||||
"igdb_id": data.get("igdb_id", rom.igdb_id),
|
||||
"moby_id": data.get("moby_id", rom.moby_id),
|
||||
}
|
||||
|
||||
if (
|
||||
cleaned_data.get("moby_id", "")
|
||||
and int(cleaned_data.get("moby_id", "")) != rom.moby_id
|
||||
):
|
||||
moby_rom = await meta_moby_handler.get_rom_by_id(cleaned_data["moby_id"])
|
||||
moby_id = cleaned_data["moby_id"]
|
||||
if moby_id and int(moby_id) != rom.moby_id:
|
||||
moby_rom = await meta_moby_handler.get_rom_by_id(int(moby_id))
|
||||
cleaned_data.update(moby_rom)
|
||||
path_screenshots = await fs_resource_handler.get_rom_screenshots(
|
||||
rom=rom,
|
||||
@@ -405,11 +412,9 @@ async def update_rom(
|
||||
)
|
||||
cleaned_data.update({"path_screenshots": path_screenshots})
|
||||
|
||||
if (
|
||||
cleaned_data.get("igdb_id", "")
|
||||
and int(cleaned_data.get("igdb_id", "")) != rom.igdb_id
|
||||
):
|
||||
igdb_rom = await meta_igdb_handler.get_rom_by_id(cleaned_data["igdb_id"])
|
||||
igdb_id = cleaned_data["igdb_id"]
|
||||
if igdb_id and int(igdb_id) != rom.igdb_id:
|
||||
igdb_rom = await meta_igdb_handler.get_rom_by_id(int(igdb_id))
|
||||
cleaned_data.update(igdb_rom)
|
||||
path_screenshots = await fs_resource_handler.get_rom_screenshots(
|
||||
rom=rom,
|
||||
@@ -424,26 +429,26 @@ async def update_rom(
|
||||
}
|
||||
)
|
||||
|
||||
new_file_name = data.get("file_name", rom.file_name)
|
||||
new_fs_name = str(data.get("fs_name") or rom.fs_name)
|
||||
|
||||
try:
|
||||
if rename_as_source:
|
||||
new_file_name = rom.file_name.replace(
|
||||
rom.file_name_no_tags or rom.file_name_no_ext,
|
||||
data.get("name", rom.name),
|
||||
new_fs_name = rom.fs_name.replace(
|
||||
rom.fs_name_no_tags or rom.fs_name_no_ext,
|
||||
str(data.get("name") or rom.name),
|
||||
)
|
||||
new_file_name = sanitize_filename(new_file_name)
|
||||
fs_rom_handler.rename_file(
|
||||
old_name=rom.file_name,
|
||||
new_name=new_file_name,
|
||||
file_path=rom.file_path,
|
||||
new_fs_name = sanitize_filename(new_fs_name)
|
||||
fs_rom_handler.rename_fs_rom(
|
||||
old_name=rom.fs_name,
|
||||
new_name=new_fs_name,
|
||||
fs_path=rom.fs_path,
|
||||
)
|
||||
elif rom.file_name != new_file_name:
|
||||
new_file_name = sanitize_filename(new_file_name)
|
||||
fs_rom_handler.rename_file(
|
||||
old_name=rom.file_name,
|
||||
new_name=new_file_name,
|
||||
file_path=rom.file_path,
|
||||
elif rom.fs_name != new_fs_name:
|
||||
new_fs_name = sanitize_filename(new_fs_name)
|
||||
fs_rom_handler.rename_fs_rom(
|
||||
old_name=rom.fs_name,
|
||||
new_name=new_fs_name,
|
||||
fs_path=rom.fs_path,
|
||||
)
|
||||
except RomAlreadyExistsException as exc:
|
||||
log.error(exc)
|
||||
@@ -453,12 +458,10 @@ async def update_rom(
|
||||
|
||||
cleaned_data.update(
|
||||
{
|
||||
"file_name": new_file_name,
|
||||
"file_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(
|
||||
new_file_name
|
||||
),
|
||||
"file_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
|
||||
new_file_name
|
||||
"fs_name": new_fs_name,
|
||||
"fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(new_fs_name),
|
||||
"fs_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
|
||||
new_fs_name
|
||||
),
|
||||
}
|
||||
)
|
||||
@@ -467,7 +470,7 @@ async def update_rom(
|
||||
cleaned_data.update(fs_resource_handler.remove_cover(rom))
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
else:
|
||||
if artwork:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
(
|
||||
path_cover_l,
|
||||
@@ -497,15 +500,18 @@ async def update_rom(
|
||||
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
||||
overwrite=True,
|
||||
entity=rom,
|
||||
url_cover=data.get("url_cover", ""),
|
||||
url_cover=str(data.get("url_cover") or ""),
|
||||
)
|
||||
cleaned_data.update(
|
||||
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
|
||||
)
|
||||
|
||||
db_rom_handler.update_rom(id, cleaned_data)
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(db_rom_handler.get_rom(id), request)
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@protected_route(router.post, "/roms/delete", [Scope.ROMS_WRITE])
|
||||
@@ -535,13 +541,13 @@ async def delete_roms(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
log.info(f"Deleting {rom.file_name} from database")
|
||||
log.info(f"Deleting {rom.fs_name} from database")
|
||||
db_rom_handler.delete_rom(id)
|
||||
|
||||
# Update collections to remove the deleted rom
|
||||
collections = db_collection_handler.get_collections_by_rom_id(id)
|
||||
for collection in collections:
|
||||
collection.roms = [rom_id for rom_id in collection.roms if rom_id != id]
|
||||
collection.roms = {rom_id for rom_id in collection.roms if rom_id != id}
|
||||
db_collection_handler.update_collection(
|
||||
collection.id, {"roms": collection.roms}
|
||||
)
|
||||
@@ -552,13 +558,13 @@ async def delete_roms(
|
||||
log.error(f"Couldn't find resources to delete for {rom.name}")
|
||||
|
||||
if id in delete_from_fs:
|
||||
log.info(f"Deleting {rom.file_name} from filesystem")
|
||||
log.info(f"Deleting {rom.fs_name} from filesystem")
|
||||
try:
|
||||
fs_rom_handler.remove_file(
|
||||
file_name=rom.file_name, file_path=rom.file_path
|
||||
)
|
||||
fs_rom_handler.remove_from_fs(fs_path=rom.fs_path, fs_name=rom.fs_name)
|
||||
except FileNotFoundError as exc:
|
||||
error = f"Rom file {rom.file_name} not found for platform {rom.platform_slug}"
|
||||
error = (
|
||||
f"Rom file {rom.fs_name} not found for platform {rom.platform_slug}"
|
||||
)
|
||||
log.error(error)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=error
|
||||
@@ -603,4 +609,6 @@ async def update_rom_user(request: Request, id: int) -> RomUserSchema:
|
||||
if data.get("update_last_played", False):
|
||||
cleaned_data.update({"last_played": datetime.now(timezone.utc)})
|
||||
|
||||
return db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
|
||||
rom_user = db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
|
||||
|
||||
return RomUserSchema.model_validate(rom_user)
|
||||
|
||||
@@ -29,18 +29,15 @@ def add_saves(
|
||||
current_user = request.user
|
||||
log.info(f"Uploading saves to {rom.name}")
|
||||
|
||||
if saves is None:
|
||||
log.error("No saves were uploaded")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="No saves were uploaded",
|
||||
)
|
||||
|
||||
saves_path = fs_asset_handler.build_saves_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator
|
||||
)
|
||||
|
||||
for save in saves:
|
||||
if not save.filename:
|
||||
log.error("Save file has no filename")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=save, path=saves_path)
|
||||
|
||||
# Scan or update save
|
||||
@@ -79,7 +76,11 @@ def add_saves(
|
||||
|
||||
return {
|
||||
"uploaded": len(saves),
|
||||
"saves": [s for s in rom.saves if s.user_id == current_user.id],
|
||||
"saves": [
|
||||
SaveSchema.model_validate(s)
|
||||
for s in rom.saves
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -109,7 +110,7 @@ async def update_save(request: Request, id: int) -> SaveSchema:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
|
||||
if "file" in data:
|
||||
file: UploadFile = data["file"]
|
||||
file: UploadFile = data["file"] # type: ignore
|
||||
fs_asset_handler.write_file(file=file, path=db_save.file_path)
|
||||
db_save_handler.update_save(db_save.id, {"file_size_bytes": file.size})
|
||||
|
||||
@@ -124,7 +125,7 @@ async def update_save(request: Request, id: int) -> SaveSchema:
|
||||
|
||||
# Refetch the save to get updated fields
|
||||
db_save = db_save_handler.get_save(id)
|
||||
return db_save
|
||||
return SaveSchema.model_validate(db_save)
|
||||
|
||||
|
||||
@protected_route(router.post, "/saves/delete", [Scope.ASSETS_WRITE])
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.assets import UploadedScreenshotsResponse
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, Request, UploadFile
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler, db_screenshot_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
@@ -18,21 +19,21 @@ def add_screenshots(
|
||||
screenshots: list[UploadFile] = File(...), # noqa: B008
|
||||
) -> UploadedScreenshotsResponse:
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading screenshots to {rom.name}")
|
||||
|
||||
if screenshots is None:
|
||||
log.error("No screenshots were uploaded")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="No screenshots were uploaded",
|
||||
)
|
||||
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform_slug
|
||||
)
|
||||
|
||||
for screenshot in screenshots:
|
||||
if not screenshot.filename:
|
||||
log.warning("Skipping empty screenshot")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=screenshot, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
@@ -56,8 +57,15 @@ def add_screenshots(
|
||||
db_screenshot_handler.add_screenshot(scanned_screenshot)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(screenshots),
|
||||
"screenshots": [s for s in rom.screenshots if s.user_id == current_user.id],
|
||||
"screenshots": [
|
||||
ScreenshotSchema.model_validate(s)
|
||||
for s in rom.screenshots
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
"merged_screenshots": rom.merged_screenshots,
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ from fastapi import HTTPException, Request, status
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_sgdb_handler
|
||||
from handler.metadata.igdb_handler import IGDB_API_ENABLED
|
||||
from handler.metadata.moby_handler import MOBY_API_ENABLED
|
||||
from handler.metadata.igdb_handler import IGDB_API_ENABLED, IGDBRom
|
||||
from handler.metadata.moby_handler import MOBY_API_ENABLED, MobyGamesRom
|
||||
from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED
|
||||
from handler.scan_handler import _get_main_platform_igdb_id
|
||||
from logger.logger import log
|
||||
@@ -47,7 +47,7 @@ async def search_rom(
|
||||
if not rom:
|
||||
return []
|
||||
|
||||
search_term = search_term or rom.file_name_no_tags
|
||||
search_term = search_term or rom.fs_name_no_tags
|
||||
if not search_term:
|
||||
return []
|
||||
|
||||
@@ -57,10 +57,10 @@ async def search_rom(
|
||||
matched_roms: list = []
|
||||
|
||||
log.info(f"Searching by {search_by.lower()}: {search_term}")
|
||||
log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.file_name}"))
|
||||
log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.fs_name}"))
|
||||
|
||||
igdb_matched_roms = []
|
||||
moby_matched_roms = []
|
||||
igdb_matched_roms: list[IGDBRom] = []
|
||||
moby_matched_roms: list[MobyGamesRom] = []
|
||||
|
||||
if search_by.lower() == "id":
|
||||
try:
|
||||
@@ -76,19 +76,20 @@ async def search_rom(
|
||||
igdb_matched_roms = [igdb_rom] if igdb_rom else []
|
||||
moby_matched_roms = [moby_rom] if moby_rom else []
|
||||
elif search_by.lower() == "name":
|
||||
main_platform_igdb_id = await _get_main_platform_igdb_id(rom.platform)
|
||||
igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_name(
|
||||
search_term, (await _get_main_platform_igdb_id(rom.platform))
|
||||
search_term, main_platform_igdb_id or rom.platform.igdb_id
|
||||
)
|
||||
moby_matched_roms = await meta_moby_handler.get_matched_roms_by_name(
|
||||
search_term, rom.platform.moby_id
|
||||
)
|
||||
|
||||
merged_dict = {
|
||||
item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")}
|
||||
item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")} # type: ignore
|
||||
for item in igdb_matched_roms
|
||||
}
|
||||
for item in moby_matched_roms:
|
||||
merged_dict[item["name"]] = {
|
||||
merged_dict[item["name"]] = { # type: ignore
|
||||
**item,
|
||||
"moby_url_cover": item.pop("url_cover", ""),
|
||||
**merged_dict.get(item.get("name", ""), {}),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from itertools import batched
|
||||
from typing import Any, Final
|
||||
@@ -23,20 +24,51 @@ from handler.filesystem import (
|
||||
fs_rom_handler,
|
||||
)
|
||||
from handler.filesystem.roms_handler import FSRom
|
||||
from handler.redis_handler import high_prio_queue, redis_client
|
||||
from handler.redis_handler import high_prio_queue, low_prio_queue, redis_client
|
||||
from handler.scan_handler import ScanType, scan_firmware, scan_platform, scan_rom
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.formatter import LIGHTYELLOW
|
||||
from logger.formatter import LIGHTYELLOW, RED
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.rom import Rom, RomFile
|
||||
from rq import Worker
|
||||
from rq.job import Job
|
||||
from sqlalchemy.inspection import inspect
|
||||
from utils.context import initialize_context
|
||||
|
||||
STOP_SCAN_FLAG: Final = "scan:stop"
|
||||
NON_HASHABLE_PLATFORMS = frozenset(
|
||||
(
|
||||
"amazon-alexa",
|
||||
"amazon-fire-tv",
|
||||
"android",
|
||||
"gear-vr",
|
||||
"ios",
|
||||
"ipad",
|
||||
"linux",
|
||||
"mac",
|
||||
"meta-quest-2",
|
||||
"meta-quest-3",
|
||||
"oculus-go",
|
||||
"oculus-quest",
|
||||
"oculus-rift",
|
||||
"pc",
|
||||
"ps3",
|
||||
"ps4",
|
||||
"ps4--1",
|
||||
"ps5",
|
||||
"psvr",
|
||||
"psvr2",
|
||||
"series-x",
|
||||
"switch",
|
||||
"wiiu",
|
||||
"win",
|
||||
"xbox-360",
|
||||
"xbox360",
|
||||
"xboxone",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -141,7 +173,9 @@ async def scan_platforms(
|
||||
|
||||
try:
|
||||
platform_list = [
|
||||
db_platform_handler.get_platform(s).fs_slug for s in platform_ids
|
||||
platform.fs_slug
|
||||
for s in platform_ids
|
||||
if (platform := db_platform_handler.get_platform(s)) is not None
|
||||
] or fs_platforms
|
||||
|
||||
if len(platform_list) == 0:
|
||||
@@ -267,16 +301,16 @@ async def _identify_platform(
|
||||
log.info(f" {len(fs_roms)} roms found in the file system")
|
||||
|
||||
for fs_roms_batch in batched(fs_roms, 200):
|
||||
rom_by_filename_map = db_rom_handler.get_roms_by_filename(
|
||||
rom_by_filename_map = db_rom_handler.get_roms_by_fs_name(
|
||||
platform_id=platform.id,
|
||||
file_names={fs_rom["file_name"] for fs_rom in fs_roms_batch},
|
||||
fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch},
|
||||
)
|
||||
|
||||
for fs_rom in fs_roms_batch:
|
||||
scan_stats += await _identify_rom(
|
||||
platform=platform,
|
||||
fs_rom=fs_rom,
|
||||
rom=rom_by_filename_map.get(fs_rom["file_name"]),
|
||||
rom=rom_by_filename_map.get(fs_rom["fs_name"]),
|
||||
scan_type=scan_type,
|
||||
roms_ids=roms_ids,
|
||||
metadata_sources=metadata_sources,
|
||||
@@ -288,12 +322,12 @@ async def _identify_platform(
|
||||
# the folder structure is not correct or the drive is not mounted
|
||||
if len(fs_roms) > 0:
|
||||
purged_roms = db_rom_handler.purge_roms(
|
||||
platform.id, [rom["file_name"] for rom in fs_roms]
|
||||
platform.id, [rom["fs_name"] for rom in fs_roms]
|
||||
)
|
||||
if len(purged_roms) > 0:
|
||||
log.info("Purging roms not found in the filesystem:")
|
||||
for r in purged_roms:
|
||||
log.info(f" - {r.file_name}")
|
||||
log.info(f" - {r.fs_name}")
|
||||
|
||||
# Same protection for firmware
|
||||
if len(fs_firmware) > 0:
|
||||
@@ -333,6 +367,51 @@ async def _identify_firmware(
|
||||
return scan_stats
|
||||
|
||||
|
||||
def _set_rom_hashes(rom_id: int):
|
||||
"""Set the hashes for the given rom
|
||||
|
||||
Args:
|
||||
rom_id (int): Rom id
|
||||
"""
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
return
|
||||
|
||||
try:
|
||||
rom_hash, rom_file_hashes = fs_rom_handler.get_rom_hashes(rom)
|
||||
except zlib.error as e:
|
||||
# Set empty hashes if calculating them fails for corrupted files
|
||||
log.error(
|
||||
f"Hashes of {rom.fs_name} couldn't be calculated: {hl(str(e), color=RED)}"
|
||||
)
|
||||
db_rom_handler.update_rom(
|
||||
rom_id,
|
||||
{
|
||||
"crc_hash": "",
|
||||
"md5_hash": "",
|
||||
"sha1_hash": "",
|
||||
},
|
||||
)
|
||||
else:
|
||||
db_rom_handler.update_rom(
|
||||
rom_id,
|
||||
{
|
||||
"crc_hash": rom_hash["crc_hash"],
|
||||
"md5_hash": rom_hash["md5_hash"],
|
||||
"sha1_hash": rom_hash["sha1_hash"],
|
||||
},
|
||||
)
|
||||
for file_hash in rom_file_hashes:
|
||||
db_rom_handler.update_rom_file(
|
||||
file_hash["id"],
|
||||
{
|
||||
"crc_hash": file_hash["crc_hash"],
|
||||
"md5_hash": file_hash["md5_hash"],
|
||||
"sha1_hash": file_hash["sha1_hash"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _identify_rom(
|
||||
platform: Platform,
|
||||
fs_rom: FSRom,
|
||||
@@ -349,15 +428,9 @@ async def _identify_rom(
|
||||
return scan_stats
|
||||
|
||||
if not _should_scan_rom(scan_type=scan_type, rom=rom, roms_ids=roms_ids):
|
||||
if rom and (
|
||||
rom.file_name != fs_rom["file_name"]
|
||||
or rom.multi != fs_rom["multi"]
|
||||
or rom.files != fs_rom["files"]
|
||||
):
|
||||
if rom and rom.fs_name != fs_rom["fs_name"]:
|
||||
# Just to update the filesystem data
|
||||
rom.file_name = fs_rom["file_name"]
|
||||
rom.multi = fs_rom["multi"]
|
||||
rom.files = fs_rom["files"]
|
||||
rom.fs_name = fs_rom["fs_name"]
|
||||
db_rom_handler.add_rom(rom)
|
||||
|
||||
return scan_stats
|
||||
@@ -376,6 +449,37 @@ async def _identify_rom(
|
||||
|
||||
_added_rom = db_rom_handler.add_rom(scanned_rom)
|
||||
|
||||
# Delete the existing rom files in the DB
|
||||
db_rom_handler.purge_rom_files(_added_rom.id)
|
||||
|
||||
# Create each file entry for the rom
|
||||
new_rom_files = [
|
||||
RomFile(
|
||||
rom_id=_added_rom.id,
|
||||
file_name=file.file_name,
|
||||
file_path=file.file_path,
|
||||
file_size_bytes=file.file_size_bytes,
|
||||
last_modified=file.last_modified,
|
||||
category=file.category,
|
||||
)
|
||||
for file in fs_rom["files"]
|
||||
]
|
||||
for new_rom_file in new_rom_files:
|
||||
db_rom_handler.add_rom_file(new_rom_file)
|
||||
|
||||
# Calculating hashes is expensive, so we only do it if necessary
|
||||
if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES:
|
||||
# Skip hashing games for platforms that don't have a hash database
|
||||
if platform.slug not in NON_HASHABLE_PLATFORMS:
|
||||
# Uncomment this to run scan in the current process
|
||||
# _set_rom_hashes(_added_rom.id)
|
||||
|
||||
low_prio_queue.enqueue(
|
||||
_set_rom_hashes,
|
||||
_added_rom.id,
|
||||
job_timeout=60 * 15, # Timeout (15 minutes)
|
||||
)
|
||||
|
||||
# Return early if we're only scanning for hashes
|
||||
if scan_type == ScanType.HASHES:
|
||||
return scan_stats
|
||||
|
||||
@@ -29,18 +29,15 @@ def add_states(
|
||||
current_user = request.user
|
||||
log.info(f"Uploading states to {rom.name}")
|
||||
|
||||
if states is None:
|
||||
log.error("No states were uploaded")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="No states were uploaded",
|
||||
)
|
||||
|
||||
states_path = fs_asset_handler.build_states_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator
|
||||
)
|
||||
|
||||
for state in states:
|
||||
if not state.filename:
|
||||
log.warning("Skipping file with no filename")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=state, path=states_path)
|
||||
|
||||
# Scan or update state
|
||||
@@ -73,9 +70,16 @@ def add_states(
|
||||
)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(states),
|
||||
"states": [s for s in rom.states if s.user_id == current_user.id],
|
||||
"states": [
|
||||
StateSchema.model_validate(s)
|
||||
for s in rom.states
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +109,7 @@ async def update_state(request: Request, id: int) -> StateSchema:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
|
||||
if "file" in data:
|
||||
file: UploadFile = data["file"]
|
||||
file: UploadFile = data["file"] # type: ignore
|
||||
fs_asset_handler.write_file(file=file, path=db_state.file_path)
|
||||
db_state_handler.update_state(db_state.id, {"file_size_bytes": file.size})
|
||||
|
||||
@@ -119,7 +123,7 @@ async def update_state(request: Request, id: int) -> StateSchema:
|
||||
)
|
||||
|
||||
db_state = db_state_handler.get_state(id)
|
||||
return db_state
|
||||
return StateSchema.model_validate(db_state)
|
||||
|
||||
|
||||
@protected_route(router.post, "/states/delete", [Scope.ASSETS_WRITE])
|
||||
|
||||
@@ -37,9 +37,9 @@ def test_get_all_roms(client, access_token, rom, platform):
|
||||
assert body[0]["id"] == rom.id
|
||||
|
||||
|
||||
@patch.object(FSRomsHandler, "rename_file")
|
||||
@patch.object(FSRomsHandler, "rename_fs_rom")
|
||||
@patch.object(IGDBBaseHandler, "get_rom_by_id", return_value=IGDBRom(igdb_id=None))
|
||||
def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token, rom):
|
||||
def test_update_rom(rename_fs_rom_mock, get_rom_by_id_mock, client, access_token, rom):
|
||||
response = client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
@@ -48,7 +48,7 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token,
|
||||
"igdb_id": "236663",
|
||||
"name": "Metroid Prime Remastered",
|
||||
"slug": "metroid-prime-remastered",
|
||||
"file_name": "Metroid Prime Remastered.zip",
|
||||
"fs_name": "Metroid Prime Remastered.zip",
|
||||
"summary": "summary test",
|
||||
"url_cover": "https://images.igdb.com/igdb/image/upload/t_cover_big/co2l7z.jpg",
|
||||
"genres": '[{"id": 5, "name": "Shooter"}, {"id": 8, "name": "Platform"}, {"id": 31, "name": "Adventure"}]',
|
||||
@@ -70,9 +70,9 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token,
|
||||
assert response.status_code == 200
|
||||
|
||||
body = response.json()
|
||||
assert body["file_name"] == "Metroid Prime Remastered.zip"
|
||||
assert body["fs_name"] == "Metroid Prime Remastered.zip"
|
||||
|
||||
assert rename_file_mock.called
|
||||
assert rename_fs_rom_mock.called
|
||||
assert get_rom_by_id_mock.called
|
||||
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ def add_user(
|
||||
role=Role[role.upper()],
|
||||
)
|
||||
|
||||
return db_user_handler.add_user(user)
|
||||
return UserSchema.model_validate(db_user_handler.add_user(user))
|
||||
|
||||
|
||||
@protected_route(router.get, "/users", [Scope.USERS_READ])
|
||||
@@ -88,7 +88,7 @@ def get_users(request: Request) -> list[UserSchema]:
|
||||
list[UserSchema]: All users stored in the RomM's database
|
||||
"""
|
||||
|
||||
return [u for u in db_user_handler.get_users()]
|
||||
return [UserSchema.model_validate(u) for u in db_user_handler.get_users()]
|
||||
|
||||
|
||||
@protected_route(router.get, "/users/me", [Scope.ME_READ])
|
||||
@@ -120,7 +120,7 @@ def get_user(request: Request, id: int) -> UserSchema:
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return user
|
||||
return UserSchema.model_validate(user)
|
||||
|
||||
|
||||
@protected_route(router.put, "/users/{id}", [Scope.ME_WRITE])
|
||||
@@ -214,7 +214,13 @@ async def update_user(
|
||||
if request.user.id == id and creds_updated:
|
||||
request.session.clear()
|
||||
|
||||
return db_user_handler.get_user(id)
|
||||
db_user = db_user_handler.get_user(id)
|
||||
if not db_user:
|
||||
msg = f"Username with id {id} not found"
|
||||
log.error(msg)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg)
|
||||
|
||||
return UserSchema.model_validate(db_user)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/users/{id}", [Scope.USERS_WRITE])
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
from fastapi.security.http import HTTPBasic
|
||||
from handler.auth import auth_handler, oauth_handler
|
||||
from models.user import User
|
||||
from starlette.authentication import AuthCredentials, AuthenticationBackend
|
||||
from starlette.requests import HTTPConnection
|
||||
|
||||
|
||||
class HybridAuthBackend(AuthenticationBackend):
|
||||
async def authenticate(self, conn: HTTPConnection):
|
||||
async def authenticate(
|
||||
self, conn: HTTPConnection
|
||||
) -> tuple[AuthCredentials, User] | None:
|
||||
# Check if session key already stored in cache
|
||||
user = await auth_handler.get_current_active_user_from_session(conn)
|
||||
if user:
|
||||
@@ -14,7 +17,7 @@ class HybridAuthBackend(AuthenticationBackend):
|
||||
|
||||
# Check if Authorization header exists
|
||||
if "Authorization" not in conn.headers:
|
||||
return (AuthCredentials([]), None)
|
||||
return None
|
||||
|
||||
scheme, token = conn.headers["Authorization"].split()
|
||||
|
||||
@@ -22,13 +25,13 @@ class HybridAuthBackend(AuthenticationBackend):
|
||||
if scheme.lower() == "basic":
|
||||
credentials = await HTTPBasic().__call__(conn) # type: ignore[arg-type]
|
||||
if not credentials:
|
||||
return (AuthCredentials([]), None)
|
||||
return None
|
||||
|
||||
user = auth_handler.authenticate_user(
|
||||
credentials.username, credentials.password
|
||||
)
|
||||
if user is None:
|
||||
return (AuthCredentials([]), None)
|
||||
return None
|
||||
|
||||
user.set_last_active()
|
||||
return (AuthCredentials(user.oauth_scopes), user)
|
||||
@@ -39,18 +42,18 @@ class HybridAuthBackend(AuthenticationBackend):
|
||||
user,
|
||||
claims,
|
||||
) = await oauth_handler.get_current_active_user_from_bearer_token(token)
|
||||
if user is None:
|
||||
return (AuthCredentials([]), None)
|
||||
if user is None or claims is None:
|
||||
return None
|
||||
|
||||
# Only access tokens can request resources
|
||||
if claims.get("type") != "access":
|
||||
return (AuthCredentials([]), None)
|
||||
return None
|
||||
|
||||
# Only grant access to resources with overlapping scopes
|
||||
token_scopes = set(list(claims.get("scopes").split(" ")))
|
||||
token_scopes = set(list(claims.get("scopes", "").split(" ")))
|
||||
overlapping_scopes = list(token_scopes & set(user.oauth_scopes))
|
||||
|
||||
user.set_last_active()
|
||||
return (AuthCredentials(overlapping_scopes), user)
|
||||
|
||||
return (AuthCredentials([]), None)
|
||||
return None
|
||||
|
||||
@@ -7,6 +7,7 @@ from handler.auth.constants import WRITE_SCOPES
|
||||
from handler.auth.hybrid_auth import HybridAuthBackend
|
||||
from handler.database import db_user_handler
|
||||
from models.user import User
|
||||
from starlette.requests import HTTPConnection
|
||||
|
||||
|
||||
def test_verify_password():
|
||||
@@ -26,9 +27,10 @@ def test_authenticate_user(admin_user: User):
|
||||
|
||||
|
||||
async def test_get_current_active_user_from_session(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
|
||||
conn = MockConnection()
|
||||
current_user = await auth_handler.get_current_active_user_from_session(conn)
|
||||
@@ -39,9 +41,10 @@ async def test_get_current_active_user_from_session(editor_user: User):
|
||||
|
||||
|
||||
async def test_get_current_active_user_from_session_bad_username(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {"iss": "romm:auth", "sub": "not_real_username"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self.scope["session"] = {"iss": "romm:auth", "sub": "not_real_username"}
|
||||
|
||||
conn = MockConnection()
|
||||
|
||||
@@ -53,10 +56,11 @@ async def test_get_current_active_user_from_session_bad_username(editor_user: Us
|
||||
|
||||
|
||||
async def test_get_current_active_user_from_session_disabled_user(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
self.headers = {}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
self._headers = {}
|
||||
|
||||
conn = MockConnection()
|
||||
|
||||
@@ -70,33 +74,34 @@ async def test_get_current_active_user_from_session_disabled_user(editor_user: U
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_session(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is not None
|
||||
|
||||
creds, user = result
|
||||
assert user.id == editor_user.id
|
||||
assert creds.scopes == editor_user.oauth_scopes
|
||||
assert creds.scopes == WRITE_SCOPES
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_empty_session_and_headers(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
|
||||
assert not user
|
||||
assert creds.scopes == []
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is None
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_bearer_auth_header(editor_user: User):
|
||||
@@ -109,25 +114,27 @@ async def test_hybrid_auth_backend_bearer_auth_header(editor_user: User):
|
||||
},
|
||||
)
|
||||
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": f"Bearer {access_token}"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": f"Bearer {access_token}"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is not None
|
||||
|
||||
creds, user = result
|
||||
assert user.id == editor_user.id
|
||||
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": "Bearer invalid_token"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": "Bearer invalid_token"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
@@ -139,26 +146,28 @@ async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User):
|
||||
async def test_hybrid_auth_backend_basic_auth_header(editor_user: User):
|
||||
token = b64encode(b"test_editor:test_editor_password").decode()
|
||||
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": f"Basic {token}"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": f"Basic {token}"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is not None
|
||||
|
||||
creds, user = result
|
||||
assert user.id == editor_user.id
|
||||
assert creds.scopes == WRITE_SCOPES
|
||||
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User):
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": "Basic test_editor:test_editor_password"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": "Basic test_editor:test_editor_password"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
@@ -168,18 +177,16 @@ async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_invalid_scheme():
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": "Some invalid_scheme"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": "Some invalid_scheme"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
|
||||
assert not user
|
||||
assert creds.scopes == []
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is None
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_with_refresh_token(editor_user: User):
|
||||
@@ -192,18 +199,16 @@ async def test_hybrid_auth_backend_with_refresh_token(editor_user: User):
|
||||
},
|
||||
)
|
||||
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": f"Bearer {refresh_token}"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": f"Bearer {refresh_token}"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
|
||||
assert not user
|
||||
assert creds.scopes == []
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is None
|
||||
|
||||
|
||||
async def test_hybrid_auth_backend_scope_subset(editor_user: User):
|
||||
@@ -217,16 +222,18 @@ async def test_hybrid_auth_backend_scope_subset(editor_user: User):
|
||||
},
|
||||
)
|
||||
|
||||
class MockConnection:
|
||||
class MockConnection(HTTPConnection):
|
||||
def __init__(self):
|
||||
self.session = {}
|
||||
self.headers = {"Authorization": f"Bearer {access_token}"}
|
||||
self.scope: dict[str, dict] = {"session": {}}
|
||||
self._headers = {"Authorization": f"Bearer {access_token}"}
|
||||
|
||||
backend = HybridAuthBackend()
|
||||
conn = MockConnection()
|
||||
|
||||
creds, user = await backend.authenticate(conn)
|
||||
result = await backend.authenticate(conn)
|
||||
assert result is not None
|
||||
|
||||
creds, user = result
|
||||
assert user.id == editor_user.id
|
||||
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
|
||||
assert set(creds.scopes).issubset(scopes)
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
from typing import Any, Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import Collection
|
||||
from sqlalchemy import Select, delete, select, update
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.sql import ColumnExpressionArgument
|
||||
from utils.database import json_array_contains_value
|
||||
@@ -15,10 +14,11 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def add_collection(
|
||||
self, collection: Collection, session: Session = None
|
||||
) -> Collection | None:
|
||||
) -> Collection:
|
||||
collection = session.merge(collection)
|
||||
session.flush()
|
||||
return session.scalar(select(Collection).filter_by(id=collection.id).limit(1))
|
||||
|
||||
return session.query(Collection).filter_by(id=collection.id).one()
|
||||
|
||||
@begin_session
|
||||
def get_collection(self, id: int, session: Session = None) -> Collection | None:
|
||||
@@ -33,9 +33,9 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_collections(self, session: Session = None) -> Select[tuple[Collection]]:
|
||||
def get_collections(self, session: Session = None) -> Sequence[Collection]:
|
||||
return (
|
||||
session.scalars(select(Collection).order_by(Collection.name.asc())) # type: ignore[attr-defined]
|
||||
session.scalars(select(Collection).order_by(Collection.name.asc()))
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
@@ -47,7 +47,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
*,
|
||||
order_by: Sequence[str | ColumnExpressionArgument[Any]] | None = None,
|
||||
session: Session = None,
|
||||
) -> list[Collection]:
|
||||
) -> Sequence[Collection]:
|
||||
query = select(Collection).filter(
|
||||
json_array_contains_value(Collection.roms, rom_id, session=session)
|
||||
)
|
||||
@@ -69,8 +69,8 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
return session.query(Collection).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_collection(self, id: int, session: Session = None) -> int:
|
||||
return session.execute(
|
||||
def delete_collection(self, id: int, session: Session = None) -> None:
|
||||
session.execute(
|
||||
delete(Collection)
|
||||
.where(Collection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.firmware import Firmware
|
||||
from sqlalchemy import and_, delete, select, update
|
||||
@@ -26,7 +28,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
*,
|
||||
platform_id: int | None = None,
|
||||
session: Session = None,
|
||||
) -> list[Firmware]:
|
||||
) -> Sequence[Firmware]:
|
||||
return session.scalars(
|
||||
select(Firmware)
|
||||
.filter_by(platform_id=platform_id)
|
||||
@@ -45,16 +47,17 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def update_firmware(self, id: int, data: dict, session: Session = None) -> Firmware:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(Firmware)
|
||||
.where(Firmware.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(Firmware).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_firmware(self, id: int, session: Session = None) -> None:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
delete(Firmware)
|
||||
.where(Firmware.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
@@ -62,8 +65,8 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_firmware(
|
||||
self, platform_id: int, fs_firmwares: list[str], session: Session = None
|
||||
) -> None:
|
||||
self, platform_id: int, fs_firmwares_to_keep: list[str], session: Session = None
|
||||
) -> Sequence[Firmware]:
|
||||
purged_firmware = (
|
||||
session.scalars(
|
||||
select(Firmware)
|
||||
@@ -71,7 +74,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
.where(
|
||||
and_(
|
||||
Firmware.platform_id == platform_id,
|
||||
Firmware.file_name.not_in(fs_firmwares),
|
||||
Firmware.file_name.not_in(fs_firmwares_to_keep),
|
||||
)
|
||||
)
|
||||
) # type: ignore[attr-defined]
|
||||
@@ -83,7 +86,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
.where(
|
||||
and_(
|
||||
Firmware.platform_id == platform_id,
|
||||
Firmware.file_name.not_in(fs_firmwares),
|
||||
Firmware.file_name.not_in(fs_firmwares_to_keep),
|
||||
)
|
||||
)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from sqlalchemy import Select, delete, or_, select
|
||||
from sqlalchemy import delete, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
@@ -12,39 +14,33 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
def add_platform(
|
||||
self,
|
||||
platform: Platform,
|
||||
session: Session,
|
||||
session: Session = None,
|
||||
) -> Platform:
|
||||
platform = session.merge(platform)
|
||||
session.flush()
|
||||
|
||||
new_platform = session.scalar(
|
||||
select(Platform).filter_by(id=platform.id).limit(1)
|
||||
)
|
||||
if not new_platform:
|
||||
raise ValueError("Could not find newlyewly created platform")
|
||||
|
||||
return new_platform
|
||||
return session.query(Platform).filter_by(id=platform.id).one()
|
||||
|
||||
@begin_session
|
||||
def get_platform(self, id: int, *, session: Session) -> Platform | None:
|
||||
def get_platform(self, id: int, *, session: Session = None) -> Platform | None:
|
||||
return session.scalar(select(Platform).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_platforms(self, *, session: Session) -> Select[tuple[Platform]]:
|
||||
def get_platforms(self, *, session: Session = None) -> Sequence[Platform]:
|
||||
return (
|
||||
session.scalars(select(Platform).order_by(Platform.name.asc())) # type: ignore[attr-defined]
|
||||
session.scalars(select(Platform).order_by(Platform.name.asc()))
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_platform_by_fs_slug(
|
||||
self, fs_slug: str, session: Session
|
||||
self, fs_slug: str, session: Session = None
|
||||
) -> Platform | None:
|
||||
return session.scalar(select(Platform).filter_by(fs_slug=fs_slug).limit(1))
|
||||
|
||||
@begin_session
|
||||
def delete_platform(self, id: int, session: Session) -> None:
|
||||
def delete_platform(self, id: int, session: Session = None) -> None:
|
||||
# Remove all roms from that platforms first
|
||||
session.execute(
|
||||
delete(Rom)
|
||||
@@ -60,14 +56,17 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_platforms(
|
||||
self, fs_platforms: list[str], session: Session
|
||||
) -> Select[tuple[Platform]]:
|
||||
self, fs_platforms_to_keep: list[str], session: Session = None
|
||||
) -> Sequence[Platform]:
|
||||
purged_platforms = (
|
||||
session.scalars(
|
||||
select(Platform)
|
||||
.order_by(Platform.name.asc())
|
||||
.where(
|
||||
or_(Platform.fs_slug.not_in(fs_platforms), Platform.slug.is_(None))
|
||||
or_(
|
||||
Platform.fs_slug.not_in(fs_platforms_to_keep),
|
||||
Platform.slug.is_(None),
|
||||
)
|
||||
)
|
||||
) # type: ignore[attr-defined]
|
||||
.unique()
|
||||
@@ -75,7 +74,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
)
|
||||
session.execute(
|
||||
delete(Platform)
|
||||
.where(or_(Platform.fs_slug.not_in(fs_platforms), Platform.slug.is_(None))) # type: ignore[attr-defined]
|
||||
.where(or_(Platform.fs_slug.not_in(fs_platforms_to_keep), Platform.slug.is_(None))) # type: ignore[attr-defined]
|
||||
.execution_options(synchronize_session="fetch")
|
||||
)
|
||||
return purged_platforms
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import functools
|
||||
from collections.abc import Iterable
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import Collection
|
||||
from models.rom import Rom, RomUser
|
||||
from models.rom import Rom, RomFile, RomUser
|
||||
from sqlalchemy import and_, delete, func, or_, select, update
|
||||
from sqlalchemy.orm import Query, Session, selectinload
|
||||
|
||||
@@ -72,8 +73,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
if search_term:
|
||||
data = data.filter(
|
||||
or_(
|
||||
Rom.file_name.ilike(f"%{search_term}%"), # type: ignore[attr-defined]
|
||||
Rom.name.ilike(f"%{search_term}%"), # type: ignore[attr-defined]
|
||||
Rom.fs_name.ilike(f"%{search_term}%"),
|
||||
Rom.name.ilike(f"%{search_term}%"),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -119,7 +120,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
offset: int | None = None,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> list[Rom]:
|
||||
) -> Sequence[Rom]:
|
||||
filtered_query = self._filter(
|
||||
query, platform_id, collection_id, search_term, session
|
||||
)
|
||||
@@ -130,68 +131,65 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_filename(
|
||||
def get_rom_by_fs_name(
|
||||
self,
|
||||
platform_id: int,
|
||||
file_name: str,
|
||||
fs_name: str,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> Rom | None:
|
||||
return session.scalar(
|
||||
query.filter_by(platform_id=platform_id, file_name=file_name).limit(1)
|
||||
query.filter_by(platform_id=platform_id, fs_name=fs_name).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_roms_by_filename(
|
||||
def get_roms_by_fs_name(
|
||||
self,
|
||||
platform_id: int,
|
||||
file_names: Iterable[str],
|
||||
fs_names: Iterable[str],
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> dict[str, Rom]:
|
||||
"""Retrieve a dictionary of roms by their file names."""
|
||||
"""Retrieve a dictionary of roms by their filesystem names."""
|
||||
query = query or select(Rom)
|
||||
roms = (
|
||||
session.scalars(
|
||||
query.filter(Rom.file_name.in_(file_names)).filter_by(
|
||||
query.filter(Rom.fs_name.in_(fs_names)).filter_by(
|
||||
platform_id=platform_id
|
||||
)
|
||||
)
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
return {rom.file_name: rom for rom in roms}
|
||||
return {rom.fs_name: rom for rom in roms}
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_filename_no_tags(
|
||||
self, file_name_no_tags: str, query: Query = None, session: Session = None
|
||||
def get_rom_by_fs_name_no_tags(
|
||||
self, fs_name_no_tags: str, query: Query = None, session: Session = None
|
||||
) -> Rom | None:
|
||||
return session.scalar(
|
||||
query.filter_by(file_name_no_tags=file_name_no_tags).limit(1)
|
||||
)
|
||||
return session.scalar(query.filter_by(fs_name_no_tags=fs_name_no_tags).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_filename_no_ext(
|
||||
self, file_name_no_ext: str, query: Query = None, session: Session = None
|
||||
def get_rom_by_fs_name_no_ext(
|
||||
self, fs_name_no_ext: str, query: Query = None, session: Session = None
|
||||
) -> Rom | None:
|
||||
return session.scalar(
|
||||
query.filter_by(file_name_no_ext=file_name_no_ext).limit(1)
|
||||
)
|
||||
return session.scalar(query.filter_by(fs_name_no_ext=fs_name_no_ext).limit(1))
|
||||
|
||||
@begin_session
|
||||
def update_rom(self, id: int, data: dict, session: Session = None) -> Rom:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(Rom)
|
||||
.where(Rom.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(Rom).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_rom(self, id: int, session: Session = None) -> Rom:
|
||||
return session.execute(
|
||||
def delete_rom(self, id: int, session: Session = None) -> None:
|
||||
session.execute(
|
||||
delete(Rom)
|
||||
.where(Rom.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
@@ -199,22 +197,29 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_roms(
|
||||
self, platform_id: int, fs_roms: list[str], session: Session = None
|
||||
) -> list[Rom]:
|
||||
self, platform_id: int, fs_roms_to_keep: list[str], session: Session = None
|
||||
) -> Sequence[Rom]:
|
||||
purged_roms = (
|
||||
session.scalars(
|
||||
select(Rom)
|
||||
.order_by(Rom.file_name.asc())
|
||||
.order_by(Rom.fs_name.asc())
|
||||
.where(
|
||||
and_(Rom.platform_id == platform_id, Rom.file_name.not_in(fs_roms))
|
||||
and_(
|
||||
Rom.platform_id == platform_id,
|
||||
Rom.fs_name.not_in(fs_roms_to_keep),
|
||||
)
|
||||
)
|
||||
) # type: ignore[attr-defined]
|
||||
)
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
session.execute(
|
||||
delete(Rom)
|
||||
.where(and_(Rom.platform_id == platform_id, Rom.file_name.not_in(fs_roms))) # type: ignore[attr-defined]
|
||||
.where(
|
||||
and_(
|
||||
Rom.platform_id == platform_id, Rom.fs_name.not_in(fs_roms_to_keep)
|
||||
)
|
||||
)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return purged_roms
|
||||
@@ -248,7 +253,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
offset: int | None = None,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> list[Rom]:
|
||||
) -> Sequence[Rom]:
|
||||
filtered_query = (
|
||||
query.join(RomUser)
|
||||
.filter(RomUser.user_id == user_id)
|
||||
@@ -266,7 +271,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
return session.scalar(select(RomUser).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def update_rom_user(self, id: int, data: dict, session: Session = None) -> RomUser:
|
||||
def update_rom_user(
|
||||
self, id: int, data: dict, session: Session = None
|
||||
) -> RomUser | None:
|
||||
session.execute(
|
||||
update(RomUser)
|
||||
.where(RomUser.id == id)
|
||||
@@ -275,11 +282,16 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
rom_user = self.get_rom_user_by_id(id)
|
||||
if not rom_user:
|
||||
return None
|
||||
|
||||
if not data.get("is_main_sibling", False):
|
||||
return rom_user
|
||||
|
||||
rom = self.get_rom(rom_user.rom_id)
|
||||
if not rom:
|
||||
return rom_user
|
||||
|
||||
session.execute(
|
||||
update(RomUser)
|
||||
.where(
|
||||
@@ -291,4 +303,41 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.values(is_main_sibling=False)
|
||||
)
|
||||
|
||||
return self.get_rom_user_by_id(id)
|
||||
return session.query(RomUser).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def add_rom_file(self, rom_file: RomFile, session: Session = None) -> RomFile:
|
||||
return session.merge(rom_file)
|
||||
|
||||
@begin_session
|
||||
def get_rom_files(self, rom_id: int, session: Session = None) -> Sequence[RomFile]:
|
||||
return session.scalars(select(RomFile).filter_by(rom_id=rom_id)).unique().all()
|
||||
|
||||
@begin_session
|
||||
def get_rom_file_by_id(self, id: int, session: Session = None) -> RomFile | None:
|
||||
return session.scalar(select(RomFile).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def update_rom_file(self, id: int, data: dict, session: Session = None) -> RomFile:
|
||||
session.execute(
|
||||
update(RomFile)
|
||||
.where(RomFile.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.query(RomFile).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def purge_rom_files(
|
||||
self, rom_id: int, session: Session = None
|
||||
) -> Sequence[RomFile]:
|
||||
purged_rom_files = (
|
||||
session.scalars(select(RomFile).filter_by(rom_id=rom_id)).unique().all()
|
||||
)
|
||||
session.execute(
|
||||
delete(RomFile)
|
||||
.where(RomFile.rom_id == rom_id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return purged_rom_files
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.assets import Save
|
||||
from sqlalchemy import and_, delete, select, update
|
||||
@@ -12,7 +14,7 @@ class DBSavesHandler(DBBaseHandler):
|
||||
return session.merge(save)
|
||||
|
||||
@begin_session
|
||||
def get_save(self, id: int, session: Session = None) -> Save:
|
||||
def get_save(self, id: int, session: Session = None) -> Save | None:
|
||||
return session.get(Save, id)
|
||||
|
||||
@begin_session
|
||||
@@ -27,16 +29,17 @@ class DBSavesHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def update_save(self, id: int, data: dict, session: Session = None) -> Save:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(Save)
|
||||
.where(Save.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(Save).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_save(self, id: int, session: Session = None) -> None:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
delete(Save)
|
||||
.where(Save.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
@@ -44,16 +47,32 @@ class DBSavesHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_saves(
|
||||
self, rom_id: int, user_id: int, saves: list[str], session: Session = None
|
||||
) -> None:
|
||||
return session.execute(
|
||||
self,
|
||||
rom_id: int,
|
||||
user_id: int,
|
||||
saves_to_keep: list[str],
|
||||
session: Session = None,
|
||||
) -> Sequence[Save]:
|
||||
purged_saves = session.scalars(
|
||||
select(Save).filter(
|
||||
and_(
|
||||
Save.rom_id == rom_id,
|
||||
Save.user_id == user_id,
|
||||
Save.file_name.not_in(saves_to_keep),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
|
||||
session.execute(
|
||||
delete(Save)
|
||||
.where(
|
||||
and_(
|
||||
Save.rom_id == rom_id,
|
||||
Save.user_id == user_id,
|
||||
Save.file_name.not_in(saves),
|
||||
Save.file_name.not_in(saves_to_keep),
|
||||
)
|
||||
)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return purged_saves
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.assets import Screenshot
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy import and_, delete, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
@@ -14,7 +16,7 @@ class DBScreenshotsHandler(DBBaseHandler):
|
||||
return session.merge(screenshot)
|
||||
|
||||
@begin_session
|
||||
def get_screenshot(self, id, session: Session = None) -> Screenshot:
|
||||
def get_screenshot(self, id, session: Session = None) -> Screenshot | None:
|
||||
return session.get(Screenshot, id)
|
||||
|
||||
@begin_session
|
||||
@@ -31,16 +33,17 @@ class DBScreenshotsHandler(DBBaseHandler):
|
||||
def update_screenshot(
|
||||
self, id: int, data: dict, session: Session = None
|
||||
) -> Screenshot:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(Screenshot)
|
||||
.where(Screenshot.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(Screenshot).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_screenshot(self, id: int, session: Session = None) -> None:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
delete(Screenshot)
|
||||
.where(Screenshot.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
@@ -48,14 +51,32 @@ class DBScreenshotsHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_screenshots(
|
||||
self, rom_id: int, user_id: int, screenshots: list[str], session: Session = None
|
||||
) -> None:
|
||||
return session.execute(
|
||||
self,
|
||||
rom_id: int,
|
||||
user_id: int,
|
||||
screenshots_to_keep: list[str],
|
||||
session: Session = None,
|
||||
) -> Sequence[Screenshot]:
|
||||
purged_screenshots = session.scalars(
|
||||
select(Screenshot).filter(
|
||||
and_(
|
||||
Screenshot.rom_id == rom_id,
|
||||
Screenshot.user_id == user_id,
|
||||
Screenshot.file_name.not_in(screenshots_to_keep),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
|
||||
session.execute(
|
||||
delete(Screenshot)
|
||||
.where(
|
||||
Screenshot.rom_id == rom_id,
|
||||
Screenshot.user_id == user_id,
|
||||
Screenshot.file_name.not_in(screenshots),
|
||||
and_(
|
||||
Screenshot.rom_id == rom_id,
|
||||
Screenshot.user_id == user_id,
|
||||
Screenshot.file_name.not_in(screenshots_to_keep),
|
||||
)
|
||||
)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return purged_screenshots
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.assets import State
|
||||
from sqlalchemy import and_, delete, select, update
|
||||
@@ -12,7 +14,7 @@ class DBStatesHandler(DBBaseHandler):
|
||||
return session.merge(state)
|
||||
|
||||
@begin_session
|
||||
def get_state(self, id: int, session: Session = None) -> State:
|
||||
def get_state(self, id: int, session: Session = None) -> State | None:
|
||||
return session.get(State, id)
|
||||
|
||||
@begin_session
|
||||
@@ -27,16 +29,17 @@ class DBStatesHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def update_state(self, id: int, data: dict, session: Session = None) -> State:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(State)
|
||||
.where(State.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(State).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_state(self, id: int, session: Session = None) -> None:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
delete(State)
|
||||
.where(State.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
@@ -44,16 +47,32 @@ class DBStatesHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def purge_states(
|
||||
self, rom_id: int, user_id: int, states: list[str], session: Session = None
|
||||
) -> None:
|
||||
return session.execute(
|
||||
self,
|
||||
rom_id: int,
|
||||
user_id: int,
|
||||
states_to_keep: list[str],
|
||||
session: Session = None,
|
||||
) -> Sequence[State]:
|
||||
purged_states = session.scalars(
|
||||
select(State).filter(
|
||||
and_(
|
||||
State.rom_id == rom_id,
|
||||
State.user_id == user_id,
|
||||
State.file_name.not_in(states_to_keep),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
|
||||
session.execute(
|
||||
delete(State)
|
||||
.where(
|
||||
and_(
|
||||
State.rom_id == rom_id,
|
||||
State.user_id == user_id,
|
||||
State.file_name.not_in(states),
|
||||
State.file_name.not_in(states_to_keep),
|
||||
)
|
||||
)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return purged_states
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from decorators.database import begin_session
|
||||
from models.assets import Save, Screenshot, State
|
||||
from models.rom import Rom
|
||||
from models.rom import Rom, RomFile
|
||||
from sqlalchemy import distinct, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -11,29 +11,35 @@ class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_platforms_count(self, session: Session = None) -> int:
|
||||
"""Get the number of platforms with any roms."""
|
||||
return session.scalar(
|
||||
select(func.count(distinct(Rom.platform_id))).select_from(Rom)
|
||||
return (
|
||||
session.scalar(
|
||||
select(func.count(distinct(Rom.platform_id))).select_from(Rom)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_roms_count(self, session: Session = None) -> int:
|
||||
return session.scalar(select(func.count()).select_from(Rom))
|
||||
return session.scalar(select(func.count()).select_from(Rom)) or 0
|
||||
|
||||
@begin_session
|
||||
def get_saves_count(self, session: Session = None) -> int:
|
||||
return session.scalar(select(func.count()).select_from(Save))
|
||||
return session.scalar(select(func.count()).select_from(Save)) or 0
|
||||
|
||||
@begin_session
|
||||
def get_states_count(self, session: Session = None) -> int:
|
||||
return session.scalar(select(func.count()).select_from(State))
|
||||
return session.scalar(select(func.count()).select_from(State)) or 0
|
||||
|
||||
@begin_session
|
||||
def get_screenshots_count(self, session: Session = None) -> int:
|
||||
return session.scalar(select(func.count()).select_from(Screenshot))
|
||||
return session.scalar(select(func.count()).select_from(Screenshot)) or 0
|
||||
|
||||
@begin_session
|
||||
def get_total_filesize(self, session: Session = None) -> int:
|
||||
"""Get the total filesize of all roms in the database, in bytes."""
|
||||
return (
|
||||
session.scalar(select(func.sum(Rom.file_size_bytes)).select_from(Rom)) or 0
|
||||
session.scalar(
|
||||
select(func.sum(RomFile.file_size_bytes)).select_from(RomFile)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.user import Role, User
|
||||
from sqlalchemy import delete, select, update
|
||||
@@ -27,15 +29,16 @@ class DBUsersHandler(DBBaseHandler):
|
||||
|
||||
@begin_session
|
||||
def update_user(self, id: int, data: dict, session: Session = None) -> User:
|
||||
return session.execute(
|
||||
session.execute(
|
||||
update(User)
|
||||
.where(User.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(User).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def get_users(self, session: Session = None) -> list[User]:
|
||||
def get_users(self, session: Session = None) -> Sequence[User]:
|
||||
return session.scalars(select(User)).all()
|
||||
|
||||
@begin_session
|
||||
@@ -47,5 +50,5 @@ class DBUsersHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_admin_users(self, session: Session = None) -> list[User]:
|
||||
def get_admin_users(self, session: Session = None) -> Sequence[User]:
|
||||
return session.scalars(select(User).filter_by(role=Role.ADMIN)).all()
|
||||
|
||||
@@ -21,6 +21,10 @@ class FSAssetsHandler(FSHandler):
|
||||
shutil.rmtree(os.path.join(ASSETS_BASE_PATH, file_path, file_name))
|
||||
|
||||
def write_file(self, file: UploadFile, path: str) -> None:
|
||||
if not file.filename:
|
||||
log.error("No file name provided")
|
||||
return
|
||||
|
||||
Path(os.path.join(ASSETS_BASE_PATH, path)).mkdir(parents=True, exist_ok=True)
|
||||
log.info(f" - Uploading {file.filename}")
|
||||
file_location = os.path.join(ASSETS_BASE_PATH, path, file.filename)
|
||||
|
||||
@@ -85,6 +85,10 @@ class FSFirmwareHandler(FSHandler):
|
||||
return f"{LIBRARY_BASE_PATH}/{file_path}"
|
||||
|
||||
def write_file(self, file: UploadFile, path: str) -> None:
|
||||
if not file.filename:
|
||||
log.error("No file name provided")
|
||||
return
|
||||
|
||||
Path(path).mkdir(parents=True, exist_ok=True)
|
||||
log.info(f" - Uploading {file.filename}")
|
||||
file_location = os.path.join(path, file.filename)
|
||||
|
||||
@@ -84,8 +84,7 @@ class FSResourcesHandler(FSHandler):
|
||||
"""Returns rom cover filesystem path adapted to frontend folder structure
|
||||
|
||||
Args:
|
||||
fs_slug: short name of the platform
|
||||
file_name: name of rom file
|
||||
entity: Rom or Collection object
|
||||
size: size of the cover
|
||||
"""
|
||||
async for matched_file in Path(
|
||||
@@ -95,7 +94,7 @@ class FSResourcesHandler(FSHandler):
|
||||
return ""
|
||||
|
||||
async def get_cover(
|
||||
self, entity: Rom | Collection | None, overwrite: bool, url_cover: str = ""
|
||||
self, entity: Rom | Collection | None, overwrite: bool, url_cover: str | None
|
||||
) -> tuple[str, str]:
|
||||
if not entity:
|
||||
return "", ""
|
||||
@@ -155,8 +154,7 @@ class FSResourcesHandler(FSHandler):
|
||||
"""Store roms resources in filesystem
|
||||
|
||||
Args:
|
||||
fs_slug: short name of the platform
|
||||
file_name: name of rom
|
||||
rom: Rom object
|
||||
url: url to get the screenshot
|
||||
"""
|
||||
screenshot_file = f"{idx}.jpg"
|
||||
@@ -185,16 +183,15 @@ class FSResourcesHandler(FSHandler):
|
||||
"""Returns rom cover filesystem path adapted to frontend folder structure
|
||||
|
||||
Args:
|
||||
fs_slug: short name of the platform
|
||||
file_name: name of rom
|
||||
rom: Rom object
|
||||
idx: index number of screenshot
|
||||
"""
|
||||
return f"{rom.fs_resources_path}/screenshots/{idx}.jpg"
|
||||
|
||||
async def get_rom_screenshots(
|
||||
self, rom: Rom | None, url_screenshots: list
|
||||
self, rom: Rom | None, url_screenshots: list | None
|
||||
) -> list[str]:
|
||||
if not rom:
|
||||
if not rom or not url_screenshots:
|
||||
return []
|
||||
|
||||
path_screenshots: list[str] = []
|
||||
|
||||
@@ -8,7 +8,7 @@ import tarfile
|
||||
import zipfile
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, TypedDict
|
||||
from typing import Any, Final, Literal, TypedDict
|
||||
|
||||
import magic
|
||||
import py7zr
|
||||
@@ -16,7 +16,7 @@ import zipfile_deflate64 # trunk-ignore(ruff/F401): Patches zipfile to support
|
||||
from config import LIBRARY_BASE_PATH
|
||||
from config.config_manager import config_manager as cm
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException, RomsNotFoundException
|
||||
from models.rom import RomFile
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from py7zr.exceptions import (
|
||||
Bad7zFile,
|
||||
DecompressionError,
|
||||
@@ -63,10 +63,17 @@ FILE_READ_CHUNK_SIZE = 1024 * 8
|
||||
|
||||
class FSRom(TypedDict):
|
||||
multi: bool
|
||||
file_name: str
|
||||
fs_name: str
|
||||
files: list[RomFile]
|
||||
|
||||
|
||||
class FileHash(TypedDict):
|
||||
id: int
|
||||
crc_hash: str
|
||||
md5_hash: str
|
||||
sha1_hash: str
|
||||
|
||||
|
||||
def is_compressed_file(file_path: str) -> bool:
|
||||
mime = magic.Magic(mime=True)
|
||||
file_type = mime.from_file(file_path)
|
||||
@@ -94,7 +101,9 @@ def read_zip_file(file_path: Path) -> Iterator[bytes]:
|
||||
yield chunk
|
||||
|
||||
|
||||
def read_tar_file(file_path: Path, mode: str = "r") -> Iterator[bytes]:
|
||||
def read_tar_file(
|
||||
file_path: Path, mode: Literal["r", "r:*", "r:", "r:gz", "r:bz2", "r:xz"] = "r"
|
||||
) -> Iterator[bytes]:
|
||||
try:
|
||||
with tarfile.open(file_path, mode) as f:
|
||||
for member in f.getmembers():
|
||||
@@ -164,22 +173,26 @@ def read_bz2_file(file_path: Path) -> Iterator[bytes]:
|
||||
yield chunk
|
||||
|
||||
|
||||
def category_matches(category: str, path_parts: list[str]):
|
||||
return category in path_parts or f"{category}s" in path_parts
|
||||
|
||||
|
||||
class FSRomsHandler(FSHandler):
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def remove_file(self, file_name: str, file_path: str) -> None:
|
||||
def remove_from_fs(self, fs_path: str, fs_name: str) -> None:
|
||||
try:
|
||||
os.remove(f"{LIBRARY_BASE_PATH}/{file_path}/{file_name}")
|
||||
os.remove(f"{LIBRARY_BASE_PATH}/{fs_path}/{fs_name}")
|
||||
except IsADirectoryError:
|
||||
shutil.rmtree(f"{LIBRARY_BASE_PATH}/{file_path}/{file_name}")
|
||||
shutil.rmtree(f"{LIBRARY_BASE_PATH}/{fs_path}/{fs_name}")
|
||||
|
||||
def parse_tags(self, file_name: str) -> tuple:
|
||||
def parse_tags(self, fs_name: str) -> tuple:
|
||||
rev = ""
|
||||
regs = []
|
||||
langs = []
|
||||
other_tags = []
|
||||
tags = [tag[0] or tag[1] for tag in TAG_REGEX.findall(file_name)]
|
||||
tags = [tag[0] or tag[1] for tag in TAG_REGEX.findall(fs_name)]
|
||||
tags = [tag for subtags in tags for tag in subtags.split(",")]
|
||||
tags = [tag.strip() for tag in tags]
|
||||
|
||||
@@ -229,40 +242,69 @@ class FSRomsHandler(FSHandler):
|
||||
|
||||
return [f for f in roms if f not in filtered_files]
|
||||
|
||||
def _build_rom_file(self, path: Path) -> RomFile:
|
||||
def _build_rom_file(self, rom_path: Path, file_name: str) -> RomFile:
|
||||
# Absolute path to roms
|
||||
abs_file_path = Path(LIBRARY_BASE_PATH, rom_path, file_name)
|
||||
|
||||
path_parts_lower = list(map(str.lower, rom_path.parts))
|
||||
matching_category = next(
|
||||
(
|
||||
category
|
||||
for category in RomFileCategory
|
||||
if category_matches(category.value, path_parts_lower)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
return RomFile(
|
||||
filename=path.name,
|
||||
size=os.stat(path).st_size,
|
||||
last_modified=os.path.getmtime(path),
|
||||
file_name=file_name,
|
||||
file_path=str(rom_path),
|
||||
file_size_bytes=os.stat(abs_file_path).st_size,
|
||||
last_modified=os.path.getmtime(abs_file_path),
|
||||
category=matching_category,
|
||||
)
|
||||
|
||||
def get_rom_files(self, rom: str, roms_path: str) -> list[RomFile]:
|
||||
abs_fs_path = f"{LIBRARY_BASE_PATH}/{roms_path}" # Absolute path to roms
|
||||
rom_files: list[RomFile] = []
|
||||
|
||||
# Check if rom is a multi-part rom
|
||||
if os.path.isdir(f"{roms_path}/{rom}"):
|
||||
multi_files = os.listdir(f"{roms_path}/{rom}")
|
||||
for file in self._exclude_files(multi_files, "multi_parts"):
|
||||
path = Path(roms_path, rom, file)
|
||||
rom_files.append(self._build_rom_file(path))
|
||||
if os.path.isdir(f"{abs_fs_path}/{rom}"):
|
||||
for f_path, file in iter_files(f"{abs_fs_path}/{rom}", recursive=True):
|
||||
rom_files.append(
|
||||
self._build_rom_file(f_path.relative_to(LIBRARY_BASE_PATH), file)
|
||||
)
|
||||
else:
|
||||
path = Path(roms_path, rom)
|
||||
rom_files.append(self._build_rom_file(path))
|
||||
rom_files.append(self._build_rom_file(Path(roms_path), rom))
|
||||
|
||||
return rom_files
|
||||
|
||||
def _calculate_rom_hashes(
|
||||
self, file_path: Path, crc_c: int, md5_h: Any, sha1_h: Any
|
||||
) -> tuple[int, Any, Any]:
|
||||
self,
|
||||
file_path: Path,
|
||||
rom_crc_c: int,
|
||||
rom_md5_h: Any,
|
||||
rom_sha1_h: Any,
|
||||
) -> tuple[int, int, Any, Any, Any, Any]:
|
||||
mime = magic.Magic(mime=True)
|
||||
file_type = mime.from_file(file_path)
|
||||
extension = Path(file_path).suffix.lower()
|
||||
|
||||
crc_c = 0
|
||||
md5_h = hashlib.md5(usedforsecurity=False)
|
||||
sha1_h = hashlib.sha1(usedforsecurity=False)
|
||||
|
||||
def update_hashes(chunk: bytes | bytearray):
|
||||
md5_h.update(chunk)
|
||||
rom_md5_h.update(chunk)
|
||||
|
||||
sha1_h.update(chunk)
|
||||
rom_sha1_h.update(chunk)
|
||||
|
||||
nonlocal crc_c
|
||||
crc_c = binascii.crc32(chunk, crc_c)
|
||||
nonlocal rom_crc_c
|
||||
rom_crc_c = binascii.crc32(chunk, rom_crc_c)
|
||||
|
||||
if extension == ".zip" or file_type == "application/zip":
|
||||
for chunk in read_zip_file(file_path):
|
||||
@@ -291,35 +333,39 @@ class FSRomsHandler(FSHandler):
|
||||
for chunk in read_basic_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
return crc_c, md5_h, sha1_h
|
||||
return crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h
|
||||
|
||||
def get_rom_hashes(self, rom: str, roms_path: str) -> dict[str, str]:
|
||||
roms_file_path = f"{LIBRARY_BASE_PATH}/{roms_path}"
|
||||
def get_rom_hashes(self, rom: Rom) -> tuple[FileHash, list[FileHash]]:
|
||||
rom_crc_c = 0
|
||||
rom_md5_h = hashlib.md5(usedforsecurity=False)
|
||||
rom_sha1_h = hashlib.sha1(usedforsecurity=False)
|
||||
|
||||
crc_c = 0
|
||||
md5_h = hashlib.md5(usedforsecurity=False)
|
||||
sha1_h = hashlib.sha1(usedforsecurity=False)
|
||||
files = rom.files
|
||||
hashed_files = []
|
||||
|
||||
# Check if rom is a multi-part rom
|
||||
if os.path.isdir(f"{roms_file_path}/{rom}"):
|
||||
multi_files = os.listdir(f"{roms_file_path}/{rom}")
|
||||
for file in self._exclude_files(multi_files, "multi_parts"):
|
||||
path = Path(roms_file_path, rom, file)
|
||||
# Pass the raw hashes to the next iteration
|
||||
crc_c, md5_h, sha1_h = self._calculate_rom_hashes(
|
||||
path, crc_c, md5_h, sha1_h
|
||||
for file in files:
|
||||
path = Path(LIBRARY_BASE_PATH, file.file_path, file.file_name)
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
self._calculate_rom_hashes(path, rom_crc_c, rom_md5_h, rom_sha1_h)
|
||||
)
|
||||
hashed_files.append(
|
||||
FileHash(
|
||||
id=file.id,
|
||||
crc_hash=crc32_to_hex(crc_c),
|
||||
md5_hash=md5_h.hexdigest(),
|
||||
sha1_hash=sha1_h.hexdigest(),
|
||||
)
|
||||
else:
|
||||
path = Path(roms_file_path, rom)
|
||||
crc_c, md5_h, sha1_h = self._calculate_rom_hashes(
|
||||
path, crc_c, md5_h, sha1_h
|
||||
)
|
||||
|
||||
return {
|
||||
"crc_hash": crc32_to_hex(crc_c),
|
||||
"md5_hash": md5_h.hexdigest(),
|
||||
"sha1_hash": sha1_h.hexdigest(),
|
||||
}
|
||||
return (
|
||||
FileHash(
|
||||
id=rom.id,
|
||||
crc_hash=crc32_to_hex(rom_crc_c),
|
||||
md5_hash=rom_md5_h.hexdigest(),
|
||||
sha1_hash=rom_sha1_h.hexdigest(),
|
||||
),
|
||||
hashed_files,
|
||||
)
|
||||
|
||||
def get_roms(self, platform_fs_slug: str) -> list[FSRom]:
|
||||
"""Gets all filesystem roms for a platform
|
||||
@@ -329,24 +375,26 @@ class FSRomsHandler(FSHandler):
|
||||
Returns:
|
||||
list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH
|
||||
"""
|
||||
roms_path = self.get_roms_fs_structure(platform_fs_slug)
|
||||
roms_file_path = f"{LIBRARY_BASE_PATH}/{roms_path}"
|
||||
rel_roms_path = self.get_roms_fs_structure(
|
||||
platform_fs_slug
|
||||
) # Relative path to roms
|
||||
abs_fs_path = f"{LIBRARY_BASE_PATH}/{rel_roms_path}" # Absolute path to roms
|
||||
|
||||
try:
|
||||
fs_single_roms = [f for _, f in iter_files(roms_file_path)]
|
||||
fs_single_roms = [f for _, f in iter_files(abs_fs_path)]
|
||||
except IndexError as exc:
|
||||
raise RomsNotFoundException(platform_fs_slug) from exc
|
||||
|
||||
try:
|
||||
fs_multi_roms = [d for _, d in iter_directories(roms_file_path)]
|
||||
fs_multi_roms = [d for _, d in iter_directories(abs_fs_path)]
|
||||
except IndexError as exc:
|
||||
raise RomsNotFoundException(platform_fs_slug) from exc
|
||||
|
||||
fs_roms: list[dict] = [
|
||||
{"multi": False, "file_name": rom}
|
||||
{"multi": False, "fs_name": rom}
|
||||
for rom in self._exclude_files(fs_single_roms, "single")
|
||||
] + [
|
||||
{"multi": True, "file_name": rom}
|
||||
{"multi": True, "fs_name": rom}
|
||||
for rom in self._exclude_multi_roms(fs_multi_roms)
|
||||
]
|
||||
|
||||
@@ -354,35 +402,35 @@ class FSRomsHandler(FSHandler):
|
||||
[
|
||||
FSRom(
|
||||
multi=rom["multi"],
|
||||
file_name=rom["file_name"],
|
||||
files=self.get_rom_files(rom["file_name"], roms_file_path),
|
||||
fs_name=rom["fs_name"],
|
||||
files=self.get_rom_files(rom["fs_name"], rel_roms_path),
|
||||
)
|
||||
for rom in fs_roms
|
||||
],
|
||||
key=lambda rom: rom["file_name"],
|
||||
key=lambda rom: rom["fs_name"],
|
||||
)
|
||||
|
||||
def file_exists(self, path: str, file_name: str) -> bool:
|
||||
def file_exists(self, fs_path: str, fs_name: str) -> bool:
|
||||
"""Check if file exists in filesystem
|
||||
|
||||
Args:
|
||||
path: path to file
|
||||
file_name: name of file
|
||||
fs_name: name of file
|
||||
Returns
|
||||
True if file exists in filesystem else False
|
||||
"""
|
||||
return bool(os.path.exists(f"{LIBRARY_BASE_PATH}/{path}/{file_name}"))
|
||||
return bool(os.path.exists(f"{LIBRARY_BASE_PATH}/{fs_path}/{fs_name}"))
|
||||
|
||||
def rename_file(self, old_name: str, new_name: str, file_path: str) -> None:
|
||||
def rename_fs_rom(self, old_name: str, new_name: str, fs_path: str) -> None:
|
||||
if new_name != old_name:
|
||||
if self.file_exists(path=file_path, file_name=new_name):
|
||||
if self.file_exists(fs_path=fs_path, fs_name=new_name):
|
||||
raise RomAlreadyExistsException(new_name)
|
||||
|
||||
os.rename(
|
||||
f"{LIBRARY_BASE_PATH}/{file_path}/{old_name}",
|
||||
f"{LIBRARY_BASE_PATH}/{file_path}/{new_name}",
|
||||
f"{LIBRARY_BASE_PATH}/{fs_path}/{old_name}",
|
||||
f"{LIBRARY_BASE_PATH}/{fs_path}/{new_name}",
|
||||
)
|
||||
|
||||
def build_upload_file_path(self, fs_slug: str) -> str:
|
||||
def build_upload_fs_path(self, fs_slug: str) -> str:
|
||||
file_path = self.get_roms_fs_structure(fs_slug)
|
||||
return f"{LIBRARY_BASE_PATH}/{file_path}"
|
||||
|
||||
@@ -32,10 +32,10 @@ def test_get_roms():
|
||||
roms = fs_rom_handler.get_roms(platform_fs_slug=platform.fs_slug)
|
||||
|
||||
assert len(roms) == 2
|
||||
assert roms[0]["file_name"] == "Paper Mario (USA).z64"
|
||||
assert roms[0]["fs_name"] == "Paper Mario (USA).z64"
|
||||
assert not roms[0]["multi"]
|
||||
|
||||
assert roms[1]["file_name"] == "Super Mario 64 (J) (Rev A)"
|
||||
assert roms[1]["fs_name"] == "Super Mario 64 (J) (Rev A)"
|
||||
assert roms[1]["multi"]
|
||||
|
||||
|
||||
|
||||
@@ -236,6 +236,8 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
|
||||
async def _request(self, url: str, data: str, timeout: int = 120) -> list:
|
||||
httpx_client = ctx_httpx_client.get()
|
||||
masked_headers = {}
|
||||
|
||||
try:
|
||||
masked_headers = self._mask_sensitive_values(self.headers)
|
||||
log.debug(
|
||||
@@ -413,7 +415,7 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
return IGDBPlatform(igdb_id=None, slug=slug)
|
||||
|
||||
@check_twitch_token
|
||||
async def get_rom(self, file_name: str, platform_igdb_id: int) -> IGDBRom:
|
||||
async def get_rom(self, fs_name: str, platform_igdb_id: int) -> IGDBRom:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
if not IGDB_API_ENABLED:
|
||||
@@ -422,17 +424,17 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
if not platform_igdb_id:
|
||||
return IGDBRom(igdb_id=None)
|
||||
|
||||
search_term = fs_rom_handler.get_file_name_with_no_tags(file_name)
|
||||
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name)
|
||||
fallback_rom = IGDBRom(igdb_id=None)
|
||||
|
||||
# Support for PS2 OPL filename format
|
||||
match = PS2_OPL_REGEX.match(file_name)
|
||||
match = PS2_OPL_REGEX.match(fs_name)
|
||||
if platform_igdb_id == PS2_IGDB_ID and match:
|
||||
search_term = await self._ps2_opl_format(match, search_term)
|
||||
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
|
||||
|
||||
# Support for sony serial filename format (PS, PS3, PS3)
|
||||
match = SONY_SERIAL_REGEX.search(file_name, re.IGNORECASE)
|
||||
match = SONY_SERIAL_REGEX.search(fs_name, re.IGNORECASE)
|
||||
if platform_igdb_id == PS1_IGDB_ID and match:
|
||||
search_term = await self._ps1_serial_format(match, search_term)
|
||||
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
|
||||
@@ -446,7 +448,7 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
fallback_rom = IGDBRom(igdb_id=None, name=search_term)
|
||||
|
||||
# Support for switch titleID filename format
|
||||
match = SWITCH_TITLEDB_REGEX.search(file_name)
|
||||
match = SWITCH_TITLEDB_REGEX.search(fs_name)
|
||||
if platform_igdb_id == SWITCH_IGDB_ID and match:
|
||||
search_term, index_entry = await self._switch_titledb_format(
|
||||
match, search_term
|
||||
@@ -461,7 +463,7 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
)
|
||||
|
||||
# Support for switch productID filename format
|
||||
match = SWITCH_PRODUCT_ID_REGEX.search(file_name)
|
||||
match = SWITCH_PRODUCT_ID_REGEX.search(fs_name)
|
||||
if platform_igdb_id == SWITCH_IGDB_ID and match:
|
||||
search_term, index_entry = await self._switch_productid_format(
|
||||
match, search_term
|
||||
@@ -567,7 +569,7 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
|
||||
@check_twitch_token
|
||||
async def get_matched_roms_by_name(
|
||||
self, search_term: str, platform_igdb_id: int
|
||||
self, search_term: str, platform_igdb_id: int | None
|
||||
) -> list[IGDBRom]:
|
||||
if not IGDB_API_ENABLED:
|
||||
return []
|
||||
@@ -637,7 +639,7 @@ class IGDBBaseHandler(MetadataHandler):
|
||||
)
|
||||
),
|
||||
"url_screenshots": [
|
||||
self._normalize_cover_url(s.get("url", "")).replace(
|
||||
self._normalize_cover_url(s.get("url", "")).replace( # type: ignore[attr-defined]
|
||||
"t_thumb", "t_720p"
|
||||
)
|
||||
for s in rom.get("screenshots", [])
|
||||
|
||||
@@ -180,7 +180,7 @@ class MobyGamesHandler(MetadataHandler):
|
||||
name=platform["name"],
|
||||
)
|
||||
|
||||
async def get_rom(self, file_name: str, platform_moby_id: int) -> MobyGamesRom:
|
||||
async def get_rom(self, fs_name: str, platform_moby_id: int) -> MobyGamesRom:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
if not MOBY_API_ENABLED:
|
||||
@@ -189,17 +189,17 @@ class MobyGamesHandler(MetadataHandler):
|
||||
if not platform_moby_id:
|
||||
return MobyGamesRom(moby_id=None)
|
||||
|
||||
search_term = fs_rom_handler.get_file_name_with_no_tags(file_name)
|
||||
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name)
|
||||
fallback_rom = MobyGamesRom(moby_id=None)
|
||||
|
||||
# Support for PS2 OPL filename format
|
||||
match = PS2_OPL_REGEX.match(file_name)
|
||||
match = PS2_OPL_REGEX.match(fs_name)
|
||||
if platform_moby_id == PS2_MOBY_ID and match:
|
||||
search_term = await self._ps2_opl_format(match, search_term)
|
||||
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
|
||||
|
||||
# Support for sony serial filename format (PS, PS3, PS3)
|
||||
match = SONY_SERIAL_REGEX.search(file_name, re.IGNORECASE)
|
||||
match = SONY_SERIAL_REGEX.search(fs_name, re.IGNORECASE)
|
||||
if platform_moby_id == PS1_MOBY_ID and match:
|
||||
search_term = await self._ps1_serial_format(match, search_term)
|
||||
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
|
||||
@@ -213,7 +213,7 @@ class MobyGamesHandler(MetadataHandler):
|
||||
fallback_rom = MobyGamesRom(moby_id=None, name=search_term)
|
||||
|
||||
# Support for switch titleID filename format
|
||||
match = SWITCH_TITLEDB_REGEX.search(file_name)
|
||||
match = SWITCH_TITLEDB_REGEX.search(fs_name)
|
||||
if platform_moby_id == SWITCH_MOBY_ID and match:
|
||||
search_term, index_entry = await self._switch_titledb_format(
|
||||
match, search_term
|
||||
@@ -228,7 +228,7 @@ class MobyGamesHandler(MetadataHandler):
|
||||
)
|
||||
|
||||
# Support for switch productID filename format
|
||||
match = SWITCH_PRODUCT_ID_REGEX.search(file_name)
|
||||
match = SWITCH_PRODUCT_ID_REGEX.search(fs_name)
|
||||
if platform_moby_id == SWITCH_MOBY_ID and match:
|
||||
search_term, index_entry = await self._switch_productid_format(
|
||||
match, search_term
|
||||
@@ -310,7 +310,7 @@ class MobyGamesHandler(MetadataHandler):
|
||||
return rom if rom["moby_id"] else None
|
||||
|
||||
async def get_matched_roms_by_name(
|
||||
self, search_term: str, platform_moby_id: int
|
||||
self, search_term: str, platform_moby_id: int | None
|
||||
) -> list[MobyGamesRom]:
|
||||
if not MOBY_API_ENABLED:
|
||||
return []
|
||||
@@ -325,8 +325,8 @@ class MobyGamesHandler(MetadataHandler):
|
||||
matched_roms = (await self._request(str(url))).get("games", [])
|
||||
|
||||
return [
|
||||
MobyGamesRom( # type: ignore[misc]
|
||||
{
|
||||
MobyGamesRom(
|
||||
{ # type: ignore[misc]
|
||||
k: v
|
||||
for k, v in {
|
||||
"moby_id": rom["game_id"],
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import zlib
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
@@ -11,7 +10,7 @@ from handler.filesystem.roms_handler import FSRom
|
||||
from handler.metadata import meta_igdb_handler, meta_moby_handler
|
||||
from handler.metadata.igdb_handler import IGDBPlatform, IGDBRom
|
||||
from handler.metadata.moby_handler import MobyGamesPlatform, MobyGamesRom
|
||||
from logger.formatter import BLUE, RED
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.assets import Save, Screenshot, State
|
||||
@@ -20,37 +19,6 @@ from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
|
||||
NON_HASHABLE_PLATFORMS = frozenset(
|
||||
(
|
||||
"amazon-alexa",
|
||||
"amazon-fire-tv",
|
||||
"android",
|
||||
"gear-vr",
|
||||
"ios",
|
||||
"ipad",
|
||||
"linux",
|
||||
"mac",
|
||||
"meta-quest-2",
|
||||
"meta-quest-3",
|
||||
"oculus-go",
|
||||
"oculus-quest",
|
||||
"oculus-rift",
|
||||
"pc",
|
||||
"ps3",
|
||||
"ps4",
|
||||
"ps4--1",
|
||||
"ps5",
|
||||
"psvr",
|
||||
"psvr2",
|
||||
"series-x",
|
||||
"switch",
|
||||
"wiiu",
|
||||
"win",
|
||||
"xbox360",
|
||||
"xboxone",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ScanType(Enum):
|
||||
NEW_PLATFORMS = "new_platforms"
|
||||
@@ -144,7 +112,9 @@ async def scan_platform(
|
||||
)
|
||||
else:
|
||||
log.warning(
|
||||
emoji.emojize(f" {platform_attrs['slug']} not identified :cross_mark:")
|
||||
emoji.emojize(
|
||||
f" Platform {platform_attrs['slug']} not identified :cross_mark:"
|
||||
)
|
||||
)
|
||||
|
||||
return Platform(**platform_attrs)
|
||||
@@ -207,18 +177,19 @@ async def scan_rom(
|
||||
|
||||
roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug)
|
||||
|
||||
log.info(f"\t · {hl(fs_rom['file_name'])}")
|
||||
log.info(f"\t · {hl(fs_rom['fs_name'])}")
|
||||
|
||||
if fs_rom.get("multi", False):
|
||||
for file in fs_rom["files"]:
|
||||
log.info(f"\t\t · {file['filename']}")
|
||||
log.info(f"\t\t · {file.file_name}")
|
||||
|
||||
# Set default properties
|
||||
rom_attrs = {
|
||||
**fs_rom,
|
||||
"id": rom.id if rom else None,
|
||||
"multi": fs_rom["multi"],
|
||||
"fs_name": fs_rom["fs_name"],
|
||||
"platform_id": platform.id,
|
||||
"name": fs_rom["file_name"],
|
||||
"name": fs_rom["fs_name"],
|
||||
"url_cover": "",
|
||||
"url_screenshots": [],
|
||||
}
|
||||
@@ -244,23 +215,20 @@ async def scan_rom(
|
||||
)
|
||||
|
||||
# Update properties that don't require metadata
|
||||
file_size = sum([file["size"] for file in rom_attrs["files"]])
|
||||
regs, rev, langs, other_tags = fs_rom_handler.parse_tags(rom_attrs["file_name"])
|
||||
filesize = sum([file.file_size_bytes for file in fs_rom["files"]])
|
||||
regs, rev, langs, other_tags = fs_rom_handler.parse_tags(rom_attrs["fs_name"])
|
||||
rom_attrs.update(
|
||||
{
|
||||
"file_path": roms_path,
|
||||
"file_name": rom_attrs["file_name"],
|
||||
"file_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(
|
||||
rom_attrs["file_name"]
|
||||
"fs_path": roms_path,
|
||||
"fs_name": rom_attrs["fs_name"],
|
||||
"fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(
|
||||
rom_attrs["fs_name"]
|
||||
),
|
||||
"file_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
|
||||
rom_attrs["file_name"]
|
||||
"fs_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
|
||||
rom_attrs["fs_name"]
|
||||
),
|
||||
"file_extension": fs_rom_handler.parse_file_extension(
|
||||
rom_attrs["file_name"]
|
||||
),
|
||||
"file_size_bytes": file_size,
|
||||
"multi": rom_attrs["multi"],
|
||||
"fs_extension": fs_rom_handler.parse_file_extension(rom_attrs["fs_name"]),
|
||||
"fs_size_bytes": filesize,
|
||||
"regions": regs,
|
||||
"revision": rev,
|
||||
"languages": langs,
|
||||
@@ -268,23 +236,9 @@ async def scan_rom(
|
||||
}
|
||||
)
|
||||
|
||||
# Calculating hashes is expensive, so we only do it if necessary
|
||||
# Set empty hashes when we plan to recalculate them
|
||||
if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES:
|
||||
# Skip hashing games for platforms that don't have a hash database
|
||||
if platform.slug in NON_HASHABLE_PLATFORMS:
|
||||
rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""})
|
||||
else:
|
||||
try:
|
||||
rom_hashes = fs_rom_handler.get_rom_hashes(
|
||||
rom_attrs["file_name"], roms_path
|
||||
)
|
||||
rom_attrs.update(**rom_hashes)
|
||||
except zlib.error as e:
|
||||
# Return empty hashes if calculating them fails for corrupted files
|
||||
log.error(
|
||||
f"Hashes of {rom_attrs['file_name']} couldn't be calculated: {hl(str(e), color=RED)}"
|
||||
)
|
||||
rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""})
|
||||
rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""})
|
||||
|
||||
# If no metadata scan is required
|
||||
if scan_type == ScanType.HASHES:
|
||||
@@ -303,7 +257,7 @@ async def scan_rom(
|
||||
):
|
||||
main_platform_igdb_id = await _get_main_platform_igdb_id(platform)
|
||||
return await meta_igdb_handler.get_rom(
|
||||
rom_attrs["file_name"], main_platform_igdb_id
|
||||
rom_attrs["fs_name"], main_platform_igdb_id or platform.igdb_id
|
||||
)
|
||||
|
||||
return IGDBRom(igdb_id=None)
|
||||
@@ -320,7 +274,7 @@ async def scan_rom(
|
||||
)
|
||||
):
|
||||
return await meta_moby_handler.get_rom(
|
||||
rom_attrs["file_name"], platform_moby_id=platform.moby_id
|
||||
rom_attrs["fs_name"], platform_moby_id=platform.moby_id
|
||||
)
|
||||
|
||||
return MobyGamesRom(moby_id=None)
|
||||
@@ -336,7 +290,9 @@ async def scan_rom(
|
||||
# If not found in IGDB or MobyGames
|
||||
if not igdb_handler_rom.get("igdb_id") and not moby_handler_rom.get("moby_id"):
|
||||
log.warning(
|
||||
emoji.emojize(f"\t {rom_attrs['file_name']} not identified :cross_mark:")
|
||||
emoji.emojize(
|
||||
f"\t Rom {rom_attrs['fs_name']} not identified :cross_mark:"
|
||||
)
|
||||
)
|
||||
return Rom(**rom_attrs)
|
||||
|
||||
|
||||
@@ -51,12 +51,11 @@ def rom(platform: Platform):
|
||||
platform_id=platform.id,
|
||||
name="test_rom",
|
||||
slug="test_rom_slug",
|
||||
file_name="test_rom.zip",
|
||||
file_name_no_tags="test_rom",
|
||||
file_name_no_ext="test_rom",
|
||||
file_extension="zip",
|
||||
file_path=f"{platform.slug}/roms",
|
||||
file_size_bytes=1000.0,
|
||||
fs_name="test_rom.zip",
|
||||
fs_name_no_tags="test_rom",
|
||||
fs_name_no_ext="test_rom",
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
)
|
||||
return db_rom_handler.add_rom(rom)
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ def test_platforms():
|
||||
assert len(platforms) == 1
|
||||
|
||||
platform = db_platform_handler.get_platform_by_fs_slug(platform.fs_slug)
|
||||
assert platform is not None
|
||||
assert platform.name == "test_platform"
|
||||
|
||||
db_platform_handler.purge_platforms([])
|
||||
@@ -37,33 +38,32 @@ def test_roms(rom: Rom, platform: Platform):
|
||||
platform_id=rom.platform_id,
|
||||
name="test_rom_2",
|
||||
slug="test_rom_slug_2",
|
||||
file_name="test_rom_2",
|
||||
file_name_no_tags="test_rom_2",
|
||||
file_name_no_ext="test_rom_2",
|
||||
file_extension="zip",
|
||||
file_path=f"{platform.slug}/roms",
|
||||
file_size_bytes=1000.0,
|
||||
fs_name="test_rom_2",
|
||||
fs_name_no_tags="test_rom_2",
|
||||
fs_name_no_ext="test_rom_2",
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
)
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms(platform_id=platform.id)
|
||||
assert len(roms) == 2
|
||||
|
||||
rom = db_rom_handler.get_rom(roms[0].id)
|
||||
assert rom is not None
|
||||
assert rom.file_name == "test_rom.zip"
|
||||
rom_1 = db_rom_handler.get_rom(roms[0].id)
|
||||
assert rom_1 is not None
|
||||
assert rom_1.fs_name == "test_rom.zip"
|
||||
|
||||
db_rom_handler.update_rom(roms[1].id, {"file_name": "test_rom_2_updated"})
|
||||
db_rom_handler.update_rom(roms[1].id, {"fs_name": "test_rom_2_updated"})
|
||||
rom_2 = db_rom_handler.get_rom(roms[1].id)
|
||||
assert rom_2 is not None
|
||||
assert rom_2.file_name == "test_rom_2_updated"
|
||||
assert rom_2.fs_name == "test_rom_2_updated"
|
||||
|
||||
db_rom_handler.delete_rom(rom.id)
|
||||
|
||||
roms = db_rom_handler.get_roms(platform_id=platform.id)
|
||||
assert len(roms) == 1
|
||||
|
||||
db_rom_handler.purge_roms(rom_2.platform_id, [rom_2.id])
|
||||
db_rom_handler.purge_roms(rom_2.platform_id, [])
|
||||
|
||||
roms = db_rom_handler.get_roms(platform_id=platform.id)
|
||||
assert len(roms) == 0
|
||||
@@ -71,12 +71,11 @@ def test_roms(rom: Rom, platform: Platform):
|
||||
|
||||
def test_utils(rom: Rom, platform: Platform):
|
||||
roms = db_rom_handler.get_roms(platform_id=platform.id)
|
||||
assert (
|
||||
db_rom_handler.get_rom_by_filename(
|
||||
platform_id=platform.id, file_name=rom.file_name
|
||||
).id
|
||||
== roms[0].id
|
||||
rom_1 = db_rom_handler.get_rom_by_fs_name(
|
||||
platform_id=platform.id, fs_name=rom.fs_name
|
||||
)
|
||||
assert rom_1
|
||||
assert rom_1.id == roms[0].id
|
||||
|
||||
|
||||
def test_users(admin_user):
|
||||
@@ -91,6 +90,7 @@ def test_users(admin_user):
|
||||
assert len(all_users) == 2
|
||||
|
||||
new_user = db_user_handler.get_user_by_username("new_user")
|
||||
assert new_user is not None
|
||||
assert new_user.username == "new_user"
|
||||
assert new_user.role == Role.VIEWER
|
||||
assert new_user.enabled
|
||||
@@ -98,6 +98,7 @@ def test_users(admin_user):
|
||||
db_user_handler.update_user(new_user.id, {"role": Role.EDITOR})
|
||||
|
||||
new_user = db_user_handler.get_user(new_user.id)
|
||||
assert new_user is not None
|
||||
assert new_user.role == Role.EDITOR
|
||||
|
||||
db_user_handler.delete_user(new_user.id)
|
||||
@@ -136,14 +137,16 @@ def test_saves(save: Save, platform: Platform, admin_user: User):
|
||||
assert rom is not None
|
||||
assert len(rom.saves) == 2
|
||||
|
||||
save = db_save_handler.get_save(rom.saves[0].id)
|
||||
assert save.file_name == "test_save.sav"
|
||||
new_save = db_save_handler.get_save(rom.saves[0].id)
|
||||
assert new_save is not None
|
||||
assert new_save.file_name == "test_save.sav"
|
||||
|
||||
db_save_handler.update_save(save.id, {"file_name": "test_save_2.sav"})
|
||||
save = db_save_handler.get_save(save.id)
|
||||
assert save.file_name == "test_save_2.sav"
|
||||
db_save_handler.update_save(new_save.id, {"file_name": "test_save_2.sav"})
|
||||
new_save = db_save_handler.get_save(new_save.id)
|
||||
assert new_save is not None
|
||||
assert new_save.file_name == "test_save_2.sav"
|
||||
|
||||
db_save_handler.delete_save(save.id)
|
||||
db_save_handler.delete_save(new_save.id)
|
||||
|
||||
rom = db_rom_handler.get_rom(save.rom_id)
|
||||
assert rom is not None
|
||||
@@ -168,14 +171,16 @@ def test_states(state: State, platform: Platform, admin_user: User):
|
||||
assert rom is not None
|
||||
assert len(rom.states) == 2
|
||||
|
||||
state = db_state_handler.get_state(rom.states[0].id)
|
||||
assert state.file_name == "test_state.state"
|
||||
new_state = db_state_handler.get_state(rom.states[0].id)
|
||||
assert new_state is not None
|
||||
assert new_state.file_name == "test_state.state"
|
||||
|
||||
db_state_handler.update_state(state.id, {"file_name": "test_state_2.state"})
|
||||
state = db_state_handler.get_state(state.id)
|
||||
assert state.file_name == "test_state_2.state"
|
||||
db_state_handler.update_state(new_state.id, {"file_name": "test_state_2.state"})
|
||||
new_state = db_state_handler.get_state(new_state.id)
|
||||
assert new_state is not None
|
||||
assert new_state.file_name == "test_state_2.state"
|
||||
|
||||
db_state_handler.delete_state(state.id)
|
||||
db_state_handler.delete_state(new_state.id)
|
||||
|
||||
rom = db_rom_handler.get_rom(state.rom_id)
|
||||
assert rom is not None
|
||||
@@ -200,16 +205,18 @@ def test_screenshots(screenshot: Screenshot, platform: Platform, admin_user: Use
|
||||
assert rom is not None
|
||||
assert len(rom.screenshots) == 2
|
||||
|
||||
screenshot = db_screenshot_handler.get_screenshot(rom.screenshots[0].id)
|
||||
assert screenshot.file_name == "test_screenshot.png"
|
||||
new_screenshot = db_screenshot_handler.get_screenshot(rom.screenshots[0].id)
|
||||
assert new_screenshot is not None
|
||||
assert new_screenshot.file_name == "test_screenshot.png"
|
||||
|
||||
db_screenshot_handler.update_screenshot(
|
||||
screenshot.id, {"file_name": "test_screenshot_2.png"}
|
||||
new_screenshot.id, {"file_name": "test_screenshot_2.png"}
|
||||
)
|
||||
screenshot = db_screenshot_handler.get_screenshot(screenshot.id)
|
||||
assert screenshot.file_name == "test_screenshot_2.png"
|
||||
new_screenshot = db_screenshot_handler.get_screenshot(new_screenshot.id)
|
||||
assert new_screenshot is not None
|
||||
assert new_screenshot.file_name == "test_screenshot_2.png"
|
||||
|
||||
db_screenshot_handler.delete_screenshot(screenshot.id)
|
||||
db_screenshot_handler.delete_screenshot(new_screenshot.id)
|
||||
|
||||
rom = db_rom_handler.get_rom(screenshot.rom_id)
|
||||
assert rom is not None
|
||||
|
||||
@@ -32,23 +32,23 @@ async def test_scan_rom():
|
||||
async with initialize_context():
|
||||
files = [
|
||||
RomFile(
|
||||
filename="Paper Mario (USA).z64",
|
||||
size=1024,
|
||||
file_name="Paper Mario (USA).z64",
|
||||
file_path="n64/Paper Mario (USA)",
|
||||
file_size_bytes=1024,
|
||||
last_modified=1620000000,
|
||||
)
|
||||
]
|
||||
|
||||
rom = await scan_rom(
|
||||
platform,
|
||||
{"file_name": "Paper Mario (USA).z64", "multi": False, "files": files},
|
||||
{"fs_name": "Paper Mario (USA).z64", "multi": False, "files": files},
|
||||
ScanType.QUICK,
|
||||
)
|
||||
|
||||
assert type(rom) is Rom
|
||||
assert rom.file_name == "Paper Mario (USA).z64"
|
||||
assert rom.fs_name == "Paper Mario (USA).z64"
|
||||
assert rom.name == "Paper Mario"
|
||||
assert rom.igdb_id == 3340
|
||||
assert rom.file_size_bytes == 1024
|
||||
assert rom.files == files
|
||||
assert rom.fs_size_bytes == 1024
|
||||
assert rom.tags == []
|
||||
assert not rom.multi
|
||||
|
||||
@@ -45,17 +45,17 @@ class Formatter(logging.Formatter):
|
||||
level = "%(levelname)s"
|
||||
dots = f"{Fore.RESET}:"
|
||||
identifier = (
|
||||
f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]"
|
||||
f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]"
|
||||
if hasattr(record, "module_name")
|
||||
else f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]"
|
||||
)
|
||||
identifier_warning = (
|
||||
f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]"
|
||||
f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]"
|
||||
if hasattr(record, "module_name")
|
||||
else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]"
|
||||
)
|
||||
identifier_critical = (
|
||||
f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]"
|
||||
f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]"
|
||||
if hasattr(record, "module_name")
|
||||
else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]"
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, TypedDict
|
||||
from typing import TYPE_CHECKING, Any, Sequence
|
||||
|
||||
from config import FRONTEND_RESOURCES_PATH
|
||||
from models.base import BaseModel
|
||||
@@ -29,10 +29,39 @@ if TYPE_CHECKING:
|
||||
from models.user import User
|
||||
|
||||
|
||||
class RomFile(TypedDict):
|
||||
filename: str
|
||||
size: int
|
||||
last_modified: float | None
|
||||
class RomFileCategory(enum.StrEnum):
|
||||
DLC = "dlc"
|
||||
HACK = "hack"
|
||||
MANUAL = "manual"
|
||||
PATCH = "patch"
|
||||
UPDATE = "update"
|
||||
MOD = "mod"
|
||||
DEMO = "demo"
|
||||
TRANSLATION = "translation"
|
||||
PROTOTYPE = "prototype"
|
||||
|
||||
|
||||
class RomFile(BaseModel):
|
||||
__tablename__ = "rom_files"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE"))
|
||||
file_name: Mapped[str] = mapped_column(String(length=450))
|
||||
file_path: Mapped[str] = mapped_column(String(length=1000))
|
||||
file_size_bytes: Mapped[int] = mapped_column(BigInteger(), default=0)
|
||||
last_modified: Mapped[float | None] = mapped_column(default=None)
|
||||
crc_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
md5_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
sha1_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
category: Mapped[RomFileCategory | None] = mapped_column(
|
||||
Enum(RomFileCategory), default=None
|
||||
)
|
||||
|
||||
rom: Mapped[Rom] = relationship(lazy="joined")
|
||||
|
||||
@cached_property
|
||||
def full_path(self) -> str:
|
||||
return f"{self.file_path}/{self.file_name}"
|
||||
|
||||
|
||||
class Rom(BaseModel):
|
||||
@@ -49,12 +78,11 @@ class Rom(BaseModel):
|
||||
Index("idx_roms_moby_id", "moby_id"),
|
||||
)
|
||||
|
||||
file_name: Mapped[str] = mapped_column(String(length=450))
|
||||
file_name_no_tags: Mapped[str] = mapped_column(String(length=450))
|
||||
file_name_no_ext: Mapped[str] = mapped_column(String(length=450))
|
||||
file_extension: Mapped[str] = mapped_column(String(length=100))
|
||||
file_path: Mapped[str] = mapped_column(String(length=1000))
|
||||
file_size_bytes: Mapped[int] = mapped_column(BigInteger(), default=0)
|
||||
fs_name: Mapped[str] = mapped_column(String(length=450))
|
||||
fs_name_no_tags: Mapped[str] = mapped_column(String(length=450))
|
||||
fs_name_no_ext: Mapped[str] = mapped_column(String(length=450))
|
||||
fs_extension: Mapped[str] = mapped_column(String(length=100))
|
||||
fs_path: Mapped[str] = mapped_column(String(length=1000))
|
||||
|
||||
name: Mapped[str | None] = mapped_column(String(length=350))
|
||||
slug: Mapped[str | None] = mapped_column(String(length=400))
|
||||
@@ -82,8 +110,6 @@ class Rom(BaseModel):
|
||||
CustomJSON(), default=[], doc="URLs to screenshots stored in IGDB"
|
||||
)
|
||||
|
||||
multi: Mapped[bool] = mapped_column(default=False)
|
||||
files: Mapped[list[RomFile] | None] = mapped_column(CustomJSON(), default=[])
|
||||
crc_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
md5_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
sha1_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
@@ -98,7 +124,7 @@ class Rom(BaseModel):
|
||||
primaryjoin="Rom.id == SiblingRom.rom_id",
|
||||
secondaryjoin="Rom.id == SiblingRom.sibling_rom_id",
|
||||
)
|
||||
|
||||
files: Mapped[list[RomFile]] = relationship(back_populates="rom", lazy="immediate")
|
||||
saves: Mapped[list[Save]] = relationship(back_populates="rom")
|
||||
states: Mapped[list[State]] = relationship(back_populates="rom")
|
||||
screenshots: Mapped[list[Screenshot]] = relationship(back_populates="rom")
|
||||
@@ -126,7 +152,7 @@ class Rom(BaseModel):
|
||||
|
||||
@cached_property
|
||||
def full_path(self) -> str:
|
||||
return f"{self.file_path}/{self.file_name}"
|
||||
return f"{self.fs_path}/{self.fs_name}"
|
||||
|
||||
@cached_property
|
||||
def has_cover(self) -> bool:
|
||||
@@ -141,7 +167,15 @@ class Rom(BaseModel):
|
||||
]
|
||||
return screenshots
|
||||
|
||||
def get_collections(self) -> list[Collection]:
|
||||
@cached_property
|
||||
def multi(self) -> bool:
|
||||
return len(self.files) > 1
|
||||
|
||||
@cached_property
|
||||
def fs_size_bytes(self) -> int:
|
||||
return sum(f.file_size_bytes for f in self.files)
|
||||
|
||||
def get_collections(self) -> Sequence[Collection]:
|
||||
from handler.database import db_collection_handler
|
||||
|
||||
return db_collection_handler.get_collections_by_rom_id(
|
||||
@@ -231,7 +265,7 @@ class Rom(BaseModel):
|
||||
return f"roms/{str(self.platform_id)}/{str(self.id)}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.file_name
|
||||
return self.fs_name
|
||||
|
||||
|
||||
class RomUserStatus(enum.StrEnum):
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
def test_rom(rom):
|
||||
assert rom.file_path == "test_platform_slug/roms"
|
||||
from models.rom import Rom
|
||||
|
||||
|
||||
def test_rom(rom: Rom):
|
||||
assert rom.fs_path == "test_platform_slug/roms"
|
||||
assert rom.full_path == "test_platform_slug/roms/test_rom.zip"
|
||||
|
||||
@@ -5,6 +5,7 @@ import httpx
|
||||
from exceptions.task_exceptions import SchedulerException
|
||||
from handler.redis_handler import low_prio_queue
|
||||
from logger.logger import log
|
||||
from rq.job import Job
|
||||
from rq_scheduler import Scheduler
|
||||
from utils.context import ctx_httpx_client
|
||||
|
||||
@@ -27,7 +28,7 @@ class PeriodicTask(ABC):
|
||||
def _get_existing_job(self):
|
||||
existing_jobs = tasks_scheduler.get_jobs()
|
||||
for job in existing_jobs:
|
||||
if job.func_name == self.func:
|
||||
if isinstance(job, Job) and job.func_name == self.func:
|
||||
return job
|
||||
|
||||
return None
|
||||
|
||||
@@ -13,6 +13,7 @@ from endpoints.sockets.scan import scan_platforms
|
||||
from handler.database import db_platform_handler
|
||||
from handler.scan_handler import ScanType
|
||||
from logger.logger import log
|
||||
from rq.job import Job
|
||||
from tasks.tasks import tasks_scheduler
|
||||
from utils import get_version
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
@@ -58,14 +59,15 @@ class EventHandler(FileSystemEventHandler):
|
||||
|
||||
# Skip if a scan is already scheduled
|
||||
for job in tasks_scheduler.get_jobs():
|
||||
if job.func_name == "endpoints.sockets.scan.scan_platforms":
|
||||
if job.args[0] == []:
|
||||
log.info("Full rescan already scheduled")
|
||||
return
|
||||
if isinstance(job, Job):
|
||||
if job.func_name == "endpoints.sockets.scan.scan_platforms":
|
||||
if job.args[0] == []:
|
||||
log.info("Full rescan already scheduled")
|
||||
return
|
||||
|
||||
if db_platform and db_platform.id in job.args[0]:
|
||||
log.info(f"Scan already scheduled for {fs_slug}")
|
||||
return
|
||||
if db_platform and db_platform.id in job.args[0]:
|
||||
log.info(f"Scan already scheduled for {fs_slug}")
|
||||
return
|
||||
|
||||
time_delta = timedelta(minutes=RESCAN_ON_FILESYSTEM_CHANGE_DELAY)
|
||||
rescan_in_msg = f"rescanning in {RESCAN_ON_FILESYSTEM_CHANGE_DELAY} minutes."
|
||||
@@ -77,12 +79,13 @@ class EventHandler(FileSystemEventHandler):
|
||||
elif db_platform:
|
||||
# Otherwise trigger a rescan for the specific platform
|
||||
log.info(f"Change detected in {fs_slug} folder, {rescan_in_msg}")
|
||||
return tasks_scheduler.enqueue_in(
|
||||
tasks_scheduler.enqueue_in(
|
||||
time_delta,
|
||||
scan_platforms,
|
||||
[db_platform.id],
|
||||
scan_type=ScanType.QUICK,
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
3
frontend/src/__generated__/index.ts
generated
3
frontend/src/__generated__/index.ts
generated
@@ -31,7 +31,8 @@ export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform';
|
||||
export type { OIDCDict } from './models/OIDCDict';
|
||||
export type { PlatformSchema } from './models/PlatformSchema';
|
||||
export type { Role } from './models/Role';
|
||||
export type { RomFile } from './models/RomFile';
|
||||
export type { RomFileCategory } from './models/RomFileCategory';
|
||||
export type { RomFileSchema } from './models/RomFileSchema';
|
||||
export type { RomIGDBMetadata } from './models/RomIGDBMetadata';
|
||||
export type { RomMobyMetadata } from './models/RomMobyMetadata';
|
||||
export type { RomSchema } from './models/RomSchema';
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import type { CollectionSchema } from './CollectionSchema';
|
||||
import type { RomFile } from './RomFile';
|
||||
import type { RomFileSchema } from './RomFileSchema';
|
||||
import type { RomIGDBMetadata } from './RomIGDBMetadata';
|
||||
import type { RomMobyMetadata } from './RomMobyMetadata';
|
||||
import type { RomSchema } from './RomSchema';
|
||||
@@ -25,12 +25,12 @@ export type DetailedRomSchema = {
|
||||
platform_name: string;
|
||||
platform_custom_name: (string | null);
|
||||
platform_display_name: string;
|
||||
file_name: string;
|
||||
file_name_no_tags: string;
|
||||
file_name_no_ext: string;
|
||||
file_extension: string;
|
||||
file_path: string;
|
||||
file_size_bytes: number;
|
||||
fs_name: string;
|
||||
fs_name_no_tags: string;
|
||||
fs_name_no_ext: string;
|
||||
fs_extension: string;
|
||||
fs_path: string;
|
||||
fs_size_bytes: number;
|
||||
name: (string | null);
|
||||
slug: (string | null);
|
||||
summary: (string | null);
|
||||
@@ -54,11 +54,11 @@ export type DetailedRomSchema = {
|
||||
regions: Array<string>;
|
||||
languages: Array<string>;
|
||||
tags: Array<string>;
|
||||
multi: boolean;
|
||||
files: Array<RomFile>;
|
||||
crc_hash: (string | null);
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
multi: boolean;
|
||||
files: Array<RomFileSchema>;
|
||||
full_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
|
||||
@@ -3,9 +3,4 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
export type RomFile = {
|
||||
filename: string;
|
||||
size: number;
|
||||
last_modified: (number | null);
|
||||
};
|
||||
|
||||
export type RomFileCategory = 'dlc' | 'hack' | 'manual' | 'patch' | 'update' | 'mod' | 'demo' | 'translation' | 'prototype';
|
||||
24
frontend/src/__generated__/models/RomFileSchema.ts
generated
Normal file
24
frontend/src/__generated__/models/RomFileSchema.ts
generated
Normal file
@@ -0,0 +1,24 @@
|
||||
/* generated using openapi-typescript-codegen -- do no edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
import type { RomFileCategory } from './RomFileCategory';
|
||||
|
||||
export type RomFileSchema = {
|
||||
id: number;
|
||||
rom_id: number;
|
||||
file_name: string;
|
||||
file_path: string;
|
||||
file_size_bytes: number;
|
||||
full_path: string;
|
||||
relative_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
last_modified: string;
|
||||
crc_hash: (string | null);
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
category: (RomFileCategory | null);
|
||||
};
|
||||
|
||||
18
frontend/src/__generated__/models/RomSchema.ts
generated
18
frontend/src/__generated__/models/RomSchema.ts
generated
@@ -3,7 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
import type { RomFile } from './RomFile';
|
||||
import type { RomFileSchema } from './RomFileSchema';
|
||||
import type { RomIGDBMetadata } from './RomIGDBMetadata';
|
||||
import type { RomMobyMetadata } from './RomMobyMetadata';
|
||||
|
||||
@@ -18,12 +18,12 @@ export type RomSchema = {
|
||||
platform_name: string;
|
||||
platform_custom_name: (string | null);
|
||||
platform_display_name: string;
|
||||
file_name: string;
|
||||
file_name_no_tags: string;
|
||||
file_name_no_ext: string;
|
||||
file_extension: string;
|
||||
file_path: string;
|
||||
file_size_bytes: number;
|
||||
fs_name: string;
|
||||
fs_name_no_tags: string;
|
||||
fs_name_no_ext: string;
|
||||
fs_extension: string;
|
||||
fs_path: string;
|
||||
fs_size_bytes: number;
|
||||
name: (string | null);
|
||||
slug: (string | null);
|
||||
summary: (string | null);
|
||||
@@ -47,11 +47,11 @@ export type RomSchema = {
|
||||
regions: Array<string>;
|
||||
languages: Array<string>;
|
||||
tags: Array<string>;
|
||||
multi: boolean;
|
||||
files: Array<RomFile>;
|
||||
crc_hash: (string | null);
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
multi: boolean;
|
||||
files: Array<RomFileSchema>;
|
||||
full_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
|
||||
18
frontend/src/__generated__/models/SimpleRomSchema.ts
generated
18
frontend/src/__generated__/models/SimpleRomSchema.ts
generated
@@ -3,7 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
import type { RomFile } from './RomFile';
|
||||
import type { RomFileSchema } from './RomFileSchema';
|
||||
import type { RomIGDBMetadata } from './RomIGDBMetadata';
|
||||
import type { RomMobyMetadata } from './RomMobyMetadata';
|
||||
import type { RomSchema } from './RomSchema';
|
||||
@@ -20,12 +20,12 @@ export type SimpleRomSchema = {
|
||||
platform_name: string;
|
||||
platform_custom_name: (string | null);
|
||||
platform_display_name: string;
|
||||
file_name: string;
|
||||
file_name_no_tags: string;
|
||||
file_name_no_ext: string;
|
||||
file_extension: string;
|
||||
file_path: string;
|
||||
file_size_bytes: number;
|
||||
fs_name: string;
|
||||
fs_name_no_tags: string;
|
||||
fs_name_no_ext: string;
|
||||
fs_extension: string;
|
||||
fs_path: string;
|
||||
fs_size_bytes: number;
|
||||
name: (string | null);
|
||||
slug: (string | null);
|
||||
summary: (string | null);
|
||||
@@ -49,11 +49,11 @@ export type SimpleRomSchema = {
|
||||
regions: Array<string>;
|
||||
languages: Array<string>;
|
||||
tags: Array<string>;
|
||||
multi: boolean;
|
||||
files: Array<RomFile>;
|
||||
crc_hash: (string | null);
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
multi: boolean;
|
||||
files: Array<RomFileSchema>;
|
||||
full_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
|
||||
@@ -49,7 +49,7 @@ const is3DSRom = computed(() => {
|
||||
async function copyDownloadLink(rom: DetailedRom) {
|
||||
const downloadLink = getDownloadLink({
|
||||
rom,
|
||||
files: downloadStore.filesToDownload,
|
||||
fileIDs: downloadStore.fileIDsToDownload,
|
||||
});
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(downloadLink);
|
||||
@@ -74,7 +74,7 @@ async function copyDownloadLink(rom: DetailedRom) {
|
||||
@click="
|
||||
romApi.downloadRom({
|
||||
rom,
|
||||
files: downloadStore.filesToDownload,
|
||||
fileIDs: downloadStore.fileIDsToDownload,
|
||||
})
|
||||
"
|
||||
>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { RomFileSchema } from "@/__generated__";
|
||||
import VersionSwitcher from "@/components/Details/VersionSwitcher.vue";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storeAuth from "@/stores/auth";
|
||||
@@ -28,6 +29,14 @@ async function toggleMainSibling() {
|
||||
});
|
||||
}
|
||||
|
||||
function itemProps(item: RomFileSchema) {
|
||||
return {
|
||||
key: item.id,
|
||||
title: item.full_path.replace(props.rom.full_path, ""),
|
||||
value: item,
|
||||
};
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.rom,
|
||||
async () => (romUser.value = props.rom.rom_user),
|
||||
@@ -81,7 +90,7 @@ watch(
|
||||
<span>{{ t("rom.file") }}</span>
|
||||
</v-col>
|
||||
<v-col>
|
||||
<span class="text-body-1">{{ rom.file_name }}</span>
|
||||
<span class="text-body-1">{{ rom.fs_name }}</span>
|
||||
</v-col>
|
||||
</v-row>
|
||||
<v-row v-if="rom.multi" class="align-center my-3" no-gutters>
|
||||
@@ -91,9 +100,9 @@ watch(
|
||||
<v-col>
|
||||
<v-select
|
||||
v-model="downloadStore.filesToDownload"
|
||||
:label="rom.file_name"
|
||||
item-title="file_name"
|
||||
:items="rom.files.map((f) => f.filename)"
|
||||
:label="rom.fs_name"
|
||||
:items="rom.files"
|
||||
:itemProps="itemProps"
|
||||
rounded="0"
|
||||
density="compact"
|
||||
variant="outlined"
|
||||
@@ -102,7 +111,31 @@ watch(
|
||||
hide-details
|
||||
clearable
|
||||
chips
|
||||
/>
|
||||
>
|
||||
<template #item="{ item, props }">
|
||||
<v-list-item v-bind="props">
|
||||
<template v-slot:prepend="{ isSelected }">
|
||||
<v-checkbox-btn
|
||||
:model-value="isSelected"
|
||||
density="compact"
|
||||
class="mr-2"
|
||||
/>
|
||||
</template>
|
||||
<v-list-item-subtitle class="mt-1">
|
||||
<v-chip
|
||||
color="romm-accent-1"
|
||||
size="x-small"
|
||||
class="mr-1"
|
||||
v-if="item.raw.category"
|
||||
>{{ item.raw.category.toLocaleUpperCase() }}</v-chip
|
||||
>
|
||||
<v-chip size="x-small">{{
|
||||
formatBytes(item.raw.file_size_bytes)
|
||||
}}</v-chip>
|
||||
</v-list-item-subtitle>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</v-select>
|
||||
</v-col>
|
||||
</v-row>
|
||||
<v-row no-gutters class="align-center my-3">
|
||||
@@ -114,17 +147,16 @@ watch(
|
||||
<v-col cols="12">
|
||||
<v-chip size="small" class="mr-2 px-0" label>
|
||||
<v-chip label>{{ t("rom.size") }}</v-chip
|
||||
><span class="px-2">{{
|
||||
formatBytes(rom.file_size_bytes)
|
||||
}}</span>
|
||||
><span class="px-2">{{ formatBytes(rom.fs_size_bytes) }}</span>
|
||||
</v-chip>
|
||||
</v-col>
|
||||
<v-col
|
||||
v-for="info in romInfo"
|
||||
v-if="!rom.multi && rom.sha1_hash"
|
||||
cols="12"
|
||||
>
|
||||
<v-chip size="small" class="mt-1 mr-2 px-0" label>
|
||||
<v-col v-for="info in romInfo" cols="12">
|
||||
<v-chip
|
||||
v-if="info.value"
|
||||
size="small"
|
||||
class="mt-1 mr-2 px-0"
|
||||
label
|
||||
>
|
||||
<v-chip label>{{ info.label }}</v-chip
|
||||
><span class="px-2">{{ info.value }}</span>
|
||||
</v-chip>
|
||||
|
||||
@@ -143,7 +143,7 @@ function closeDialog() {
|
||||
hide-default-header
|
||||
>
|
||||
<template #item.name="{ item }">
|
||||
<rom-list-item :rom="item" with-filename />
|
||||
<rom-list-item :rom="item" with-filename with-size />
|
||||
</template>
|
||||
<template #bottom>
|
||||
<v-divider />
|
||||
|
||||
@@ -116,7 +116,7 @@ function closeDialog() {
|
||||
hide-default-header
|
||||
>
|
||||
<template #item.name="{ item }">
|
||||
<rom-list-item :rom="item" with-filename />
|
||||
<rom-list-item :rom="item" with-filename with-size />
|
||||
</template>
|
||||
<template #bottom>
|
||||
<v-divider />
|
||||
|
||||
@@ -122,7 +122,7 @@ function closeDialog() {
|
||||
show-select
|
||||
>
|
||||
<template #item.name="{ item }">
|
||||
<rom-list-item :rom="item" with-filename>
|
||||
<rom-list-item :rom="item" with-filename with-size>
|
||||
<template #append-body>
|
||||
<v-row v-if="romsToDeleteFromFs.includes(item.id)" no-gutters>
|
||||
<v-col>
|
||||
|
||||
@@ -126,7 +126,7 @@ async function unmatchRom() {
|
||||
}
|
||||
|
||||
async function updateRom() {
|
||||
if (!rom.value?.file_name) {
|
||||
if (!rom.value?.fs_name) {
|
||||
emitter?.emit("snackbarShow", {
|
||||
msg: "Cannot save: file name is required",
|
||||
icon: "mdi-close-circle",
|
||||
@@ -176,7 +176,7 @@ function closeDialog() {
|
||||
<v-row class="px-2" no-gutters>
|
||||
<v-col>
|
||||
<v-text-field
|
||||
v-model="rom.file_name"
|
||||
v-model="rom.fs_name"
|
||||
class="py-2"
|
||||
:rules="[(value: string) => !!value]"
|
||||
:label="rom.multi ? t('rom.foldername') : t('rom.filename')"
|
||||
@@ -190,7 +190,7 @@ function closeDialog() {
|
||||
mdi-folder-file-outline
|
||||
</v-icon>
|
||||
<span>
|
||||
/romm/library/{{ rom.file_path }}/{{ rom.file_name }}
|
||||
/romm/library/{{ rom.fs_path }}/{{ rom.fs_name }}
|
||||
</span>
|
||||
</v-label>
|
||||
</template>
|
||||
|
||||
@@ -51,7 +51,7 @@ emitter?.on("showMatchRomDialog", (romToSearch) => {
|
||||
searchTerm.value =
|
||||
romToSearch.igdb_id || romToSearch.moby_id
|
||||
? (romToSearch.name ?? "")
|
||||
: romToSearch.file_name_no_tags;
|
||||
: romToSearch.fs_name_no_tags;
|
||||
|
||||
if (searchTerm.value) {
|
||||
searchRom();
|
||||
@@ -449,16 +449,12 @@ onBeforeUnmount(() => {
|
||||
<br />
|
||||
<span>{{ t("rom.rename-file-part3") }}</span
|
||||
><span class="text-romm-accent-1 ml-1"
|
||||
>{{ rom?.file_name_no_tags }}.{{
|
||||
rom?.file_extension
|
||||
}}</span
|
||||
>{{ rom?.fs_name_no_tags }}.{{ rom?.fs_extension }}</span
|
||||
>
|
||||
<br />
|
||||
<span class="mx-1">{{ t("rom.rename-file-part4") }}</span
|
||||
><span class="text-romm-accent-2"
|
||||
>{{ selectedMatchRom?.name }}.{{
|
||||
rom?.file_extension
|
||||
}}</span
|
||||
>{{ selectedMatchRom?.name }}.{{ rom?.fs_extension }}</span
|
||||
>
|
||||
<br />
|
||||
<span class="text-caption font-italic font-weight-bold"
|
||||
|
||||
@@ -22,7 +22,7 @@ emitter?.on("showQRCodeDialog", async (romToView: SimpleRom) => {
|
||||
|
||||
const downloadLink = getDownloadLink({
|
||||
rom: romToView,
|
||||
files: is3DSFile ? [] : [matchingFiles[0].filename],
|
||||
fileIDs: is3DSFile ? [] : [matchingFiles[0].id],
|
||||
});
|
||||
|
||||
const qrCode = document.getElementById("qr-code");
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import RAvatarRom from "@/components/common/Game/RAvatar.vue";
|
||||
import { formatBytes } from "@/utils";
|
||||
import { useDisplay } from "vuetify";
|
||||
|
||||
// Props
|
||||
withDefaults(
|
||||
@@ -18,7 +17,7 @@ withDefaults(
|
||||
withAvatar: true,
|
||||
withName: true,
|
||||
withFilename: false,
|
||||
withSize: true,
|
||||
withSize: false,
|
||||
withLink: false,
|
||||
},
|
||||
);
|
||||
@@ -41,14 +40,14 @@ withDefaults(
|
||||
><v-col>{{ rom.name }}</v-col></v-row
|
||||
>
|
||||
<v-row v-if="withFilename" no-gutters
|
||||
><v-col class="text-romm-accent-1">{{ rom.file_name }}</v-col></v-row
|
||||
><v-col class="text-romm-accent-1">{{ rom.fs_name }}</v-col></v-row
|
||||
>
|
||||
<slot name="append-body"></slot>
|
||||
<template #append>
|
||||
<v-row no-gutters>
|
||||
<v-col v-if="withSize" cols="auto">
|
||||
<v-chip size="x-small" label>{{
|
||||
formatBytes(rom.file_size_bytes)
|
||||
formatBytes(rom.fs_size_bytes)
|
||||
}}</v-chip>
|
||||
</v-col>
|
||||
<v-col>
|
||||
|
||||
@@ -53,7 +53,7 @@ const HEADERS = [
|
||||
title: "Size",
|
||||
align: "start",
|
||||
sortable: true,
|
||||
key: "file_size_bytes",
|
||||
key: "fs_size_bytes",
|
||||
},
|
||||
{
|
||||
title: "Added",
|
||||
@@ -201,7 +201,7 @@ onMounted(() => {
|
||||
</v-row>
|
||||
<v-row no-gutters>
|
||||
<v-col class="text-romm-accent-1">
|
||||
{{ item.file_name }}
|
||||
{{ item.fs_name }}
|
||||
</v-col>
|
||||
</v-row>
|
||||
<template #append>
|
||||
@@ -220,8 +220,8 @@ onMounted(() => {
|
||||
</v-list-item>
|
||||
</td>
|
||||
</template>
|
||||
<template #item.file_size_bytes="{ item }">
|
||||
<span class="text-no-wrap">{{ formatBytes(item.file_size_bytes) }}</span>
|
||||
<template #item.fs_size_bytes="{ item }">
|
||||
<span class="text-no-wrap">{{ formatBytes(item.fs_size_bytes) }}</span>
|
||||
</template>
|
||||
<template #item.created_at="{ item }">
|
||||
<span v-if="item.created_at" class="text-no-wrap">{{
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Nur neue Dateien scannen",
|
||||
"unidentified-games": "Unidentifizierte Spiele",
|
||||
"unidentified-games-desc": "Scanne Spiele ohne Metadaten",
|
||||
"hashes": "Hashes neu berechnen",
|
||||
"hashes-desc": "Berechne Hashes für alle Dateien neu",
|
||||
"partial-metadata": "Unvollständige Metadaten",
|
||||
"partial-metadata-desc": "Scanne Spiele mit unvollständigen Metadaten",
|
||||
"complete-rescan": "Vollständiger Scan",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Scan new files only",
|
||||
"unidentified-games": "Unidentified games",
|
||||
"unidentified-games-desc": "Scan games with no metadata match",
|
||||
"hashes": "Recalculate hashes",
|
||||
"hashes-desc": "Recalculates hashes for all files",
|
||||
"partial-metadata": "Partial metadata",
|
||||
"partial-metadata-desc": "Scan games with partial metadata matches",
|
||||
"complete-rescan": "Complete rescan",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Scan new files only",
|
||||
"unidentified-games": "Unidentified games",
|
||||
"unidentified-games-desc": "Scan games with no metadata match",
|
||||
"hashes": "Recalculate hashes",
|
||||
"hashes-desc": "Recalculates hashes for all files",
|
||||
"partial-metadata": "Partial metadata",
|
||||
"partial-metadata-desc": "Scan games with partial metadata matches",
|
||||
"complete-rescan": "Complete rescan",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Escanea tu biblioteca en busca nuevos ficheros",
|
||||
"unidentified-games": "Juegos sin identificar",
|
||||
"unidentified-games-desc": "Escanea únicamente juegos sin identificar por ninguna de las fuentes de metadatos",
|
||||
"hashes": "Recalcular hashes",
|
||||
"hashes-desc": "Recalcula los hashes de todos los ficheros",
|
||||
"partial-metadata": "Metadatos parciales",
|
||||
"partial-metadata-desc": "Escanea únicamente juegos identificados con metadatos a medias",
|
||||
"complete-rescan": "Escaneo completo",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Scanner votre bibliothèque à la recherche de nouveaux fichiers",
|
||||
"unidentified-games": "Jeux non identifiés",
|
||||
"unidentified-games-desc": "Scanner uniquement les jeux non identifiés par aucune des sources de métadonnées",
|
||||
"hashes": "Recalculer les hachages",
|
||||
"hashes-desc": "Recalculer les hachages de tous les fichiers",
|
||||
"partial-metadata": "Métadonnées partielles",
|
||||
"partial-metadata-desc": "Scanner uniquement les jeux identifiés avec des métadonnées partielles",
|
||||
"complete-rescan": "Scan complet",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Escanear apenas novos arquivos",
|
||||
"unidentified-games": "Jogos não identificados",
|
||||
"unidentified-games-desc": "Escanear jogos sem correspondência de metadados",
|
||||
"hashes": "Recalcular hashes",
|
||||
"hashes-desc": "Recalcular hashes para todos os arquivos",
|
||||
"partial-metadata": "Metadados parciais",
|
||||
"partial-metadata-desc": "Escanear jogos com correspondências parciais de metadados",
|
||||
"complete-rescan": "Reescanear completamente",
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"quick-scan-desc": "Сканировать только новые файлы",
|
||||
"unidentified-games": "Неопознанные игры",
|
||||
"unidentified-games-desc": "Сканировать игры без совпадений метаданных",
|
||||
"hashes": "Пересчитать хеши",
|
||||
"hashes-desc": "Пересчитать хеши для всех файлов",
|
||||
"partial-metadata": "Частичные метаданные",
|
||||
"partial-metadata-desc": "Сканировать игры с частичными совпадениями метаданных",
|
||||
"complete-rescan": "Полное пересканирование",
|
||||
|
||||
@@ -120,13 +120,13 @@ async function searchRom({
|
||||
// Used only for multi-file downloads
|
||||
async function downloadRom({
|
||||
rom,
|
||||
files = [],
|
||||
fileIDs = [],
|
||||
}: {
|
||||
rom: SimpleRom;
|
||||
files?: string[];
|
||||
fileIDs?: number[];
|
||||
}) {
|
||||
const a = document.createElement("a");
|
||||
a.href = getDownloadPath({ rom, files });
|
||||
a.href = getDownloadPath({ rom, fileIDs });
|
||||
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
@@ -152,7 +152,7 @@ async function updateRom({
|
||||
if (rom.igdb_id) formData.append("igdb_id", rom.igdb_id.toString());
|
||||
if (rom.moby_id) formData.append("moby_id", rom.moby_id.toString());
|
||||
formData.append("name", rom.name || "");
|
||||
formData.append("file_name", rom.file_name);
|
||||
formData.append("fs_name", rom.fs_name);
|
||||
formData.append("summary", rom.summary || "");
|
||||
formData.append("url_cover", rom.url_cover || "");
|
||||
if (rom.artwork) formData.append("artwork", rom.artwork);
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { type RomFileSchema } from "@/__generated__";
|
||||
|
||||
export default defineStore("download", {
|
||||
state: () => ({
|
||||
value: [] as number[],
|
||||
filesToDownload: [] as string[],
|
||||
filesToDownload: [] as RomFileSchema[],
|
||||
}),
|
||||
|
||||
getters: {
|
||||
fileIDsToDownload: (state) => state.filesToDownload.map((file) => file.id),
|
||||
},
|
||||
|
||||
actions: {
|
||||
add(id: number) {
|
||||
this.value.push(id);
|
||||
@@ -15,7 +20,7 @@ export default defineStore("download", {
|
||||
},
|
||||
clear() {
|
||||
this.value = [] as number[];
|
||||
this.filesToDownload = [] as string[];
|
||||
this.filesToDownload = [] as RomFileSchema[];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -191,7 +191,7 @@ export default defineStore("roms", {
|
||||
.filter(
|
||||
(rom) =>
|
||||
rom.name?.toLowerCase().includes(searchFilter.toLowerCase()) ||
|
||||
rom.file_name?.toLowerCase().includes(searchFilter.toLowerCase()),
|
||||
rom.fs_name?.toLowerCase().includes(searchFilter.toLowerCase()),
|
||||
)
|
||||
.map((roms) => roms.id),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import cronstrue from "cronstrue";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import type { Heartbeat } from "@/stores/heartbeat";
|
||||
import type { RomFile, RomUserStatus } from "@/__generated__";
|
||||
import type { RomFileSchema, RomUserStatus } from "@/__generated__";
|
||||
|
||||
/**
|
||||
* Views configuration object.
|
||||
@@ -88,28 +88,26 @@ export function convertCronExperssion(expression: string) {
|
||||
*/
|
||||
export function getDownloadPath({
|
||||
rom,
|
||||
files = [],
|
||||
fileIDs = [],
|
||||
}: {
|
||||
rom: SimpleRom;
|
||||
files?: string[];
|
||||
fileIDs?: number[];
|
||||
}) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (files.length) {
|
||||
files.forEach((file) => queryParams.append("files", file));
|
||||
if (fileIDs.length > 0) {
|
||||
fileIDs.forEach((fileId) => queryParams.append("files", fileId.toString()));
|
||||
}
|
||||
return `/api/roms/${rom.id}/content/${
|
||||
rom.file_name
|
||||
}?${queryParams.toString()}`;
|
||||
return `/api/roms/${rom.id}/content/${rom.fs_name}?${queryParams.toString()}`;
|
||||
}
|
||||
|
||||
export function getDownloadLink({
|
||||
rom,
|
||||
files = [],
|
||||
fileIDs = [],
|
||||
}: {
|
||||
rom: SimpleRom;
|
||||
files?: string[];
|
||||
fileIDs?: number[];
|
||||
}) {
|
||||
return `${window.location.origin}${encodeURI(getDownloadPath({ rom, files }))}`;
|
||||
return `${window.location.origin}${encodeURI(getDownloadPath({ rom, fileIDs }))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -570,12 +568,12 @@ export function getStatusKeyForText(text: string) {
|
||||
}
|
||||
|
||||
export function is3DSCIAFile(rom: SimpleRom): boolean {
|
||||
return rom.file_extension.toLowerCase() == "cia";
|
||||
return rom.fs_extension.toLowerCase() == "cia";
|
||||
}
|
||||
|
||||
export function get3DSCIAFiles(rom: SimpleRom): RomFile[] {
|
||||
export function get3DSCIAFiles(rom: SimpleRom): RomFileSchema[] {
|
||||
return rom.files.filter((file) =>
|
||||
file.filename.toLowerCase().endsWith(".cia"),
|
||||
file.file_name.toLowerCase().endsWith(".cia"),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ onMounted(async () => {
|
||||
src="/assets/emulatorjs/powered_by_emulatorjs.png"
|
||||
/>
|
||||
<v-divider class="my-4" />
|
||||
<rom-list-item :rom="rom" with-filename />
|
||||
<rom-list-item :rom="rom" with-filename with-size />
|
||||
<v-divider class="my-4" />
|
||||
<v-select
|
||||
v-if="supportedCores.length > 1"
|
||||
|
||||
@@ -62,7 +62,7 @@ window.EJS_controlScheme = getControlSchemeForPlatform(
|
||||
);
|
||||
window.EJS_threads = areThreadsRequiredForEJSCore(window.EJS_core);
|
||||
window.EJS_gameID = romRef.value.id;
|
||||
window.EJS_gameUrl = `/api/roms/${romRef.value.id}/content/${romRef.value.file_name}`;
|
||||
window.EJS_gameUrl = `/api/roms/${romRef.value.id}/content/${romRef.value.fs_name}`;
|
||||
window.EJS_biosUrl = props.bios
|
||||
? `/api/firmware/${props.bios.id}/content/${props.bios.file_name}`
|
||||
: "";
|
||||
@@ -118,7 +118,7 @@ onMounted(() => {
|
||||
|
||||
function buildStateName(): string {
|
||||
const states = romRef.value.user_states?.map((s) => s.file_name) ?? [];
|
||||
const romName = romRef.value.file_name_no_ext.trim();
|
||||
const romName = romRef.value.fs_name_no_ext.trim();
|
||||
let stateName = `${romName}.state.auto`;
|
||||
if (!states.includes(stateName)) return stateName;
|
||||
|
||||
@@ -134,7 +134,7 @@ function buildStateName(): string {
|
||||
|
||||
function buildSaveName(): string {
|
||||
const saves = romRef.value.user_saves?.map((s) => s.file_name) ?? [];
|
||||
const romName = romRef.value.file_name_no_ext.trim();
|
||||
const romName = romRef.value.fs_name_no_ext.trim();
|
||||
let saveName = `${romName}.srm`;
|
||||
if (!saves.includes(saveName)) return saveName;
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ function onPlay() {
|
||||
backgroundColor: "#0D1117",
|
||||
openUrlMode: "confirm",
|
||||
publicPath: "/assets/ruffle/",
|
||||
url: `/api/roms/${rom.value?.id}/content/${rom.value?.file_name}`,
|
||||
url: `/api/roms/${rom.value?.id}/content/${rom.value?.fs_name}`,
|
||||
});
|
||||
player.style.width = "100%";
|
||||
player.style.height = "100%";
|
||||
@@ -111,7 +111,7 @@ onMounted(async () => {
|
||||
src="/assets/ruffle/powered_by_ruffle.png"
|
||||
/>
|
||||
<v-divider class="my-4" />
|
||||
<rom-list-item :rom="rom" with-filename />
|
||||
<rom-list-item :rom="rom" with-filename with-size />
|
||||
<v-divider class="my-4" />
|
||||
</v-col>
|
||||
</v-row>
|
||||
|
||||
@@ -71,6 +71,11 @@ const scanOptions = [
|
||||
subtitle: t("scan.partial-metadata-desc"),
|
||||
value: "partial",
|
||||
},
|
||||
{
|
||||
title: t("scan.hashes"),
|
||||
subtitle: t("scan.hashes-desc"),
|
||||
value: "hashes",
|
||||
},
|
||||
{
|
||||
title: t("scan.complete-rescan"),
|
||||
subtitle: t("scan.complete-rescan-desc"),
|
||||
|
||||
Reference in New Issue
Block a user