Calculate hashes for rom files

This commit is contained in:
Georges-Antoine Assi
2024-07-15 18:27:29 -04:00
parent da295bc14a
commit 2b2ff875ee
57 changed files with 144149 additions and 312 deletions

View File

@@ -11,7 +11,7 @@ from fastapi.responses import StreamingResponse
from handler.metadata.igdb_handler import IGDBMetadata
from handler.metadata.moby_handler import MobyMetadata
from handler.socket_handler import socket_handler
from models.rom import Rom
from models.rom import Rom, RomFile
from pydantic import BaseModel, Field, computed_field
from typing_extensions import TypedDict
@@ -108,7 +108,7 @@ class RomSchema(BaseModel):
tags: list[str]
multi: bool
files: list[str]
files: list[RomFile]
full_path: str
created_at: datetime
updated_at: datetime

View File

@@ -173,7 +173,7 @@ def head_rom_content(request: Request, id: int, file_name: str):
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
return FileResponse(
path=rom_path if not rom.multi else f"{rom_path}/{rom.files[0]}",
path=rom_path if not rom.multi else f'{rom_path}/{rom.files[0]["filename"]}',
filename=file_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.name)}.zip"',
@@ -210,7 +210,7 @@ def get_rom_content(
raise RomNotFoundInDatabaseException(id)
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
files_to_download = files or rom.files or []
files_to_download = files or [r["filename"] for r in rom.files]
if not rom.multi:
return FileResponse(path=rom_path, filename=rom.file_name)

View File

@@ -259,6 +259,12 @@ async def scan_platforms(
},
)
await sm.emit("", None)
elif rom:
# Just to update the filesystem data
rom.file_name = fs_rom["file_name"]
rom.multi = fs_rom["multi"]
rom.files = fs_rom["files"]
db_rom_handler.add_rom(rom)
# Only purge entries if there are some file remaining in the library
# This protects against accidental deletion of entries when

View File

@@ -1,3 +1,5 @@
import binascii
import hashlib
import os
import re
import shutil
@@ -84,12 +86,39 @@ class FSRomsHandler(FSHandler):
return [f for f in roms if f not in filtered_files]
def _calculate_rom_size(self, data: bytes) -> int:
return {
"crc_hash": (binascii.crc32(data) & 0xFFFFFFFF)
.to_bytes(4, byteorder="big")
.hex(),
"md5_hash": hashlib.md5(data).hexdigest(),
"sha1_hash": hashlib.sha1(data).hexdigest(),
}
def get_rom_files(self, rom: str, roms_path: str) -> list[str]:
rom_files: list[str] = []
for path, _, files in os.walk(f"{roms_path}/{rom}"):
for f in self._exclude_files(files, "multi_parts"):
rom_files.append(f"{Path(path, f)}".replace(f"{roms_path}/{rom}/", ""))
# 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 multi_files:
with open(Path(roms_path, rom, file), "rb") as f:
data = f.read()
rom_files.append(
{
"filename": file,
**self._calculate_rom_size(data),
}
)
else:
with open(Path(roms_path, rom), "rb") as f:
data = f.read()
rom_files.append(
{
"filename": rom,
**self._calculate_rom_size(data),
}
)
return rom_files

View File

@@ -22,6 +22,7 @@ class ScanType(Enum):
UNIDENTIFIED = "unidentified"
PARTIAL = "partial"
COMPLETE = "complete"
NO_SCAN = "no_scan"
def _get_main_platform_igdb_id(platform: Platform):

File diff suppressed because it is too large Load Diff

View File

@@ -24,12 +24,21 @@ def test_scan_platform():
@pytest.mark.vcr
async def test_scan_rom():
platform = Platform(fs_slug="n64", igdb_id=4)
files = [
{
"file_name": "Paper Mario (USA).z64",
"crc_hash": "9d0d1c6e",
"md5_hash": "f1b7f9e4f4d0e0b7b9faa1b1f2f8e4e9",
"sha1_hash": "c3c7f9f3d1d0e0b7b9faa1b1f2f8e4e9",
}
]
rom = await scan_rom(
platform,
{
"file_name": "Paper Mario (USA).z64",
"multi": False,
"files": ["Paper Mario (USA).z64"],
"files": files,
},
ScanType.QUICK,
)
@@ -39,6 +48,6 @@ async def test_scan_rom():
assert rom.name == "Paper Mario"
assert rom.igdb_id == 3340
assert rom.file_size_bytes == 1024
assert rom.files == ["Paper Mario (USA).z64"]
assert rom.files == files
assert rom.tags == []
assert not rom.multi

