Merge pull request #204 from zurdi15/develop

v1.8
This commit is contained in:
Zurdi
2023-04-26 03:24:59 +02:00
committed by GitHub
89 changed files with 5683 additions and 1357 deletions

3
.gitignore vendored
View File

@@ -39,8 +39,5 @@ envs.env
# database
mariadb
# data test
library
# config test
romm

View File

@@ -1,3 +1,20 @@
# v1.8 (_25-04-2023_)
## Added
- Home screen.
- Config option to associate custom system folders to platforms (Complete scan needed). Check [config.yml](docker/config.example.yml) example. Solves [#152](https://github.com/zurdi15/romm/issues/152).
- Sega Saturn and Master System support added. Check [platforms support](https://github.com/zurdi15/romm#platforms-support). Solves [#194](https://github.com/zurdi15/romm/issues/194).
- Progress bar when games are being downloaded.
## Changed
- Routes to different RomM sections and games changed now allow share direct links to platforms and games.
- RomM now can scan subdirectories in a multi-part game. Solves [#179](https://github.com/zurdi15/romm/issues/179).
- Settings and Scan sections are now in the main drawer menu.
- Some UI changes.
## Fixed
- Code base stability and speed improved.
<br>
# v1.7.1 (_15-04-2023_)
## Added

151
README.md
View File

@@ -1,11 +1,11 @@
<div align="center">
<h1 style="padding:20px;"><img src="romm.svg" height="220px" width="auto" alt="RomM Logo"></h1>
<img alt="GitHub" src="https://img.shields.io/github/license/zurdi15/romm">
<img alt="GitHub release (latest SemVer)" src="https://img.shields.io/github/v/release/zurdi15/romm">
<img alt="GitHub Workflow Status (with branch)" src="https://img.shields.io/github/actions/workflow/status/zurdi15/romm/image.yml?branch=master">
<img alt="GitHub" src="https://img.shields.io/github/license/zurdi15/romm?style=flat-square">
<img alt="GitHub release (latest SemVer)" src="https://img.shields.io/github/v/release/zurdi15/romm?style=flat-square">
<img alt="GitHub Workflow Status (with branch)" src="https://img.shields.io/github/actions/workflow/status/zurdi15/romm/image.yml?style=flat-square&branch=master">
<a href="https://hub.docker.com/r/zurdi15/romm">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/zurdi15/romm">
<img alt="Docker Image Size (latest by date)" src="https://img.shields.io/docker/image-size/zurdi15/romm">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/zurdi15/romm?style=flat-square">
<img alt="Docker Image Size (latest by date)" src="https://img.shields.io/docker/image-size/zurdi15/romm?style=flat-square">
</div>
<br>
<div align="center">
@@ -44,11 +44,11 @@ Available as a docker [image](https://hub.docker.com/r/zurdi15/romm) (amd64/arm6
## 🖥 Desktop
<details><summary>Video preview</summary><p>https://user-images.githubusercontent.com/34356590/227992371-33056130-c067-49c1-ae32-b3ba78db6798.mp4</p></details>
<details><summary>Video preview</summary><span>https://user-images.githubusercontent.com/34356590/227992371-33056130-c067-49c1-ae32-b3ba78db6798.mp4</span></details>
## 📱 Mobile
<details><summary>Video preview</summary><p>https://user-images.githubusercontent.com/34356590/228007442-0a9cbf6b-4b62-4c1a-aad8-48b13e6337e8.mp4</p></details>
<details><summary>Video preview</summary><span>https://user-images.githubusercontent.com/34356590/228007442-0a9cbf6b-4b62-4c1a-aad8-48b13e6337e8.mp4</span></details>
# Installation
@@ -129,75 +129,78 @@ This will change over the time, adding games metadata for more platforms. Make s
<br>
<details>
<summary>Platforms support list</summary>
<p>
<span>
| slug | name | games metadata |
|---------------|-------------------------------------| :----: |
| 3ds | Nintendo 3DS | ✅ |
| amiga | Amiga | ✅ |
| arcade | Arcade | ✅ |
| atari | atari | ❌ |
| coleco | coleco | ❌ |
| c64 | Commodore C64/128/MAX | ✅ |
| cpc | cpc | ❌ |
| cps1 | cps1 | ❌ |
| cps2 | cps2 | ❌ |
| cps3 | cps3 | ❌ |
| daphne | daphne | ❌ |
| dc | Dreamcast | ✅ |
| dos | DOS | ✅ |
| fairchild | fairchild | ❌ |
| fba2012 | fba2012 | ❌ |
| fbneo | fbneo | ❌ |
| fds | Family Computer Disk System | ✅ |
| gb | Game Boy | ✅ |
| gba | Game Boy Advance | ✅ |
| gbc | Game Boy Color | ✅ |
| gg | gg | ❌ |
| gw | gw | ❌ |
| intellivision | Intellivision | ✅ |
| jaguar | Atari Jaguar | ✅ |
| lynx | Atari Lynx | ✅ |
| md | md | ❌ |
| megaduck | megaduck | ❌ |
| ms | ms | ❌ |
| msx | MSX | ✅ |
| n64 | Nintendo 64 | ✅ |
| nds | Nintendo DS | ✅ |
| neocd | neocd | ❌ |
| neogeo | neogeo | ❌ |
| nes | Nintendo Entertainment System | ✅ |
| ngc | Nintendo GameCube | ✅ |
| ngp | ngp | ❌ |
| odyssey | odyssey | ❌ |
| pce | pce | ❌ |
| pcecd | pcecd | ❌ |
| pico | pico | ❌ |
| poke | poke | ❌ |
| ps | PlayStation | ✅ |
| ps2 | PlayStation 2 | ✅ |
| ps3 | PlayStation 3 | ✅ |
| ps4 | ps4 | ❌ |
| psp | PlayStation Portable | ✅ |
| psvita | PlayStation Vita | ✅ |
| scummvm | scummvm | ❌ |
| segacd | Sega CD | ✅ |
| segasgone | segasgone | ❌ |
| sgb | sgb | ❌ |
| sgfx | sgfx | ❌ |
| snes | Super Nintendo Entertainment System | ✅ |
| supervision | supervision | ❌ |
| switch | Nintendo Switch | ✅ |
| wii | Wii | ✅ |
| win | PC (Microsoft Windows) | ✅ |
| wiiu | Wii U | ✅ |
| wonderswan | WonderSwan | ✅ |
| wonderswan-color| WonderSwan Color | ✅ |
| xbox | Xbox | ✅ |
| xbox360 | Xbox 360 | ✅ |
| xboxone | Xbox One | ✅ |
| slug | name | games metadata |
|--------------- |-------------------------------------| :----: |
| 3ds | Nintendo 3DS | ✅ |
| amiga | Amiga | ✅ |
| arcade | Arcade | ✅ |
| atari | atari | ❌ |
| coleco | coleco | ❌ |
| c64 | Commodore C64/128/MAX | ✅ |
| cpc | cpc | ❌ |
| cps1 | cps1 | ❌ |
| cps2 | cps2 | ❌ |
| cps3 | cps3 | ❌ |
| daphne | daphne | ❌ |
| dc | Dreamcast | ✅ |
| dos | DOS | ✅ |
| fairchild | fairchild | ❌ |
| fba2012 | fba2012 | ❌ |
| fbneo | fbneo | ❌ |
| fds | Family Computer Disk System | ✅ |
| gb | Game Boy | ✅ |
| gba | Game Boy Advance | ✅ |
| gbc | Game Boy Color | ✅ |
| genesis-slash-megadrive | Sega Mega Drive/Genesis | ✅ |
| gg | gg | ❌ |
| gw | gw | ❌ |
| intellivision | Intellivision | ✅ |
| jaguar | Atari Jaguar | ✅ |
| lynx | Atari Lynx | ✅ |
| md | md | ❌ |
| megaduck | megaduck | ❌ |
| ms | ms | ❌ |
| msx | MSX | ✅ |
| n64 | Nintendo 64 | ✅ |
| nds | Nintendo DS | ✅ |
| neocd | neocd | ❌ |
| neogeo | neogeo | ❌ |
| nes | Nintendo Entertainment System | ✅ |
| ngc | Nintendo GameCube | ✅ |
| ngp | ngp | ❌ |
| odyssey | odyssey | ❌ |
| pce | pce | ❌ |
| pcecd | pcecd | ❌ |
| pico | pico | ❌ |
| poke | poke | ❌ |
| ps | PlayStation | ✅ |
| ps2 | PlayStation 2 | ✅ |
| ps3 | PlayStation 3 | ✅ |
| ps4 | ps4 | ❌ |
| psp | PlayStation Portable | ✅ |
| psvita | PlayStation Vita | ✅ |
| saturn | Sega Saturn | ✅ |
| scummvm | scummvm | ❌ |
| segacd | Sega CD | ✅ |
| segasgone | segasgone | ❌ |
| sms | Sega Master System/Mark III | ✅ |
| sgb | sgb | ❌ |
| sgfx | sgfx | ❌ |
| snes | Super Nintendo Entertainment System | ✅ |
| supervision | supervision | ❌ |
| switch | Nintendo Switch | ✅ |
| wii | Wii | ✅ |
| win | PC (Microsoft Windows) | ✅ |
| wiiu | Wii U | ✅ |
| wonderswan | WonderSwan | ✅ |
| wonderswan-color | WonderSwan Color | ✅ |
| xbox | Xbox | ✅ |
| xbox360 | Xbox 360 | ✅ |
| xboxone | Xbox One | ✅ |
</p>
</span>
</details>
<br>

View File

@@ -4,7 +4,8 @@ from pathlib import Path
from logging.config import fileConfig
from sqlalchemy import create_engine
from config.config_loader import get_db_engine
from config.config_loader import ConfigLoader
cl = ConfigLoader()
from alembic import context
@@ -45,8 +46,9 @@ def run_migrations_offline() -> None:
"""
context.configure(
url=get_db_engine(),
url=cl.get_db_engine(),
target_metadata=target_metadata,
render_as_batch=True,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
@@ -63,11 +65,13 @@ def run_migrations_online() -> None:
"""
engine = create_engine(get_db_engine())
engine = create_engine(cl.get_db_engine())
with engine.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
connection=connection,
target_metadata=target_metadata,
render_as_batch=True
)
with context.begin_transaction():

View File

@@ -1,4 +1,4 @@
"""init
"""init to 1.6.2
Revision ID: 1.6.2
Revises:
@@ -21,35 +21,35 @@ def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
try:
op.create_table('platforms',
sa.Column('igdb_id', sa.String(length=10), nullable=True),
sa.Column('sgdb_id', sa.String(length=10), nullable=True),
sa.Column('slug', sa.String(length=50), nullable=False),
sa.Column('name', sa.String(length=400), nullable=True),
sa.Column('logo_path', sa.String(length=1000), nullable=True),
sa.Column('n_roms', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('slug')
sa.Column('igdb_id', sa.String(length=10), nullable=True),
sa.Column('sgdb_id', sa.String(length=10), nullable=True),
sa.Column('slug', sa.String(length=50), nullable=False),
sa.Column('name', sa.String(length=400), nullable=True),
sa.Column('logo_path', sa.String(length=1000), nullable=True),
sa.Column('n_roms', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('slug')
)
op.create_table('roms',
sa.Column('r_igdb_id', sa.String(length=10), nullable=True),
sa.Column('p_igdb_id', sa.String(length=10), nullable=True),
sa.Column('r_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_slug', sa.String(length=50), nullable=False),
sa.Column('file_name', sa.String(length=450), nullable=False),
sa.Column('file_name_no_tags', sa.String(length=450), nullable=True),
sa.Column('file_extension', sa.String(length=10), nullable=True),
sa.Column('file_path', sa.String(length=1000), nullable=True),
sa.Column('file_size', sa.Float(), nullable=True),
sa.Column('name', sa.String(length=350), nullable=True),
sa.Column('r_slug', sa.String(length=100), nullable=True),
sa.Column('summary', sa.Text(), nullable=True),
sa.Column('path_cover_s', sa.Text(), nullable=True),
sa.Column('path_cover_l', sa.Text(), nullable=True),
sa.Column('has_cover', sa.Boolean(), nullable=True),
sa.Column('region', sa.String(length=20), nullable=True),
sa.Column('revision', sa.String(length=20), nullable=True),
sa.Column('tags', sa.JSON(), nullable=True),
sa.PrimaryKeyConstraint('p_slug', 'file_name')
sa.Column('r_igdb_id', sa.String(length=10), nullable=True),
sa.Column('p_igdb_id', sa.String(length=10), nullable=True),
sa.Column('r_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_slug', sa.String(length=50), nullable=False),
sa.Column('file_name', sa.String(length=450), nullable=False),
sa.Column('file_name_no_tags', sa.String(length=450), nullable=True),
sa.Column('file_extension', sa.String(length=10), nullable=True),
sa.Column('file_path', sa.String(length=1000), nullable=True),
sa.Column('file_size', sa.Float(), nullable=True),
sa.Column('name', sa.String(length=350), nullable=True),
sa.Column('r_slug', sa.String(length=100), nullable=True),
sa.Column('summary', sa.Text(), nullable=True),
sa.Column('path_cover_s', sa.Text(), nullable=True),
sa.Column('path_cover_l', sa.Text(), nullable=True),
sa.Column('has_cover', sa.Boolean(), nullable=True),
sa.Column('region', sa.String(length=20), nullable=True),
sa.Column('revision', sa.String(length=20), nullable=True),
sa.Column('tags', sa.JSON(), nullable=True),
sa.PrimaryKeyConstraint('p_slug', 'file_name')
)
except OperationalError:
pass

View File

@@ -1,4 +1,4 @@
"""add multifile games
"""update to 1.6.3
Revision ID: 1.6.3
Revises: 1.6.2
@@ -18,13 +18,15 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('roms', sa.Column('multi', sa.Boolean(), nullable=True))
op.add_column('roms', sa.Column('files', sa.JSON(), nullable=True))
with op.batch_alter_table("roms") as batch_op:
batch_op.add_column(sa.Column('multi', sa.Boolean(), nullable=True))
batch_op.add_column(sa.Column('files', sa.JSON(), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('roms', 'files')
op.drop_column('roms', 'multi')
with op.batch_alter_table("roms") as batch_op:
batch_op.drop_column('files')
batch_op.drop_column('multi')
# ### end Alembic commands ###

View File

@@ -1,4 +1,4 @@
"""empty message
"""update to 1.7.1
Revision ID: 1.7.1
Revises: 1.6.3
@@ -18,11 +18,13 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('roms', sa.Column('file_size_units', sa.String(length=10), nullable=True))
with op.batch_alter_table("roms") as batch_op:
batch_op.add_column(sa.Column('file_size_units', sa.String(length=10), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('roms', 'file_size_units')
with op.batch_alter_table("roms") as batch_op:
batch_op.drop_column('file_size_units')
# ### end Alembic commands ###

View File

@@ -0,0 +1,104 @@
"""update to 1.8
Revision ID: 1.8
Revises: 1.7.1
Create Date: 2023-04-17 12:03:19.163501
"""
import os
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import sqlite
# revision identifiers, used by Alembic.
revision = '1.8'
down_revision = '1.7.1'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms") as batch_op:
batch_op.execute("ALTER TABLE platforms RENAME TO old_platforms")
op.create_table('platforms',
sa.Column('igdb_id', sa.String(length=10), nullable=True),
sa.Column('sgdb_id', sa.String(length=10), nullable=True),
sa.Column('slug', sa.String(length=50), nullable=False),
sa.Column('fs_slug', sa.String(length=50), nullable=False),
sa.Column('name', sa.String(length=400), nullable=True),
sa.Column('logo_path', sa.String(length=1000), nullable=True),
sa.Column('n_roms', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('fs_slug')
)
batch_op.execute("INSERT INTO platforms(igdb_id, sgdb_id, slug, fs_slug, name, logo_path, n_roms) \
SELECT igdb_id, sgdb_id, slug, slug, name, logo_path, n_roms \
FROM old_platforms")
op.drop_table('old_platforms')
with op.batch_alter_table("roms") as batch_op:
batch_op.add_column(sa.Column('p_name', sa.String(length=150), nullable=True))
batch_op.add_column(sa.Column('url_cover', sa.Text(), nullable=True))
batch_op.alter_column('name', new_column_name='r_name', type_=sa.String(length=150), existing_type=sa.String(length=150))
batch_op.alter_column('p_slug', existing_type=sa.String(length=50), nullable=False)
batch_op.alter_column('file_name', existing_type=sa.String(length=450), nullable=False)
with op.batch_alter_table("roms") as batch_op:
batch_op.execute("ALTER TABLE roms RENAME TO old_roms")
op.create_table('roms',
sa.Column('id', sa.Integer(), autoincrement=True),
sa.Column('r_igdb_id', sa.String(length=10), nullable=True),
sa.Column('p_igdb_id', sa.String(length=10), nullable=True),
sa.Column('r_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_sgdb_id', sa.String(length=10), nullable=True),
sa.Column('p_slug', sa.String(length=50), nullable=False),
sa.Column('p_name', sa.String(length=150), nullable=True),
sa.Column('file_name', sa.String(length=450), nullable=False),
sa.Column('file_name_no_tags', sa.String(length=450), nullable=False),
sa.Column('file_extension', sa.String(length=10), nullable=True),
sa.Column('file_path', sa.String(length=1000), nullable=True),
sa.Column('file_size', sa.Float(), nullable=True),
sa.Column('file_size_units', sa.String(length=10), nullable=True),
sa.Column('r_name', sa.String(length=350), nullable=True),
sa.Column('r_slug', sa.String(length=100), nullable=True),
sa.Column('summary', sa.Text(), nullable=True),
sa.Column('path_cover_s', sa.Text(), nullable=True),
sa.Column('path_cover_l', sa.Text(), nullable=True),
sa.Column('has_cover', sa.Boolean(), nullable=True),
sa.Column('region', sa.String(length=20), nullable=True),
sa.Column('revision', sa.String(length=20), nullable=True),
sa.Column('tags', sa.JSON(), nullable=True),
sa.Column('multi', sa.Boolean(), nullable=True),
sa.Column('files', sa.JSON(), nullable=True),
sa.Column('url_cover', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
batch_op.execute("INSERT INTO roms(\
r_igdb_id, p_igdb_id, r_sgdb_id, p_sgdb_id, p_slug, p_name, \
file_name, file_name_no_tags, file_extension, file_path, file_size, \
file_size_units, r_name, r_slug, summary, path_cover_s, path_cover_l, has_cover, \
region, revision, tags, multi, files, url_cover) \
SELECT \
r_igdb_id, p_igdb_id, r_sgdb_id, p_sgdb_id, p_slug, p_name, \
file_name, file_name_no_tags, file_extension, file_path, file_size, \
file_size_units, r_name, r_slug, summary, path_cover_s, path_cover_l, has_cover, \
region, revision, tags, multi, files, url_cover \
FROM old_roms")
op.drop_table('old_roms')
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms") as batch_op:
batch_op.drop_column('fs_slug')
with op.batch_alter_table("roms") as batch_op:
batch_op.drop_constraint('PRIMARY', type_="primary")
batch_op.drop_column('id')
batch_op.drop_column('p_name')
batch_op.drop_column('url_cover')
batch_op.alter_column('r_name', new_column_name='name', type_=sa.String(length=150), existing_type=sa.String(length=150))
batch_op.alter_column('p_slug', existing_type=sa.String(length=50), nullable=False)
batch_op.alter_column('file_name', existing_type=sa.String(length=450), nullable=False)
# ### end Alembic commands ###

View File

@@ -2,30 +2,36 @@ import os
import sys
from urllib.parse import quote_plus
from config import ROMM_DB_DRIVER, SUPPORTED_DB_DRIVERS, SQLITE_DB_BASE_PATH
from config import ROMM_DB_DRIVER, SUPPORTED_DB_DRIVERS, SQLITE_DB_BASE_PATH, user_config
from logger.logger import log
def get_db_engine():
if ROMM_DB_DRIVER in SUPPORTED_DB_DRIVERS:
class ConfigLoader:
if ROMM_DB_DRIVER == 'mariadb':
DB_HOST: str = os.getenv('DB_HOST')
try:
DB_PORT: int = int(os.getenv('DB_PORT'))
except TypeError:
log.critical(f"DB_PORT variable not set properly")
sys.exit(3)
DB_USER: str = os.getenv('DB_USER')
DB_PASSWD: str = os.getenv('DB_PASSWD')
DB_NAME: str = os.getenv('DB_NAME', 'romm')
return f"mariadb+mariadbconnector://{DB_USER}:%s@{DB_HOST}:{DB_PORT}/{DB_NAME}" % quote_plus(DB_PASSWD)
def __init__(self):
pass
elif ROMM_DB_DRIVER == 'sqlite':
if not os.path.exists(SQLITE_DB_BASE_PATH): os.makedirs(SQLITE_DB_BASE_PATH)
return f"sqlite:////{SQLITE_DB_BASE_PATH}/romm.db"
else:
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)
def get_db_engine(self):
if ROMM_DB_DRIVER in SUPPORTED_DB_DRIVERS:
if ROMM_DB_DRIVER == 'mariadb':
DB_HOST: str = os.getenv('DB_HOST')
try:
DB_PORT: int = int(os.getenv('DB_PORT'))
except TypeError:
log.critical(f"DB_PORT variable not set properly")
sys.exit(3)
DB_USER: str = os.getenv('DB_USER')
DB_PASSWD: str = os.getenv('DB_PASSWD')
DB_NAME: str = os.getenv('DB_NAME', 'romm')
return f"mariadb+mariadbconnector://{DB_USER}:%s@{DB_HOST}:{DB_PORT}/{DB_NAME}" % quote_plus(DB_PASSWD)
elif ROMM_DB_DRIVER == 'sqlite':
if not os.path.exists(SQLITE_DB_BASE_PATH): os.makedirs(SQLITE_DB_BASE_PATH)
return f"sqlite:////{SQLITE_DB_BASE_PATH}/romm.db"
else:
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)

View File

@@ -0,0 +1,12 @@
from fastapi import APIRouter
from handler import dbh
router = APIRouter()
@router.get("/platforms", status_code=200)
def platforms() -> dict:
"""Returns platforms data"""
return {'data': dbh.get_platforms()}

View File

@@ -0,0 +1,63 @@
from fastapi import APIRouter, Request, status, HTTPException
from logger.logger import log
from handler import dbh
from utils import fs, get_file_name_with_no_tags
from utils.exceptions import RomNotFoundError, RomAlreadyExistsException
from models.rom import Rom
from models.platform import Platform
router = APIRouter()
@router.get("/platforms/{p_slug}/roms/{id}", status_code=200)
def rom(id: int) -> dict:
"""Returns one rom data of the desired platform"""
return {'data': dbh.get_rom(id)}
@router.get("/platforms/{p_slug}/roms", status_code=200)
def roms(p_slug: str) -> dict:
"""Returns all roms of the desired platform"""
return {'data': dbh.get_roms(p_slug)}
@router.patch("/platforms/{p_slug}/roms/{id}", status_code=200)
async def updateRom(req: Request, p_slug: str, id: int) -> dict:
"""Updates rom details"""
data: dict = await req.json()
updated_rom: dict = data['updatedRom']
db_rom: Rom = dbh.get_rom(id)
platform: Platform = dbh.get_platform(p_slug)
try:
fs.rename_rom(platform.fs_slug, db_rom.file_name, updated_rom['file_name'])
except RomAlreadyExistsException as e:
error: str = f"{e}"
log.error(error)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error)
updated_rom['file_name_no_tags'] = get_file_name_with_no_tags(updated_rom['file_name'])
updated_rom.update(fs.get_cover_details(True, p_slug, updated_rom['file_name'], updated_rom['url_cover']))
dbh.update_rom(id, updated_rom)
return {'data': dbh.get_rom(id), 'msg': f"{updated_rom['file_name']} updated successfully!"}
@router.delete("/platforms/{p_slug}/roms/{id}", status_code=200)
def delete_rom(p_slug: str, id: int, filesystem: bool=False) -> dict:
"""Detele rom from database [and filesystem]"""
rom: Rom = dbh.get_rom(id)
log.info(f"Deleting {rom.file_name} from database")
dbh.delete_rom(id)
if filesystem:
log.info(f"Deleting {rom.file_name} from filesystem")
try:
platform: Platform = dbh.get_platform(p_slug)
fs.remove_rom(platform.fs_slug, rom.file_name)
except RomNotFoundError as e:
error: str = f"{e}. Couldn't delete from filesystem."
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
return {'msg': f'{rom.file_name} deleted successfully!'}

View File

@@ -0,0 +1,56 @@
from fastapi import APIRouter, status, HTTPException
import emoji
import json
from logger.logger import log, COLORS
from config import user_config
from utils import fs, fastapi
from utils.exceptions import PlatformsNotFoundException, RomsNotFoundException
from handler import dbh
from models.platform import Platform
from models.rom import Rom
router = APIRouter()
@router.get("/scan", status_code=200)
def scan(platforms: str, full_scan: bool=False) -> dict:
"""Scan platforms and roms and write them in database."""
log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning "))
fs.store_default_resources()
# Scanning platforms
try:
fs_platforms: list[str] = fs.get_platforms()
except PlatformsNotFoundException as e:
error: str = f"{e}"
log.warning(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
platforms: list[str] = json.loads(platforms) if len(json.loads(platforms)) > 0 else fs_platforms
log.info(f"Platforms to be scanned: {', '.join(platforms)}")
for platform in platforms:
log.info(emoji.emojize(f":video_game: {platform} {COLORS['reset']}"))
scanned_platform: Platform = fastapi.scan_platform(platform)
if platform != str(scanned_platform): log.info(f"Identified as {COLORS['blue']}{scanned_platform}{COLORS['reset']}")
dbh.add_platform(scanned_platform)
# Scanning roms
try:
fs_roms: list[str] = fs.get_roms(scanned_platform.fs_slug)
except RomsNotFoundException as e:
error: str = f"{e}"
log.warning(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
for rom in fs_roms:
if rom['multi']: [log.info(f"\t - {COLORS['orange_i']}{file}{COLORS['reset']}") for file in rom['files']]
rom_id: int = dbh.rom_exists(rom['file_name'], scanned_platform.slug)
if rom_id and not full_scan: continue
log.info(f"Scanning {COLORS['orange']}{rom['file_name']}{COLORS['reset']}")
scanned_rom: Rom = fastapi.scan_rom(scanned_platform, rom)
if rom_id: scanned_rom.id = rom_id
dbh.add_rom(scanned_rom)
dbh.purge_roms(scanned_platform.slug, [rom['file_name'] for rom in fs_roms])
dbh.purge_platforms(fs_platforms)
return {'msg': 'Scan completed successfully!'}

View File

@@ -0,0 +1,25 @@
from fastapi import APIRouter, Request
import emoji
from logger.logger import log, COLORS
from handler import igdbh
router = APIRouter()
@router.put("/search/roms/igdb", status_code=200)
async def search_rom_igdb(req: Request, igdb_id: str = None) -> dict:
"""Get all the roms matched from igdb."""
data: dict = await req.json()
rom: dict = data['rom']
log.info(emoji.emojize(":magnifying_glass_tilted_right: IGDB Searching"))
if igdb_id:
log.info(f"Searching by id: {igdb_id}")
matched_roms = igdbh.get_matched_roms_by_id(igdb_id)
else:
log.info(emoji.emojize(f":video_game: {rom['p_slug']}: {COLORS['orange']}{rom['file_name']}{COLORS['reset']}"))
matched_roms = igdbh.get_matched_roms(rom['file_name'], rom['p_igdb_id'], rom['p_slug'])
log.info("Results:")
[log.info(f"\t - {COLORS['blue']}{rom['r_name']}{COLORS['reset']}") for rom in matched_roms]
return {'data': matched_roms, 'msg': 'success'}

View File

@@ -1,12 +1,12 @@
import functools
from fastapi import HTTPException
from sqlalchemy import create_engine
from fastapi import status, HTTPException
from sqlalchemy import create_engine, select, or_
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
from sqlalchemy.exc import ProgrammingError
from config.config_loader import get_db_engine
from logger.logger import log
from config.config_loader import ConfigLoader
from models.platform import Platform
from models.rom import Rom
@@ -14,7 +14,8 @@ from models.rom import Rom
class DBHandler:
def __init__(self) -> None:
self.engine = create_engine(get_db_engine(), pool_pre_ping=True)
cl = ConfigLoader()
self.engine = create_engine(cl.get_db_engine(), pool_pre_ping=True)
self.session = sessionmaker(bind=self.engine, expire_on_commit=False)
@@ -25,54 +26,108 @@ class DBHandler:
return wrapper
@staticmethod
def raise_error(e: Exception) -> None:
error: str = f"{e}"
log.critical(error)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error)
# ========= Platforms =========
def add_platform(self, Platform: Platform) -> None:
try:
with self.session.begin() as s:
s.merge(Platform)
except ProgrammingError as e:
raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}")
self.raise_error(e)
def get_platforms(self) -> list[Platform]:
try:
with self.session.begin() as s:
return s.scalars(select(Platform).order_by(Platform.slug.asc())).all()
except ProgrammingError as e:
raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}")
self.raise_error(e)
def get_platform(self, slug: str) -> Platform:
try:
with self.session.begin() as s:
return s.scalars(select(Platform).filter_by(slug=slug)).first()
except ProgrammingError as e:
self.raise_error(e)
def purge_platforms(self, platforms: list[str]) -> None:
with self.session.begin() as s:
s.query(Platform) \
.filter(Platform.slug.not_in(platforms)) \
.delete(synchronize_session='evaluate')
try:
with self.session.begin() as s:
s.query(Platform) \
.filter(or_(Platform.fs_slug.not_in(platforms),
Platform.fs_slug.is_(None))) \
.delete(synchronize_session='evaluate')
except ProgrammingError as e:
self.raise_error(e)
# ========= Roms =========
def add_rom(self, rom: Rom) -> None:
with self.session.begin() as s:
s.merge(rom)
try:
with self.session.begin() as s:
s.merge(rom)
except ProgrammingError as e:
self.raise_error(e)
def get_roms(self, p_slug: str) -> list[Rom]:
with self.session.begin() as s:
return s.scalars(select(Rom).filter_by(p_slug=p_slug).order_by(Rom.file_name.asc())).all()
try:
with self.session.begin() as s:
return s.scalars(select(Rom).filter_by(p_slug=p_slug).order_by(Rom.file_name.asc())).all()
except ProgrammingError as e:
self.raise_error(e)
def get_rom(self, p_slug: str, file_name: str) -> Rom:
with self.session.begin() as s:
return s.scalars(select(Rom).filter_by(p_slug=p_slug, file_name=file_name)).first()
def update_rom(self, p_slug: str, file_name: str, data: dict) -> None:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.file_name==file_name) \
.update(data, synchronize_session='evaluate')
def get_rom(self, id) -> Rom:
try:
with self.session.begin() as s:
return s.scalars(select(Rom).filter_by(id=id)).first()
except ProgrammingError as e:
self.raise_error(e)
def delete_rom(self, p_slug: str, file_name: str) -> None:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.file_name==file_name) \
.delete(synchronize_session='evaluate')
def purge_roms(self, p_slug: str, roms: list[dict]) -> None:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.file_name.not_in([rom['file_name'] for rom in roms])) \
.delete(synchronize_session='evaluate')
def update_rom(self, id: int, data: dict) -> None:
try:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.id==id).update(data, synchronize_session='evaluate')
except ProgrammingError as e:
self.raise_error(e)
def delete_rom(self, id: int) -> None:
try:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.id==id).delete(synchronize_session='evaluate')
except ProgrammingError as e:
self.raise_error(e)
def purge_roms(self, p_slug: str, roms: list[str]) -> None:
try:
with self.session.begin() as s:
s.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.file_name.not_in(roms)) \
.delete(synchronize_session='evaluate')
except ProgrammingError as e:
self.raise_error(e)
# ==== Utils ======
def rom_exists(self, file_name: str, platform: str) -> int:
db_roms: list = self.get_roms(platform)
rom_id: int = 0
for db_rom in db_roms:
if db_rom.file_name == file_name:
rom_id = db_rom.id
break
return rom_id

View File

@@ -1,12 +1,11 @@
import sys
import functools
import re
import unidecode
from time import time
import requests
from config import CLIENT_ID, CLIENT_SECRET, DEFAULT_URL_COVER_L
from utils import get_file_name_with_no_tags
from logger.logger import log
@@ -46,10 +45,10 @@ class IGDBHandler():
@check_twitch_token
def get_rom_details(self, file_name: str, p_igdb_id: int, r_igdb_id_search: str) -> dict:
file_name_no_tags: str = re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0])
search_term: str = unidecode.unidecode(get_file_name_with_no_tags(file_name))
r_igdb_id: str = ""
slug: str = ""
name: str = ""
r_slug: str = ""
r_name: str = ""
summary: str = ""
url_cover: str = ""
@@ -57,23 +56,21 @@ class IGDBHandler():
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"fields id, slug, name, summary; where id={r_igdb_id_search};").json()[0]
r_igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
r_slug = res_details['slug']
r_name = res_details['name']
try:
summary = res_details['summary']
except KeyError:
pass
else: #TODO: improve API calls to make only one
search_term: str = unidecode.unidecode(file_name_no_tags)
if p_igdb_id:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{search_term}\";fields id, slug, name, summary; where platforms=[{p_igdb_id}] & category=0;").json()[0]
r_igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
r_slug = res_details['slug']
r_name = res_details['name']
try:
summary = res_details['summary']
except KeyError:
@@ -83,8 +80,8 @@ class IGDBHandler():
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}] & category=10;").json()[0]
r_igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
r_slug = res_details['slug']
r_name = res_details['name']
try:
summary = res_details['summary']
except KeyError:
@@ -94,8 +91,8 @@ class IGDBHandler():
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()[0]
r_igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
r_slug = res_details['slug']
r_name = res_details['name']
try:
summary = res_details['summary']
except KeyError:
@@ -108,16 +105,16 @@ class IGDBHandler():
data=f"fields url; where game={r_igdb_id};").json()[0]
url_cover: str = f"https:{res_details['url']}"
except IndexError:
log.warning(f"{name} cover not found in IGDB")
if not name: name = file_name_no_tags
return (r_igdb_id, file_name_no_tags, slug, name, summary, url_cover)
log.warning(f"{r_name} cover not found in IGDB")
if not r_name: r_name = search_term
return {'r_igdb_id': r_igdb_id, 'r_slug': r_slug, 'r_name': r_name, 'summary': summary, 'url_cover': url_cover}
@check_twitch_token
def get_matched_roms(self, file_name: str, p_igdb_id: int, p_slug: str) -> list:
matched_roms: list[dict] = []
if p_igdb_id != '':
search_term: str = unidecode.unidecode(re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0]))
search_term: str = unidecode.unidecode(get_file_name_with_no_tags(file_name))
matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()
for rom in matched_roms:
@@ -129,23 +126,29 @@ class IGDBHandler():
rom['url_cover'] = DEFAULT_URL_COVER_L
rom['r_igdb_id'] = rom.pop('id')
rom['r_slug'] = rom.pop('slug')
rom['r_name'] = rom.pop('name')
else:
log.warning(f"{p_slug} is not supported!")
return matched_roms
def get_matched_roms_by_id(self, igdb_id: str) -> list:
matched_roms: list[dict] = []
matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"fields name, id, slug, summary; where id={igdb_id};").json()
for rom in matched_roms:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
data=f"fields url; where game={rom['id']};").json()[0]
rom['url_cover'] = f"https:{res_details['url']}".replace('t_thumb', f't_cover_big')
except IndexError:
rom['url_cover'] = DEFAULT_URL_COVER_L
rom['r_igdb_id'] = rom.pop('id')
rom['r_slug'] = rom.pop('slug')
res: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"fields name, id, slug, summary; where id={igdb_id};")
if res.status_code == 200:
matched_roms = res.json()
for rom in matched_roms:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
data=f"fields url; where game={rom['id']};").json()[0]
rom['url_cover'] = f"https:{res_details['url']}".replace('t_thumb', f't_cover_big')
except IndexError:
rom['url_cover'] = DEFAULT_URL_COVER_L
rom['r_igdb_id'] = rom.pop('id')
rom['r_slug'] = rom.pop('slug')
rom['r_name'] = rom.pop('name')
else:
matched_roms: list = []
return matched_roms

