mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
Merge pull request #1137 from rommapp/romm-829
[ROMM-829] Status fields on rom user
This commit is contained in:
@@ -8,7 +8,7 @@ from models.assets import Save, Screenshot, State # noqa
|
||||
from models.base import BaseModel
|
||||
from models.firmware import Firmware # noqa
|
||||
from models.platform import Platform # noqa
|
||||
from models.rom import Rom # noqa
|
||||
from models.rom import Rom, SiblingRom # noqa
|
||||
from models.user import User # noqa
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
@@ -33,6 +33,14 @@ target_metadata = BaseModel.metadata
|
||||
# ... etc.
|
||||
|
||||
|
||||
# Ignore specific models when running migrations
|
||||
def include_object(object, name, type_, reflected, compare_to):
|
||||
if type_ == "table" and name in [SiblingRom.__tablename__]: # Virtual table
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
@@ -53,6 +61,7 @@ def run_migrations_offline() -> None:
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
include_object=include_object,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
@@ -75,6 +84,7 @@ def run_migrations_online() -> None:
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=True,
|
||||
compare_type=True,
|
||||
include_object=include_object,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
|
||||
84
backend/alembic/versions/0026_romuser_status_fields.py
Normal file
84
backend/alembic/versions/0026_romuser_status_fields.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0026_romuser_status_fields
|
||||
Revises: 0025_roms_hashes
|
||||
Create Date: 2024-08-29 15:52:56.031850
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0026_romuser_status_fields"
|
||||
down_revision = "0025_roms_hashes"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("collections", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"path_cover_l",
|
||||
existing_type=mysql.VARCHAR(length=1000),
|
||||
type_=sa.Text(),
|
||||
existing_nullable=True,
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"path_cover_s",
|
||||
existing_type=mysql.VARCHAR(length=1000),
|
||||
type_=sa.Text(),
|
||||
existing_nullable=True,
|
||||
)
|
||||
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("last_played", sa.DateTime(timezone=True), nullable=True)
|
||||
)
|
||||
batch_op.add_column(sa.Column("backlogged", sa.Boolean(), nullable=False))
|
||||
batch_op.add_column(sa.Column("now_playing", sa.Boolean(), nullable=False))
|
||||
batch_op.add_column(sa.Column("hidden", sa.Boolean(), nullable=False))
|
||||
batch_op.add_column(sa.Column("rating", sa.Integer(), nullable=False))
|
||||
batch_op.add_column(sa.Column("difficulty", sa.Integer(), nullable=False))
|
||||
batch_op.add_column(sa.Column("completion", sa.Integer(), nullable=False))
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"status",
|
||||
sa.Enum(
|
||||
"INCOMPLETE",
|
||||
"FINISHED",
|
||||
"COMPLETED_100",
|
||||
"RETIRED",
|
||||
"NEVER_PLAYING",
|
||||
name="romuserstatus",
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.drop_column("status")
|
||||
batch_op.drop_column("completion")
|
||||
batch_op.drop_column("difficulty")
|
||||
batch_op.drop_column("rating")
|
||||
batch_op.drop_column("hidden")
|
||||
batch_op.drop_column("now_playing")
|
||||
batch_op.drop_column("backlogged")
|
||||
batch_op.drop_column("last_played")
|
||||
|
||||
with op.batch_alter_table("collections", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"path_cover_s",
|
||||
existing_type=sa.Text(),
|
||||
type_=mysql.VARCHAR(length=1000),
|
||||
existing_nullable=True,
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"path_cover_l",
|
||||
existing_type=sa.Text(),
|
||||
type_=mysql.VARCHAR(length=1000),
|
||||
existing_nullable=True,
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated, Final
|
||||
|
||||
from endpoints.forms.identity import OAuth2RequestForm
|
||||
@@ -161,9 +161,8 @@ def login(
|
||||
request.session.update({"iss": "romm:auth", "sub": user.username})
|
||||
|
||||
# Update last login and active times
|
||||
db_user_handler.update_user(
|
||||
user.id, {"last_login": datetime.now(), "last_active": datetime.now()}
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
db_user_handler.update_user(user.id, {"last_login": now, "last_active": now})
|
||||
|
||||
return {"msg": "Successfully logged in"}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
@@ -69,6 +69,7 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
|
||||
db_platforms_map = {p.name: p.id for p in db_platforms}
|
||||
|
||||
for platform in IGDB_PLATFORM_LIST:
|
||||
now = datetime.now(timezone.utc)
|
||||
sup_plat = {
|
||||
"id": -1,
|
||||
"name": platform["name"],
|
||||
@@ -77,8 +78,8 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
|
||||
"logo_path": "",
|
||||
"roms": [],
|
||||
"rom_count": 0,
|
||||
"created_at": datetime.now(),
|
||||
"updated_at": datetime.now(),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
if platform["name"] in db_platforms_map:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import NotRequired, TypedDict, get_type_hints
|
||||
|
||||
from endpoints.responses.assets import SaveSchema, ScreenshotSchema, StateSchema
|
||||
@@ -9,8 +9,8 @@ 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
|
||||
from pydantic import BaseModel, Field, computed_field
|
||||
from models.rom import Rom, RomFile, RomUserStatus
|
||||
from pydantic import BaseModel, computed_field
|
||||
|
||||
SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s")
|
||||
|
||||
@@ -26,6 +26,28 @@ RomMobyMetadata = TypedDict( # type: ignore[misc]
|
||||
)
|
||||
|
||||
|
||||
def rom_user_schema_factory() -> RomUserSchema:
|
||||
now = datetime.now(timezone.utc)
|
||||
return RomUserSchema(
|
||||
id=-1,
|
||||
user_id=-1,
|
||||
rom_id=-1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
note_raw_markdown="",
|
||||
note_is_public=False,
|
||||
is_main_sibling=False,
|
||||
backlogged=False,
|
||||
now_playing=False,
|
||||
hidden=False,
|
||||
rating=0,
|
||||
difficulty=0,
|
||||
completion=0,
|
||||
status=None,
|
||||
user__username="",
|
||||
)
|
||||
|
||||
|
||||
class RomUserSchema(BaseModel):
|
||||
id: int
|
||||
user_id: int
|
||||
@@ -35,18 +57,26 @@ class RomUserSchema(BaseModel):
|
||||
note_raw_markdown: str
|
||||
note_is_public: bool
|
||||
is_main_sibling: bool
|
||||
backlogged: bool
|
||||
now_playing: bool
|
||||
hidden: bool
|
||||
rating: int
|
||||
difficulty: int
|
||||
completion: int
|
||||
status: RomUserStatus | None
|
||||
user__username: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@classmethod
|
||||
def for_user(cls, user_id: int, db_rom: Rom) -> RomUserSchema | None:
|
||||
def for_user(cls, user_id: int, db_rom: Rom) -> RomUserSchema:
|
||||
for n in db_rom.rom_users:
|
||||
if n.user_id == user_id:
|
||||
return cls.model_validate(n)
|
||||
|
||||
return None
|
||||
# Return a dummy RomUserSchema if the user + rom combination doesn't exist
|
||||
return rom_user_schema_factory()
|
||||
|
||||
@classmethod
|
||||
def notes_for_user(cls, user_id: int, db_rom: Rom) -> list[UserNotesSchema]:
|
||||
@@ -131,52 +161,52 @@ class RomSchema(BaseModel):
|
||||
|
||||
|
||||
class SimpleRomSchema(RomSchema):
|
||||
sibling_roms: list[RomSchema] = Field(default_factory=list)
|
||||
rom_user: RomUserSchema | None = Field(default=None)
|
||||
sibling_roms: list[RomSchema]
|
||||
rom_user: RomUserSchema
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> SimpleRomSchema:
|
||||
rom = cls.model_validate(db_rom)
|
||||
def from_orm_with_request(
|
||||
cls, db_rom: Rom, request: Request
|
||||
) -> SimpleRomSchema | None:
|
||||
user_id = request.user.id
|
||||
|
||||
rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
|
||||
|
||||
return rom
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
|
||||
class DetailedRomSchema(RomSchema):
|
||||
merged_screenshots: list[str]
|
||||
sibling_roms: list[RomSchema] = Field(default_factory=list)
|
||||
rom_user: RomUserSchema | None = Field(default=None)
|
||||
user_saves: list[SaveSchema] = Field(default_factory=list)
|
||||
user_states: list[StateSchema] = Field(default_factory=list)
|
||||
user_screenshots: list[ScreenshotSchema] = Field(default_factory=list)
|
||||
user_notes: list[UserNotesSchema] = Field(default_factory=list)
|
||||
user_collections: list[CollectionSchema] = Field(default_factory=list)
|
||||
sibling_roms: list[RomSchema]
|
||||
rom_user: RomUserSchema
|
||||
user_saves: list[SaveSchema]
|
||||
user_states: list[StateSchema]
|
||||
user_screenshots: list[ScreenshotSchema]
|
||||
user_notes: list[UserNotesSchema]
|
||||
user_collections: list[CollectionSchema]
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
|
||||
rom = cls.model_validate(db_rom)
|
||||
user_id = request.user.id
|
||||
|
||||
rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
|
||||
rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom)
|
||||
rom.user_saves = [
|
||||
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 = [
|
||||
SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id
|
||||
]
|
||||
rom.user_states = [
|
||||
db_rom.user_states = [
|
||||
StateSchema.model_validate(s) for s in db_rom.states if s.user_id == user_id
|
||||
]
|
||||
rom.user_screenshots = [
|
||||
db_rom.user_screenshots = [
|
||||
ScreenshotSchema.model_validate(s)
|
||||
for s in db_rom.screenshots
|
||||
if s.user_id == user_id
|
||||
]
|
||||
rom.user_collections = CollectionSchema.for_user(
|
||||
db_rom.user_collections = CollectionSchema.for_user(
|
||||
user_id, db_rom.get_collections()
|
||||
)
|
||||
|
||||
return rom
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
|
||||
class UserNotesSchema(TypedDict):
|
||||
|
||||
@@ -126,7 +126,8 @@ def get_roms(
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
return [SimpleRomSchema.from_orm_with_request(rom, request) for rom in roms]
|
||||
roms = [SimpleRomSchema.from_orm_with_request(rom, request) for rom in roms]
|
||||
return [rom for rom in roms if rom]
|
||||
|
||||
|
||||
@protected_route(
|
||||
@@ -539,12 +540,36 @@ async def update_rom_user(request: Request, id: int) -> RomUserSchema:
|
||||
id, request.user.id
|
||||
) or db_rom_handler.add_rom_user(id, request.user.id)
|
||||
|
||||
cleaned_data = {
|
||||
"note_raw_markdown": data.get(
|
||||
"note_raw_markdown", db_rom_user.note_raw_markdown
|
||||
),
|
||||
"note_is_public": data.get("note_is_public", db_rom_user.note_is_public),
|
||||
"is_main_sibling": data.get("is_main_sibling", db_rom_user.is_main_sibling),
|
||||
}
|
||||
cleaned_data = {}
|
||||
|
||||
if "note_raw_markdown" in data:
|
||||
cleaned_data.update({"note_raw_markdown": data.get("note_raw_markdown")})
|
||||
|
||||
if "note_is_public" in data:
|
||||
cleaned_data.update({"note_is_public": data.get("note_is_public")})
|
||||
|
||||
if "is_main_sibling" in data:
|
||||
cleaned_data.update({"is_main_sibling": data.get("is_main_sibling")})
|
||||
|
||||
if "backlogged" in data:
|
||||
cleaned_data.update({"backlogged": data.get("backlogged")})
|
||||
|
||||
if "now_playing" in data:
|
||||
cleaned_data.update({"now_playing": data.get("now_playing")})
|
||||
|
||||
if "hidden" in data:
|
||||
cleaned_data.update({"hidden": data.get("hidden")})
|
||||
|
||||
if "rating" in data:
|
||||
cleaned_data.update({"rating": data.get("rating")})
|
||||
|
||||
if "difficulty" in data:
|
||||
cleaned_data.update({"difficulty": data.get("difficulty")})
|
||||
|
||||
if "completion" in data:
|
||||
cleaned_data.update({"completion": data.get("completion")})
|
||||
|
||||
if "status" in data:
|
||||
cleaned_data.update({"status": data.get("status")})
|
||||
|
||||
return db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.assets import SaveSchema, UploadedSavesResponse
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from handler.database import db_rom_handler, db_save_handler, db_screenshot_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
@@ -19,6 +22,9 @@ def add_saves(
|
||||
emulator: str | None = None,
|
||||
) -> UploadedSavesResponse:
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading saves to {rom.name}")
|
||||
|
||||
@@ -57,7 +63,19 @@ def add_saves(
|
||||
scanned_save.emulator = emulator
|
||||
db_save_handler.add_save(scanned_save)
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
# Refetch the rom to get updated saves
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(saves),
|
||||
"saves": [s for s in rom.saves if s.user_id == current_user.id],
|
||||
@@ -94,6 +112,16 @@ async def update_save(request: Request, id: int) -> SaveSchema:
|
||||
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})
|
||||
|
||||
# Set the last played time for the current user
|
||||
current_user = request.user
|
||||
rom_user = db_rom_handler.get_rom_user(db_save.rom_id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(db_save.rom_id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
# Refetch the save to get updated fields
|
||||
db_save = db_save_handler.get_save(id)
|
||||
return db_save
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.assets import StateSchema, UploadedStatesResponse
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from handler.database import db_rom_handler, db_screenshot_handler, db_state_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
@@ -19,6 +22,9 @@ def add_states(
|
||||
emulator: str | None = None,
|
||||
) -> UploadedStatesResponse:
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading states to {rom.name}")
|
||||
|
||||
@@ -57,6 +63,14 @@ def add_states(
|
||||
scanned_state.emulator = emulator
|
||||
db_state_handler.add_state(scanned_state)
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
return {
|
||||
"uploaded": len(states),
|
||||
@@ -94,6 +108,15 @@ async def update_state(request: Request, id: int) -> StateSchema:
|
||||
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})
|
||||
|
||||
# Set the last played time for the current user
|
||||
current_user = request.user
|
||||
rom_user = db_rom_handler.get_rom_user(db_state.rom_id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(db_state.rom_id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
db_state = db_state_handler.get_state(id)
|
||||
return db_state
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Final
|
||||
|
||||
from config import ROMM_AUTH_SECRET_KEY
|
||||
@@ -106,9 +106,11 @@ class OAuthHandler:
|
||||
to_encode = data.copy()
|
||||
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=DEFAULT_OAUTH_TOKEN_EXPIRY)
|
||||
expire = datetime.now(timezone.utc) + timedelta(
|
||||
minutes=DEFAULT_OAUTH_TOKEN_EXPIRY
|
||||
)
|
||||
|
||||
to_encode.update({"exp": expire})
|
||||
|
||||
|
||||
@@ -226,7 +226,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
rom_user = self.get_rom_user_by_id(id)
|
||||
|
||||
if data["is_main_sibling"]:
|
||||
if data.get("is_main_sibling", False):
|
||||
rom = self.get_rom(rom_user.rom_id)
|
||||
|
||||
session.execute(
|
||||
|
||||
@@ -46,7 +46,7 @@ def __get_sync_cache() -> Redis:
|
||||
|
||||
return FakeRedis(version=7)
|
||||
|
||||
log.info(f"Connecting to redis in {sys.argv[0]}...")
|
||||
log.info(f"Connecting to sync redis in {sys.argv[0]}...")
|
||||
# A separate client that auto-decodes responses is needed
|
||||
client = Redis(
|
||||
host=REDIS_HOST,
|
||||
@@ -56,7 +56,7 @@ def __get_sync_cache() -> Redis:
|
||||
db=REDIS_DB,
|
||||
decode_responses=True,
|
||||
)
|
||||
log.info(f"Redis connection established in {sys.argv[0]}!")
|
||||
log.info(f"Redis sync connection established in {sys.argv[0]}!")
|
||||
return client
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ def __get_async_cache() -> AsyncRedis:
|
||||
|
||||
return FakeAsyncRedis(version=7)
|
||||
|
||||
log.info(f"Connecting to redis in {sys.argv[0]}...")
|
||||
log.info(f"Connecting to async redis in {sys.argv[0]}...")
|
||||
# A separate client that auto-decodes responses is needed
|
||||
client = AsyncRedis(
|
||||
host=REDIS_HOST,
|
||||
@@ -77,7 +77,7 @@ def __get_async_cache() -> AsyncRedis:
|
||||
db=REDIS_DB,
|
||||
decode_responses=True,
|
||||
)
|
||||
log.info(f"Redis connection established in {sys.argv[0]}!")
|
||||
log.info(f"Redis async connection established in {sys.argv[0]}!")
|
||||
return client
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, TypedDict
|
||||
|
||||
@@ -8,6 +10,8 @@ from models.base import BaseModel
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
BigInteger,
|
||||
DateTime,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
@@ -174,6 +178,14 @@ class Rom(BaseModel):
|
||||
return self.file_name
|
||||
|
||||
|
||||
class RomUserStatus(enum.StrEnum):
|
||||
INCOMPLETE = "incomplete" # Started but not finished
|
||||
FINISHED = "finished" # Reached the end of the game
|
||||
COMPLETED_100 = "completed_100" # Completed 100%
|
||||
RETIRED = "retired" # Won't play again
|
||||
NEVER_PLAYING = "never_playing" # Will never play
|
||||
|
||||
|
||||
class RomUser(BaseModel):
|
||||
__tablename__ = "rom_user"
|
||||
__table_args__ = (
|
||||
@@ -186,6 +198,17 @@ class RomUser(BaseModel):
|
||||
note_is_public: Mapped[bool] = mapped_column(default=False)
|
||||
|
||||
is_main_sibling: Mapped[bool] = mapped_column(default=False)
|
||||
last_played: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
backlogged: Mapped[bool] = mapped_column(default=False)
|
||||
now_playing: Mapped[bool] = mapped_column(default=False)
|
||||
hidden: Mapped[bool] = mapped_column(default=False)
|
||||
rating: Mapped[int] = mapped_column(default=0)
|
||||
difficulty: Mapped[int] = mapped_column(default=0)
|
||||
completion: Mapped[int] = mapped_column(default=0)
|
||||
status: Mapped[RomUserStatus | None] = mapped_column(
|
||||
Enum(RomUserStatus), default=None
|
||||
)
|
||||
|
||||
rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from models.base import BaseModel
|
||||
@@ -61,4 +61,6 @@ class User(BaseModel, SimpleUser):
|
||||
def set_last_active(self):
|
||||
from handler.database import db_user_handler
|
||||
|
||||
db_user_handler.update_user(self.id, {"last_active": datetime.now()})
|
||||
db_user_handler.update_user(
|
||||
self.id, {"last_active": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
1
frontend/src/__generated__/index.ts
generated
1
frontend/src/__generated__/index.ts
generated
@@ -32,6 +32,7 @@ export type { RomIGDBMetadata } from './models/RomIGDBMetadata';
|
||||
export type { RomMobyMetadata } from './models/RomMobyMetadata';
|
||||
export type { RomSchema } from './models/RomSchema';
|
||||
export type { RomUserSchema } from './models/RomUserSchema';
|
||||
export type { RomUserStatus } from './models/RomUserStatus';
|
||||
export type { SaveSchema } from './models/SaveSchema';
|
||||
export type { SchedulerDict } from './models/SchedulerDict';
|
||||
export type { ScreenshotSchema } from './models/ScreenshotSchema';
|
||||
|
||||
@@ -58,13 +58,13 @@ export type DetailedRomSchema = {
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
merged_screenshots: Array<string>;
|
||||
sibling_roms?: Array<RomSchema>;
|
||||
rom_user?: (RomUserSchema | null);
|
||||
user_saves?: Array<SaveSchema>;
|
||||
user_states?: Array<StateSchema>;
|
||||
user_screenshots?: Array<ScreenshotSchema>;
|
||||
user_notes?: Array<UserNotesSchema>;
|
||||
user_collections?: Array<CollectionSchema>;
|
||||
sibling_roms: Array<RomSchema>;
|
||||
rom_user: RomUserSchema;
|
||||
user_saves: Array<SaveSchema>;
|
||||
user_states: Array<StateSchema>;
|
||||
user_screenshots: Array<ScreenshotSchema>;
|
||||
user_notes: Array<UserNotesSchema>;
|
||||
user_collections: Array<CollectionSchema>;
|
||||
readonly sort_comparator: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
import type { RomUserStatus } from './RomUserStatus';
|
||||
|
||||
export type RomUserSchema = {
|
||||
id: number;
|
||||
user_id: number;
|
||||
@@ -12,6 +14,13 @@ export type RomUserSchema = {
|
||||
note_raw_markdown: string;
|
||||
note_is_public: boolean;
|
||||
is_main_sibling: boolean;
|
||||
backlogged: boolean;
|
||||
now_playing: boolean;
|
||||
hidden: boolean;
|
||||
rating: number;
|
||||
difficulty: number;
|
||||
completion: number;
|
||||
status: (RomUserStatus | null);
|
||||
user__username: string;
|
||||
};
|
||||
|
||||
|
||||
6
frontend/src/__generated__/models/RomUserStatus.ts
generated
Normal file
6
frontend/src/__generated__/models/RomUserStatus.ts
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
/* generated using openapi-typescript-codegen -- do no edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
export type RomUserStatus = 'incomplete' | 'finished' | 'completed_100' | 'retired' | 'never_playing';
|
||||
@@ -52,8 +52,8 @@ export type SimpleRomSchema = {
|
||||
full_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
sibling_roms?: Array<RomSchema>;
|
||||
rom_user?: (RomUserSchema | null);
|
||||
sibling_roms: Array<RomSchema>;
|
||||
rom_user: RomUserSchema;
|
||||
readonly sort_comparator: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -14,17 +14,7 @@ import { ref, watch } from "vue";
|
||||
const props = defineProps<{ rom: DetailedRom; platform: Platform }>();
|
||||
const downloadStore = storeDownload();
|
||||
const auth = storeAuth();
|
||||
const romUser = ref(
|
||||
props.rom.rom_user ?? {
|
||||
id: null,
|
||||
user_id: auth.user?.id,
|
||||
rom_id: props.rom.id,
|
||||
updated_at: new Date(),
|
||||
note_raw_markdown: "",
|
||||
note_is_public: false,
|
||||
is_main_sibling: false,
|
||||
},
|
||||
);
|
||||
const romUser = ref(props.rom.rom_user);
|
||||
|
||||
// Functions
|
||||
function collectionsWithoutFavourites(collections: Collection[]) {
|
||||
@@ -35,25 +25,13 @@ async function toggleMainSibling() {
|
||||
romUser.value.is_main_sibling = !romUser.value.is_main_sibling;
|
||||
romApi.updateUserRomProps({
|
||||
romId: props.rom.id,
|
||||
noteRawMarkdown: romUser.value.note_raw_markdown,
|
||||
noteIsPublic: romUser.value.note_is_public,
|
||||
isMainSibling: romUser.value.is_main_sibling,
|
||||
data: romUser.value,
|
||||
});
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.rom,
|
||||
async () => {
|
||||
romUser.value = props.rom.rom_user ?? {
|
||||
id: null,
|
||||
user_id: auth.user?.id,
|
||||
rom_id: props.rom.id,
|
||||
updated_at: new Date(),
|
||||
note_raw_markdown: "",
|
||||
note_is_public: false,
|
||||
is_main_sibling: false,
|
||||
};
|
||||
},
|
||||
async () => (romUser.value = props.rom.rom_user),
|
||||
);
|
||||
</script>
|
||||
<template>
|
||||
|
||||
@@ -11,6 +11,7 @@ const galleryFilterStore = storeGalleryFilter();
|
||||
const show = ref(false);
|
||||
const carousel = ref(0);
|
||||
const router = useRouter();
|
||||
const filters = ["genres", "franchises", "collections", "companies"] as const;
|
||||
|
||||
function onFilterClick(filter: FilterType, value: string) {
|
||||
router.push({
|
||||
@@ -24,7 +25,7 @@ function onFilterClick(filter: FilterType, value: string) {
|
||||
<v-row no-gutters>
|
||||
<v-col>
|
||||
<v-divider class="mx-2 my-4" />
|
||||
<template v-for="filter in galleryFilterStore.filters" :key="filter">
|
||||
<template v-for="filter in filters" :key="filter">
|
||||
<v-row
|
||||
v-if="rom[filter].length > 0"
|
||||
class="align-center my-3"
|
||||
|
||||
@@ -2,69 +2,179 @@
|
||||
import romApi from "@/services/api/rom";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { RomUserStatus } from "@/__generated__";
|
||||
import { getTextForStatus } from "@/utils";
|
||||
import { MdEditor, MdPreview } from "md-editor-v3";
|
||||
import "md-editor-v3/lib/style.css";
|
||||
import { ref, watch } from "vue";
|
||||
import { useTheme } from "vuetify";
|
||||
|
||||
// Props
|
||||
const props = defineProps<{ rom: DetailedRom }>();
|
||||
const auth = storeAuth();
|
||||
const theme = useTheme();
|
||||
const editingNote = ref(false);
|
||||
const romUser = ref(
|
||||
props.rom.rom_user ?? {
|
||||
id: null,
|
||||
user_id: auth.user?.id,
|
||||
rom_id: props.rom.id,
|
||||
updated_at: new Date(),
|
||||
note_raw_markdown: "",
|
||||
note_is_public: false,
|
||||
is_main_sibling: false,
|
||||
},
|
||||
);
|
||||
const romUser = ref(props.rom.rom_user);
|
||||
const publicNotes =
|
||||
props.rom.user_notes?.filter((note) => note.user_id !== auth.user?.id) ?? [];
|
||||
|
||||
// Functions
|
||||
function togglePublic() {
|
||||
romUser.value.note_is_public = !romUser.value.note_is_public;
|
||||
romApi.updateUserRomProps({
|
||||
romId: props.rom.id,
|
||||
noteRawMarkdown: romUser.value.note_raw_markdown,
|
||||
noteIsPublic: romUser.value.note_is_public,
|
||||
isMainSibling: romUser.value.is_main_sibling,
|
||||
});
|
||||
}
|
||||
const difficultyEmojis = [
|
||||
"😴",
|
||||
"🥱",
|
||||
"😐",
|
||||
"😄",
|
||||
"🤔",
|
||||
"🤯",
|
||||
"😓",
|
||||
"😡",
|
||||
"🤬",
|
||||
"😵",
|
||||
];
|
||||
|
||||
const statusOptions = [
|
||||
null,
|
||||
"incomplete",
|
||||
"finished",
|
||||
"completed_100",
|
||||
"retired",
|
||||
"never_playing",
|
||||
];
|
||||
|
||||
function editNote() {
|
||||
if (editingNote.value) {
|
||||
romApi.updateUserRomProps({
|
||||
romId: props.rom.id,
|
||||
noteRawMarkdown: romUser.value.note_raw_markdown,
|
||||
noteIsPublic: romUser.value.note_is_public,
|
||||
isMainSibling: romUser.value.is_main_sibling,
|
||||
data: romUser.value,
|
||||
});
|
||||
}
|
||||
editingNote.value = !editingNote.value;
|
||||
}
|
||||
|
||||
function onStatusItemClick(status: string | null) {
|
||||
romUser.value.status = status as RomUserStatus | null;
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.rom,
|
||||
async () => {
|
||||
romUser.value = props.rom.rom_user ?? {
|
||||
id: null,
|
||||
user_id: auth.user?.id,
|
||||
rom_id: props.rom.id,
|
||||
updated_at: new Date(),
|
||||
note_raw_markdown: "",
|
||||
note_is_public: false,
|
||||
is_main_sibling: false,
|
||||
};
|
||||
async () => (romUser.value = props.rom.rom_user),
|
||||
);
|
||||
|
||||
watch(
|
||||
romUser,
|
||||
() => {
|
||||
romApi.updateUserRomProps({
|
||||
romId: props.rom.id,
|
||||
data: romUser.value,
|
||||
});
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-card rounded="0" class="mb-2">
|
||||
<v-card-title class="bg-terciary">
|
||||
<v-list-item class="pl-2 pr-0">
|
||||
<span class="text-h6">Status</span>
|
||||
</v-list-item>
|
||||
</v-card-title>
|
||||
<v-card-text class="py-4 px-8">
|
||||
<v-row no-gutters>
|
||||
<v-col cols="6">
|
||||
<v-checkbox
|
||||
label="Backlogged"
|
||||
v-model="romUser.backlogged"
|
||||
color="romm-accent-1"
|
||||
hide-details
|
||||
/>
|
||||
<v-checkbox
|
||||
label="Now playing"
|
||||
v-model="romUser.now_playing"
|
||||
color="romm-accent-1"
|
||||
hide-details
|
||||
/>
|
||||
<v-checkbox
|
||||
label="Hidden"
|
||||
v-model="romUser.hidden"
|
||||
color="romm-accent-1"
|
||||
hide-details
|
||||
/>
|
||||
</v-col>
|
||||
<v-col cols="6">
|
||||
<div class="d-flex align-center mt-2">
|
||||
<v-label class="text-body-2 mr-4">Rating</v-label>
|
||||
<v-rating
|
||||
hover
|
||||
ripple
|
||||
length="10"
|
||||
size="32"
|
||||
v-model="romUser.rating"
|
||||
@update:model-value="
|
||||
romUser.rating =
|
||||
typeof $event === 'number' ? $event : parseInt($event)
|
||||
"
|
||||
active-color="romm-accent-1"
|
||||
/>
|
||||
</div>
|
||||
<div class="d-flex align-center mt-3">
|
||||
<v-label class="text-body-2 mr-4">Difficulty</v-label>
|
||||
<v-slider
|
||||
v-model="romUser.difficulty"
|
||||
min="1"
|
||||
max="10"
|
||||
step="1"
|
||||
hide-details
|
||||
track-fill-color="romm-accent-1"
|
||||
/>
|
||||
<v-label class="ml-2 opacity-100">
|
||||
{{
|
||||
difficultyEmojis[Math.floor(romUser.difficulty) - 1] ?? "😀"
|
||||
}}</v-label
|
||||
>
|
||||
</div>
|
||||
<div class="d-flex align-center mt-3">
|
||||
<v-label class="text-body-2 mr-4">Completion %</v-label>
|
||||
<v-slider
|
||||
v-model="romUser.completion"
|
||||
min="1"
|
||||
max="100"
|
||||
step="1"
|
||||
hide-details
|
||||
track-fill-color="romm-accent-1"
|
||||
/>
|
||||
<v-label class="text-body-2 ml-2 opacity-100">
|
||||
{{ romUser.completion }}%
|
||||
</v-label>
|
||||
</div>
|
||||
<div class="d-flex align-center mt-3">
|
||||
<v-select
|
||||
v-model="romUser.status"
|
||||
:items="statusOptions"
|
||||
hide-details
|
||||
label="Status"
|
||||
dense
|
||||
rounded="0"
|
||||
variant="outlined"
|
||||
density="compact"
|
||||
class="mt-1"
|
||||
>
|
||||
<template v-slot:selection="{ item }">
|
||||
<span>{{ getTextForStatus(item.raw as RomUserStatus) }}</span>
|
||||
</template>
|
||||
<template v-slot:item="{ item }">
|
||||
<v-list-item
|
||||
link
|
||||
rounded="0"
|
||||
@click="onStatusItemClick(item.raw)"
|
||||
>
|
||||
{{ getTextForStatus(item.raw as RomUserStatus) }}
|
||||
</v-list-item>
|
||||
</template>
|
||||
</v-select>
|
||||
</div>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
<v-card rounded="0">
|
||||
<v-card-title class="bg-terciary">
|
||||
<v-list-item class="pl-2 pr-0">
|
||||
@@ -79,7 +189,7 @@ watch(
|
||||
open-delay="500"
|
||||
><template #activator="{ props: tooltipProps }">
|
||||
<v-btn
|
||||
@click="togglePublic"
|
||||
@click="romUser.note_is_public = !romUser.note_is_public"
|
||||
v-bind="tooltipProps"
|
||||
class="bg-terciary"
|
||||
>
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { Platform } from "@/stores/platforms";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import { languageToEmoji, regionToEmoji } from "@/utils";
|
||||
import type { RomSchema } from "@/__generated__";
|
||||
import { ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
@@ -11,7 +12,7 @@ const router = useRouter();
|
||||
const version = ref(props.rom.id);
|
||||
|
||||
// Functions
|
||||
function formatTitle(rom: DetailedRom) {
|
||||
function formatTitle(rom: RomSchema) {
|
||||
const langs = rom.languages.map((l) => languageToEmoji(l)).join(" ");
|
||||
const regions = rom.regions.map((r) => regionToEmoji(r)).join(" ");
|
||||
const tags = rom.tags.map((t) => `(${t})`).join(" ");
|
||||
|
||||
@@ -7,11 +7,9 @@ import storeGalleryFilter from "@/stores/galleryFilter";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import type { Emitter } from "mitt";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { inject, nextTick, ref } from "vue";
|
||||
import { inject, nextTick } from "vue";
|
||||
import { useDisplay } from "vuetify";
|
||||
|
||||
// Props
|
||||
const show = ref(false);
|
||||
const { xs } = useDisplay();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const galleryFilterStore = storeGalleryFilter();
|
||||
@@ -25,6 +23,8 @@ const {
|
||||
filterCollections,
|
||||
selectedCompany,
|
||||
filterCompanies,
|
||||
selectedStatus,
|
||||
filterStatuses,
|
||||
} = storeToRefs(galleryFilterStore);
|
||||
const filters = [
|
||||
{
|
||||
@@ -47,14 +47,19 @@ const filters = [
|
||||
selected: selectedCompany,
|
||||
items: filterCompanies,
|
||||
},
|
||||
{
|
||||
label: "Status",
|
||||
selected: selectedStatus,
|
||||
items: filterStatuses,
|
||||
},
|
||||
];
|
||||
|
||||
// Functions
|
||||
function resetFilters() {
|
||||
selectedGenre.value = null;
|
||||
selectedFranchise.value = null;
|
||||
selectedCollection.value = null;
|
||||
selectedCompany.value = null;
|
||||
selectedStatus.value = null;
|
||||
galleryFilterStore.disableFilterUnmatched();
|
||||
galleryFilterStore.disableFilterFavourites();
|
||||
nextTick(() => emitter?.emit("filter", null));
|
||||
@@ -93,8 +98,8 @@ function resetFilters() {
|
||||
</v-list-item>
|
||||
<v-list-item class="justify-center d-flex">
|
||||
<v-btn size="small" variant="tonal" @click="resetFilters">
|
||||
Reset filters</v-btn
|
||||
>
|
||||
Reset filters
|
||||
</v-btn>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</v-navigation-drawer>
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { type SimpleRom } from "@/stores/roms.js";
|
||||
import { languageToEmoji, regionToEmoji } from "@/utils";
|
||||
import {
|
||||
languageToEmoji,
|
||||
regionToEmoji,
|
||||
getEmojiForStatus,
|
||||
getTextForStatus,
|
||||
} from "@/utils";
|
||||
import { identity, isNull } from "lodash";
|
||||
|
||||
defineProps<{ rom: SimpleRom }>();
|
||||
const props = defineProps<{ rom: SimpleRom }>();
|
||||
const showRegions = isNull(localStorage.getItem("settings.showRegions"))
|
||||
? true
|
||||
: localStorage.getItem("settings.showRegions") === "true";
|
||||
@@ -13,6 +19,12 @@ const showLanguages = isNull(localStorage.getItem("settings.showLanguages"))
|
||||
const showSiblings = isNull(localStorage.getItem("settings.showSiblings"))
|
||||
? true
|
||||
: localStorage.getItem("settings.showSiblings") === "true";
|
||||
|
||||
const playingStatus = computed(() => {
|
||||
if (props.rom.rom_user.now_playing) return "now_playing";
|
||||
if (props.rom.rom_user.backlogged) return "backlogged";
|
||||
return props.rom.rom_user.status;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -38,6 +50,14 @@ const showSiblings = isNull(localStorage.getItem("settings.showSiblings"))
|
||||
{{ languageToEmoji(language) }}
|
||||
</span>
|
||||
</v-chip>
|
||||
<v-chip
|
||||
v-if="playingStatus"
|
||||
class="translucent-dark mr-1 mt-1"
|
||||
density="compact"
|
||||
:title="getTextForStatus(playingStatus)"
|
||||
>
|
||||
{{ getEmojiForStatus(playingStatus) }}
|
||||
</v-chip>
|
||||
<v-chip
|
||||
v-if="rom.sibling_roms && rom.sibling_roms.length > 0 && showSiblings"
|
||||
class="translucent-dark mr-1 mt-1"
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { MessageResponse, SearchRomSchema } from "@/__generated__";
|
||||
import type {
|
||||
MessageResponse,
|
||||
SearchRomSchema,
|
||||
RomUserSchema,
|
||||
} from "@/__generated__";
|
||||
import api from "@/services/api/index";
|
||||
import socket from "@/services/socket";
|
||||
import storeUpload from "@/stores/upload";
|
||||
@@ -169,20 +173,12 @@ async function deleteRoms({
|
||||
|
||||
async function updateUserRomProps({
|
||||
romId,
|
||||
noteRawMarkdown,
|
||||
noteIsPublic,
|
||||
isMainSibling,
|
||||
data,
|
||||
}: {
|
||||
romId: number;
|
||||
noteRawMarkdown: string;
|
||||
noteIsPublic: boolean;
|
||||
isMainSibling: boolean;
|
||||
data: Partial<RomUserSchema>;
|
||||
}): Promise<{ data: DetailedRom }> {
|
||||
return api.put(`/roms/${romId}/props`, {
|
||||
note_raw_markdown: noteRawMarkdown,
|
||||
note_is_public: noteIsPublic,
|
||||
is_main_sibling: isMainSibling,
|
||||
});
|
||||
return api.put(`/roms/${romId}/props`, data);
|
||||
}
|
||||
|
||||
export default {
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { normalizeString } from "@/utils";
|
||||
import { defineStore } from "pinia";
|
||||
import { romStatusMap } from "@/utils";
|
||||
|
||||
const filters = ["genres", "franchises", "collections", "companies"] as const;
|
||||
const filters = [
|
||||
"genres",
|
||||
"franchises",
|
||||
"collections",
|
||||
"companies",
|
||||
"status",
|
||||
] as const;
|
||||
|
||||
const statusFilters = Object.values(romStatusMap).map((status) => status.text);
|
||||
|
||||
export type FilterType = (typeof filters)[number];
|
||||
|
||||
@@ -14,6 +23,7 @@ export default defineStore("galleryFilter", {
|
||||
filterFranchises: [] as string[],
|
||||
filterCollections: [] as string[],
|
||||
filterCompanies: [] as string[],
|
||||
filterStatuses: statusFilters,
|
||||
filterUnmatched: false,
|
||||
filterFavourites: false,
|
||||
filterDuplicates: false,
|
||||
@@ -21,6 +31,7 @@ export default defineStore("galleryFilter", {
|
||||
selectedFranchise: null as string | null,
|
||||
selectedCollection: null as string | null,
|
||||
selectedCompany: null as string | null,
|
||||
selectedStatus: null as string | null,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
@@ -54,6 +65,9 @@ export default defineStore("galleryFilter", {
|
||||
setSelectedFilterCompany(company: string) {
|
||||
this.selectedCompany = company;
|
||||
},
|
||||
setSelectedFilterStatus(status: string) {
|
||||
this.selectedStatus = status;
|
||||
},
|
||||
switchFilterUnmatched() {
|
||||
this.filterUnmatched = !this.filterUnmatched;
|
||||
},
|
||||
@@ -81,7 +95,8 @@ export default defineStore("galleryFilter", {
|
||||
this.selectedGenre ||
|
||||
this.selectedFranchise ||
|
||||
this.selectedCollection ||
|
||||
this.selectedCompany,
|
||||
this.selectedCompany ||
|
||||
this.selectedStatus,
|
||||
);
|
||||
},
|
||||
reset() {
|
||||
@@ -93,6 +108,7 @@ export default defineStore("galleryFilter", {
|
||||
this.selectedFranchise = null;
|
||||
this.selectedCollection = null;
|
||||
this.selectedCompany = null;
|
||||
this.selectedStatus = null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { SearchRomSchema } from "@/__generated__";
|
||||
import type { DetailedRomSchema, SimpleRomSchema } from "@/__generated__/";
|
||||
import { getStatusKeyForText } from "@/utils";
|
||||
import { type Platform } from "@/stores/platforms";
|
||||
import { type Collection } from "@/stores/collections";
|
||||
import type { ExtractPiniaStoreType } from "@/types";
|
||||
@@ -151,6 +152,16 @@ export default defineStore("roms", {
|
||||
if (galleryFilter.selectedCompany) {
|
||||
this._filterCompany(galleryFilter.selectedCompany);
|
||||
}
|
||||
if (galleryFilter.selectedStatus) {
|
||||
this._filterStatus(galleryFilter.selectedStatus);
|
||||
} else {
|
||||
this._filteredIDs = new Set(
|
||||
// Filter hidden roms if the status is not hidden
|
||||
this.filteredRoms
|
||||
.filter((rom) => !rom.rom_user.hidden)
|
||||
.map((rom) => rom.id),
|
||||
);
|
||||
}
|
||||
},
|
||||
_filterSearch(searchFilter: string) {
|
||||
const bySearch = new Set(
|
||||
@@ -246,6 +257,26 @@ export default defineStore("roms", {
|
||||
// @ts-expect-error intersection is recently defined on Set
|
||||
this._filteredIDs = byCompany.intersection(this._filteredIDs);
|
||||
},
|
||||
_filterStatus(statusToFilter: string) {
|
||||
const stf = getStatusKeyForText(statusToFilter);
|
||||
|
||||
const byStatus = new Set(
|
||||
this.filteredRoms
|
||||
.filter(
|
||||
(rom) =>
|
||||
rom.rom_user.status === stf ||
|
||||
(stf === "now_playing" && rom.rom_user.now_playing) ||
|
||||
(stf === "backlogged" && rom.rom_user.backlogged) ||
|
||||
(stf === "hidden" && rom.rom_user.hidden),
|
||||
)
|
||||
// Filter hidden roms if the status is not hidden
|
||||
.filter((rom) => (stf === "hidden" ? true : !rom.rom_user.hidden))
|
||||
.map((rom) => rom.id),
|
||||
);
|
||||
|
||||
// @ts-expect-error intersection is recently defined on Set
|
||||
this._filteredIDs = byStatus.intersection(this._filteredIDs);
|
||||
},
|
||||
// Selected roms
|
||||
setSelection(roms: SimpleRom[]) {
|
||||
this._selectedIDs = new Set(roms.map((rom) => rom.id));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import cronstrue from "cronstrue";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import type { Heartbeat } from "@/stores/heartbeat";
|
||||
import type { RomUserStatus } from "@/__generated__";
|
||||
|
||||
export const views: Record<
|
||||
number,
|
||||
@@ -365,3 +366,35 @@ export function isRuffleEmulationSupported(
|
||||
!heartbeat.EMULATION.DISABLE_RUFFLE_RS
|
||||
);
|
||||
}
|
||||
|
||||
type PlayingStatus = RomUserStatus | "backlogged" | "now_playing" | "hidden";
|
||||
|
||||
export const romStatusMap: Record<
|
||||
PlayingStatus,
|
||||
{ emoji: string; text: string }
|
||||
> = {
|
||||
backlogged: { emoji: "🔜", text: "Backlogged" },
|
||||
now_playing: { emoji: "🕹️", text: "Now Playing" },
|
||||
incomplete: { emoji: "🚧", text: "Incomplete" },
|
||||
finished: { emoji: "🏁", text: "Finished" },
|
||||
completed_100: { emoji: "💯", text: "Completed 100%" },
|
||||
retired: { emoji: "🏴", text: "Retired" },
|
||||
never_playing: { emoji: "🚫", text: "Never Playing" },
|
||||
hidden: { emoji: "👻", text: "Hidden" },
|
||||
};
|
||||
|
||||
const inverseRomStatusMap = Object.fromEntries(
|
||||
Object.entries(romStatusMap).map(([key, value]) => [value.text, key]),
|
||||
) as Record<string, PlayingStatus>;
|
||||
|
||||
export function getEmojiForStatus(status: PlayingStatus) {
|
||||
return romStatusMap[status].emoji;
|
||||
}
|
||||
|
||||
export function getTextForStatus(status: PlayingStatus) {
|
||||
return romStatusMap[status].text;
|
||||
}
|
||||
|
||||
export function getStatusKeyForText(text: string) {
|
||||
return inverseRomStatusMap[text];
|
||||
}
|
||||
|
||||
@@ -121,7 +121,6 @@ async function onFilterChange() {
|
||||
function onGameClick(emitData: { rom: SimpleRom; event: MouseEvent }) {
|
||||
let index = filteredRoms.value.indexOf(emitData.rom);
|
||||
if (
|
||||
emitData.event.ctrlKey ||
|
||||
emitData.event.shiftKey ||
|
||||
romsStore.selecting ||
|
||||
romsStore.selectedRoms.length > 0
|
||||
@@ -152,16 +151,14 @@ function onGameClick(emitData: { rom: SimpleRom; event: MouseEvent }) {
|
||||
} else {
|
||||
romsStore.updateLastSelected(index);
|
||||
}
|
||||
} else if (emitData.event.metaKey || emitData.event.ctrlKey) {
|
||||
const link = router.resolve({
|
||||
name: "rom",
|
||||
params: { rom: emitData.rom.id },
|
||||
});
|
||||
window.open(link.href, "_blank");
|
||||
} else {
|
||||
if (emitData.event.metaKey || emitData.event.ctrlKey) {
|
||||
const link = router.resolve({
|
||||
name: "rom",
|
||||
params: { rom: emitData.rom.id },
|
||||
});
|
||||
window.open(link.href, "_blank");
|
||||
} else {
|
||||
router.push({ name: "rom", params: { rom: emitData.rom.id } });
|
||||
}
|
||||
router.push({ name: "rom", params: { rom: emitData.rom.id } });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -121,7 +121,6 @@ async function onFilterChange() {
|
||||
function onGameClick(emitData: { rom: SimpleRom; event: MouseEvent }) {
|
||||
let index = filteredRoms.value.indexOf(emitData.rom);
|
||||
if (
|
||||
emitData.event.ctrlKey ||
|
||||
emitData.event.shiftKey ||
|
||||
romsStore.selecting ||
|
||||
romsStore.selectedRoms.length > 0
|
||||
@@ -152,16 +151,14 @@ function onGameClick(emitData: { rom: SimpleRom; event: MouseEvent }) {
|
||||
} else {
|
||||
romsStore.updateLastSelected(index);
|
||||
}
|
||||
} else if (emitData.event.metaKey || emitData.event.ctrlKey) {
|
||||
const link = router.resolve({
|
||||
name: "rom",
|
||||
params: { rom: emitData.rom.id },
|
||||
});
|
||||
window.open(link.href, "_blank");
|
||||
} else {
|
||||
if (emitData.event.metaKey || emitData.event.ctrlKey) {
|
||||
const link = router.resolve({
|
||||
name: "rom",
|
||||
params: { rom: emitData.rom.id },
|
||||
});
|
||||
window.open(link.href, "_blank");
|
||||
} else {
|
||||
router.push({ name: "rom", params: { rom: emitData.rom.id } });
|
||||
}
|
||||
router.push({ name: "rom", params: { rom: emitData.rom.id } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,6 +206,7 @@ const filterToSetFilter: Record<FilterType, Function> = {
|
||||
franchises: galleryFilterStore.setSelectedFilterFranchise,
|
||||
collections: galleryFilterStore.setSelectedFilterCollection,
|
||||
companies: galleryFilterStore.setSelectedFilterCompany,
|
||||
status: galleryFilterStore.setSelectedFilterStatus,
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import AdditionalContent from "@/components/Details/AdditionalContent.vue";
|
||||
import BackgroundHeader from "@/components/Details/BackgroundHeader.vue";
|
||||
import FileInfo from "@/components/Details/Info/FileInfo.vue";
|
||||
import GameInfo from "@/components/Details/Info/GameInfo.vue";
|
||||
import Notes from "@/components/Details/Notes.vue";
|
||||
import Personal from "@/components/Details/Personal.vue";
|
||||
import RelatedGames from "@/components/Details/RelatedGames.vue";
|
||||
import Saves from "@/components/Details/Saves.vue";
|
||||
import States from "@/components/Details/States.vue";
|
||||
@@ -30,7 +30,7 @@ const tab = ref<
|
||||
| "details"
|
||||
| "saves"
|
||||
| "states"
|
||||
| "notes"
|
||||
| "personal"
|
||||
| "additionalcontent"
|
||||
| "screenshots"
|
||||
| "relatedgames"
|
||||
@@ -152,7 +152,7 @@ watch(
|
||||
<v-tab value="details" rounded="0"> Details </v-tab>
|
||||
<v-tab value="saves" rounded="0"> Saves </v-tab>
|
||||
<v-tab value="states" rounded="0"> States </v-tab>
|
||||
<v-tab value="notes" rounded="0"> Notes </v-tab>
|
||||
<v-tab value="personal" rounded="0"> Personal </v-tab>
|
||||
<v-tab
|
||||
v-if="
|
||||
mdAndDown &&
|
||||
@@ -197,8 +197,8 @@ watch(
|
||||
<v-window-item value="states">
|
||||
<states :rom="currentRom" />
|
||||
</v-window-item>
|
||||
<v-window-item value="notes">
|
||||
<notes :rom="currentRom" />
|
||||
<v-window-item value="personal">
|
||||
<personal :rom="currentRom" />
|
||||
</v-window-item>
|
||||
<v-window-item
|
||||
v-if="
|
||||
|
||||
Reference in New Issue
Block a user