Merge pull request #645 from zurdi15/filter-assets-per-user

General fixes for filtering assets per user
This commit is contained in:
Zurdi
2024-02-08 20:10:59 +01:00
committed by GitHub
31 changed files with 198 additions and 181 deletions

View File

@@ -7,6 +7,8 @@ from typing_extensions import TypedDict
class BaseAsset(BaseModel):
id: int
rom_id: int
user_id: int
file_name: str
file_name_no_tags: str
file_name_no_ext: str
@@ -23,7 +25,7 @@ class BaseAsset(BaseModel):
class ScreenshotSchema(BaseAsset):
rom_id: int
pass
class UploadedScreenshotsResponse(TypedDict):
@@ -34,7 +36,6 @@ class UploadedScreenshotsResponse(TypedDict):
class SaveSchema(BaseAsset):
rom_id: int
emulator: Optional[str]
screenshot: Optional[ScreenshotSchema]
@@ -45,7 +46,6 @@ class UploadedSavesResponse(TypedDict):
class StateSchema(BaseAsset):
rom_id: int
emulator: Optional[str]
screenshot: Optional[ScreenshotSchema]

View File

@@ -1,13 +1,19 @@
import re
from typing import Optional
from endpoints.responses.assets import SaveSchema, ScreenshotSchema, StateSchema
from fastapi import Request
from fastapi.responses import StreamingResponse
from handler import socket_handler
from handler.igdb_handler import IGDBRelatedGame
from pydantic import BaseModel
from pydantic import BaseModel, computed_field, Field
from models.rom import Rom
from typing_extensions import TypedDict, NotRequired
SORT_COMPARE_REGEX = r"^([Tt]he|[Aa]|[Aa]nd)\s"
class RomMetadata(TypedDict):
expansions: NotRequired[list[IGDBRelatedGame]]
dlcs: NotRequired[list[IGDBRelatedGame]]
@@ -50,9 +56,6 @@ class RomSchema(BaseModel):
game_modes: list[str]
igdb_metadata: Optional[RomMetadata]
# Used for sorting on the frontend
sort_comparator: str
path_cover_s: Optional[str]
path_cover_l: Optional[str]
has_cover: bool
@@ -65,20 +68,53 @@ class RomSchema(BaseModel):
multi: bool
files: list[str]
saves: list[SaveSchema]
states: list[StateSchema]
screenshots: list[ScreenshotSchema]
url_screenshots: list[str]
merged_screenshots: list[str]
full_path: str
download_path: str
sibling_roms: list["RomSchema"] = Field(default_factory=list)
user_saves: list[SaveSchema] = Field(default_factory=list)
user_states: list[StateSchema] = Field(default_factory=list)
user_screenshots: list[ScreenshotSchema] = Field(default_factory=list)
class Config:
from_attributes = True
@computed_field
@property
def sort_comparator(self) -> str:
return (
re.sub(
SORT_COMPARE_REGEX,
"",
self.name or self.file_name_no_tags,
)
.strip()
.lower()
)
class EnhancedRomSchema(RomSchema):
sibling_roms: list["RomSchema"]
@classmethod
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> "RomSchema":
rom = cls.model_validate(db_rom)
user_id = request.user.id
rom.sibling_roms = [
RomSchema.model_validate(r) for r in db_rom.get_sibling_roms()
]
rom.user_saves = [
SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id
]
rom.user_states = [
StateSchema.model_validate(s) for s in db_rom.states if s.user_id == user_id
]
rom.user_screenshots = [
ScreenshotSchema.model_validate(s)
for s in db_rom.screenshots
if s.user_id == user_id
]
return rom
class AddRomsResponse(TypedDict):

View File