View File

@@ -1,17 +1,22 @@
from fastapi import FastAPI, Request
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import json
import emoji
from logger.logger import log, COLORS
from handler import igdbh, dbh
from config import DEV_PORT, DEV_HOST
from models.platform import Platform
from utils import fs, fastapi
from endpoints import scan, search, platform, rom
app = FastAPI()
fastapi.allow_cors(app)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(scan.router)
app.include_router(search.router)
app.include_router(platform.router)
app.include_router(rom.router)
@app.on_event("startup")
@@ -20,113 +25,5 @@ def startup() -> None:
pass
@app.get("/scan")
def scan(platforms: str, full_scan: bool=False) -> dict:
"""Scan platforms and roms and write them in database."""
log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning "))
fs.store_default_resources()
fs_platforms: list[str] = fs.get_platforms()
platforms: list[str] = json.loads(platforms) if len(json.loads(platforms)) > 0 else fs_platforms
log.info(f"Platforms to be scanned: {', '.join(platforms)}")
for p_slug in platforms:
log.info(emoji.emojize(f":video_game: {p_slug} {COLORS['reset']}"))
platform: Platform = fastapi.scan_platform(p_slug)
if p_slug != str(platform): log.info(f"Identified as {COLORS['blue']}{platform}{COLORS['reset']}")
dbh.add_platform(platform)
log.info(f"Searching new roms")
roms: list[dict] = fs.get_roms(p_slug, full_scan)
for rom in roms:
log.info(f"Getting {COLORS['orange']}{rom['file_name']}{COLORS['reset']} details")
if rom['multi']: [log.info(f"\t - {COLORS['orange_i']}{file}{COLORS['reset']}") for file in rom['files']]
rom = fastapi.scan_rom(platform, rom)
dbh.add_rom(rom)
log.info(emoji.emojize(":wastebasket: Purging database"))
[dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) for p_slug in platforms]
dbh.purge_platforms(fs_platforms)
return {'msg': 'success'}
@app.get("/platforms")
def platforms() -> dict:
"""Returns platforms data"""
return {'data': dbh.get_platforms()}
@app.get("/platforms/{p_slug}/roms/{file_name}")
def rom(p_slug: str, file_name: str) -> dict:
"""Returns one rom data of the desired platform"""
return {'data': dbh.get_rom(p_slug, file_name)}
@app.get("/platforms/{p_slug}/roms")
def roms(p_slug: str) -> dict:
"""Returns all roms of the desired platform"""
return {'data': dbh.get_roms(p_slug)}
@app.patch("/platforms/{p_slug}/roms")
async def updateRom(req: Request, p_slug: str) -> dict:
"""Updates rom details"""
data: dict = await req.json()
rom: dict = data['rom']
updatedRom: dict = data['updatedRom']
log.info(f"Updating {COLORS['orange']}{updatedRom['file_name']}{COLORS['reset']} details")
r_igdb_id, file_name_no_tags, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(updatedRom['file_name'], rom['p_igdb_id'], updatedRom['r_igdb_id'])
path_cover_s, path_cover_l, has_cover = fs.get_cover_details(True, p_slug, updatedRom['file_name'], url_cover)
updatedRom['file_name_no_tags'] = file_name_no_tags
updatedRom['r_igdb_id'] = r_igdb_id
updatedRom['p_igdb_id'] = rom['p_igdb_id']
updatedRom['r_slug'] = r_slug
updatedRom['p_slug'] = p_slug
updatedRom['name'] = r_name
updatedRom['summary'] = summary
updatedRom['path_cover_s'] = path_cover_s
updatedRom['path_cover_l'] = path_cover_l
updatedRom['has_cover'] = has_cover
updatedRom['file_path'] = rom['file_path']
updatedRom['file_size'] = rom['file_size']
updatedRom['file_extension'] = updatedRom['file_name'].split('.')[-1] if '.' in updatedRom['file_name'] else ""
reg, rev, other_tags = fs.parse_tags(updatedRom['file_name'])
updatedRom.update({'region': reg, 'revision': rev, 'tags': other_tags})
if 'url_cover' in updatedRom.keys(): del updatedRom['url_cover']
fs.rename_rom(p_slug, rom['file_name'], updatedRom['file_name'])
dbh.update_rom(p_slug, rom['file_name'], updatedRom)
return {'data': updatedRom}
@app.delete("/platforms/{p_slug}/roms/{file_name}")
def remove_rom(p_slug: str, file_name: str, filesystem: bool=False) -> dict:
"""Detele rom from filesystem and database"""
log.info(f"Deleting {file_name} from database")
dbh.delete_rom(p_slug, file_name)
if filesystem:
log.info(f"Removing {file_name} from filesystem")
fs.remove_rom(p_slug, file_name)
return {'msg': 'success'}
@app.put("/search/roms/igdb")
async def search_rom_igdb(req: Request, igdb_id: str=None) -> dict:
"""Get all the roms matched from igdb."""
data: dict = await req.json()
log.info(emoji.emojize(":magnifying_glass_tilted_right: IGDB Searching"))
if igdb_id:
log.info(f"Searching by id: {igdb_id}")
matched_roms = igdbh.get_matched_roms_by_id(igdb_id)
else:
log.info(emoji.emojize(f":video_game: {data['rom']['p_slug']}: {COLORS['orange']}{data['rom']['file_name']}{COLORS['reset']}"))
matched_roms = igdbh.get_matched_roms(data['rom']['file_name'], data['rom']['p_igdb_id'], data['rom']['p_slug'])
log.info("Results:")
[log.info(f"\t - {COLORS['blue']}{rom['name']}{COLORS['reset']}") for rom in matched_roms]
return {'data': matched_roms}
if __name__ == '__main__':
uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True)