View File

@@ -4,10 +4,15 @@ from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
import alembic.config
import endpoints.sockets.scan # noqa
import httpx
import uvicorn
from config import DEV_HOST, DEV_PORT, DISABLE_CSRF_PROTECTION, ROMM_AUTH_SECRET_KEY
from config import (
DEV_HOST,
DEV_PORT,
DISABLE_CSRF_PROTECTION,
ROMM_AUTH_SECRET_KEY,
SCAN_TIMEOUT,
)
from endpoints import (
auth,
collections,
@@ -26,12 +31,15 @@ from endpoints import (
tasks,
user,
)
from endpoints.sockets.scan import scan_platforms
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from handler.auth.base_handler import ALGORITHM
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.auth.middleware import CustomCSRFMiddleware, SessionMiddleware
from handler.redis_handler import high_prio_queue
from handler.scan_handler import ScanType
from handler.socket_handler import socket_handler
from starlette.middleware.authentication import AuthenticationMiddleware
from utils import get_version
@@ -104,5 +112,10 @@ if __name__ == "__main__":
# Run migrations
alembic.config.main(argv=["upgrade", "head"])
# Run a no-scan in the background on startup
high_prio_queue.enqueue(
scan_platforms, [], ScanType.NO_SCAN, [], [], job_timeout=SCAN_TIMEOUT
)
# Run application
uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True)

View File