@@ -8,7 +8,6 @@ from endpoints.responses import MessageResponse
from endpoints.responses.rom import (
AddRomsResponse,
CustomStreamingResponse,
EnhancedRomSchema,
RomSchema,
)
from exceptions.fs_exceptions import RomAlreadyExistsException
@@ -102,7 +101,7 @@ def get_roms(
id (int, optional): Rom internal id
Returns:
EnhancedRomSchema: Rom stored in RomM's database
RomSchema: Rom stored in the database
"""
with db_rom_handler.session.begin() as session:
@@ -117,7 +116,7 @@ def get_roms(
@protected_route(router.get, "/roms/{id}", ["roms.read"])
def get_rom(request: Request, id: int) -> EnhancedRomSchema:
def get_rom(request: Request, id: int) -> RomSchema:
"""Get rom endpoint
Args:
@@ -125,10 +124,9 @@ def get_rom(request: Request, id: int) -> EnhancedRomSchema:
id (int): Rom internal id
Returns:
EnhancedRomSchema: Rom stored in RomM's database
RomSchema: Rom stored in the database
"""
return db_rom_handler.get_roms(id)
return RomSchema.from_orm_with_request(db_rom_handler.get_roms(id), request)
@protected_route(router.get, "/roms/{id}/content", ["roms.read"])
@@ -200,7 +198,7 @@ async def update_rom(
HTTPException: If a rom already have that name when enabling the rename_as_igdb flag
Returns:
RomSchema: Rom stored in RomM's database
RomSchema: Rom stored in the database
"""
data = await request.form()

View File

@@ -22,7 +22,9 @@ def add_saves(
emulator: str = None,
) -> UploadedSavesResponse:
rom = db_rom_handler.get_roms(rom_id)
current_user = request.user
log.info(f"Uploading saves to {rom.name}")
if saves is None:
log.error("No saves were uploaded")
raise HTTPException(
@@ -44,7 +46,9 @@ def add_saves(
platform_fs_slug=rom.platform.fs_slug,
emulator=emulator,
)
db_save = db_save_handler.get_save_by_filename(rom.id, save.filename)
db_save = db_save_handler.get_save_by_filename(
rom_id=rom.id, user_id=current_user.id, file_name=save.filename
)
if db_save:
db_save_handler.update_save(
db_save.id, {"file_size_bytes": scanned_save.file_size_bytes}
@@ -52,12 +56,15 @@ def add_saves(
continue
scanned_save.rom_id = rom.id
scanned_save.user_id = request.user.id
scanned_save.user_id = current_user.id
scanned_save.emulator = emulator
db_save_handler.add_save(scanned_save)
rom = db_rom_handler.get_roms(rom_id)
return {"uploaded": len(saves), "saves": rom.saves}
return {
"uploaded": len(saves),
"saves": [s for s in rom.saves if s.user_id == current_user.id],
}
# @protected_route(router.get, "/saves", ["assets.read"])
@@ -80,6 +87,11 @@ async def update_save(request: Request, id: int) -> SaveSchema:
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
if db_save.user_id != request.user.id:
error = "You are not authorized to update this save"
log.error(error)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
if "file" in data:
file: UploadFile = data["file"]
fs_asset_handler.write_file(file=file, path=db_save.file_path)
@@ -107,6 +119,11 @@ async def delete_saves(request: Request) -> MessageResponse:
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
if save.user_id != request.user.id:
error = "You are not authorized to delete this save"
log.error(error)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
db_save_handler.delete_save(save_id)
if delete_from_fs:
@@ -134,4 +151,4 @@ async def delete_saves(request: Request) -> MessageResponse:
error = f"Screenshot file {save.screenshot.file_name} not found for save {save.file_name}"
log.error(error)
return {"msg": f"Successfully deleted {len(save_ids)} saves."}
return {"msg": f"Successfully deleted {len(save_ids)} saves"}

View File

@@ -13,7 +13,9 @@ def add_screenshots(
request: Request, rom_id: int, screenshots: list[UploadFile] = File(...)
) -> UploadedScreenshotsResponse:
rom = db_rom_handler.get_roms(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(
@@ -35,7 +37,7 @@ def add_screenshots(
platform_fs_slug=rom.platform_slug,
)
db_screenshot = db_screenshot_handler.get_screenshot_by_filename(
file_name=screenshot.filename, rom_id=rom.id
rom_id=rom.id, user_id=current_user.id, file_name=screenshot.filename
)
if db_screenshot:
db_screenshot_handler.update_screenshot(
@@ -45,13 +47,13 @@ def add_screenshots(
continue
scanned_screenshot.rom_id = rom.id
scanned_screenshot.user_id = request.user.id
scanned_screenshot.user_id = current_user.id
db_screenshot_handler.add_screenshot(scanned_screenshot)
rom = db_rom_handler.get_roms(rom_id)
return {
"uploaded": len(screenshots),
"screenshots": rom.screenshots,
"screenshots": [s for s in rom.screenshots if s.user_id == current_user.id],
"url_screenshots": rom.url_screenshots,
"merged_screenshots": rom.merged_screenshots,
}

View File

@@ -22,7 +22,9 @@ def add_states(
emulator: str = None,
) -> UploadedStatesResponse:
rom = db_rom_handler.get_roms(rom_id)
current_user = request.user
log.info(f"Uploading states to {rom.name}")
if states is None:
log.error("No states were uploaded")
raise HTTPException(
@@ -44,7 +46,9 @@ def add_states(
platform_fs_slug=rom.platform.fs_slug,
emulator=emulator,
)
db_state = db_state_handler.get_state_by_filename(rom.id, state.filename)
db_state = db_state_handler.get_state_by_filename(
rom_id=rom.id, user_id=current_user.id, file_name=state.filename
)
if db_state:
db_state_handler.update_state(
db_state.id, {"file_size_bytes": scanned_state.file_size_bytes}
@@ -52,12 +56,15 @@ def add_states(
continue
scanned_state.rom_id = rom.id
scanned_state.user_id = request.user.id
scanned_state.user_id = current_user.id
scanned_state.emulator = emulator
db_state_handler.add_state(scanned_state)
rom = db_rom_handler.get_roms(rom_id)
return {"uploaded": len(states), "states": rom.states}
return {
"uploaded": len(states),
"states": [s for s in rom.states if s.user_id == current_user.id],
}
# @protected_route(router.get, "/states", ["assets.read"])
@@ -80,6 +87,11 @@ async def update_state(request: Request, id: int) -> StateSchema:
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
if db_state.user_id != request.user.id:
error = "You are not authorized to update this save state"
log.error(error)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
if "file" in data:
file: UploadFile = data["file"]
fs_asset_handler.write_file(file=file, path=db_state.file_path)
@@ -107,6 +119,11 @@ async def delete_states(request: Request) -> MessageResponse:
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
if state.user_id != request.user.id:
error = "You are not authorized to delete this save state"
log.error(error)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
db_state_handler.delete_state(state_id)
if delete_from_fs:
@@ -133,4 +150,4 @@ async def delete_states(request: Request) -> MessageResponse:
error = f"Screenshot file {state.screenshot.file_name} not found for state {state.file_name}"
log.error(error)
return {"msg": f"Successfully deleted {len(state_ids)} states."}
return {"msg": f"Successfully deleted {len(state_ids)} states"}

View File

@@ -14,7 +14,7 @@ def test_delete_saves(access_token, save):
assert response.status_code == 200
body = response.json()
assert body['msg'] == "Successfully deleted 1 saves."
assert body['msg'] == "Successfully deleted 1 saves"
def test_delete_states(access_token, state):
@@ -26,4 +26,4 @@ def test_delete_states(access_token, state):
assert response.status_code == 200
body = response.json()
assert body['msg'] == "Successfully deleted 1 states."
assert body['msg'] == "Successfully deleted 1 states"

View File

@@ -23,12 +23,12 @@ DEFAULT_SCOPES_MAP: Final = {
"roms.read": "View ROMs",
"platforms.read": "View platforms",
"assets.read": "View assets",
"assets.write": "Modify assets",
}
WRITE_SCOPES_MAP: Final = {
"roms.write": "Modify ROMs",
"platforms.write": "Modify platforms",
"assets.write": "Modify assets",
}
FULL_SCOPES_MAP: Final = {

View File

@@ -16,10 +16,12 @@ class DBSavesHandler(DBHandler):
@begin_session
def get_save_by_filename(
self, rom_id: str, file_name: str, session: Session = None
self, rom_id: int, user_id: int, file_name: str, session: Session = None
):
return session.scalars(
select(Save).filter_by(rom_id=rom_id, file_name=file_name).limit(1)
select(Save)
.filter_by(rom_id=rom_id, user_id=user_id, file_name=file_name)
.limit(1)
).first()
@begin_session
@@ -40,9 +42,17 @@ class DBSavesHandler(DBHandler):
)
@begin_session
def purge_saves(self, rom_id: int, saves: list[str], session: Session = None):
def purge_saves(
self, rom_id: int, user_id: int, saves: list[str], session: Session = None
):
return session.execute(
delete(Save)
.where(and_(Save.rom_id == rom_id, Save.file_name.not_in(saves)))
.where(
and_(
Save.rom_id == rom_id,
Save.user_id == user_id,
Save.file_name.not_in(saves),
)
)
.execution_options(synchronize_session="evaluate")
)

View File

@@ -16,12 +16,11 @@ class DBScreenshotsHandler(DBHandler):
@begin_session
def get_screenshot_by_filename(
self, file_name: str, rom_id: str = None, session: Session = None
self, rom_id: int, user_id: int, file_name: str, session: Session = None
):
return session.scalars(
select(Screenshot)
.filter_by(file_name=file_name)
.where(Screenshot.rom_id == rom_id if rom_id else True)
.filter_by(rom_id=rom_id, user_id=user_id, file_name=file_name)
.limit(1)
).first()
@@ -44,12 +43,13 @@ class DBScreenshotsHandler(DBHandler):
@begin_session
def purge_screenshots(
self, rom_id: int, screenshots: list[str], session: Session = None
self, rom_id: int, user_id: int, screenshots: list[str], session: Session = None
):
return session.execute(
delete(Screenshot)
.where(
Screenshot.rom_id == rom_id,
Screenshot.user_id == user_id,
Screenshot.file_name.not_in(screenshots),
)
.execution_options(synchronize_session="evaluate")

View File

@@ -16,10 +16,12 @@ class DBStatesHandler(DBHandler):
@begin_session
def get_state_by_filename(
self, rom_id: str, file_name: str, session: Session = None
self, rom_id: int, user_id: int, file_name: str, session: Session = None
):
return session.scalars(
select(State).filter_by(rom_id=rom_id, file_name=file_name).limit(1)
select(State)
.filter_by(rom_id=rom_id, user_id=user_id, file_name=file_name)
.limit(1)
).first()
@begin_session
@@ -40,9 +42,17 @@ class DBStatesHandler(DBHandler):
)
@begin_session
def purge_states(self, rom_id: int, states: list[str], session: Session = None):
def purge_states(
self, rom_id: int, user_id: int, states: list[str], session: Session = None
):
return session.execute(
delete(State)
.where(and_(State.rom_id == rom_id, State.file_name.not_in(states)))
.where(
and_(
State.rom_id == rom_id,
State.user_id == user_id,
State.file_name.not_in(states),
)
)
.execution_options(synchronize_session="evaluate")
)

View File

@@ -1,4 +1,3 @@
import re
from functools import cached_property
from config import FRONTEND_RESOURCES_PATH
@@ -17,8 +16,6 @@ from sqlalchemy import (
)
from sqlalchemy.orm import Mapped, relationship
SORT_COMPARE_REGEX = r"^([Tt]he|[Aa]|[Aa]nd)\s"
class Rom(BaseModel):
__tablename__ = "roms"
@@ -105,21 +102,8 @@ class Rom(BaseModel):
f"{FRONTEND_RESOURCES_PATH}/{s}" for s in self.path_screenshots
]
@cached_property
def sort_comparator(self) -> str:
return (
re.sub(
SORT_COMPARE_REGEX,
"",
self.name or self.file_name_no_tags,
)
.strip()
.lower()
)
# This is an expensive operation so don't call it on a list of roms
@cached_property
def sibling_roms(self) -> list["Rom"]:
def get_sibling_roms(self) -> list["Rom"]:
from handler import db_rom_handler
if not self.igdb_id:

View File

@@ -13,7 +13,6 @@ export type { Body_update_rom_roms__id__put } from './models/Body_update_rom_rom
export type { Body_update_user_users__id__put } from './models/Body_update_user_users__id__put';
export type { ConfigResponse } from './models/ConfigResponse';
export type { CursorPage_RomSchema_ } from './models/CursorPage_RomSchema_';
export type { EnhancedRomSchema } from './models/EnhancedRomSchema';
export type { HeartbeatResponse } from './models/HeartbeatResponse';
export type { HTTPValidationError } from './models/HTTPValidationError';
export type { IGDBMetadata } from './models/IGDBMetadata';

View File

@@ -1,58 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { RomMetadata } from './RomMetadata';
import type { RomSchema } from './RomSchema';
import type { SaveSchema } from './SaveSchema';
import type { ScreenshotSchema } from './ScreenshotSchema';
import type { StateSchema } from './StateSchema';
export type EnhancedRomSchema = {
id: number;
igdb_id: (number | null);
sgdb_id: (number | null);
platform_id: number;
platform_slug: string;
platform_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;
name: (string | null);
slug: (string | null);
summary: (string | null);
total_rating: (string | null);
aggregated_rating: (string | null);
first_release_date: (number | null);
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;
collections: Array<string>;
companies: Array<string>;
game_modes: Array<string>;
igdb_metadata: (RomMetadata | null);
sort_comparator: string;
path_cover_s: (string | null);
path_cover_l: (string | null);
has_cover: boolean;
url_cover: (string | null);
revision: (string | null);
regions: Array<string>;
languages: Array<string>;
tags: Array<string>;
multi: boolean;
files: Array<string>;
saves: Array<SaveSchema>;
states: Array<StateSchema>;
screenshots: Array<ScreenshotSchema>;
url_screenshots: Array<string>;
merged_screenshots: Array<string>;
full_path: string;
download_path: string;
sibling_roms: Array<RomSchema>;
};

View File

@@ -34,7 +34,6 @@ export type RomSchema = {
companies: Array<string>;
game_modes: Array<string>;
igdb_metadata: (RomMetadata | null);
sort_comparator: string;
path_cover_s: (string | null);
path_cover_l: (string | null);
has_cover: boolean;
@@ -45,12 +44,14 @@ export type RomSchema = {
tags: Array<string>;
multi: boolean;
files: Array<string>;
saves: Array<SaveSchema>;
states: Array<StateSchema>;
screenshots: Array<ScreenshotSchema>;
url_screenshots: Array<string>;
merged_screenshots: Array<string>;
full_path: string;
download_path: string;
sibling_roms?: Array<RomSchema>;
user_saves?: Array<SaveSchema>;
user_states?: Array<StateSchema>;
user_screenshots?: Array<ScreenshotSchema>;
readonly sort_comparator: string;
};

View File

@@ -7,6 +7,8 @@ import type { ScreenshotSchema } from './ScreenshotSchema';
export type SaveSchema = {
id: number;
rom_id: number;
user_id: number;
file_name: string;
file_name_no_tags: string;
file_name_no_ext: string;
@@ -17,7 +19,6 @@ export type SaveSchema = {
download_path: string;
created_at: string;
updated_at: string;
rom_id: number;
emulator: (string | null);
screenshot: (ScreenshotSchema | null);
};

View File

@@ -5,6 +5,8 @@
export type ScreenshotSchema = {
id: number;
rom_id: number;
user_id: number;
file_name: string;
file_name_no_tags: string;
file_name_no_ext: string;
@@ -15,6 +17,5 @@ export type ScreenshotSchema = {
download_path: string;
created_at: string;
updated_at: string;
rom_id: number;
};

View File

@@ -7,6 +7,8 @@ import type { ScreenshotSchema } from './ScreenshotSchema';
export type StateSchema = {
id: number;
rom_id: number;
user_id: number;
file_name: string;
file_name_no_tags: string;
file_name_no_ext: string;
@@ -17,7 +19,6 @@ export type StateSchema = {
download_path: string;
created_at: string;
updated_at: string;
rom_id: number;
emulator: (string | null);
screenshot: (ScreenshotSchema | null);
};

View File

@@ -45,11 +45,11 @@ function onPlay() {
label="Save"
v-model="saveRef"
:items="
props.rom.saves.map((s) => ({
props.rom.user_saves?.map((s) => ({
title: s.file_name,
subtitle: `${s.emulator} - ${formatBytes(s.file_size_bytes)}`,
value: s,
}))
})) ?? []
"
/>
<v-select
@@ -61,11 +61,11 @@ function onPlay() {
label="State"
v-model="stateRef"
:items="
props.rom.states.map((s) => ({
props.rom.user_states?.map((s) => ({
title: s.file_name,
subtitle: `${s.emulator} - ${formatBytes(s.file_size_bytes)}`,
value: s,
}))
})) ?? []
"
/>
<!-- <v-select

View File

@@ -1,11 +1,10 @@
<script setup lang="ts">
import type { EnhancedRomSchema, PlatformSchema } from "@/__generated__";
import type { PlatformSchema } from "@/__generated__";
import FileInfo from "@/components/Details/Info/FileInfo.vue";
import GameInfo from "@/components/Details/Info/GameInfo.vue";
import storeDownload from "@/stores/download";
import { useDisplay } from "vuetify";
import type { Rom } from "@/stores/roms";
defineProps<{ rom: EnhancedRomSchema; platform: PlatformSchema }>();
defineProps<{ rom: Rom; platform: PlatformSchema }>();
</script>
<template>
<file-info :rom="rom" :platform="platform" />

View File

@@ -1,15 +1,16 @@
<script setup lang="ts">
import type { EnhancedRomSchema, PlatformSchema } from "@/__generated__";
import type { PlatformSchema } from "@/__generated__";
import VersionSwitcher from "@/components/Details/VersionSwitcher.vue";
import storeDownload from "@/stores/download";
import type { Rom } from "@/stores/roms";
import { formatBytes } from "@/utils";
defineProps<{ rom: EnhancedRomSchema; platform: PlatformSchema }>();
defineProps<{ rom: Rom; platform: PlatformSchema }>();
const downloadStore = storeDownload();
</script>
<template>
<v-row
v-if="rom?.sibling_roms && rom.sibling_roms.length > 0"
v-if="rom.sibling_roms && rom.sibling_roms.length > 0"
class="align-center my-3"
no-gutters
>

View File

@@ -1,9 +1,9 @@
<script setup lang="ts">
import type { EnhancedRomSchema } from "@/__generated__";
import storeGalleryFilter from "@/stores/galleryFilter";
import type { Rom } from "@/stores/roms";
import { useDisplay } from "vuetify";
defineProps<{ rom: EnhancedRomSchema }>();
defineProps<{ rom: Rom }>();
const { xs } = useDisplay();
const galleryFilter = storeGalleryFilter();
const capitalizeString = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);

View File

@@ -17,7 +17,7 @@ const romsStore = storeRoms();
emitter?.on("romUpdated", (rom) => {
if (rom?.id === props.rom.id) {
props.rom.saves = rom.saves;
props.rom.user_saves = rom.user_saves;
}
});
@@ -46,7 +46,7 @@ async function uploadSaves() {
})
.then(({ data }) => {
const { saves, uploaded } = data;
props.rom.saves = saves;
props.rom.user_saves = saves;
romsStore.update(props.rom);
savesToUpload.value = [];
@@ -100,7 +100,7 @@ async function uploadSaves() {
<v-list rounded="0" class="pa-0">
<v-list-item
class="px-3"
v-for="save in rom.saves"
v-for="save in rom.user_saves"
:key="save.id"
:title="save.file_name"
:subtitle="`${save.emulator || 'unknown'} - ${formatBytes(save.file_size_bytes)}`"

View File

@@ -17,7 +17,7 @@ const romsStore = storeRoms();
emitter?.on("romUpdated", (rom) => {
if (rom?.id === props.rom.id) {
props.rom.states = rom.states;
props.rom.user_states = rom.user_states;
}
});
@@ -46,7 +46,7 @@ async function uploadStates() {
})
.then(({ data }) => {
const { states, uploaded } = data;
props.rom.states = states;
props.rom.user_states = states;
romsStore.update(props.rom);
statesToUpload.value = [];
@@ -100,7 +100,7 @@ async function uploadStates() {
<v-list rounded="0" class="pa-0">
<v-list-item
class="pa-2 pl-4"
v-for="state in rom.states"
v-for="state in rom.user_states"
:key="state.id"
:title="state.file_name"
:subtitle="`${state.emulator || 'unknown'} - ${formatBytes(state.file_size_bytes)}`"

View File

@@ -4,29 +4,28 @@ import { useDisplay } from "vuetify";
import type { Emitter } from "mitt";
import type { Events } from "@/types/emitter";
import storeRoms from "@/stores/roms";
import storeRoms, { type Rom } from "@/stores/roms";
import saveApi from "@/services/api/save";
import stateApi from "@/services/api/state";
import type { Rom } from "@/stores/roms";
import type { SaveSchema, StateSchema } from "@/__generated__";
const { xs, mdAndDown, lgAndUp } = useDisplay();
const romsStore = storeRoms();
const show = ref(false);
const assetType = ref<"saves" | "states">("saves");
const assetType = ref<"user_saves" | "user_states">("user_saves");
const romRef = ref<Rom | null>(null);
const assets = ref<(SaveSchema | StateSchema)[]>([]);
const deleteFromFs = ref(false);
const emitter = inject<Emitter<Events>>("emitter");
emitter?.on("showDeleteSavesDialog", ({ rom, saves }) => {
assetType.value = "saves";
assetType.value = "user_saves";
assets.value = saves;
show.value = true;
romRef.value = rom;
});
emitter?.on("showDeleteStatesDialog", ({ rom, states }) => {
assetType.value = "states";
assetType.value = "user_states";
assets.value = states;
show.value = true;
romRef.value = rom;
@@ -36,7 +35,7 @@ async function deleteAssets() {
if (!assets.value) return;
const result =
assetType.value === "saves"
assetType.value === "user_saves"
? saveApi.deleteSaves({
saves: assets.value,
deleteFromFs: deleteFromFs.value,
@@ -50,9 +49,9 @@ async function deleteAssets() {
.then(() => {
if (romRef.value?.[assetType.value]) {
const deletedAssetIds = assets.value.map((asset) => asset.id);
romRef.value[assetType.value] = romRef.value[assetType.value].filter(
romRef.value[assetType.value] = romRef.value[assetType.value]?.filter(
(asset) => !deletedAssetIds.includes(asset.id)
);
) ?? [];
romsStore.update(romRef.value);
emitter?.emit("romUpdated", romRef.value);
}

View File

@@ -1,7 +1,6 @@
import type {
AddRomsResponse,
CursorPage_RomSchema_,
EnhancedRomSchema,
MessageResponse,
RomSchema,
SearchRomSchema,
@@ -68,7 +67,7 @@ async function getRom({
romId,
}: {
romId: number;
}): Promise<{ data: EnhancedRomSchema }> {
}): Promise<{ data: Rom }> {
return api.get(`/roms/${romId}`);
}

View File

@@ -4,7 +4,6 @@ import { nanoid } from "nanoid";
import { defineStore } from "pinia";
export type Rom = RomSchema & {
sibling_roms?: RomSchema[]; // Returned by the API
siblings?: RomSchema[]; // Added by the frontend
};

View File

@@ -5,9 +5,9 @@ import { inject, onBeforeMount, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useDisplay } from "vuetify";
import type { EnhancedRomSchema, PlatformSchema } from "@/__generated__";
import type { PlatformSchema } from "@/__generated__";
import ActionBar from "@/components/Details/ActionBar.vue";
import AditionalContent from "@/components/Details/AditionalContent.vue";
import AdditionalContent from "@/components/Details/AdditionalContent.vue";
import BackgroundHeader from "@/components/Details/BackgroundHeader.vue";
import Cover from "@/components/Details/Cover.vue";
import Info from "@/components/Details/Info/Base.vue";
@@ -23,15 +23,16 @@ import EditRomDialog from "@/components/Dialog/Rom/EditRom.vue";
import SearchRomDialog from "@/components/Dialog/Rom/SearchRom.vue";
import platformApi from "@/services/api/platform";
import romApi from "@/services/api/rom";
import type { Rom } from "@/stores/roms";
const route = useRoute();
const rom = ref<EnhancedRomSchema>();
const rom = ref<Rom>();
const platform = ref<PlatformSchema>();
const tab = ref<
| "details"
| "saves"
| "states"
| "aditionalcontent"
| "additionalcontent"
| "screenshots"
| "relatedgames"
| "emulation"
@@ -168,9 +169,9 @@ watch(
mdAndDown &&
(rom.igdb_metadata?.expansions || rom.igdb_metadata?.dlcs)
"
value="aditionalcontent"
value="additionalcontent"
rounded="0"
>Aditional content</v-tab
>Additional content</v-tab
>
<!-- TODO: user screenshots -->
<!-- <v-tab value="screenshots" rounded="0">Screenshots</v-tab> -->
@@ -212,9 +213,9 @@ watch(
mdAndDown &&
(rom.igdb_metadata?.expansions || rom.igdb_metadata?.dlcs)
"
value="aditionalcontent"
value="additionalcontent"
>
<aditional-content :rom="rom" />
<additional-content :rom="rom" />
</v-window-item>
<!-- TODO: user screenshots -->
<!-- <v-window-item v-if="rom.user_screenshots.lenght > 0" value="screenshots">
@@ -243,7 +244,7 @@ watch(
<template v-if="lgAndUp">
<v-col class="px-6">
<aditional-content :rom="rom" />
<additional-content :rom="rom" />
</v-col>
</template>
</v-row>

View File

@@ -1,11 +1,11 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { Rom } from "@/stores/roms";
import type { SaveSchema, StateSchema } from "@/__generated__";
import { formatBytes } from "@/utils";
import romApi from "@/services/api/rom";
import { useRoute } from "vue-router";
import Player from "@/views/Play/Player.vue";
import type { Rom } from "@/stores/roms";
const route = useRoute();
const rom = ref<Rom | null>(null);
@@ -61,11 +61,11 @@ function onPlay() {
label="Save"
v-model="saveRef"
:items="
rom.saves.map((s) => ({
rom.user_saves?.map((s) => ({
title: s.file_name,
subtitle: `${s.emulator} - ${formatBytes(s.file_size_bytes)}`,
value: s,
}))
})) ?? []
"
/>
<v-select
@@ -76,11 +76,11 @@ function onPlay() {
label="State"
v-model="stateRef"
:items="
rom.states.map((s) => ({
rom.user_states?.map((s) => ({
title: s.file_name,
subtitle: `${s.emulator} - ${formatBytes(s.file_size_bytes)}`,
value: s,
}))
})) ?? []
"
/>
<!-- <v-select

View File

@@ -3,9 +3,9 @@ import { ref, onBeforeUnmount } from "vue";
import stateApi from "@/services/api/state";
import saveApi, { saveApi as api } from "@/services/api/save";
import screenshotApi from "@/services/api/screenshot";
import type { Rom } from "@/stores/roms";
import { platformSlugEJSCoreMap } from "@/utils";
import type { SaveSchema, StateSchema } from "@/__generated__";
import type { Rom } from "@/stores/roms";
const props = defineProps<{
rom: Rom;
@@ -60,7 +60,7 @@ window.EJS_defaultOptions = { "save-state-location": "browser" };
if (props.rom.name) window.EJS_gameName = props.rom.name;
function buildStateName(): string {
const states = props.rom.states.map((s) => s.file_name);
const states = props.rom.user_states?.map((s) => s.file_name) ?? [];
const romName = props.rom.file_name_no_ext.trim();
let stateName = `${romName}.state.auto`;
if (!states.includes(stateName)) return stateName;
@@ -76,7 +76,7 @@ function buildStateName(): string {
}
function buildSaveName(): string {
const saves = props.rom.saves.map((s) => s.file_name);
const saves = props.rom.user_saves?.map((s) => s.file_name) ?? [];
const romName = props.rom.file_name_no_ext.trim();
let saveName = `${romName}.srm`;
if (!saves.includes(saveName)) return saveName;
@@ -162,7 +162,7 @@ window.EJS_onSaveState = function ({
})
.then(({ data }) => {
if (stateRef.value) stateRef.value.screenshot = data.screenshots[0];
props.rom.screenshots = data.screenshots;
props.rom.user_screenshots = data.screenshots;
props.rom.url_screenshots = data.url_screenshots;
props.rom.merged_screenshots = data.merged_screenshots;
});
@@ -182,7 +182,7 @@ window.EJS_onSaveState = function ({
const allStates = data.states.sort(
(a: StateSchema, b: StateSchema) => a.id - b.id
);
if (props.rom) props.rom.states = allStates;
if (props.rom) props.rom.user_states = allStates;
stateRef.value = allStates.pop() ?? null;
});
@@ -196,7 +196,7 @@ window.EJS_onSaveState = function ({
],
})
.then(({ data }) => {
props.rom.screenshots = data.screenshots;
props.rom.user_screenshots = data.screenshots;
props.rom.url_screenshots = data.url_screenshots;
props.rom.merged_screenshots = data.merged_screenshots;
});
@@ -274,7 +274,7 @@ window.EJS_onSaveSave = function ({
})
.then(({ data }) => {
if (saveRef.value) saveRef.value.screenshot = data.screenshots[0];
props.rom.screenshots = data.screenshots;
props.rom.user_screenshots = data.screenshots;
props.rom.url_screenshots = data.url_screenshots;
props.rom.merged_screenshots = data.merged_screenshots;
});
@@ -294,7 +294,7 @@ window.EJS_onSaveSave = function ({
const allSaves = data.saves.sort(
(a: SaveSchema, b: SaveSchema) => a.id - b.id
);
if (props.rom) props.rom.saves = allSaves;
if (props.rom) props.rom.user_saves = allSaves;
saveRef.value = allSaves.pop() ?? null;
});
@@ -308,7 +308,7 @@ window.EJS_onSaveSave = function ({
],
})
.then(({ data }) => {
props.rom.screenshots = data.screenshots;
props.rom.user_screenshots = data.screenshots;
props.rom.url_screenshots = data.url_screenshots;
props.rom.merged_screenshots = data.merged_screenshots;
});