View File

@@ -9,12 +9,14 @@ class Platform(BaseModel):
igdb_id = Column(String(length=10), default="")
sgdb_id = Column(String(length=10), default="")
slug = Column(String(length=50), primary_key=True)
slug = Column(String(length=50), default="")
name = Column(String(length=400), default="")
logo_path = Column(String(length=1000), default=DEFAULT_PATH_COVER_S)
n_roms = Column(Integer, default=0)
fs_slug = Column(String(length=50), primary_key=True)
def __repr__(self) -> str:
return self.name

View File

@@ -1,4 +1,4 @@
from sqlalchemy import Column, String, Text, Boolean, Float, JSON
from sqlalchemy import Integer, Column, String, Text, Boolean, Float, JSON
from config import DEFAULT_PATH_COVER_S, DEFAULT_PATH_COVER_L
from models.base import BaseModel
@@ -6,21 +6,24 @@ from models.base import BaseModel
class Rom(BaseModel):
__tablename__ = 'roms'
id = Column(Integer(), primary_key=True, autoincrement=True)
r_igdb_id = Column(String(length=10), default="")
p_igdb_id = Column(String(length=10), default="")
r_sgdb_id = Column(String(length=10), default="")
p_sgdb_id = Column(String(length=10), default="")
p_slug = Column(String(length=50), primary_key=True)
p_slug = Column(String(length=50))
p_name = Column(String(length=150), default="")
file_name = Column(String(length=450), primary_key=True)
file_name_no_tags = Column(String(length=450), default="")
file_name = Column(String(length=450))
file_name_no_tags = Column(String(length=450))
file_extension = Column(String(length=10), default="")
file_path = Column(String(length=1000), default="")
file_size = Column(Float, default=0.0)
file_size_units = Column(String(length=10), default="")
name = Column(String(length=350), default="")
r_name = Column(String(length=350), default="")
r_slug = Column(String(length=100), default="")
summary = Column(Text, default="")
@@ -28,6 +31,7 @@ class Rom(BaseModel):
path_cover_s = Column(Text, default=DEFAULT_PATH_COVER_S)
path_cover_l = Column(Text, default=DEFAULT_PATH_COVER_L)
has_cover = Column(Boolean, default=False)
url_cover = Column(Text, default=DEFAULT_PATH_COVER_L)
region = Column(String(20), default="")
revision = Column(String(20), default="")

View File

@@ -0,0 +1,26 @@
import re
def parse_tags(file_name: str) -> tuple:
reg: str = ''
rev: str = ''
other_tags: list = []
tags: list = re.findall('\(([^)]+)', file_name)
for tag in tags:
if tag.split('-')[0].lower() == 'reg':
try: reg = tag.split('-', 1)[1]
except IndexError: pass
elif tag.split('-')[0].lower() == 'rev':
try: rev = tag.split('-', 1)[1]
except IndexError: pass
else:
other_tags.append(tag)
return reg, rev, other_tags
def get_file_name_with_no_tags(file_name: str) -> str:
return re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0])
def get_file_extension(rom: dict) -> str:
return rom['file_name'].split('.')[-1] if not rom['multi'] else ''

View File

@@ -0,0 +1,34 @@
class PlatformsNotFoundException(Exception):
def __init__(self):
self.message = f"Platforms not found"
super().__init__(self.message)
def __repr__(self) -> str:
return self.message
class RomsNotFoundException(Exception):
def __init__(self, platform: str):
self.message = f"Roms not found for platform {platform}"
super().__init__(self.message)
def __repr__(self) -> str:
return self.message
class RomNotFoundError(Exception):
def __init__(self, rom: str, platform: str):
self.message = f"Rom {rom} not found for platform {platform}"
super().__init__(self.message)
def __repr__(self) -> str:
return self.message
class RomAlreadyExistsException(Exception):
def __init__(self, rom_name: str):
self.message = f"Can't rename: {rom_name} already exists"
super().__init__(self.message)
def __repr__(self) -> str:
return self.message

View File