@@ -8,6 +8,7 @@ from models.base import BaseModel
from sqlalchemy import JSON, BigInteger, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.dialects.mysql.json import JSON as MySQLJSON
from sqlalchemy.orm import Mapped, mapped_column, relationship
from typing_extensions import TypedDict
if TYPE_CHECKING:
from models.assets import Save, Screenshot, State
@@ -16,6 +17,13 @@ if TYPE_CHECKING:
from models.user import User
class RomFile(TypedDict):
filename: str
crc_hash: str
md5_hash: str
sha1_hash: str
class Rom(BaseModel):
__tablename__ = "roms"
@@ -59,7 +67,7 @@ class Rom(BaseModel):
)
multi: Mapped[bool] = mapped_column(default=False)
files: Mapped[list[str] | None] = mapped_column(JSON, default=[])
files: Mapped[list[RomFile] | None] = mapped_column(JSON, default=[])
platform_id: Mapped[int] = mapped_column(
ForeignKey("platforms.id", ondelete="CASCADE")

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type { AddFirmwareResponse } from "./models/AddFirmwareResponse";
export type { AddRomsResponse } from "./models/AddRomsResponse";
@@ -27,6 +28,7 @@ export type { MetadataSourcesDict } from "./models/MetadataSourcesDict";
export type { MobyMetadataPlatform } from "./models/MobyMetadataPlatform";
export type { PlatformSchema } from "./models/PlatformSchema";
export type { Role } from "./models/Role";
export type { RomFile } from "./models/RomFile";
export type { RomIGDBMetadata } from "./models/RomIGDBMetadata";
export type { RomMobyMetadata } from "./models/RomMobyMetadata";
export type { RomSchema } from "./models/RomSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { FirmwareSchema } from "./FirmwareSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type AddRomsResponse = {
uploaded_roms: Array<string>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_collection_collections_post = {
artwork?: Blob | null;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_firmware_firmware_post = {
files: Array<Blob>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_roms_roms_post = {
roms: Array<Blob>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_saves_saves_post = {
saves: Array<Blob>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_screenshots_screenshots_post = {
screenshots: Array<Blob>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_add_states_states_post = {
states: Array<Blob>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_token_token_post = {
grant_type?: string;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_update_collection_collections__id__put = {
artwork?: Blob | null;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_update_rom_roms__id__put = {
artwork?: Blob | null;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_update_user_users__id__put = {
avatar?: Blob | null;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type CollectionSchema = {
id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ConfigResponse = {
EXCLUDED_PLATFORMS: Array<string>;

View File

@@ -1,8 +1,10 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { CollectionSchema } from "./CollectionSchema";
import type { RomFile } from "./RomFile";
import type { RomIGDBMetadata } from "./RomIGDBMetadata";
import type { RomMobyMetadata } from "./RomMobyMetadata";
import type { RomSchema } from "./RomSchema";
@@ -47,7 +49,7 @@ export type DetailedRomSchema = {
languages: Array<string>;
tags: Array<string>;
multi: boolean;
files: Array<string>;
files: Array<RomFile>;
full_path: string;
created_at: string;
updated_at: string;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type FirmwareSchema = {
id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ValidationError } from "./ValidationError";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type IGDBMetadataPlatform = {
igdb_id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type IGDBRelatedGame = {
id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type MessageResponse = {
msg: string;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type MetadataSourcesDict = {
IGDB_API_ENABLED: boolean;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type MobyMetadataPlatform = {
moby_id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { FirmwareSchema } from "./FirmwareSchema";

View File

@@ -1,5 +1,6 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Role = "viewer" | "editor" | "admin";

View File

@@ -0,0 +1,11 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type RomFile = {
filename: string;
crc_hash: string;
md5_hash: string;
sha1_hash: string;
};

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { IGDBMetadataPlatform } from "./IGDBMetadataPlatform";
import type { IGDBRelatedGame } from "./IGDBRelatedGame";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { MobyMetadataPlatform } from "./MobyMetadataPlatform";

View File

@@ -1,7 +1,9 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { RomFile } from "./RomFile";
import type { RomIGDBMetadata } from "./RomIGDBMetadata";
import type { RomMobyMetadata } from "./RomMobyMetadata";
import type { RomUserSchema } from "./RomUserSchema";
@@ -41,7 +43,7 @@ export type RomSchema = {
languages: Array<string>;
tags: Array<string>;
multi: boolean;
files: Array<string>;
files: Array<RomFile>;
full_path: string;
created_at: string;
updated_at: string;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type RomUserSchema = {
id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ScreenshotSchema } from "./ScreenshotSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { TaskDict } from "./TaskDict";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ScreenshotSchema = {
id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type SearchRomSchema = {
igdb_id?: number | null;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ScreenshotSchema } from "./ScreenshotSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type StatsReturn = {
PLATFORMS: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type TaskDict = {
ENABLED: boolean;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type TokenResponse = {
access_token: string;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { SaveSchema } from "./SaveSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ScreenshotSchema } from "./ScreenshotSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { StateSchema } from "./StateSchema";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserNotesSchema = {
user_id: number;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { Role } from "./Role";

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ValidationError = {
loc: Array<string | number>;

View File

@@ -1,6 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type WatcherDict = {
ENABLED: boolean;

View File

@@ -24,7 +24,7 @@ async function copyDownloadLink(rom: DetailedRom) {
encodeURI(
getDownloadLink({
rom,
files: downloadStore.filesToDownloadMultiFileRom,
files: downloadStore.filesToDownload,
})
);
if (navigator.clipboard && window.isSecureContext) {
@@ -49,7 +49,7 @@ async function copyDownloadLink(rom: DetailedRom) {
@click="
romApi.downloadRom({
rom,
files: downloadStore.filesToDownloadMultiFileRom,
files: downloadStore.filesToDownload,
})
"
>

View File

@@ -113,10 +113,10 @@ watch(
</v-col>
<v-col>
<v-select
v-model="downloadStore.filesToDownloadMultiFileRom"
v-model="downloadStore.filesToDownload"
:label="rom.file_name"
item-title="file_name"
:items="rom.files"
:items="rom.files.map(f => f.filename)"
rounded="0"
density="compact"
variant="outlined"

View File

@@ -3,7 +3,7 @@ import { defineStore } from "pinia";
export default defineStore("download", {
state: () => ({
value: [] as number[],
filesToDownloadMultiFileRom: [] as string[],
filesToDownload: [] as string[],
}),
actions: {
@@ -15,7 +15,7 @@ export default defineStore("download", {
},
clear() {
this.value = [] as number[];
this.filesToDownloadMultiFileRom = [] as string[];
this.filesToDownload = [] as string[];
},
},
});