@@ -1,49 +1,47 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from handler import igdbh
from utils import fs
from utils import fs, parse_tags, get_file_extension, get_file_name_with_no_tags
from config import user_config
from logger.logger import log
from models.platform import Platform
from models.rom import Rom
from logger.logger import log
def allow_cors(app: FastAPI) -> None:
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def scan_platform(p_slug: str) -> Platform:
"""Get platform details from IGDB if possible
def scan_platform(fs_slug: str) -> Platform:
"""Get platform details
Args:
p_slug: short name of the platform
Returns
Platform object
"""
platform_attrs: dict = igdbh.get_platform_details(p_slug)
platform_attrs['n_roms'] = fs.get_roms(p_slug, True, only_amount=True)
platform_attrs: dict = {}
platform_attrs['fs_slug'] = fs_slug
try:
if fs_slug in user_config['system']['platforms'].keys():
platform_attrs['slug'] = user_config['system']['platforms'][fs_slug]
else:
platform_attrs['slug'] = fs_slug
except (KeyError, TypeError, AttributeError):
platform_attrs['slug'] = fs_slug
platform_attrs.update(igdbh.get_platform_details(platform_attrs['slug']))
platform_attrs['n_roms'] = len(fs.get_roms(platform_attrs['fs_slug']))
platform = Platform(**platform_attrs)
return platform
def scan_rom(platform: Platform, rom: dict, r_igbd_id_search: str = '', overwrite: bool = False) -> None:
r_igdb_id, file_name_no_tags, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(rom['file_name'], platform.igdb_id, r_igbd_id_search)
path_cover_s, path_cover_l, has_cover = fs.get_cover_details(overwrite, platform.slug, rom['file_name'], url_cover)
rom['file_name_no_tags'] = file_name_no_tags
rom['r_igdb_id'] = r_igdb_id
rom['p_igdb_id'] = platform.igdb_id
rom['r_slug'] = r_slug
rom['p_slug'] = platform.slug
rom['name'] = r_name
rom['summary'] = summary
rom['path_cover_s'] = path_cover_s
rom['path_cover_l'] = path_cover_l
rom['has_cover'] = has_cover
rom = Rom(**rom)
def scan_rom(platform: Platform, rom_attrs: dict, r_igbd_id_search: str = '', overwrite: bool = False) -> Rom:
p_slug: str = platform.fs_slug if platform.fs_slug else platform.slug
roms_path: str = fs.get_roms_structure(p_slug)
rom_attrs.update(igdbh.get_rom_details(rom_attrs['file_name'], platform.igdb_id, r_igbd_id_search))
rom_attrs.update(fs.get_cover_details(overwrite, platform.slug, rom_attrs['file_name'], rom_attrs['url_cover']))
file_size, file_size_units = fs.get_rom_size(rom_attrs['multi'], rom_attrs['file_name'], rom_attrs['files'], roms_path)
reg, rev, other_tags = parse_tags(rom_attrs['file_name'])
rom_attrs.update({'file_path': roms_path, 'file_name': rom_attrs['file_name'], 'file_name_no_tags': get_file_name_with_no_tags(rom_attrs['file_name']),
'file_extension': get_file_extension(rom_attrs), 'file_size': file_size, 'file_size_units': file_size_units,
'multi': rom_attrs['multi'], 'region': reg, 'revision': rev, 'tags': other_tags})
rom_attrs['p_igdb_id'] = platform.igdb_id
rom_attrs['p_slug'] = platform.slug
rom_attrs['p_name'] = platform.name
rom = Rom(**rom_attrs)
return rom

View File

@@ -1,222 +1,15 @@
import os
import shutil
import re
from pathlib import Path
import requests
from fastapi import HTTPException
from config import user_config, LIBRARY_BASE_PATH, HIGH_PRIO_STRUCTURE_PATH, RESOURCES_BASE_PATH, DEFAULT_URL_COVER_L, DEFAULT_PATH_COVER_L, DEFAULT_URL_COVER_S, DEFAULT_PATH_COVER_S
from handler import dbh
from logger.logger import log
from utils.exceptions import PlatformsNotFoundException, RomsNotFoundException, RomNotFoundError, RomAlreadyExistsException
# ========= Defaults utils =========
def store_default_resources() -> None:
"""Store default cover resources in the filesystem"""
defaul_covers: dict = [{'url': DEFAULT_URL_COVER_L, 'size': 'l'}, {'url': DEFAULT_URL_COVER_S, 'size': 's'}]
for cover in defaul_covers:
if not _cover_exists('default', 'cover', cover['size']):
_store_cover('default', 'cover', cover['url'], cover['size'])
# ========= Platforms utils =========
def _exclude_platforms(platforms) -> list['str']:
[platforms.remove(excluded) for excluded in user_config['exclude']['platforms'] if excluded in platforms]
def get_platforms() -> list[str]:
"""Gets all filesystem platforms
Returns list with all the filesystem platforms found in the LIBRARY_BASE_PATH.
Automatically exclude folders defined in user config.
"""
try:
platforms: list[str] = list(os.walk(HIGH_PRIO_STRUCTURE_PATH))[0][1] if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else list(os.walk(LIBRARY_BASE_PATH))[0][1]
try:
_exclude_platforms(platforms)
except (KeyError, TypeError):
pass
return platforms
except IndexError:
error: str = "Platforms not found"
log.critical(error)
raise HTTPException(status_code=404, detail=error)
# ========= Roms utils =========
def _get_roms_structure(p_slug) -> tuple:
return f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms"
def _exclude_single_roms(roms) -> list[str]:
try:
excluded_extensions: list = []
excluded_extensions = user_config['exclude']['roms']['single_file']['extensions']
except (TypeError, KeyError):
pass
try:
excluded_names: list = []
excluded_names = user_config['exclude']['roms']['single_file']['names']
except (TypeError, KeyError):
pass
filtered_files: list = []
for rom in roms:
try:
if rom.split('.')[-1] in excluded_extensions or rom in excluded_names:
filtered_files.append(rom)
except TypeError:
pass
roms = [f for f in roms if f not in filtered_files]
return roms
def _exclude_multi_roms(roms) -> list[str]:
try:
excluded_names: list = []
excluded_names = user_config['exclude']['roms']['multi_file']['names']
except (TypeError, KeyError):
pass
filtered_files: list = []
for rom in roms:
try:
if rom in excluded_names:
filtered_files.append(rom)
except TypeError:
pass
roms = [f for f in roms if f not in filtered_files]
return roms
def _exclude_multi_roms_parts(parts) -> list[str]:
try:
excluded_extensions: list = []
excluded_extensions = user_config['exclude']['roms']['multi_file']['parts']['extensions']
except (TypeError, KeyError):
pass
try:
excluded_names: list = []
excluded_names = user_config['exclude']['roms']['multi_file']['parts']['names']
except (TypeError, KeyError):
pass
filtered_files: list = []
for part in parts:
try:
if part.split('.')[-1] in excluded_extensions or part in excluded_names:
filtered_files.append(part)
except TypeError:
log.warning(f"Config file is malformed")
parts = [f for f in parts if f not in filtered_files]
return parts
def parse_tags(file_name: str) -> tuple:
reg: str = ''
rev: str = ''
other_tags: list = []
tags: list = re.findall('\(([^)]+)', file_name)
for tag in tags:
if tag.split('-')[0].lower() == 'reg':
try: reg = tag.split('-', 1)[1]
except IndexError: pass
elif tag.split('-')[0].lower() == 'rev':
try: rev = tag.split('-', 1)[1]
except IndexError: pass
else:
other_tags.append(tag)
return reg, rev, other_tags
def _get_file_extension(rom: dict) -> str:
return rom['file'].split('.')[-1] if not rom['multi'] else ''
def _get_rom_files(multi: bool, rom: str, roms_path: str) -> list[str]:
return [] if not multi else _exclude_multi_roms_parts(list(os.walk(f"{roms_path}/{rom}"))[0][2])
def _convert_size_human_readable(size, decimals=2) -> tuple:
for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
if size < 1024.0 or unit == 'PB': break
size /= 1024.0
return round(size, 2), unit
def _get_file_size(multi: bool, rom: str, files: list, roms_path:str) -> str:
files: list = [f"{roms_path}/{rom}"] if not multi else [f"{roms_path}/{rom}/{file}" for file in files]
total_size: int = 0
for file in files:
total_size += os.stat(file).st_size
return _convert_size_human_readable(total_size)
def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[dict]:
"""Gets all filesystem roms for a platform
Args:
p_slug: short name of the platform
full_scan: flag to get all roms in fs or only new ones
only_amount: flag to return only amount of roms instead of all info
Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH. Just the amount of them if only_amount=True
"""
roms_path = _get_roms_structure(p_slug)
roms: list[dict] = []
db_roms: list[str] = [rom.file_name for rom in dbh.get_roms(p_slug)]
fs_single_roms: list[str] = list(os.walk(roms_path))[0][2]
fs_multi_roms: list[str] = list(os.walk(roms_path))[0][1]
fs_roms: list[dict] = [{'multi': False, 'file': rom} for rom in _exclude_single_roms(fs_single_roms)] + \
[{'multi': True, 'file': rom} for rom in _exclude_multi_roms(fs_multi_roms)]
if only_amount: return len(fs_roms)
for rom in fs_roms:
if rom['file'] in db_roms and not full_scan and not rom['multi']: continue
reg, rev, other_tags = parse_tags(rom['file'])
file_extension: str = _get_file_extension(rom)
files: list = _get_rom_files(rom['multi'], rom['file'], roms_path)
file_size, file_size_units = _get_file_size(rom['multi'], rom['file'], files, roms_path)
roms.append({'file_name': rom['file'], 'file_path': roms_path, 'multi': rom['multi'],
'files': files, 'file_size': file_size, 'file_size_units': file_size_units, 'file_extension': file_extension,
'region': reg, 'revision': rev, 'tags': other_tags})
return roms
def _rom_exists(p_slug: str, file_name: str) -> bool:
"""Check if rom exists in filesystem
Args:
p_slug: short name of the platform
file_name: rom file_name
Returns
True if rom exists in filesystem else False
"""
rom_path = _get_roms_structure(p_slug)
exists: bool = True if os.path.exists(f"{rom_path}/{file_name}") else False
return exists
def rename_rom(p_slug: str, old_name: str, new_name: str) -> None:
if new_name != old_name:
rom_path = _get_roms_structure(p_slug)
if _rom_exists(p_slug, new_name):
log.info(f"Can't rename {old_name} to {new_name}. {new_name} already exists")
raise HTTPException(status_code=500, detail=f"Can't rename: {new_name} already exists.")
os.rename(f"{rom_path}/{old_name}", f"{rom_path}/{new_name}")
def remove_rom(p_slug: str, file_name: str) -> None:
rom_path = _get_roms_structure(p_slug)
try:
try:
os.remove(f"{rom_path}/{file_name}")
except IsADirectoryError:
shutil.rmtree(f"{rom_path}/{file_name}")
except FileNotFoundError:
log.error(f"{rom_path}/{file_name} not found in filesystem")
# ========= Resources utils =========
def _cover_exists(p_slug: str, file_name: str, size: str) -> bool:
"""Check if rom cover exists in filesystem
@@ -278,4 +71,159 @@ def get_cover_details(overwrite: bool, p_slug: str, file_name: str, url_cover: s
if _cover_exists(p_slug, file_name, 'l'):
path_cover_l = _get_cover_path(p_slug, file_name, 'l')
has_cover = 1
return path_cover_s, path_cover_l, has_cover
return {'path_cover_s': path_cover_s, 'path_cover_l': path_cover_l, 'has_cover': has_cover}
def store_default_resources() -> None:
"""Store default cover resources in the filesystem"""
defaul_covers: dict = [{'url': DEFAULT_URL_COVER_L, 'size': 'l'}, {'url': DEFAULT_URL_COVER_S, 'size': 's'}]
for cover in defaul_covers:
if not _cover_exists('default', 'cover', cover['size']):
_store_cover('default', 'cover', cover['url'], cover['size'])
# ========= Platforms utils =========
def _exclude_platforms(platforms) -> list['str']:
[platforms.remove(excluded) for excluded in user_config['exclude']['platforms'] if excluded in platforms]
def get_platforms() -> list[str]:
"""Gets all filesystem platforms
Returns list with all the filesystem platforms found in the LIBRARY_BASE_PATH.
Automatically exclude folders defined in user config.
"""
try:
platforms: list[str] = list(os.walk(HIGH_PRIO_STRUCTURE_PATH))[0][1] if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else list(os.walk(LIBRARY_BASE_PATH))[0][1]
except IndexError:
raise PlatformsNotFoundException
try:
_exclude_platforms(platforms)
except (KeyError, TypeError):
pass
return platforms
# ========= Roms utils =========
def get_roms_structure(p_slug: str) -> tuple:
return f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms"
def get_rom_files(rom: str, roms_path: str) -> list[str]:
rom_files: list = []
for path, _, files in os.walk(f"{roms_path}/{rom}"):
[rom_files.append(f"{Path(path, f)}".replace(f"{roms_path}/{rom}/", '')) for f in _exclude_files(files, 'multi')]
return rom_files
def _exclude_files(files, type) -> list[str]:
if type == 'single':
try:
excluded_extensions = user_config['exclude']['roms'][f'{type}_file']['extensions']
except (TypeError, KeyError):
excluded_extensions: list = []
try:
excluded_names = user_config['exclude']['roms'][f'{type}_file']['names']
except (TypeError, KeyError):
excluded_names: list = []
elif type == 'multi':
try:
excluded_extensions = user_config['exclude']['roms'][f'{type}_file']['parts']['extensions']
except (TypeError, KeyError):
excluded_extensions: list = []
try:
excluded_names = user_config['exclude']['roms'][f'{type}_file']['parts']['names']
except (TypeError, KeyError):
excluded_names: list = []
filtered_files: list = []
for file in files:
try:
if file.split('.')[-1] in excluded_extensions or file in excluded_names:
filtered_files.append(file)
except TypeError:
pass
files = [f for f in files if f not in filtered_files]
return files
def _exclude_multi_roms(roms) -> list[str]:
try:
excluded_names: list = []
excluded_names = user_config['exclude']['roms']['multi_file']['names']
except (TypeError, KeyError):
pass
filtered_files: list = []
for rom in roms:
try:
if rom in excluded_names:
filtered_files.append(rom)
except TypeError:
pass
roms = [f for f in roms if f not in filtered_files]
return roms
def get_rom_size(multi: bool, rom: str, files: list, roms_path:str) -> str:
files: list = [f"{roms_path}/{rom}"] if not multi else [f"{roms_path}/{rom}/{file}" for file in files]
total_size: int = 0
for file in files:
total_size += os.stat(file).st_size
for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
if total_size < 1024.0 or unit == 'PB': break
total_size /= 1024.0
return round(total_size, 2), unit
def get_roms(p_slug: str) -> list[dict] or int:
"""Gets all filesystem roms for a platform
Args:
p_slug: short name of the platform
Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH.
"""
roms_path = get_roms_structure(p_slug)
try:
fs_single_roms: list[str] = list(os.walk(roms_path))[0][2]
except IndexError:
raise RomsNotFoundException(p_slug)
try:
fs_multi_roms: list[str] = list(os.walk(roms_path))[0][1]
except IndexError:
raise RomsNotFoundException(p_slug)
fs_roms: list[dict] = [{'multi': False, 'file_name': rom} for rom in _exclude_files(fs_single_roms, 'single')] + \
[{'multi': True, 'file_name': rom} for rom in _exclude_multi_roms(fs_multi_roms)]
[rom.update({'files': get_rom_files(rom['file_name'], roms_path)}) for rom in fs_roms]
return fs_roms
def _rom_exists(p_slug: str, file_name: str) -> bool:
"""Check if rom exists in filesystem
Args:
p_slug: short name of the platform
file_name: rom file_name
Returns
True if rom exists in filesystem else False
"""
rom_path = get_roms_structure(p_slug)
exists: bool = True if os.path.exists(f"{rom_path}/{file_name}") else False
return exists
def rename_rom(p_slug: str, old_name: str, new_name: str) -> None:
if new_name != old_name:
rom_path = get_roms_structure(p_slug)
if _rom_exists(p_slug, new_name):
raise RomAlreadyExistsException(new_name)
os.rename(f"{rom_path}/{old_name}", f"{rom_path}/{new_name}")
def remove_rom(p_slug: str, file_name: str) -> None:
rom_path = get_roms_structure(p_slug)
try:
try:
os.remove(f"{rom_path}/{file_name}")
except IsADirectoryError:
shutil.rmtree(f"{rom_path}/{file_name}")
except FileNotFoundError:
raise RomNotFoundError(file_name, p_slug)

View File

@@ -28,4 +28,11 @@ exclude:
- 'data.xml'
# Exclude all files with certain extensions to be scanned from multi file roms
extensions:
- 'txt'
- 'txt'
# Asociate different platform names to your current file system platform names
system:
platforms:
# [your custom platform folder name]: [RomM platform name]
gc: 'ngc' # In this example if you have a 'gc' folder, RomM will treat it like the 'ngc' folder
psx: 'ps' # In this example if you have a 'psx' folder, RomM will treat it like the 'ps' folder

View File

@@ -1 +1 @@
VITE_ROMM_VERSION=1.7.1
VITE_ROMM_VERSION=1.8

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 46 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 47 KiB

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/public/favicon.svg" />
<link rel="icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RomM</title>
</head>

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "romm",
"version": "1.7.1",
"version": "1.8",
"private": true,
"scripts": {
"dev": "vite --host",
@@ -15,10 +15,11 @@
"file-saver": "^2.0.5",
"jszip": "^3.10.1",
"mitt": "^3.0.0",
"pinia": "^2.0.35",
"roboto-fontface": "*",
"vue": "^3.2.13",
"vue-router": "^4.0.0",
"vuetify": "^3.0.0",
"vuetify": "^3.1.15",
"webfontloader": "^1.0.0"
},
"devDependencies": {
@@ -28,6 +29,8 @@
"eslint-plugin-vue": "^9.3.0",
"sass": "^1.55.0",
"vite": "^3.1.9",
"vite-plugin-pwa": "^0.14.7",
"vite-plugin-rewrite-all": "^1.0.1",
"vite-plugin-vuetify": "^1.0.0-alpha.12"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 47 KiB

View File

@@ -1,28 +1,41 @@
<script setup>
import { ref, inject } from "vue"
import { ref, inject, onMounted } from "vue"
import { useTheme } from "vuetify"
import AppBar from '@/components/AppBar/Base.vue'
import PlatformsDrawer from '@/components/PlatformsDrawer/Base.vue'
import SettingsDrawer from '@/components/SettingsDrawer/Base.vue'
import MainDrawer from '@/components/MainDrawer/Base.vue'
import Notification from '@/components/Notification.vue'
import { getPlatforms } from '@/services/api.js'
import { storePlatforms } from '@/stores/platforms.js'
import { storeScanning } from '@/stores/scanning.js'
// Props
const scanning = storeScanning()
const platforms = storePlatforms()
useTheme().global.name.value = localStorage.getItem('theme') || 'rommDark'
const refresh = ref(false)
// Event listeners bus
const emitter = inject('emitter')
emitter.on('refresh', () => { refresh.value = !refresh.value })
emitter.on('refresh', () => {
getPlatforms()
.then((res) => { platforms.add(res.data.data) })
.catch((error) => { console.log(error);console.log("Couldn't fetch platforms") })
refresh.value = !refresh.value
})
onMounted(() => {
getPlatforms()
.then((res) => { platforms.add(res.data.data) })
.catch((error) => { console.log(error);console.log("Couldn't fetch platforms") })
})
</script>
<template>
<v-app>
<settings-drawer/>
<v-progress-linear color="rommAccent1" :active="scanning.value" :indeterminate="true" absolute/>
<app-bar/>
<platforms-drawer :key="refresh"/>
<main-drawer :key="refresh"/>
<v-main>
<v-container fluid>
@@ -30,7 +43,7 @@ emitter.on('refresh', () => { refresh.value = !refresh.value })
</v-container>
</v-main>
<notification/>
<notification class="mt-6"/>
</v-app>
</template>
@@ -58,25 +71,4 @@ emitter.on('refresh', () => { refresh.value = !refresh.value })
background-color: #808080;
border-radius: 5px;
}
rommDark {
primary: #161b22;
secondary: #a452fe;
background: #0d1117;
notification: #0d1117;
surface: #161b22;
tooltip: #161b22;
chip: #161b22;
rommAccent1: #a452fe;
rommAccent2: #9a00ea;
rommAccent3: #7b00e1;
rommAccent4: #702bcf;
rommAccent5: #3808a4;
rommWhite: #fefdfe;
rommBlack: #000000;
rommRed: #da3633;
}
</style>

View File

@@ -1,45 +1,29 @@
<script setup>
import { ref, inject } from "vue"
import { useRouter } from 'vue-router'
import PlatformsBtn from '@/components/AppBar/PlatformsBtn.vue'
import UploadBtn from '@/components/AppBar/UploadBtn.vue'
import SearchBar from '@/components/AppBar/SearchBar.vue'
import GalleryViewBtn from '@/components/AppBar/GalleryViewBtn.vue'
import SettingsBtn from '@/components/AppBar/SettingsBtn.vue'
import MainDrawerToggle from '@/components/AppBar/Gallery/MainDrawerToggle.vue'
import { storeScanning } from '@/stores/scanning.js'
import { storeContextBar } from '@/stores/contextBar.js'
import { useRoute } from 'vue-router'
// Props
const scanning = ref(false)
const router = useRouter()
// Event listeners bus
const emitter = inject('emitter')
emitter.on('scanning', (s) => { scanning.value = s })
// Functions
async function goHome(){
await router.push(import.meta.env.BASE_URL)
}
const scanning = storeScanning()
const contextBar = storeContextBar()
const route = useRoute()
</script>
<template>
<v-app-bar class="elevation-3">
<v-app-bar elevation="1" density="comfortable">
<v-progress-linear color="secondary" :active="scanning" :indeterminate="true" absolute/>
<v-progress-linear color="rommAccent1" :active="scanning.value" :indeterminate="true" absolute/>
<main-drawer-toggle class="ml-5 hidden-lg-and-up"/>
<v-avatar size="100" class="ml-3 home-btn hidden-sm-and-down" @click="goHome()"><v-img src="/assets/romm_complete.svg"></v-img></v-avatar>
<platforms-btn/>
<v-spacer class="hidden-xs-and-down"/>
<upload-btn/>
<search-bar/>
<template v-slot:append>
<gallery-view-btn/>
<settings-btn/>
<v-app-bar-nav-icon v-if="route.params.platform != undefined"
@click="contextBar.toggleContextBar()"
rounded="0">
<v-icon :icon="contextBar.value ? 'mdi-chevron-up' : 'mdi-chevron-down' "/>
</v-app-bar-nav-icon>
</template>
</v-app-bar>

View File

@@ -0,0 +1,35 @@
<script setup>
import MainDrawerToggle from '@/components/AppBar/Gallery/MainDrawerToggle.vue'
import FilterBar from '@/components/AppBar/Gallery/FilterBar.vue'
import FilterBtn from '@/components/AppBar/Gallery/FilterBtn.vue'
import GalleryViewBtn from '@/components/AppBar/Gallery/GalleryViewBtn.vue'
</script>
<template>
<v-app-bar elevation="0" density="comfortable">
<main-drawer-toggle class="ml-5 hidden-lg-and-up"/>
<v-spacer class="hidden-lg-and-up"/>
<v-avatar rounded="0" class="ml-5 hidden-lg-and-up">
<v-img v-if="$route.params.platform !== undefined" :src="'/assets/platforms/'+$route.params.platform+'.ico'"/>
</v-avatar>
<v-spacer class="hidden-lg-and-up"/>
<filter-bar class="mr-2 ml-2 hidden-md-and-down"/>
<template v-slot:append>
<filter-btn class="ml-2 hidden-lg-and-up"/>
<gallery-view-btn/>
</template>
</v-app-bar>
</template>
<style scoped>
.home-btn{
cursor: pointer;
}
</style>

View File

@@ -0,0 +1,27 @@
<script setup>
import { storeFilter } from '@/stores/filter'
import { inject, ref, onMounted } from 'vue'
// Props
const filter = storeFilter()
const filterValue = ref('')
// Event listeners bus
const emitter = inject('emitter')
onMounted(() => { filterValue.value = filter.value })
</script>
<template>
<v-text-field
@click:clear="filter.set('');emitter.emit('filter')"
@keyup="filter.set(filterValue);emitter.emit('filter')"
v-model="filterValue"
label="search"
prepend-inner-icon="mdi-magnify"
class="shrink"
variant="outlined"
density="compact"
hide-details
clearable/>
</template>

View File

@@ -0,0 +1,18 @@
<script setup>
import { storeFilter } from '@/stores/filter'
import { inject } from 'vue'
// Props
const filter = storeFilter()
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-app-bar-nav-icon
rounded="0"
@click="filter.toggleFilterBar();emitter.emit('filter')">
<v-icon>mdi-magnify</v-icon>
</v-app-bar-nav-icon>
</template>

View File

@@ -0,0 +1,16 @@
<script setup>
import { views } from '@/utils/utils.js'
import { storeGalleryView } from '@/stores/galleryView.js'
// Props
const galleryView = storeGalleryView()
</script>
<template>
<v-app-bar-nav-icon
@click="galleryView.next()"
rounded="0"
variant="plain">
<v-icon :icon="views[galleryView.value]['icon']"/>
</v-app-bar-nav-icon>
</template>

View File

@@ -0,0 +1,18 @@
<script setup>
import { inject } from "vue"
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-btn
@click="emitter.emit('toggleMainDrawer')"
rounded="0"
icon>
<v-avatar rounded="0">
<v-img src="/assets/isotipo.svg"/>
</v-avatar>
</v-btn>
</template>

View File

@@ -1,25 +0,0 @@
<script setup>
import { ref, inject } from "vue"
import { views } from '@/utils/utils.js'
// Event listeners bus
const emitter = inject('emitter')
const currentView = ref(JSON.parse(localStorage.getItem('currentView')) || 0)
// Functions
function changeView() {
if(currentView.value == 2){currentView.value = 0}
else{currentView.value = currentView.value + 1}
emitter.emit('currentView', currentView.value)
localStorage.setItem('currentView', currentView.value)
}
</script>
<template>
<v-app-bar-nav-icon
@click="changeView()"
class="ma-2"
rounded="0">
<v-icon :icon="views[currentView]['icon']"/>
</v-app-bar-nav-icon>
</template>

View File

@@ -1,23 +0,0 @@
<script setup>
import { ref, inject } from "vue"
// Props
const selectedPlatform = ref('')
// Event listeners bus
const emitter = inject('emitter')
emitter.on('selectedPlatform', (p) => { selectedPlatform.value = p })
</script>
<template>
<v-btn
@click="emitter.emit('togglePlatforms')"
class="ma-4 hidden-lg-and-up"
rounded="0"
icon>
<v-avatar rounded="0">
<v-img v-show="selectedPlatform != ''" :src="'/assets/platforms/'+selectedPlatform.slug+'.ico'"/>
<v-icon v-show="selectedPlatform == ''" icon="mdi-menu"/>
</v-avatar>
</v-btn>
</template>

View File

@@ -1,23 +0,0 @@
<script setup>
import { ref, inject } from "vue"
// Props
const filter = ref('')
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-text-field
@click:clear="emitter.emit('filter', '')"
@keyup="emitter.emit('filter', filter)"
v-model="filter"
label="search"
prepend-inner-icon="mdi-magnify"
class="ml-2 mr-2 shrink"
variant="outlined"
density="compact"
hide-details
clearable/>
</template>

View File

@@ -1,16 +0,0 @@
<script setup>
import { inject } from "vue"
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-app-bar-nav-icon
title="settings"
@click="emitter.emit('toggleSettings')"
class="ml-2"
rounded="0">
<v-icon>mdi-cog</v-icon>
</v-app-bar-nav-icon>
</template>

View File

@@ -1,19 +0,0 @@
<script setup>
import { inject } from "vue"
// Event listeners bus
const emitter = inject('emitter')
// Functions
function uploadRom() {console.log("uploading rom")}
</script>
<template>
<v-app-bar-nav-icon
@click="uploadRom()"
class="ma-2"
rounded="0"
disabled>
<v-icon>mdi-upload</v-icon>
</v-app-bar-nav-icon>
</template>

View File

@@ -4,7 +4,7 @@ const props = defineProps(['rom'])
<template>
<v-card class="header-background" position="absolute" rounded="0" flat>
<v-img :src="'/assets'+rom.path_cover_l+'?reload='+Date.now()" class="header-background-img" cover/>
<v-img :src="'/assets'+rom.path_cover_s+'?reload='+Date.now()" class="header-background-img" cover/>
</v-card>
</template>

View File

@@ -1,6 +1,6 @@
<script setup>
import { ref, inject } from 'vue'
import { downloadRom, downloadSave } from '@/utils/utils.js'
import { downloadRom, downloadSave } from '@/services/download.js'
// Props
const props = defineProps(['rom'])

View File

@@ -1,14 +1,17 @@
<script setup>
import ActionBar from '@/components/GameGallery/Card/ActionBar.vue'
import Cover from '@/components/GameGallery/Card/Cover.vue'
import { storeDownloader } from '@/stores/downloader.js'
// Props
const props = defineProps(['rom'])
const downloader = storeDownloader()
</script>
<template>
<v-hover v-slot="{isHovering, props}">
<v-card
:loading="downloader.value.includes(rom.file_name) ? 'rommAccent1': null"
v-bind="props"
:class="{'on-hover': isHovering}"
:elevation="isHovering ? 20 : 3">

View File

@@ -1,54 +1,50 @@
<script setup>
import { inject } from 'vue'
import { useRouter } from 'vue-router'
import { selectRom } from '@/utils/utils.js'
// Props
const props = defineProps(['rom', 'isHovering', 'hoverProps', 'size'])
const forceImgReload = Date.now()
const router = useRouter()
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-img
@click="selectRom(rom, emitter, router)"
v-bind="hoverProps"
:src="'/assets'+rom.path_cover_l+'?reload='+forceImgReload"
:lazy-src="'/assets'+rom.path_cover_s+'?reload='+forceImgReload"
class="cover"
cover>
<template v-slot:placeholder>
<div class="d-flex align-center justify-center fill-height">
<v-progress-circular color="secondary" indeterminate/>
</div>
</template>
<v-expand-transition>
<div
v-if="isHovering || !rom.has_cover"
class="rom-title d-flex transition-fast-in-fast-out bg-tooltip text-caption">
<v-list-item>{{ rom.file_name }}</v-list-item>
</div>
</v-expand-transition>
<v-chip-group class="pl-1 pt-0">
<v-chip
v-show="rom.region"
size="x-small"
class="bg-chip"
label>
{{ rom.region }}
</v-chip>
<v-chip
v-show="rom.revision"
size="x-small"
class="bg-chip"
label>
{{ rom.revision }}
</v-chip>
</v-chip-group>
</v-img>
<router-link
style="text-decoration: none; color: inherit;"
:to="`/platform/${$route.params.platform}/rom/${rom.id}`">
<v-img
:value="rom.id"
:key="rom.id"
v-bind="hoverProps"
:src="'/assets'+rom.path_cover_l+'?reload='+forceImgReload"
:lazy-src="'/assets'+rom.path_cover_s+'?reload='+forceImgReload"
class="cover"
cover>
<template v-slot:placeholder>
<div class="d-flex align-center justify-center fill-height">
<v-progress-circular color="rommAccent1" :width="2" indeterminate/>
</div>
</template>
<v-expand-transition>
<div v-if="isHovering || !rom.has_cover"
class="rom-title d-flex transition-fast-in-fast-out bg-tooltip text-caption">
<v-list-item>{{ rom.file_name }}</v-list-item>
</div>
</v-expand-transition>
<v-chip-group class="pl-1 pt-0">
<v-chip
v-show="rom.region"
size="x-small"
class="bg-chip"
label>
{{ rom.region }}
</v-chip>
<v-chip
v-show="rom.revision"
size="x-small"
class="bg-chip"
label>
{{ rom.revision }}
</v-chip>
</v-chip-group>
</v-img>
</router-link>
</template>
<style scoped>

View File

@@ -1,21 +1,26 @@
<template>
<v-list-item class="pl-2 pr-2 pb-2 ml-3 mr-3 text-body-1">
<v-row class="">
<v-col cols="3"><p>Name</p></v-col>
<v-col cols="4" class="hidden-sm-and-down"><p>File</p></v-col>
<v-col class="hidden-sm-and-down"><p>Platform</p></v-col>
<v-col class="hidden-sm-and-down"><p>Size</p></v-col>
<v-col class="hidden-sm-and-down"><p>Region</p></v-col>
<v-col class="hidden-sm-and-down"><p>Revision</p></v-col>
</v-row>
<template v-slot:prepend><v-avatar/></template>
<template v-slot:append>
<!-- TODO: remake this little trick -->
<v-col class="pa-0 ml-1">
<v-btn disabled size="x-small" variant="text"/>
<v-btn size="x-small" variant="text" disabled/>
<thead>
<v-row no-gutter>
<v-col>
<v-list-item>
<v-row class="text-subtitle-2">
<v-col cols="9" xs="9" sm="6" md="3" lg="3"><span>Name</span></v-col>
<v-col md="4" lg="4" class="hidden-sm-and-down"><span>File</span></v-col>
<v-col md="1" lg="1" class="hidden-sm-and-down"><span>Platform</span></v-col>
<v-col xs="2" sm="2" md="2" lg="2" class="hidden-xs"><span>Size</span></v-col>
<v-col xs="1" sm="1" md="1" lg="1" class="hidden-xs"><span>Reg</span></v-col>
<v-col xs="1" sm="1" md="1" lg="1" class="hidden-xs"><span>Rev</span></v-col>
</v-row>
<template v-slot:prepend>
<v-avatar></v-avatar>
</template>
</v-list-item>
</v-col>
<v-btn size="x-small" variant="text" disabled/>
</template>
</v-list-item>
<v-col cols="2" xs="2" sm="2" md="1" lg="1" class="d-flex justify-center align-center mr-6">
<v-btn size="x-small" variant="text"/>
<v-btn size="x-small" variant="text"/>
<v-btn size="x-small" variant="text"/>
</v-col>
</v-row>
</thead>
</template>

View File

@@ -1,42 +1,46 @@
<script setup>
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
import { selectRom, downloadRom, downloadSave } from '@/utils/utils.js'
import { downloadRom, downloadSave } from '@/services/download.js'
import { storeDownloader } from '@/stores/downloader.js'
// Props
const props = defineProps(['rom'])
const forceImgReload = Date.now()
const router = useRouter()
const saveFiles = ref(false)
const downloader = storeDownloader()
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-list-item
@:click="selectRom(rom, emitter, router)"
:value="rom.file_name"
:key="rom.file_name"
class="pa-2">
<v-row class="text-subtitle-2">
<v-col md="3" lg="3"><p>{{ rom.name }}</p></v-col>
<v-col md="3" lg="4" class="hidden-sm-and-down"><p>{{ rom.file_name }}</p></v-col>
<v-col class="hidden-sm-and-down"><p>{{ rom.p_slug }}</p></v-col>
<v-col class="hidden-sm-and-down"><p>{{ rom.file_size }} {{ rom.file_size_units }}</p></v-col>
<v-col class="hidden-sm-and-down"><p>{{ rom.region }}</p></v-col>
<v-col class="hidden-sm-and-down"><p>{{ rom.revision }}</p></v-col>
</v-row>
<template v-slot:prepend>
<v-avatar :rounded="0" class="ml-3">
<v-img
:src="'/assets'+rom.path_cover_l+'?reload='+forceImgReload"
:lazy-src="'/assets'+rom.path_cover_s+'?reload='+forceImgReload"
min-height="100"/>
</v-avatar>
</template>
<template v-slot:append>
<v-col class="pa-0 ml-1">
<v-row no-gutters>
<v-col>
<v-list-item
:to="`/platform/${$route.params.platform}/rom/${rom.id}`"
:value="rom.id"
:key="rom.id">
<v-row class="text-subtitle-2 justify-center align-center">
<v-col cols="9" xs="9" sm="6" md="3" lg="3"><span>{{ rom.r_name }}</span></v-col>
<v-col md="4" lg="4" class="hidden-sm-and-down"><span>{{ rom.file_name }}</span></v-col>
<v-col md="1" lg="1" class="hidden-sm-and-down"><span>{{ rom.p_slug }}</span></v-col>
<v-col xs="2" sm="2" md="2" lg="2" class="hidden-xs"><span>{{ rom.file_size }} {{ rom.file_size_units }}</span></v-col>
<v-col xs="1" sm="1" md="1" lg="1" class="hidden-xs"><span>{{ rom.region }}</span></v-col>
<v-col xs="1" sm="1" md="1" lg="1" class="hidden-xs"><span>{{ rom.revision }}</span></v-col>
</v-row>
<template v-slot:prepend>
<v-avatar :rounded="0">
<v-progress-linear color="rommAccent1" :active="downloader.value.includes(rom.file_name)" :indeterminate="true" absolute/>
<v-img
:src="'/assets'+rom.path_cover_s+'?reload='+forceImgReload"
:lazy-src="'/assets'+rom.path_cover_s+'?reload='+forceImgReload"
min-height="150"/>
</v-avatar>
</template>
</v-list-item>
</v-col>
<v-col cols="2" xs="2" sm="2" md="1" lg="1" class="d-flex justify-center align-center mr-6">
<v-btn
@click="downloadRom(rom, emitter)"
icon="mdi-download"
@@ -48,14 +52,12 @@ const emitter = inject('emitter')
size="x-small"
variant="text"
:disabled="!saveFiles"/>
</v-col>
<v-btn
@click=""
icon="mdi-dots-vertical"
size="x-small"
variant="text"
class="mr-3"
:disabled="!saveFiles"/>
</template>
</v-list-item>
</v-col>
</v-row>
</template>

View File

@@ -1,10 +0,0 @@
<script setup>
// Props
const props = defineProps(['noRoms'])
</script>
<template>
<v-row v-if="noRoms" class="d-flex justify-center align-center mt-16">
<div class="text-h6">Feels cold here... <v-icon>mdi-emoticon-sad</v-icon></div>
</v-row>
</template>

View File

@@ -0,0 +1,109 @@
<script setup>
import { ref, inject } from "vue"
import RailBtn from '@/components/MainDrawer/RailBtn.vue'
import Platform from '@/components/MainDrawer/Platform.vue'
import { storePlatforms } from '@/stores/platforms'
// Props
const platforms = storePlatforms()
const mainDrawer = ref(undefined)
const open = ref(['Platforms', 'Library', 'Settings'])
const rail = (localStorage.getItem('rail') == 'true') ? ref(true) : ref(false)
// Event listeners bus
const emitter = inject('emitter')
emitter.on('toggleMainDrawer', () => { mainDrawer.value = !mainDrawer.value })
emitter.on('toggleMainDrawerRail', () => { rail.value = !rail.value; localStorage.setItem('rail', rail.value)})
</script>
<template>
<v-navigation-drawer v-model="mainDrawer" :rail="rail" width="300" rail-width="145" elevation="0">
<v-list v-model:opened="open">
<router-link to="/">
<v-list-item class="justify-center pa-0">
<v-img src="/assets/isotipo.svg" width="70" class="home-btn"/>
</v-list-item>
</router-link>
<v-divider></v-divider>
<v-list-group value="Platforms">
<template v-slot:activator="{ props }">
<v-list-item
v-bind="props">
<span class="text-body-1 text-truncate">{{ rail ? '' : 'Platforms' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-controller</v-icon></v-avatar>
</template>
</v-list-item>
</template>
<platform class="drawer-item" v-for="platform in platforms.value" :platform="platform" :rail="rail" :key="platform.slug"/>
</v-list-group>
<v-list-group value="Library">
<template v-slot:activator="{ props }">
<v-list-item
v-bind="props">
<span class="text-body-1 text-truncate">{{ rail ? '' : 'Library' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-animation-outline</v-icon></v-avatar>
</template>
</v-list-item>
</template>
<v-list-item class="drawer-item bg-terciary" to="/library/scan">
<span class="text-body-2 text-truncate">{{ rail ? '' : 'Scan' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-magnify-scan</v-icon></v-avatar>
</template>
</v-list-item>
<v-list-item class="drawer-item bg-terciary" disabled>
<span class="text-body-2 text-truncate">{{ rail ? '' : 'Upload' }}</span>
<span class="text-caption text-truncate ml-1">{{ rail ? '' : '[comming soon]' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-upload</v-icon></v-avatar>
</template>
</v-list-item>
</v-list-group>
<v-list-group value="Settings">
<template v-slot:activator="{ props }">
<v-list-item
v-bind="props">
<span class="text-body-1 text-truncate">{{ rail ? '' : 'Settings' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-cog</v-icon></v-avatar>
</template>
</v-list-item>
</template>
<v-list-item class="drawer-item bg-terciary" to="/settings/control-panel">
<span class="text-body-2 text-truncate">{{ rail ? '' : 'Control panel' }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-icon>mdi-view-dashboard</v-icon></v-avatar>
</template>
</v-list-item>
</v-list-group>
</v-list>
<template v-slot:append>
<v-divider class="border-opacity-25" :thickness="1"/>
<rail-btn :rail="rail"/>
</template>
</v-navigation-drawer>
</template>
<style scoped>
.home-btn{
width: 100px;
height: 100px;
cursor: pointer;
}
.drawer-item {
padding-inline-start: 30px !important;
}
</style>

View File

@@ -0,0 +1,21 @@
<script setup>
// Props
const props = defineProps(['platform', 'rail'])
</script>
<template>
<v-list-item :to="`/platform/${platform.slug}`" :value="platform.slug" :key="platform" class="pt-4 pb-4 bg-terciary">
<span class="text-body-2 text-truncate">{{ rail ? '' : platform.name }}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40"><v-img :src="'/assets/platforms/'+platform.slug+'.ico'"></v-img></v-avatar>
</template>
<template v-slot:append>
<v-chip class="ml-4 bg-chip" size="x-small" label>{{ platform.n_roms }}</v-chip>
</template>
</v-list-item>
</template>
<style scoped>
</style>

View File

@@ -10,8 +10,9 @@ const emitter = inject('emitter')
<template>
<v-btn
@click="emitter.emit('togglePlatformsRail')"
@click="emitter.emit('toggleMainDrawerRail')"
rounded="0"
color="primary"
block>
<v-icon v-if="rail">mdi-arrow-collapse-right</v-icon>
<v-icon v-if="!rail">mdi-arrow-collapse-left</v-icon>

View File

@@ -14,7 +14,7 @@ emitter.on('snackbarScan', (snackbar) => {
</script>
<template>
<v-snackbar v-model="snackbarShow" :timeout="4000" location="top" class="mt-4" color="notification">
<v-snackbar v-model="snackbarShow" :timeout="4000" location="top" color="notification">
<v-icon :icon="snackbarStatus.icon" :color="snackbarStatus.color" class="ml-2 mr-2"/>
{{ snackbarStatus.msg }}
<template v-slot:actions>

View File

@@ -1,65 +0,0 @@
<script setup>
import axios from "axios"
import { ref, inject } from "vue"
import { useRouter } from 'vue-router'
import RailBtn from '@/components/PlatformsDrawer/RailBtn.vue'
import Platform from '@/components/PlatformsDrawer/Platform.vue'
// Props
const selectedPlatform = ref(JSON.parse(localStorage.getItem('selectedPlatform')) || "")
const platforms = ref([])
const platformsDrawer = ref(null)
const rail = (localStorage.getItem('rail') == 'true') ? ref(true) : ref(false)
const router = useRouter()
// Event listeners bus
const emitter = inject('emitter')
emitter.on('togglePlatforms', () => { platformsDrawer.value = !platformsDrawer.value })
emitter.on('togglePlatformsRail', () => { rail.value = !rail.value; localStorage.setItem('rail', rail.value)})
// Functions
async function getPlatforms() {
axios.get('/api/platforms').then((response) => {
platforms.value = response.data.data
emitter.emit('platforms', platforms.value)
}).catch((error) => {console.log(error)})
}
async function goHome(){
await router.push(import.meta.env.BASE_URL)
}
getPlatforms()
emitter.emit('selectedPlatform', selectedPlatform.value)
</script>
<template>
<v-navigation-drawer v-model="platformsDrawer" :rail="rail" width="300" rail-width="75">
<v-list>
<v-row @click="goHome()" class="justify-center hidden-md-and-up">
<v-img v-show="!rail" src="/assets/romm_complete.svg" class="home-btn justify-center"/>
<v-img v-show="rail" src="/assets/romm.svg" class="home-btn justify-center"/>
</v-row>
<v-divider class="border-opacity-25 hidden-md-and-up"/>
<platform v-for="platform in platforms" :platform="platform" :rail="rail"/>
</v-list>
<template v-slot:append>
<v-divider class="border-opacity-25" :thickness="1"/>
<rail-btn :rail="rail"/>
</template>
</v-navigation-drawer>
</template>
<style scoped>
.home-btn{
width: 100px;
height: 100px;
cursor: pointer;
}
</style>

View File

@@ -1,39 +0,0 @@
<script setup>
import { inject } from "vue"
import { useRouter } from 'vue-router'
import { useDisplay } from "vuetify"
// Props
const props = defineProps(['platform', 'rail'])
const { mobile } = useDisplay()
const router = useRouter()
// Event listeners bus
const emitter = inject('emitter')
// Functions
async function selectPlatform(platform){
if(mobile.value){emitter.emit('togglePlatforms')}
await router.push(import.meta.env.BASE_URL)
localStorage.setItem('selectedPlatform', JSON.stringify(platform))
emitter.emit('selectedPlatform', platform)
}
</script>
<template>
<v-list-item :value="platform.slug" :key="platform" @:click="selectPlatform(platform)" class="pt-4 pb-4">
<p class="text-subtitle-2 text-truncate">{{ rail ? '' : platform.name }}</p>
<template v-slot:prepend>
<v-avatar :rounded="0"><v-img :src="'/assets/platforms/'+platform.slug+'.ico'"></v-img></v-avatar>
</template>
<template v-slot:append>
<v-chip class="ml-4" size="small">{{ platform.n_roms }}</v-chip>
</template>
</v-list-item>
</template>
<style scoped>
.v-navigation-drawer--rail:not(.v-navigation-drawer--is-hovering) .v-list .v-avatar {
--v-avatar-height: 40px;
}
</style>

View File

@@ -1,40 +0,0 @@
<script setup>
import { ref, inject } from "vue"
import SettingsHeader from '@/components/SettingsDrawer/Header.vue'
import Scan from '@/components/SettingsDrawer/Scan.vue'
import ThemeToggle from '@/components/SettingsDrawer/ThemeToggle.vue'
import VersionLabel from '@/components/SettingsDrawer/VersionLabel.vue'
// Props
const settingsDrawer = ref(false)
// Event listeners bus
const emitter = inject('emitter')
emitter.on('toggleSettings', () => { settingsDrawer.value = !settingsDrawer.value })
</script>
<template>
<v-navigation-drawer
v-model="settingsDrawer"
location="right"
width="270"
class="bg-background"
temporary
floating>
<settings-header class="bg-primary"/>
<v-divider class="border-opacity-100" :thickness="2"/>
<scan/>
<template v-slot:append>
<v-divider class="border-opacity-25"/>
<theme-toggle/>
<v-divider class="border-opacity-25"/>
<version-label class="bg-primary"/>
</template>
</v-navigation-drawer>
</template>

View File

@@ -1,20 +0,0 @@
<script setup>
import { inject } from "vue"
// Event listeners bus
const emitter = inject('emitter')
</script>
<template>
<v-list-item
class="text-h5 d-flex align-center justify-center font-weight-bold pt-4 pb-4 pl-7">
Settings
<v-btn
title="close settings"
@click="emitter.emit('toggleSettings')"
class="ml-1"
icon="mdi-close-box"
rounded="0"
variant="plain"/>
</v-list-item>
</template>

View File

@@ -1,80 +0,0 @@
<script setup>
import axios from "axios"
import { ref, inject, toRaw } from "vue"
// Props
const platforms = ref([])
const platformsToScan = ref([])
const scanning = ref(false)
const fullScan = ref(false)
// Event listeners bus
const emitter = inject('emitter')
emitter.on('platforms', (p) => { platforms.value = p })
// Functions
async function scan() {
scanning.value = true
emitter.emit('scanning', true)
const platforms = []
toRaw(platformsToScan)._rawValue.forEach(p => {platforms.push(toRaw(p.slug))})
await axios.get('/api/scan?platforms='+JSON.stringify(platforms)+'&full_scan='+fullScan.value).then((response) => {
emitter.emit('snackbarScan', {'msg': 'Scan completed successfully!', 'icon': 'mdi-check-bold', 'color': 'green'})
}).catch((error) => {
console.log(error)
emitter.emit('snackbarScan', {'msg': "Couldn't complete scan. Something went wrong...", 'icon': 'mdi-close-circle', 'color': 'red'})
})
scanning.value = false
emitter.emit('scanning', false)
emitter.emit('refresh')
}
</script>
<template>
<v-list>
<v-select
label="Platforms"
item-title="name"
v-model="platformsToScan"
:items="platforms"
class="pl-5 pr-5 mt-2 mb-1"
density="comfortable"
variant="outlined"
multiple
return-object
clearable
hide-details
chips/>
<v-list-item class="pa-0">
<v-row class="align-center">
<v-col class="d-flex justify-center">
<v-btn
title="scan"
@click="scan()"
:disabled="scanning"
prepend-icon="mdi-magnify-scan"
class="ml-7 bg-scanBtn"
rounded="0"
inset>
<p v-if="!scanning">Scan</p>
<v-progress-circular
v-show="scanning"
class="ml-2"
color="secondary"
:width="2"
:size="20"
indeterminate/>
</v-btn>
</v-col>
<v-col class="mr-4">
<v-checkbox
v-model="fullScan"
label="Full scan"
hide-details/>
</v-col>
</v-row>
</v-list-item>
</v-list>
</template>

View File

@@ -1,26 +0,0 @@
<script setup>
import { ref } from "vue"
import { useTheme } from "vuetify"
// Props
const theme = useTheme()
const darkMode = (localStorage.getItem('theme') == 'rommLight') ? ref(false) : ref(true)
// Functions
function toggleTheme() {
theme.global.name.value = darkMode.value ? "rommDark" : "rommLight"
darkMode.value ? localStorage.setItem('theme', 'rommDark') : localStorage.setItem('theme', 'rommLight')
}
</script>
<template>
<v-list-item class="d-flex align-center justify-center">
<v-switch
@change="toggleTheme()"
v-model="darkMode"
class="pr-2 pl-2"
prepend-icon="mdi-theme-light-dark"
hide-details
inset/>
</v-list-item>
</template>

View File

@@ -1,9 +0,0 @@
<script setup>
const ROMM_VERSION = import.meta.env.VITE_ROMM_VERSION
</script>
<template>
<v-list-item class="d-flex justify-center alignt-center text-body-2">
<span class="text-secondary">RomM</span><span> v{{ ROMM_VERSION }}</span>
</v-list-item>
</template>

View File

@@ -7,11 +7,13 @@
// Plugins
import { loadFonts } from './webfontloader'
import vuetify from './vuetify'
import router from '../router'
import router from './router'
import pinia from './pinia'
export function registerPlugins (app) {
loadFonts()
app
.use(vuetify)
.use(router)
.use(pinia)
}

View File

@@ -0,0 +1,5 @@
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia

View File

@@ -4,11 +4,23 @@ import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
component: () => import('@/views/Home.vue')
},
{
path: '/platform/:platform',
component: () => import('@/views/Gallery.vue')
},
{
path: '/details',
path: '/platform/:platform/rom/:rom',
component: () => import('@/views/Details.vue')
},
{
path: '/library/scan',
component: () => import('@/views/library/Scan.vue')
},
{
path: '/settings/control-panel',
component: () => import('@/views/settings/ControlPanel.vue')
}
]

View File

@@ -7,53 +7,11 @@
// Styles
import '@mdi/font/css/materialdesignicons.css'
import 'vuetify/styles'
import { rommDark, rommLight } from '@/styles/themes.js'
// Composables
import { createVuetify } from 'vuetify'
const rommDark = {
dark: true,
colors: {
primary: '#161b22',
secondary: '#a452fe',
background: '#0d1117',
notification: '#0d1117',
surface: '#161b22',
tooltip: '#161b22',
chip: '#161b22',
rommAccent1: '#a452fe',
rommAccent2: '#c400f7',
rommAccent2: '#3808a4',
rommWhite: '#fefdfe',
rommBlack: '#000000',
rommRed: '#da3633',
rommGreen: '#3FB950'
}
}
const rommLight = {
dark: false,
colors: {
primary: '#fefdfe',
secondary: '#a452fe',
background: '#fefdfe',
notification: '#0d1117',
surface: '#fefdfe',
tooltip: '#fefdfe',
chip: '#161b22',
rommAccent1: '#a452fe',
rommAccent2: '#c400f7',
rommAccent2: '#3808a4',
rommWhite: '#fefdfe',
rommBlack: '#000000',
rommRed: '#da3633',
rommGreen: '#3FB950'
}
}
export default createVuetify({
icons: {
iconfont: 'mdi'

View File

@@ -0,0 +1,6 @@
import axios from 'axios'
export async function getPlatforms () {
return axios.get('/api/platforms')
}

View File

@@ -0,0 +1,36 @@
import JSZip from "jszip"
import { saveAs } from 'file-saver'
import { storeDownloader } from '@/stores/downloader.js'
const downloader = storeDownloader()
export async function downloadRom(rom, emitter, filesToDownload=[]) {
downloader.add(rom.file_name)
emitter.emit('snackbarScan', {'msg': "Downloading "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'})
if(rom.multi){
const zip = new JSZip()
var zipFilename = rom.file_name+".zip"
var files = []
filesToDownload.forEach(f => {files.push(f)})
if (files.length == 0){ files = rom.files }
var count = 0
files.forEach(async function (file_part) {
var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name+"/"+file_part
var file = await fetch(file_full_path)
var fileBlob = await file.blob()
var f = zip.folder(rom.file_name);
f.file(file_part, fileBlob, { binary: true });
count ++
if (count == files.length) { zip.generateAsync({ type: 'blob' }).then(function (content) { saveAs(content, zipFilename); }); }
})
}
else{
var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name
var file = await fetch(file_full_path)
var fileBlob = await file.blob()
saveAs(fileBlob, rom.file_name)
}
downloader.remove(rom.file_name)
}
export async function downloadSave(rom) { console.log("Downloading "+rom.file_name+" save file") }

View File

@@ -0,0 +1,9 @@
import { defineStore } from 'pinia'
export const storeContextBar = defineStore('contextBar', {
state: () => ({ value: false }),
actions: {
toggleContextBar() { this.value = !this.value }
}
})

View File

@@ -0,0 +1,10 @@
import { defineStore } from 'pinia'
export const storeDownloader = defineStore('downloader', {
state: () => ({ value: [] }),
actions: {
add(rom) { this.value.push(rom) },
remove(rom) { this.value.splice(this.value.indexOf(rom), 1) }
}
})

View File

@@ -0,0 +1,10 @@
import { defineStore } from 'pinia'
import { normalizeString } from '@/utils/utils.js'
export const storeFilter = defineStore('filter', {
state: () => ({ value: '' }),
actions: {
set(filter) { this.value = normalizeString(filter) }
}
})

View File

@@ -0,0 +1,16 @@
import { defineStore } from 'pinia'
export const storeGalleryView = defineStore('galleryView', {
state: () => ({ value: (JSON.parse(localStorage.getItem('currentView')) || 0)}),
actions: {
set(view) {
this.value = view
localStorage.setItem('currentView', this.value)
},
next(){
if(this.value == 2){this.set(0)}
else{this.set(this.value+1)}
}
}
})

View File

@@ -0,0 +1,11 @@
import { defineStore } from 'pinia'
export const storePlatforms = defineStore('platforms', {
state: () => ({ value: [] }),
actions: {
add(platforms) {
this.value = platforms
}
}
})

View File

@@ -0,0 +1,9 @@
import { defineStore } from 'pinia'
export const storeScanning = defineStore('scanning', {
state: () => ({ value: false }),
actions: {
set(scanning) { this.value = scanning }
}
})

View File

@@ -0,0 +1,45 @@
export const rommDark = {
dark: true,
colors: {
primary: '#161b22',
secondary: '#0d1117',
terciary: '#202832',
background: '#0d1117',
surface: '#161b22',
tooltip: '#161b22',
chip: '#161b22',
rommAccent1: '#a452fe',
rommAccent2: '#c400f7',
rommAccent3: '#3808a4',
rommRed: '#da3633',
rommGreen: '#3FB950',
rommWhite: '#fefdfe',
rommBlack: '#000000',
}
}
export const rommLight = {
dark: false,
colors: {
primary: '#fefdfe',
secondary: '#fefdfe',
terciary: '#fefdfe',
background: '#fefdfe',
surface: '#fefdfe',
tooltip: '#fefdfe',
chip: '#fefdfe',
rommAccent1: '#a452fe',
rommAccent2: '#c400f7',
rommAccent3: '#3808a4',
rommRed: '#da3633',
rommGreen: '#3FB950',
rommWhite: '#fefdfe',
rommBlack: '#000000',
}
}

View File

@@ -1,48 +1,7 @@
import JSZip from "jszip"
import { toRaw } from "vue"
import { saveAs } from 'file-saver'
export async function selectRom(rom, emitter, router) {
localStorage.setItem('currentRom', JSON.stringify(rom))
await router.push(import.meta.env.BASE_URL+'details')
emitter.emit('currentRom', rom)
}
export async function downloadRom(rom, emitter, filesToDownload=[]) {
emitter.emit('snackbarScan', {'msg': "Downloading "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'})
if(rom.multi){
const zip = new JSZip()
var zipFilename = rom.file_name+".zip"
var files = []
toRaw(filesToDownload).forEach(f => {files.push(toRaw(f))})
if (files.length == 0){ files = rom.files }
var count = 0
files.forEach(async function (file_part) {
var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name+"/"+file_part
var file = await fetch(file_full_path)
var fileBlob = await file.blob()
var f = zip.folder(rom.file_name);
f.file(file_part, fileBlob, { binary: true });
count ++
if (count == files.length) { zip.generateAsync({ type: 'blob' }).then(function (content) { saveAs(content, zipFilename); }); }
})
}
else{
var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name
var file = await fetch(file_full_path)
var fileBlob = await file.blob()
saveAs(fileBlob, rom.file_name)
}
}
export async function downloadSave(rom, emitter) { console.log("Downloading "+rom.file_name+" save file") }
export function normalizeString(s) { return s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,"") }
export const views = {
0:{'view': 'small', 'icon': 'mdi-view-module', 'size-lg': 1, 'size-md': 2, 'size-sm': 2, 'size-xs': 3, 'size-cols': 4},
1:{'view': 'big', 'icon': 'mdi-view-list', 'size-lg': 2, 'size-md': 3, 'size-sm': 3, 'size-xs': 6, 'size-cols': 6},
2:{'view': 'list', 'icon': 'mdi-view-comfy', 'size-lg': 1, 'size-md': 2, 'size-sm': 2, 'size-xs': 3, 'size-cols': 4}
}
export function normalizeString(s) { return s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,"") }

View File

@@ -1,33 +1,37 @@
<script setup>
import axios from 'axios'
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ref, inject, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDisplay } from "vuetify"
import { downloadRom, downloadSave } from '@/utils/utils.js'
import { downloadRom, downloadSave } from '@/services/download.js'
import { storeDownloader } from '@/stores/downloader.js'
import BackgroundHeader from '@/components/GameDetails/BackgroundHeader.vue'
import AppBar from '@/components/AppBar/Base.vue'
const router = useRouter()
const route = useRoute()
// Props
const rom = ref(JSON.parse(localStorage.getItem('currentRom')) || '')
const rom = ref(undefined)
const updatedRom = ref(undefined)
const saveFiles = ref(false)
const searching = ref(false)
const igdb_id = ref('')
const matchedRoms = ref([])
const updating = ref(false)
const editedRomName = ref(rom.value.file_name)
const loading = ref(true)
const renameAsIGDB = ref(false)
const dialogSearchRom = ref(false)
const dialogEditRom = ref(false)
const dialogDeleteRom = ref(false)
const deleteFromFs = ref(false)
const router = useRouter()
const filesToDownload = ref([])
const downloader = storeDownloader()
const tab = ref('info')
const selectedPlatform = ref(JSON.parse(localStorage.getItem('selectedPlatform')) || '')
const { xs, sm, mdAndUp } = useDisplay()
const { xs, sm, mdAndUp, mdAndDown } = useDisplay()
// Event listeners bus
const emitter = inject('emitter')
emitter.on('currentRom', (currentRom) => { rom.value = currentRom })
// Functions
async function searchRomIGDB() {
@@ -41,77 +45,78 @@ async function searchRomIGDB() {
searching.value = false
}
async function updateRom(updatedRom=Object.assign({},rom.value), newName=rom.value.file_name) {
updating.value = true
async function updateRom(updatedData={...updatedRom.value}) {
dialogSearchRom.value = false
if (renameAsIGDB.value) {
updatedRom.file_name = rom.value.file_name.replace(rom.value.file_name_no_tags.trim(), updatedRom.name)
editedRomName.value = updatedRom.file_name
renameAsIGDB.value = false
}
else{
updatedRom.file_name = newName
}
await axios.patch('/api/platforms/'+rom.value.p_slug+'/roms', {
rom: rom.value,
updatedRom: updatedRom
}).then((response) => {
localStorage.setItem('currentRom', JSON.stringify(response.data.data))
emitter.emit('snackbarScan', {'msg': rom.value.file_name+" updated successfully!", 'icon': 'mdi-check-bold', 'color': 'green'})
updating.value = true
updatedRom.value.r_igdb_id = updatedData.r_igdb_id
updatedRom.value.r_slug = updatedData.r_slug
updatedRom.value.summary = updatedData.summary
updatedRom.value.url_cover = updatedData.url_cover
updatedRom.value.r_name = updatedData.r_name
if (renameAsIGDB.value) { updatedRom.value.file_name = updatedRom.value.file_name.replace(updatedRom.value.file_name_no_tags, updatedData.r_name) }
await axios.patch('/api/platforms/'+rom.value.p_slug+'/roms/'+rom.value.id, { updatedRom: updatedRom.value }).then((response) => {
rom.value = response.data.data
updatedRom.value = {...response.data.data}
emitter.emit('snackbarScan', {'msg': response.data.msg, 'icon': 'mdi-check-bold', 'color': 'green'})
router.push('/platform/'+rom.value.p_slug+'/rom/'+rom.value.id)
}).catch((error) => {
console.log(error)
emitter.emit('snackbarScan', {'msg': "Couldn't updated "+rom.value.file_name+". Something went wrong...", 'icon': 'mdi-close-circle', 'color': 'red'})
emitter.emit('snackbarScan', {'msg': error.response.data.detail, 'icon': 'mdi-close-circle', 'color': 'red'})
})
renameAsIGDB.value = false
updating.value = false
dialogEditRom.value = false
}
async function deleteRom() {
await axios.delete('/api/platforms/'+rom.value.p_slug+'/roms/'+rom.value.file_name+'?filesystem='+deleteFromFs.value)
await axios.delete('/api/platforms/'+rom.value.p_slug+'/roms/'+rom.value.id+'?filesystem='+deleteFromFs.value)
.then((response) => {
emitter.emit('snackbarScan', {'msg': rom.value.file_name+" deleted successfully!", 'icon': 'mdi-check-bold', 'color': 'green'})
router.push(import.meta.env.BASE_URL)
emitter.emit('snackbarScan', {'msg': response.data.msg, 'icon': 'mdi-check-bold', 'color': 'green'})
router.push('/platform/'+rom.value.p_slug)
}).catch((error) => {
console.log(error)
emitter.emit('snackbarScan', {'msg': "Couldn't delete "+rom.value.file_name+". Something went wrong...", 'icon': 'mdi-close-circle', 'color': 'red'})
emitter.emit('snackbarScan', {'msg': error.response.data.detail, 'icon': 'mdi-close-circle', 'color': 'red'})
if (error.response.status == 404) { router.push('/platform/'+rom.value.p_slug) }
})
dialogDeleteRom.value = false
}
async function rescan() { console.log("rescan "+rom.value.id) }
onMounted(() => {
axios.get(`/api/platforms/${route.params.platform}/roms/${route.params.rom}`).then(response => {
rom.value = response.data.data
updatedRom.value = {...response.data.data}
loading.value = false
}).catch((error) => { console.log(error);loading.value = false })
})
</script>
<template>
<background-header :rom="rom"/>
<app-bar v-if="mdAndDown"/>
<div :class="{'content': mdAndUp, 'content-tablet': sm, 'content-mobile': xs}">
<background-header :rom="rom" v-if="rom !== undefined"/>
<div :class="{'content': mdAndUp, 'content-tablet': sm, 'content-mobile': xs}" v-if="rom !== undefined">
<v-row class="pt-8 justify-center">
<v-col :class="{'cover': mdAndUp, 'cover-tablet': sm, 'cover-mobile': xs}">
<v-row>
<v-col>
<v-card class="hidden-md-and-down" elevation="5">
<v-card elevation="5" :loading="downloader.value.includes(rom.file_name) ? 'rommAccent1': null">
<v-img :src="'/assets'+rom.path_cover_l+'?reload='+Date.now()" :lazy-src="'/assets'+rom.path_cover_s+'?reload='+Date.now()" cover>
<template v-slot:placeholder>
<div class="d-flex align-center justify-center fill-height">
<v-progress-circular color="secondary" :width="2" :size="20" indeterminate/>
<v-progress-circular color="rommAccent1" :width="2" :size="20" indeterminate/>
</div>
</template>
</v-img>
</v-card>
<v-card class="hidden-lg-and-up" elevation="5">
<v-img :src="'/assets'+rom.path_cover_l+'?reload='+Date.now()" :lazy-src="'/assets'+rom.path_cover_s+'?reload='+Date.now()" cover>
<template v-slot:placeholder>
<div class="d-flex align-center justify-center fill-height">
<v-progress-circular color="secondary" :width="2" :size="20" indeterminate/>
</div>
</template>
</v-img>
</v-card>
</v-col>
</v-row>
<v-row class="pl-3 pr-3">
<v-row class="pl-3 pr-3 action-buttons">
<v-col class="pa-0">
<v-btn @click="downloadRom(rom, emitter, filesToDownload)" rounded="0" block><v-icon icon="mdi-download" size="large"/></v-btn>
<v-btn @click="downloadRom(rom, emitter, filesToDownload)" rounded="0" color="primary" block><v-icon icon="mdi-download" size="large"/></v-btn>
</v-col>
<v-col class="pa-0">
<v-btn @click="downloadSave(rom, emitter)" rounded="0" block :disabled="!saveFiles"><v-icon icon="mdi-content-save-all" size="large"/></v-btn>
@@ -144,50 +149,50 @@ async function deleteRom() {
<v-col class="mt-10" :class="{'info': mdAndUp, 'info-tablet': sm, 'info-mobile': xs}">
<div class="info-header text-white">
<v-row no-gutters>
<p class="text-h4 font-weight-bold">{{ rom.name }}</p>
<span class="text-h4 font-weight-bold rom-name">{{ rom.r_name }}</span>
<v-chip-group class="ml-3 mt-1 hidden-xs">
<v-chip v-show="rom.region" size="x-small" class="bg-chip text-white" label>{{ rom.region }}</v-chip>
<v-chip v-show="rom.revision" size="x-small" class="bg-chip text-white" label>{{ rom.revision }}</v-chip>
<v-chip v-show="rom.region" size="x-small" class="bg-chip" label>{{ rom.region }}</v-chip>
<v-chip v-show="rom.revision" size="x-small" class="bg-chip" label>{{ rom.revision }}</v-chip>
</v-chip-group>
</v-row>
</v-row>
<v-row no-gutters class="align-center">
<p class="font-italic mt-1">{{ selectedPlatform['name'] }}</p>
<span class="font-italic mt-1 rom-platform">{{ rom.p_name || rom.p_slug }}</span>
<v-chip-group class="ml-3 mt-1 hidden-sm-and-up">
<v-chip v-show="rom.region" size="x-small" class="bg-chip text-white" label>{{ rom.region }}</v-chip>
<v-chip v-show="rom.revision" size="x-small" class="bg-chip text-white" label>{{ rom.revision }}</v-chip>
<v-chip v-show="rom.region" size="x-small" class="bg-chip" label>{{ rom.region }}</v-chip>
<v-chip v-show="rom.revision" size="x-small" class="bg-chip" label>{{ rom.revision }}</v-chip>
</v-chip-group>
</v-row>
</div>
<div class="mb-10" :class="{'info-content': mdAndUp, 'info-content-tablet': sm, 'info-content-mobile': xs}">
<v-tabs v-model="tab" slider-color="secondary">
<v-tab value="info">Info</v-tab>
<v-tab value="saves" disabled>Saves</v-tab>
<v-tab value="screenshots" disabled>Screenshots</v-tab>
<v-tabs v-model="tab" slider-color="rommAccent1" >
<v-tab value="info" rounded="0">Info</v-tab>
<v-tab value="saves" rounded="0" disabled>Saves</v-tab>
<v-tab value="screenshots" rounded="0" disabled>Screenshots</v-tab>
</v-tabs>
<v-window v-model="tab" class="mt-2">
<v-window-item value="info">
<v-row v-if="!rom.multi" class="d-flex align-center text-body-1 mt-0">
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><p>File</p></v-col>
<v-col class="text-body-1"><p>{{ rom.file_name }}</p></v-col>
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><span>File</span></v-col>
<v-col class="text-body-1"><span>{{ rom.file_name }}</span></v-col>
</v-row>
<v-row v-if="rom.multi" class="d-flex align-center text-body-1 mt-0">
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><p>Files</p></v-col>
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><span>Files</span></v-col>
<v-col><v-select :label="rom.file_name" item-title="file_name" v-model="filesToDownload" :items="rom.files" class="mt-2 mb-2" density="compact" variant="outlined" return-object multiple hide-details clearable chips/></v-col>
</v-row>
<v-row class="d-flex align-center text-body-1 mt-0">
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><p>Size</p></v-col>
<v-col><p>{{ rom.file_size }} {{ rom.file_size_units }}</p></v-col>
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><span>Size</span></v-col>
<v-col><span>{{ rom.file_size }} {{ rom.file_size_units }}</span></v-col>
</v-row>
<v-row v-if="rom.r_igdb_id!=''" class="d-flex align-center text-body-1 mt-0">
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><p>IGDB</p></v-col>
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><span>IGDB</span></v-col>
<v-col>
<v-chip variant="outlined" :href="'https://www.igdb.com/games/'+rom.r_slug" label>{{ rom.r_igdb_id }}</v-chip>
</v-col>
</v-row>
<v-row v-if="rom.tags.length>0" class="d-flex align-center text-body-1 mt-0">
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><p>Tags</p></v-col>
<v-col><v-chip-group class="pt-0"><v-chip v-for="tag in rom.tags" class="bg-chip" label>{{ tag }}</v-chip></v-chip-group></v-col>
<v-col cols="3" xs="3" sm="2" md="2" lg="2" class="font-weight-medium"><span>Tags</span></v-col>
<v-col><v-chip-group class="pt-0"><v-chip v-for="tag in rom.tags" :key="tag" class="bg-chip" label>{{ tag }}</v-chip></v-chip-group></v-col>
</v-row>
<v-row class="d-flex mt-3">
<v-col class="font-weight-medium text-caption"><p>{{ rom.summary }}</p></v-col>
@@ -208,10 +213,10 @@ async function deleteRom() {
</v-row>
</div>
<v-dialog v-model="dialogSearchRom" scroll-strategy="none" width="auto" :scrim="false">
<v-dialog v-model="dialogSearchRom" scroll-strategy="none" width="auto" :scrim="false" v-if="rom !== undefined">
<v-card :class="{'search-content': mdAndUp, 'search-content-tablet': sm, 'search-content-mobile': xs}">
<v-toolbar class="bg-primary pl-1 pr-1">
<v-toolbar class="bg-primary" density="compact">
<v-toolbar-title v-show="searching">Searching...</v-toolbar-title>
<v-toolbar-title v-show="!searching"><span>Results found</span></v-toolbar-title>
<v-btn icon @click="dialogSearchRom=false" class="ml-1" rounded="0"><v-icon>mdi-close</v-icon></v-btn>
@@ -219,7 +224,7 @@ async function deleteRom() {
<v-divider class="border-opacity-25" :thickness="1"/>
<v-card-text class="pa-3 scroll justify-center align-center bg-background">
<v-card-text class="pa-3 scroll justify-center align-center bg-secondary">
<v-row>
<v-text-field
@keyup.enter="searchRomIGDB()"
@@ -234,16 +239,16 @@ async function deleteRom() {
hide-details
clearable/>
</v-row>
<v-row class="justify-center align-center loader-searching" v-show="searching"><v-progress-circular :width="2" :size="40" class="pa-3 ma-3" color="secondary" indeterminate/></v-row>
<v-row class="justify-center align-center no-results-searching" v-show="!searching && matchedRoms.length==0" ><p>No results found</p></v-row>
<v-row class="justify-center align-center loader-searching" v-show="searching"><v-progress-circular :width="2" :size="40" class="pa-3 ma-3" color="rommAccent1" indeterminate/></v-row>
<v-row class="justify-center align-center no-results-searching" v-show="!searching && matchedRoms.length==0" ><span>No results found</span></v-row>
<v-row class="pl-4 pr-4">
<v-col cols="6" xs="6" sm="4" md="3" lg="3" v-show="!searching" v-for="rom in matchedRoms">
<v-col cols="6" xs="6" sm="4" md="3" lg="3" v-show="!searching" v-for="rom in matchedRoms" :key="rom.file_name">
<v-hover v-slot="{isHovering, props}">
<v-card @click="updateRom(rom, undefined)" v-bind="props" :class="{'on-hover': isHovering}" :elevation="isHovering ? 20 : 3">
<v-card @click="updateRom(updatedData=rom)" v-bind="props" :class="{'on-hover': isHovering}" :elevation="isHovering ? 20 : 3">
<v-img v-bind="props" :src="rom.url_cover" cover/>
<v-card-text>
<v-row class="pa-2">
<span class="d-inline-block text-truncate">{{ rom.name }}</span>
<span class="d-inline-block text-truncate">{{ rom.r_name }}</span>
</v-row>
</v-card-text>
</v-card>
@@ -261,35 +266,38 @@ async function deleteRom() {
</v-card>
</v-dialog>
<v-dialog v-model="dialogEditRom" scroll-strategy="none" width="auto" :scrim="false">
<v-dialog v-model="dialogEditRom" scroll-strategy="none" width="auto" :scrim="false" v-if="rom !== undefined">
<v-card rounded="0" :class="{'edit-content': mdAndUp, 'edit-content-tablet': sm, 'edit-content-mobile': xs}">
<v-toolbar class="bg-primary pl-1 pr-1">
<v-toolbar-title><span>Editing {{ rom.file_name }}</span></v-toolbar-title>
<v-toolbar class="bg-primary" density="compact">
<v-toolbar-title><span>Editing</span></v-toolbar-title>
<v-btn icon @click="dialogEditRom=false" class="ml-1" rounded="0"><v-icon>mdi-close</v-icon></v-btn>
</v-toolbar>
<v-divider class="border-opacity-25" :thickness="1"/>
<v-card-text class="pt-5 bg-background">
<v-card-text class="bg-secondary">
<v-form @submit.prevent class="ma-4">
<v-text-field @keyup.enter="updateRom()" v-model="editedRomName" label="File name" variant="outlined" required/>
<v-text-field @keyup.enter="updateRom()" v-model="updatedRom.file_name" label="File name" variant="outlined" required/>
<v-file-input @keyup.enter="updateRom()" label="Custom cover" prepend-inner-icon="mdi-image" prepend-icon="" variant="outlined" disabled/>
<v-btn type="submit" @click="updateRom(undefined, editedRomName)" class="mt-2 bg-rommGreen" block>Apply</v-btn>
</v-form>
<v-row class="justify-center mb-2">
<v-btn type="submit" @click="updateRom()" class="bg-rommGreen">Apply</v-btn>
<v-btn @click="dialogEditRom=false" class="ml-5" variant="tonal">Cancel</v-btn>
</v-row>
</v-card-text>
</v-card>
</v-dialog>
<v-dialog v-model="dialogDeleteRom" width="auto">
<v-dialog v-model="dialogDeleteRom" width="auto" v-if="rom !== undefined">
<v-card rounded="0" max-width="600">
<v-toolbar class="bg-red pl-1 pr-1">
<v-toolbar class="bg-red" density="compact">
<v-toolbar-title><span>Deleting {{ rom.file_name }}</span></v-toolbar-title>
<v-btn icon @click="dialogDeleteRom=false" class="ml-1" rounded="0"><v-icon>mdi-close</v-icon></v-btn>
</v-toolbar>
<v-divider class="border-opacity-25" :thickness="1"/>
<v-card-text class="bg-background">
<v-card-text class="bg-secondary">
<v-row class="justify-center ma-2">
<span>Deleting from RomM. Do you confirm?</span>
</v-row>
@@ -307,8 +315,8 @@ async function deleteRom() {
</v-card>
</v-dialog>
<v-dialog v-model="updating" scroll-strategy="none" width="auto" persistent>
<v-progress-circular :width="3" :size="70" color="secondary" indeterminate/>
<v-dialog :model-value="updating || loading" scroll-strategy="none" width="auto" :scrim="updating" persistent>
<v-progress-circular :width="3" :size="70" color="rommAccent1" indeterminate/>
</v-dialog>
</template>
@@ -318,6 +326,7 @@ async function deleteRom() {
overflow-y: scroll
}
.content, .content-tablet{
margin-top: 64px;
margin-left: 100px;
margin-right: 100px;
}
@@ -334,7 +343,7 @@ async function deleteRom() {
padding-left: 25px;
padding-right: 25px;
}
.info-header{
.rom-name, .rom-platform {
text-shadow: 1px 1px 3px #000000, 0 0 3px #000000;
}
.info-content{

View File

@@ -1,78 +1,98 @@
<script setup>
import axios from 'axios'
import { ref, inject, onMounted } from 'vue'
import { normalizeString, views } from '@/utils/utils.js'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import { useDisplay } from "vuetify"
import { views } from '@/utils/utils.js'
import { storeFilter } from '@/stores/filter.js'
import { storeGalleryView } from '@/stores/galleryView.js'
import { storeContextBar } from '@/stores/contextBar.js'
import { normalizeString } from '@/utils/utils.js'
import AppBar from '@/components/AppBar/Base.vue'
import GalleryViewBtn from '@/components/AppBar/Gallery/GalleryViewBtn.vue'
import FilterBar from '@/components/AppBar/Gallery/FilterBar.vue'
import GameCard from '@/components/GameGallery/Card/Base.vue'
import GameListHeader from '@/components/GameGallery/ListItem/Header.vue'
import GameListItem from '@/components/GameGallery/ListItem/Item.vue'
import NoRoms from '@/components/GameGallery/NoRoms.vue'
const route = useRoute()
// Props
const roms = ref([])
const gettingRoms = ref(false)
const noRoms = ref(false)
const roms = ref([])
const filter = storeFilter()
const romsFiltered = ref([])
const currentFilter = ref('')
const currentView = ref(JSON.parse(localStorage.getItem('currentView')) || 0)
const galleryView = storeGalleryView()
const contextBar = storeContextBar()
const { mdAndDown, lgAndUp } = useDisplay()
// Event listeners bus
const emitter = inject('emitter')
emitter.on('selectedPlatform', (platform) => { getRoms(platform.slug) })
emitter.on('filter', (filter) => { setFilter(filter) })
emitter.on('currentView', (view) => { currentView.value = view })
emitter.on('filter', () => { filterRoms() })
// Functions
async function getRoms(platform) {
noRoms.value = false
emitter.emit('gettingRoms', true)
gettingRoms.value = true
await axios.get('/api/platforms/'+platform+'/roms').then((response) => {
roms.value = response.data.data
setFilter(currentFilter.value)
}).catch((error) => {console.log(error)})
emitter.emit('gettingRoms', false)
gettingRoms.value = false
if(roms.value.length==0){noRoms.value = true}
}
function setFilter(filter) {
currentFilter.value = normalizeString(filter)
function filterRoms() {
romsFiltered.value = roms.value.filter(rom => {
return normalizeString(rom.file_name).includes(currentFilter.value)
return normalizeString(rom.file_name).includes(filter.value)
})
}
onMounted(() => {
if(localStorage.getItem('selectedPlatform')){
getRoms(JSON.parse(localStorage.getItem('selectedPlatform')).slug)
}
})
async function getRoms(platform) {
gettingRoms.value = true
await axios.get('/api/platforms/'+platform+'/roms').then((response) => {
roms.value = response.data.data
filterRoms()
}).catch((error) => {console.log(error)})
gettingRoms.value = false
}
onMounted(async () => { getRoms(route.params.platform)})
onBeforeRouteUpdate(async (to, _) => { getRoms(to.params.platform) })
</script>
<template>
<v-row v-show="currentView != 2">
<app-bar v-if="mdAndDown"/>
<v-expand-transition>
<v-row v-if="contextBar.value || lgAndUp" class="d-flex transition-fast-in-fast-out justify-center align-center">
<filter-bar class="pa-1"/>
<gallery-view-btn class="bg-secondary mr-1"/>
</v-row>
</v-expand-transition>
<v-row v-if="galleryView.value != 2 && roms.length>0">
<v-col v-for="rom in romsFiltered"
:cols="views[currentView]['size-cols']"
:xs="views[currentView]['size-xs']"
:sm="views[currentView]['size-sm']"
:md="views[currentView]['size-md']"
:lg="views[currentView]['size-lg']"
:key="rom.file_name"
:cols="views[galleryView.value]['size-cols']"
:xs="views[galleryView.value]['size-xs']"
:sm="views[galleryView.value]['size-sm']"
:md="views[galleryView.value]['size-md']"
:lg="views[galleryView.value]['size-lg']"
class="pa-1">
<game-card :rom="rom"/>
</v-col>
</v-row>
<v-list v-show="currentView == 2" class="bg-background">
<game-list-header/>
<v-divider class="border-opacity-100 ml-3 mb-4 mr-3" color="secondary" :thickness="1"/>
<game-list-item v-for="rom in romsFiltered" :rom="rom"/>
</v-list>
<v-row v-if="galleryView.value == 2 && roms.length>0" class="justify-center">
<v-col class="pa-0">
<v-table class="bg-secondary">
<game-list-header />
<v-divider class="border-opacity-100 mb-4 ml-2 mr-2" color="rommAccent1" :thickness="1"/>
<tbody>
<game-list-item v-for="rom in romsFiltered" :key="rom.file_name" :rom="rom"/>
</tbody>
</v-table>
</v-col>
</v-row>
<no-roms :noRoms="noRoms" />
<v-row v-if="roms.length==0" class="d-flex justify-center align-center">
<div class="text-h6 mt-16">Feels cold here... <v-icon>mdi-emoticon-sad</v-icon></div>
</v-row>
<v-dialog v-model="gettingRoms" scroll-strategy="none" width="auto" :scrim="false" persistent>
<v-progress-circular color="secondary" :width="3" :size="70" indeterminate/>
<v-progress-circular color="rommAccent1" :width="3" :size="70" indeterminate/>
</v-dialog>
</template>

View File

@@ -0,0 +1,33 @@
<script setup>
import { ref } from 'vue'
import { storePlatforms } from '@/stores/platforms.js'
import AppBar from '@/components/AppBar/Base.vue'
import { useDisplay } from "vuetify"
// Props
const platforms = storePlatforms()
const totalGames = ref(platforms.value.reduce((accumulator, p) => { return accumulator + p.n_roms }, 0))
const { mdAndDown, lgAndUp } = useDisplay()
</script>
<template>
<app-bar v-if="mdAndDown"/>
<v-card class="mx-auto mt-10" max-width="1000" variant="text">
<v-img
:height="lgAndUp ? 220 : 95"
src="/assets/romm_complete.svg"
cover/>
<v-card-text class="d-flex justify-center">
<span class="text-overline">Total games: {{ totalGames }}</span>
</v-card-text>
</v-card>
</template>
<style scoped>
</style>

View File

@@ -0,0 +1,77 @@
<script setup>
import axios from "axios"
import { ref, inject } from "vue"
import { useDisplay } from "vuetify"
import { storePlatforms } from '@/stores/platforms.js'
import { storeScanning } from '@/stores/scanning.js'
import AppBar from '@/components/AppBar/Base.vue'
// Props
const platforms = storePlatforms()
const platformsToScan = ref([])
const scanning = storeScanning()
const fullScan = ref(false)
const { mdAndDown } = useDisplay()
// Event listeners bus
const emitter = inject('emitter')
// Functions
async function scan() {
scanning.set(true)
const _platforms = []
platformsToScan.value.forEach(p => { _platforms.push(p.fs_slug) })
await axios.get('/api/scan?platforms='+JSON.stringify(_platforms)+'&full_scan='+fullScan.value).then((response) => {
emitter.emit('snackbarScan', {'msg': response.data.msg, 'icon': 'mdi-check-bold', 'color': 'green'})
emitter.emit('refresh')
}).catch((error) => {
console.log(error)
emitter.emit('snackbarScan', {'msg': error.response.data.detail, 'icon': 'mdi-close-circle', 'color': 'red'})
})
scanning.set(false)
}
</script>
<template>
<app-bar v-if="mdAndDown"/>
<v-select
label="Platforms"
item-title="name"
v-model="platformsToScan"
:items="platforms.value"
density="comfortable"
variant="outlined"
multiple
return-object
clearable
hide-details
chips/>
<v-checkbox
v-model="fullScan"
label="Complete Rescan"
prepend-icon="mdi-cached"
hint="Rescan every rom, including already scanned roms"
persistent-hint/>
<v-btn
title="scan"
@click="scan()"
:disabled="scanning.value"
prepend-icon="mdi-magnify-scan"
rounded="0"
class="mt-7"
inset>
<span v-if="!scanning.value">Scan</span>
<v-progress-circular
v-show="scanning.value"
color="rommAccent1"
class="ml-3 mr-2"
:width="2"
:size="20"
indeterminate/>
</v-btn>
</template>

View File

@@ -0,0 +1,55 @@
<script setup>
import { ref } from "vue"
import { useTheme } from "vuetify"
import AppBar from '@/components/AppBar/Base.vue'
import { useDisplay } from "vuetify"
// Props
const theme = useTheme()
const darkMode = (localStorage.getItem('theme') == 'rommLight') ? ref(false) : ref(true)
const ROMM_VERSION = import.meta.env.VITE_ROMM_VERSION
const tab = ref('ui')
const { mdAndDown } = useDisplay()
// Functions
function toggleTheme() {
theme.global.name.value = darkMode.value ? "rommDark" : "rommLight"
darkMode.value ? localStorage.setItem('theme', 'rommDark') : localStorage.setItem('theme', 'rommLight')
}
</script>
<template>
<app-bar v-if="mdAndDown"/>
<v-tabs v-model="tab" slider-color="rommAccent1">
<v-tab value="saves" rounded="0" disabled>General<span class="text-caption text-truncate ml-1">{{ rail ? '' : '[comming soon]' }}</span></v-tab>
<v-tab value="ui" rounded="0">User Interface</v-tab>
</v-tabs>
<v-window v-model="tab" class="mt-2">
<v-window-item value="general">
</v-window-item>
<v-window-item value="ui">
<v-row class="ml-1">
<v-col>
<v-switch
@change="toggleTheme()"
v-model="darkMode"
prepend-icon="mdi-theme-light-dark"
hide-details
inset/>
</v-col>
</v-row>
</v-window-item>
</v-window>
<v-divider class="border-opacity-25 mt-2"/>
<div class="mt-4 text-caption">
<span class="text-rommAccent1">RomM</span><span> v{{ ROMM_VERSION }}</span>
</div>
</template>
<style scoped>
</style>

View File

@@ -1,6 +1,8 @@
// Plugins
import vue from '@vitejs/plugin-vue'
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
import { VitePWA } from 'vite-plugin-pwa'
import pluginRewriteAll from 'vite-plugin-rewrite-all'
// Utilities
import { defineConfig } from 'vite'
@@ -9,16 +11,28 @@ import { fileURLToPath, URL } from 'node:url'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
pluginRewriteAll(),
vue({
template: { transformAssetUrls }
}),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
vuetify({
autoImport: true,
styles: {
configFile: 'src/styles/settings.scss',
},
}),
VitePWA({
manifest: {
icons: [
{
src: "favicon.ico",
sizes: "256x256",
type: "image/ico",
purpose: "any maskable"
}
]
}
})
],
define: { 'process.env': {} },
resolve: {

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 51 KiB