Merge branch 'master' into rom-hashing-background-task

This commit is contained in:
Georges-Antoine Assi
2025-01-15 21:50:46 -05:00
174 changed files with 6285 additions and 3321 deletions

View File

@@ -37,7 +37,27 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Generate Docker metadata
- name: Generate Docker metadata (slim)
id: meta-slim
uses: docker/metadata-action@v5
with:
images: |
name=rommapp/romm
name=ghcr.io/rommapp/romm
flavor: |
latest=auto
suffix=-slim,onlatest=true
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
labels: |
org.opencontainers.image.version={{version}}-slim
org.opencontainers.image.title="rommapp/romm"
org.opencontainers.image.description="RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators."
org.opencontainers.image.licenses="AGPLv3"
- name: Generate Docker metadata (full)
id: meta
uses: docker/metadata-action@v5
with:
@@ -58,7 +78,20 @@ jobs:
run: |
sed -i 's/<version>/${{ steps.meta.outputs.version }}/' backend/__version__.py
- name: Build base image
- name: Build slim image
id: build-slim
uses: docker/build-push-action@v6
with:
file: docker/Dockerfile
context: .
push: true
platforms: linux/arm64,linux/amd64
tags: ${{ steps.meta-slim.outputs.tags }}
labels: ${{ steps.meta-slim.outputs.labels }}
target: slim-image
- name: Build full image
id: build-full
uses: docker/build-push-action@v6
with:
file: docker/Dockerfile
@@ -67,3 +100,4 @@ jobs:
platforms: linux/arm64,linux/amd64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
target: full-image

View File

@@ -50,7 +50,7 @@ jobs:
- name: Install dependencies
run: |
poetry install --sync
poetry sync --extras test
- name: Initiate database
run: |

View File

@@ -34,3 +34,8 @@ jobs:
- name: Run typecheck
run: npm run typecheck
working-directory: frontend
- name: Lockfile lint
run: |
[ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value | has("resolved") | not)) | .key' < package-lock.json)" ]
working-directory: frontend

View File

@@ -61,7 +61,6 @@ lint:
- yaml
- css
- postcss
- sass
- html
- markdown
- json

View File

@@ -10,7 +10,11 @@ Please note that this project adheres to the Contributor Covenant [code of condu
## Contributing to the Wiki
If you would like to contribute to the project's [documentation](https://github.com/rommapp/romm/wiki), reach out to the maintainers to get edit access. We welcome any contributions that help improve the documentation (new pages, updates, or corrections).
If you would like to contribute to the project's [documentation](https://github.com/rommapp/romm/wiki), open a pull request against [the wiki repo](https://github.com/rommapp/wiki). We welcome any contributions that help improve the documentation (new pages, updates, or corrections).
## Adding Translations
If you would like to translate the project into another language, create a new folder under the `frontend/src/locales` directory, and follow the existing language files as a template. Once you've created the new language file, open a pull request to add it to the project.
## How to Contribute Code

View File

@@ -45,14 +45,14 @@ Then create the virtual environment
```sh
# Fix disable parallel installation stuck: $> poetry config experimental.new-installer false
# Fix Loading macOS/linux stuck: $> export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring
poetry install --sync
poetry sync
```
If you are on Arch Linux or another Arch-based distro, you need to run the command as follows:
```sh
# https://bbs.archlinux.org/viewtopic.php?id=296542
CFLAGS="-Wno-error=incompatible-pointer-types" poetry install --sync
CFLAGS="-Wno-error=incompatible-pointer-types" poetry sync
```
#### - Spin up mariadb in docker

View File

@@ -40,13 +40,13 @@
# Overview
RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes, and custom tags, RomM is a must-have for anyone who plays on emulators.
RomM (ROM Manager) allows you to scan, enrich, browse and play your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes, and custom tags, RomM is a must-have for anyone who plays on emulators.
## Features
- Scans your existing games library and enhances it with metadata from [IGDB][igdb-api] and [MobyGames][mobygames-api]
- Supports a large number of **[platforms][platform-support]**
- Play games directly from the browser using [EmulatorJS][wiki-emulatorjs]
- Play games directly from the browser using [EmulatorJS][wiki-emulatorjs] and RuffleRS
- Share your library with friends while [limiting access and permissions][wiki-authentication]
- Supports MAME, Nintendo Switch, and Sony Playstation naming schemes
- Detects and groups **multifile games** (e.g. PS1 games with multiple CDs)
@@ -61,14 +61,7 @@ RomM (ROM Manager) allows you to scan, enrich, and browse your game collection w
# Installation
Before running the [image][docker-tags], please ensure that Docker is installed and running on your system.
1. [Generate API keys][wiki-generate-api-keys] for IGDB and/or MobyGames to fetch metadata.
2. Verify that your library folder structure matches one of the options listed in the [folder structure][folder-structure] section.
3. Create a docker-compose.yml file by referring to the example [docker-compose.yml][docker-compose-example] file for guidance, and customize it for your setup with [the available environment variables][wiki-env-variables].
4. Launch the container(s) with `docker-compose up -d`.
> [!NOTE] > **If you are having issues with RomM, please review the [wiki page][wiki-troubleshooting] for troubleshooting steps and common issues.**
To start using RomM, check out the [Quick Start Guide][wiki-quick-start-guide] in the wiki. If you are having issues with RomM, please review the page for [troubleshooting steps][wiki-troubleshooting] and common issues, or join the [Discord][discord-invite] for support from the community.
# Configuration
@@ -202,7 +195,8 @@ Here are a few projects that we think you might like:
- [EmulatorJS](https://emulatorjs.org/): An embeddable, browser-based emulator
- [RetroDECK](https://retrodeck.net/): Retro gaming on SteamOS and Linux
- [ES-DE Frontend](https://es-de.org/): Emulator frontend for Linux, macOS and Windows
- [Gaseous](https://github.com/gaseous-project/gaseous-server): Another self-hosted ROM manager
- [Gaseous](https://github.com/gaseous-project/gaseous-server): Another ROM manager with web-based emulator
- [Retrom](https://github.com/JMBeresford/retrom): A centralized game library/collection management service
- [Steam ROM Manager](https://steamgriddb.github.io/steam-rom-manager/): An app for managing ROMs in Steam
<!-- Sections -->
@@ -225,9 +219,8 @@ Here are a few projects that we think you might like:
[wiki-platforms-icons]: https://github.com/rommapp/romm/wiki/Custom-Platform-Icons
[wiki-troubleshooting]: https://github.com/rommapp/romm/wiki/Troubleshooting
[wiki-emulatorjs]: https://github.com/rommapp/romm/wiki/EmulatorJS-Player
[wiki-env-variables]: https://github.com/rommapp/romm/wiki/Environment-Variables
[wiki-scheduled-tasks]: https://github.com/rommapp/romm/wiki/Scheduled-Tasks
[wiki-generate-api-keys]: https://github.com/rommapp/romm/wiki/Generate-API-Keys
[wiki-quick-start-guide]: https://github.com/rommapp/romm/wiki/Quick-Start-Guide
<!-- Badges -->
@@ -247,12 +240,11 @@ Here are a few projects that we think you might like:
[discord-invite-img]: https://invidget.switchblade.xyz/P5HtHnhUDH
[discord-invite]: https://discord.gg/P5HtHnhUDH
[oc-donate-img]: https://opencollective.com/romm/donate/button@2x.png?color=blue
[oc-donate-img]: https://opencollective.com/romm/donate/button.png?color=blue
[oc-donate]: https://opencollective.com/romm
<!-- External links -->
[docker-tags]: https://hub.docker.com/r/rommapp/romm/tags
[igdb-api]: https://api-docs.igdb.com/#account-creation
[mobygames-api]: https://www.mobygames.com/info/api/
[big-bear-casaos]: https://github.com/bigbeartechworld/big-bear-casaos

View File

@@ -8,8 +8,8 @@ Create Date: 2023-09-12 18:18:27.158732
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from sqlalchemy.exc import OperationalError
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "0009_models_refactor"
@@ -19,23 +19,30 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
try:
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"igdb_id", existing_type=mysql.VARCHAR(length=10), nullable=True
"igdb_id", existing_type=sa.VARCHAR(length=10), nullable=True
)
batch_op.alter_column(
"sgdb_id", existing_type=mysql.VARCHAR(length=10), nullable=True
"sgdb_id", existing_type=sa.VARCHAR(length=10), nullable=True
)
batch_op.alter_column(
"slug", existing_type=mysql.VARCHAR(length=50), nullable=False
"slug", existing_type=sa.VARCHAR(length=50), nullable=False
)
batch_op.alter_column(
"name", existing_type=mysql.VARCHAR(length=400), nullable=True
"name", existing_type=sa.VARCHAR(length=400), nullable=True
)
# Move primary key to slug
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(
constraint_name=pk_constraint_name, type_="primary"
)
batch_op.create_primary_key(constraint_name=None, columns=["slug"])
except ValueError as e:
print(f"Cannot drop primary key on platforms table: {e}")
@@ -45,46 +52,46 @@ def upgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.alter_column(
"r_igdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
new_column_name="igdb_id",
)
batch_op.alter_column(
"r_sgdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
new_column_name="sgdb_id",
)
batch_op.alter_column(
"r_slug", existing_type=mysql.VARCHAR(length=400), new_column_name="slug"
"r_slug", existing_type=sa.VARCHAR(length=400), new_column_name="slug"
)
batch_op.alter_column(
"r_name", existing_type=mysql.VARCHAR(length=350), new_column_name="name"
"r_name", existing_type=sa.VARCHAR(length=350), new_column_name="name"
)
batch_op.alter_column(
"p_slug",
existing_type=mysql.VARCHAR(length=50),
existing_type=sa.VARCHAR(length=50),
new_column_name="platform_slug",
nullable=False,
)
batch_op.alter_column(
"file_extension", existing_type=mysql.VARCHAR(length=10), nullable=False
"file_extension", existing_type=sa.VARCHAR(length=10), nullable=False
)
batch_op.alter_column(
"file_path", existing_type=mysql.VARCHAR(length=1000), nullable=False
"file_path", existing_type=sa.VARCHAR(length=1000), nullable=False
)
batch_op.alter_column("file_size", existing_type=mysql.FLOAT(), nullable=False)
batch_op.alter_column("file_size", existing_type=sa.FLOAT(), nullable=False)
batch_op.alter_column(
"file_size_units", existing_type=mysql.VARCHAR(length=10), nullable=False
"file_size_units", existing_type=sa.VARCHAR(length=10), nullable=False
)
batch_op.alter_column(
"url_screenshots",
existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"),
existing_type=CustomJSON(),
nullable=True,
existing_server_default=sa.text("(JSON_ARRAY())"),
)
batch_op.alter_column(
"path_screenshots",
existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"),
existing_type=CustomJSON(),
nullable=True,
existing_server_default=sa.text("(JSON_ARRAY())"),
)
@@ -99,51 +106,53 @@ def upgrade() -> None:
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.alter_column(
"igdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
new_column_name="r_igdb_id",
)
batch_op.alter_column(
"sgdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
new_column_name="r_sgdb_id",
)
batch_op.alter_column(
"slug", existing_type=mysql.VARCHAR(length=400), new_column_name="r_slug"
"slug", existing_type=sa.VARCHAR(length=400), new_column_name="r_slug"
)
batch_op.alter_column(
"name", existing_type=mysql.VARCHAR(length=350), new_column_name="r_name"
"name", existing_type=sa.VARCHAR(length=350), new_column_name="r_name"
)
batch_op.alter_column(
"platform_slug",
existing_type=mysql.VARCHAR(length=50),
existing_type=sa.VARCHAR(length=50),
new_column_name="p_slug",
nullable=True,
)
batch_op.alter_column(
"path_screenshots",
existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"),
existing_type=CustomJSON(),
nullable=False,
existing_server_default=sa.text("(JSON_ARRAY())"),
)
batch_op.alter_column(
"url_screenshots",
existing_type=mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"),
existing_type=CustomJSON(),
nullable=False,
existing_server_default=sa.text("(JSON_ARRAY())"),
)
batch_op.alter_column(
"file_size_units", existing_type=mysql.VARCHAR(length=10), nullable=True
"file_size_units", existing_type=sa.VARCHAR(length=10), nullable=True
)
batch_op.alter_column("file_size", existing_type=mysql.FLOAT(), nullable=True)
batch_op.alter_column("file_size", existing_type=sa.FLOAT(), nullable=True)
batch_op.alter_column(
"file_path", existing_type=mysql.VARCHAR(length=1000), nullable=True
"file_path", existing_type=sa.VARCHAR(length=1000), nullable=True
)
batch_op.alter_column(
"file_extension", existing_type=mysql.VARCHAR(length=10), nullable=True
"file_extension", existing_type=sa.VARCHAR(length=10), nullable=True
)
try:
@@ -156,12 +165,18 @@ def downgrade() -> None:
try:
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"slug", existing_type=mysql.VARCHAR(length=50), nullable=True
# Move primary key back to fs_slug
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(
constraint_name=pk_constraint_name, type_="primary"
)
batch_op.alter_column(
"slug", existing_type=sa.VARCHAR(length=50), nullable=True
)
# Move primary key back to fs_slug
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
batch_op.create_primary_key(constraint_name=None, columns=["fs_slug"])
print("Moved primary key back to fs_slug column on platforms table")
except ValueError as e:

View File

@@ -8,7 +8,6 @@ Create Date: 2023-09-14 09:57:13.487331
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "0010_igdb_id_integerr"
@@ -18,43 +17,44 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.execute('UPDATE platforms SET igdb_id = NULL WHERE igdb_id = ""')
batch_op.execute('UPDATE platforms SET sgdb_id = NULL WHERE sgdb_id = ""')
batch_op.execute("UPDATE platforms SET igdb_id = NULL WHERE igdb_id = ''")
batch_op.execute("UPDATE platforms SET sgdb_id = NULL WHERE sgdb_id = ''")
batch_op.alter_column(
"igdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="igdb_id::integer",
)
batch_op.alter_column(
"sgdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="sgdb_id::integer",
)
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute('UPDATE roms SET igdb_id = NULL WHERE igdb_id = ""')
batch_op.execute('UPDATE roms SET sgdb_id = NULL WHERE sgdb_id = ""')
batch_op.execute("UPDATE roms SET igdb_id = NULL WHERE igdb_id = ''")
batch_op.execute("UPDATE roms SET sgdb_id = NULL WHERE sgdb_id = ''")
batch_op.alter_column(
"igdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="igdb_id::integer",
)
batch_op.alter_column(
"sgdb_id",
existing_type=mysql.VARCHAR(length=10),
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="sgdb_id::integer",
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
@@ -62,13 +62,13 @@ def downgrade() -> None:
batch_op.alter_column(
"sgdb_id",
existing_type=sa.Integer(),
type_=mysql.VARCHAR(length=10),
type_=sa.VARCHAR(length=10),
existing_nullable=True,
)
batch_op.alter_column(
"igdb_id",
existing_type=sa.Integer(),
type_=mysql.VARCHAR(length=10),
type_=sa.VARCHAR(length=10),
existing_nullable=True,
)
@@ -76,13 +76,13 @@ def downgrade() -> None:
batch_op.alter_column(
"sgdb_id",
existing_type=sa.Integer(),
type_=mysql.VARCHAR(length=10),
type_=sa.VARCHAR(length=10),
existing_nullable=True,
)
batch_op.alter_column(
"igdb_id",
existing_type=sa.Integer(),
type_=mysql.VARCHAR(length=10),
type_=sa.VARCHAR(length=10),
existing_nullable=True,
)

View File

@@ -8,7 +8,6 @@ Create Date: 2023-09-16 15:28:29.221475
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "0011_drop_has_cover"
@@ -31,7 +30,7 @@ def downgrade() -> None:
batch_op.add_column(
sa.Column(
"has_cover",
mysql.BOOLEAN(),
sa.BOOLEAN(),
autoincrement=False,
nullable=True,
)

View File

@@ -8,7 +8,7 @@ Create Date: 2023-12-03 10:54:46.859106
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from utils.database import CustomJSON, is_postgresql
# revision identifiers, used by Alembic.
revision = "0012_add_regions_languages"
@@ -20,12 +20,12 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(sa.Column("regions", sa.JSON(), nullable=True))
batch_op.add_column(sa.Column("languages", sa.JSON(), nullable=True))
batch_op.add_column(sa.Column("regions", CustomJSON(), nullable=True))
batch_op.add_column(sa.Column("languages", CustomJSON(), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
# Set default values for languages and regions
batch_op.execute("UPDATE roms SET languages = '[]'")
batch_op.execute("UPDATE roms SET languages = JSON_ARRAY()")
batch_op.execute("UPDATE roms SET regions = JSON_ARRAY(region)")
batch_op.drop_column("region")
@@ -33,15 +33,15 @@ def upgrade() -> None:
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(
sa.Column("region", mysql.VARCHAR(length=20), nullable=True)
)
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("UPDATE roms SET region = JSON_EXTRACT(regions, '$[0]')")
batch_op.add_column(sa.Column("region", sa.VARCHAR(length=20), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
if is_postgresql(connection):
batch_op.execute("UPDATE roms SET region = regions->>0")
else:
batch_op.execute("UPDATE roms SET region = JSON_EXTRACT(regions, '$[0]')")
batch_op.drop_column("languages")
batch_op.drop_column("regions")
# ### end Alembic commands ###

View File

@@ -13,8 +13,8 @@ from alembic import op
from config import ROMM_DB_DRIVER
from config.config_manager import SQLITE_DB_BASE_PATH, ConfigManager
from sqlalchemy import create_engine, text
from sqlalchemy.dialects import mysql
from sqlalchemy.orm import sessionmaker
from utils.database import CustomJSON, is_postgresql
# revision identifiers, used by Alembic.
revision = "0014_asset_files"
@@ -32,26 +32,28 @@ SIZE_UNIT_TO_BYTES = {
}
def migrate_to_mysql() -> None:
if ROMM_DB_DRIVER not in ("mariadb", "mysql"):
raise Exception("Version 3.0 requires MariaDB or MySQL as database driver!")
def migrate_to_supported_engine() -> None:
if ROMM_DB_DRIVER not in ("mariadb", "mysql", "postgresql"):
raise Exception(
"Version 3.0 requires MariaDB, MySQL, or PostgreSQL as database driver!"
)
# Skip if sqlite database is not mounted
if not os.path.exists(f"{SQLITE_DB_BASE_PATH}/romm.db"):
return
maria_engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
maria_session = sessionmaker(bind=maria_engine, expire_on_commit=False)
engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
session = sessionmaker(bind=engine, expire_on_commit=False)
sqlite_engine = create_engine(
f"sqlite:////{SQLITE_DB_BASE_PATH}/romm.db", pool_pre_ping=True
)
sqlite_session = sessionmaker(bind=sqlite_engine, expire_on_commit=False)
# Copy all data from sqlite to maria
with maria_session.begin() as maria_conn:
# Copy all data from sqlite to new database
with session.begin() as conn:
with sqlite_session.begin() as sqlite_conn:
maria_conn.execute(text("SET FOREIGN_KEY_CHECKS=0"))
conn.execute(text("SET FOREIGN_KEY_CHECKS=0"))
tables = sqlite_conn.execute(
text("SELECT name FROM sqlite_master WHERE type='table';")
@@ -67,20 +69,22 @@ def migrate_to_mysql() -> None:
text(f"SELECT * FROM {table_name}") # nosec B608
).fetchall()
# Insert data into MariaDB table
# Insert data into new tables
for row in table_data:
mapped_row = {f"{i}": value for i, value in enumerate(row, start=1)}
columns = ",".join([f":{i}" for i in range(1, len(row) + 1)])
insert_query = (
f"INSERT INTO {table_name} VALUES ({columns})" # nosec B608
)
maria_conn.execute(text(insert_query), mapped_row)
conn.execute(text(insert_query), mapped_row)
maria_conn.execute(text("SET FOREIGN_KEY_CHECKS=1"))
conn.execute(text("SET FOREIGN_KEY_CHECKS=1"))
def upgrade() -> None:
migrate_to_mysql()
migrate_to_supported_engine()
connection = op.get_bind()
op.create_table(
"saves",
@@ -154,13 +158,19 @@ def upgrade() -> None:
# Drop the primary key (slug)
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(constraint_name=pk_constraint_name, type_="primary")
batch_op.drop_column("n_roms")
# Switch to new id column as platform primary key
op.execute(
"ALTER TABLE platforms ADD COLUMN id INTEGER(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
)
if is_postgresql(connection):
op.execute("ALTER TABLE platforms ADD COLUMN id SERIAL PRIMARY KEY")
else:
op.execute(
"ALTER TABLE platforms ADD COLUMN id INTEGER(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
)
# Add new columns to roms table
with op.batch_alter_table("roms", schema=None) as batch_op:
@@ -170,27 +180,37 @@ def upgrade() -> None:
batch_op.add_column(
sa.Column("file_size_bytes", sa.BigInteger(), nullable=False)
)
batch_op.add_column(sa.Column("igdb_metadata", mysql.JSON(), nullable=True))
batch_op.add_column(sa.Column("igdb_metadata", CustomJSON(), nullable=True))
batch_op.add_column(sa.Column("platform_id", sa.Integer(), nullable=False))
batch_op.alter_column(
"revision",
existing_type=mysql.VARCHAR(length=20),
existing_type=sa.VARCHAR(length=20),
type_=sa.String(length=100),
existing_nullable=True,
)
# Move data around
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("update roms set igdb_metadata = '\\{\\}'")
batch_op.execute("update roms set igdb_metadata = JSON_OBJECT()")
batch_op.execute(
"update roms set path_cover_s = '', path_cover_l = '', url_cover = '' where url_cover = 'https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png'"
)
batch_op.execute(
"update roms set file_name_no_ext = regexp_replace(file_name, '\\.[a-z]{2,}$', '')"
)
batch_op.execute(
"update roms inner join platforms on roms.platform_slug = platforms.slug set roms.platform_id = platforms.id"
)
if is_postgresql(connection):
batch_op.execute(
"""
UPDATE roms
SET platform_id = platforms.id
FROM platforms
WHERE roms.platform_slug = platforms.slug
"""
)
else:
batch_op.execute(
"update roms inner join platforms on roms.platform_slug = platforms.slug set roms.platform_id = platforms.id"
)
# Process filesize data and prepare for bulk update
connection = op.get_bind()
@@ -225,36 +245,39 @@ def upgrade() -> None:
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(
sa.Column("platform_slug", mysql.VARCHAR(length=50), nullable=False)
sa.Column("platform_slug", sa.VARCHAR(length=50), nullable=False)
)
batch_op.add_column(
sa.Column("p_igdb_id", mysql.VARCHAR(length=10), nullable=True)
sa.Column("p_igdb_id", sa.VARCHAR(length=10), nullable=True)
)
batch_op.add_column(sa.Column("p_name", sa.VARCHAR(length=150), nullable=True))
batch_op.add_column(
sa.Column("p_sgdb_id", sa.VARCHAR(length=10), nullable=True)
)
batch_op.add_column(
sa.Column("p_name", mysql.VARCHAR(length=150), nullable=True)
sa.Column("file_size_units", sa.VARCHAR(length=10), nullable=False)
)
batch_op.add_column(
sa.Column("p_sgdb_id", mysql.VARCHAR(length=10), nullable=True)
)
batch_op.add_column(
sa.Column("file_size_units", mysql.VARCHAR(length=10), nullable=False)
)
batch_op.add_column(sa.Column("file_size", mysql.FLOAT(), nullable=False))
batch_op.add_column(sa.Column("file_size", sa.FLOAT(), nullable=False))
batch_op.drop_constraint("fk_platform_id_roms", type_="foreignkey")
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.create_foreign_key(
"fk_platform_roms",
"platforms",
["platform_slug"],
["slug"],
ondelete="CASCADE",
)
batch_op.execute(
"update roms inner join platforms on roms.platform_id = platforms.id set roms.platform_slug = platforms.slug"
)
if is_postgresql(connection):
batch_op.execute(
"""
UPDATE roms
SET platform_slug = platforms.slug
FROM platforms
WHERE roms.platform_id = platforms.id
"""
)
else:
batch_op.execute(
"update roms inner join platforms on roms.platform_id = platforms.id set roms.platform_slug = platforms.slug"
)
batch_op.execute(
"update roms set url_cover = 'https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png' where url_cover = ''"
)
@@ -286,7 +309,7 @@ def downgrade() -> None:
batch_op.alter_column(
"revision",
existing_type=sa.String(length=100),
type_=mysql.VARCHAR(length=20),
type_=sa.VARCHAR(length=20),
existing_nullable=True,
)
@@ -294,12 +317,22 @@ def downgrade() -> None:
batch_op.add_column(
sa.Column(
"n_roms",
mysql.INTEGER(display_width=11),
sa.INTEGER(),
autoincrement=False,
nullable=True,
)
)
batch_op.drop_column("id")
batch_op.create_primary_key(constraint_name=None, columns=["slug"])
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.create_foreign_key(
"fk_platform_roms",
"platforms",
["platform_slug"],
["slug"],
ondelete="CASCADE",
)
op.drop_table("states")
op.drop_table("screenshots")

View File

@@ -8,7 +8,7 @@ Create Date: 2024-02-13 17:57:25.936825
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "0015_mobygames_data"
@@ -24,10 +24,10 @@ def upgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(sa.Column("moby_id", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("moby_metadata", mysql.JSON(), nullable=True))
batch_op.add_column(sa.Column("moby_metadata", CustomJSON(), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("update roms set moby_metadata = '\\{\\}'")
batch_op.execute("update roms set moby_metadata = JSON_OBJECT()")
# ### end Alembic commands ###

View File

@@ -85,7 +85,7 @@ def upgrade() -> None:
connection.execute(
sa.text(
"""
UPDATE roms
UPDATE roms
SET path_cover_s = :path_cover_s,
path_cover_l = :path_cover_l,
path_screenshots = :path_screenshots

View File

@@ -14,7 +14,7 @@ import sqlalchemy as sa
from alembic import op
from config import RESOURCES_BASE_PATH
from sqlalchemy import inspect
from sqlalchemy.dialects import mysql
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "0022_collections"
@@ -95,7 +95,7 @@ def upgrade() -> None:
sa.Column("path_cover_l", sa.String(length=1000), nullable=True),
sa.Column("path_cover_s", sa.String(length=1000), nullable=True),
sa.Column("url_cover", sa.Text(), nullable=True),
sa.Column("roms", sa.JSON(), nullable=False),
sa.Column("roms", CustomJSON(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("is_public", sa.Boolean(), nullable=False),
sa.Column(
@@ -117,7 +117,7 @@ def upgrade() -> None:
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.alter_column(
"is_main_sibling",
existing_type=mysql.TINYINT(display_width=1),
existing_type=sa.Boolean(),
nullable=True,
)
# ### end Alembic commands ###
@@ -128,7 +128,7 @@ def downgrade() -> None:
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.alter_column(
"is_main_sibling",
existing_type=mysql.TINYINT(display_width=1),
existing_type=sa.Boolean(),
nullable=False,
)

View File

@@ -8,6 +8,7 @@ Create Date: 2024-07-07 13:44:25.811184
import sqlalchemy as sa
from alembic import op
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "0023_make_columns_non_nullable"
@@ -17,6 +18,9 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
false_value = "FALSE" if is_postgresql(connection) else "0"
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.execute("UPDATE platforms SET name = '' WHERE name IS NULL")
batch_op.alter_column(
@@ -25,20 +29,22 @@ def upgrade() -> None:
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.execute(
"UPDATE rom_user SET note_is_public = 0 WHERE note_is_public IS NULL"
f"UPDATE rom_user SET note_is_public = {false_value} WHERE note_is_public IS NULL" # nosec B608
)
batch_op.alter_column(
"note_is_public", existing_type=sa.Boolean(), nullable=False
)
batch_op.execute(
"UPDATE rom_user SET is_main_sibling = 0 WHERE is_main_sibling IS NULL"
f"UPDATE rom_user SET is_main_sibling = {false_value} WHERE is_main_sibling IS NULL" # nosec B608
)
batch_op.alter_column(
"is_main_sibling", existing_type=sa.Boolean(), nullable=False
)
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("UPDATE roms SET multi = 0 WHERE multi IS NULL")
batch_op.execute(
f"UPDATE roms SET multi = {false_value} WHERE multi IS NULL" # nosec B608
)
batch_op.alter_column("multi", existing_type=sa.Boolean(), nullable=False)
with op.batch_alter_table("users", schema=None) as batch_op:
@@ -46,7 +52,9 @@ def upgrade() -> None:
batch_op.alter_column(
"username", existing_type=sa.String(length=255), nullable=False
)
batch_op.execute("UPDATE users SET enabled = 0 WHERE enabled IS NULL")
batch_op.execute(
f"UPDATE users SET enabled = {false_value} WHERE enabled IS NULL" # nosec B608
)
batch_op.alter_column("enabled", existing_type=sa.Boolean(), nullable=False)

View File

@@ -8,6 +8,7 @@ Create Date: 2024-08-08 12:00:00.000000
import sqlalchemy as sa
from alembic import op
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "0024_sibling_roms_db_view"
@@ -22,10 +23,13 @@ def upgrade() -> None:
batch_op.create_index("idx_roms_moby_id", ["moby_id"])
connection = op.get_bind()
null_safe_equal_operator = (
"IS NOT DISTINCT FROM" if is_postgresql(connection) else "<=>"
)
connection.execute(
sa.text(
"""
f"""
CREATE VIEW sibling_roms AS
SELECT
r1.id AS rom_id,
@@ -33,21 +37,21 @@ def upgrade() -> None:
r1.platform_id AS platform_id,
NOW() AS created_at,
NOW() AS updated_at,
CASE WHEN r1.igdb_id <=> r2.igdb_id THEN r1.igdb_id END AS igdb_id,
CASE WHEN r1.moby_id <=> r2.moby_id THEN r1.moby_id END AS moby_id
CASE WHEN r1.igdb_id {null_safe_equal_operator} r2.igdb_id THEN r1.igdb_id END AS igdb_id,
CASE WHEN r1.moby_id {null_safe_equal_operator} r2.moby_id THEN r1.moby_id END AS moby_id
FROM
roms r1
JOIN
roms r2
ON
JOIN
roms r2
ON
r1.platform_id = r2.platform_id
AND r1.id != r2.id
AND (
(r1.igdb_id = r2.igdb_id AND r1.igdb_id IS NOT NULL AND r1.igdb_id != '')
(r1.igdb_id = r2.igdb_id AND r1.igdb_id IS NOT NULL)
OR
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL AND r1.moby_id != '')
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
);
"""
""" # nosec B608
),
)

View File

@@ -8,7 +8,8 @@ Create Date: 2024-08-29 15:52:56.031850
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from sqlalchemy.dialects.postgresql import ENUM
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "0026_romuser_status_fields"
@@ -18,20 +19,42 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_l",
existing_type=mysql.VARCHAR(length=1000),
existing_type=sa.VARCHAR(length=1000),
type_=sa.Text(),
existing_nullable=True,
)
batch_op.alter_column(
"path_cover_s",
existing_type=mysql.VARCHAR(length=1000),
existing_type=sa.VARCHAR(length=1000),
type_=sa.Text(),
existing_nullable=True,
)
if is_postgresql(connection):
rom_user_status_enum = ENUM(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
create_type=False,
)
rom_user_status_enum.create(connection, checkfirst=False)
else:
rom_user_status_enum = sa.Enum(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
)
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.add_column(
sa.Column("last_played", sa.DateTime(timezone=True), nullable=True)
@@ -42,23 +65,12 @@ def upgrade() -> None:
batch_op.add_column(sa.Column("rating", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("difficulty", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("completion", sa.Integer(), nullable=False))
batch_op.add_column(
sa.Column(
"status",
sa.Enum(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
),
nullable=True,
)
)
batch_op.add_column(sa.Column("status", rom_user_status_enum, nullable=True))
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.drop_column("status")
batch_op.drop_column("completion")
@@ -69,16 +81,19 @@ def downgrade() -> None:
batch_op.drop_column("backlogged")
batch_op.drop_column("last_played")
if is_postgresql(connection):
ENUM(name="romuserstatus").drop(connection, checkfirst=False)
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_s",
existing_type=sa.Text(),
type_=mysql.VARCHAR(length=1000),
type_=sa.VARCHAR(length=1000),
existing_nullable=True,
)
batch_op.alter_column(
"path_cover_l",
existing_type=sa.Text(),
type_=mysql.VARCHAR(length=1000),
type_=sa.VARCHAR(length=1000),
existing_nullable=True,
)

View File

@@ -0,0 +1,25 @@
"""Change empty string in users.email to NULL.
Revision ID: 951473b0c581
Revises: 0029_platforms_custom_name
Create Date: 2025-01-14 01:30:39.696257
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "0030_user_email_null"
down_revision = "0029_platforms_custom_name"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.execute("UPDATE users SET email = NULL WHERE email = ''")
def downgrade() -> None:
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.execute("UPDATE users SET email = '' WHERE email IS NULL")

View File

@@ -9,6 +9,7 @@ Create Date: 2023-04-10 23:02:37.472055
import sqlalchemy as sa
from alembic import op
from sqlalchemy.exc import OperationalError
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "1.6.2"
@@ -50,7 +51,7 @@ def upgrade() -> None:
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("tags", CustomJSON(), nullable=True),
sa.PrimaryKeyConstraint("p_slug", "file_name"),
)
except OperationalError:

View File

@@ -8,6 +8,7 @@ Create Date: 2023-04-10 23:13:43.591414
import sqlalchemy as sa
from alembic import op
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "1.6.3"
@@ -20,7 +21,7 @@ def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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))
batch_op.add_column(sa.Column("files", CustomJSON(), nullable=True))
# ### end Alembic commands ###

View File

@@ -8,6 +8,7 @@ Create Date: 2023-04-17 12:03:19.163501
import sqlalchemy as sa
from alembic import op
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "1.8.1"
@@ -22,7 +23,7 @@ def upgrade() -> None:
batch_op.add_column(
sa.Column(
"url_screenshots",
sa.JSON(),
CustomJSON(),
nullable=False,
server_default=sa.text("(JSON_ARRAY())"),
)
@@ -30,7 +31,7 @@ def upgrade() -> None:
batch_op.add_column(
sa.Column(
"path_screenshots",
sa.JSON(),
CustomJSON(),
nullable=False,
server_default=sa.text("(JSON_ARRAY())"),
)

View File

@@ -7,6 +7,7 @@ Create Date: 2023-05-17 12:59:44.344356
"""
from alembic import op
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "1.8.3"
@@ -16,7 +17,7 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("roms") as batch_op:
batch_op.execute(
"UPDATE roms SET file_path = REPLACE(file_path, '/romm/library/', '')"
@@ -27,10 +28,14 @@ def upgrade() -> None:
batch_op.execute(
"UPDATE roms SET path_cover_l = REPLACE(path_cover_l, '/romm/resources/', '')"
)
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots, '/romm/resources/', '')"
)
# ### end Alembic commands ###
if is_postgresql(connection):
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots::text, '/romm/resources/', '')::jsonb"
)
else:
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots, '/romm/resources/', '')"
)
def downgrade() -> None:

View File

@@ -8,6 +8,7 @@ Create Date: 2023-04-17 12:03:19.163501
import sqlalchemy as sa
from alembic import op
from utils.database import CustomJSON
# revision identifiers, used by Alembic.
revision = "1.8"
@@ -78,9 +79,9 @@ def upgrade() -> None:
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("tags", CustomJSON(), nullable=True),
sa.Column("multi", sa.Boolean(), nullable=True),
sa.Column("files", sa.JSON(), nullable=True),
sa.Column("files", CustomJSON(), nullable=True),
sa.Column("url_cover", sa.Text(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)

View File

@@ -8,6 +8,8 @@ Create Date: 2023-08-10 22:18:24.012779
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "2.0.0"
@@ -39,9 +41,12 @@ def upgrade() -> None:
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_users_username"))
op.drop_table("users")
# ### end Alembic commands ###
if is_postgresql(connection):
ENUM(name="role").drop(connection, checkfirst=False)

View File

@@ -73,6 +73,7 @@ DISABLE_CSRF_PROTECTION = str_to_bool(
DISABLE_DOWNLOAD_ENDPOINT_AUTH = str_to_bool(
os.environ.get("DISABLE_DOWNLOAD_ENDPOINT_AUTH", "false")
)
DISABLE_USERPASS_LOGIN = str_to_bool(os.environ.get("DISABLE_USERPASS_LOGIN", "false"))
# OIDC
OIDC_ENABLED: Final = str_to_bool(os.environ.get("OIDC_ENABLED", "false"))
@@ -81,6 +82,7 @@ OIDC_CLIENT_ID: Final = os.environ.get("OIDC_CLIENT_ID", "")
OIDC_CLIENT_SECRET: Final = os.environ.get("OIDC_CLIENT_SECRET", "")
OIDC_REDIRECT_URI: Final = os.environ.get("OIDC_REDIRECT_URI", "")
OIDC_SERVER_APPLICATION_URL: Final = os.environ.get("OIDC_SERVER_APPLICATION_URL", "")
OIDC_TLS_CACERTFILE: Final = os.environ.get("OIDC_TLS_CACERTFILE", None)
# SCANS
SCAN_TIMEOUT: Final = int(os.environ.get("SCAN_TIMEOUT", 60 * 60 * 4)) # 4 hours
@@ -119,5 +121,8 @@ LOGLEVEL: Final = os.environ.get("LOGLEVEL", "INFO")
FORCE_COLOR: Final = str_to_bool(os.environ.get("FORCE_COLOR", "false"))
NO_COLOR: Final = str_to_bool(os.environ.get("NO_COLOR", "false"))
# SENTRY
SENTRY_DSN: Final = os.environ.get("SENTRY_DSN", None)
# TESTING
IS_PYTEST_RUN: Final = bool(os.environ.get("PYTEST_VERSION", False))

View File

@@ -93,6 +93,8 @@ class ConfigManager:
driver = "mariadb+mariadbconnector"
elif ROMM_DB_DRIVER == "mysql":
driver = "mysql+mysqlconnector"
elif ROMM_DB_DRIVER == "postgresql":
driver = "postgresql+psycopg"
else:
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)

View File

@@ -1,6 +1,7 @@
from typing import Any
from authlib.integrations.starlette_client import OAuth
from authlib.oidc.discovery import get_well_known_url
from config import (
OIDC_CLIENT_ID,
OIDC_CLIENT_SECRET,
@@ -8,12 +9,13 @@ from config import (
OIDC_PROVIDER,
OIDC_REDIRECT_URI,
OIDC_SERVER_APPLICATION_URL,
OIDC_TLS_CACERTFILE,
)
from fastapi import Security
from fastapi.security.http import HTTPBasic
from fastapi.security.oauth2 import OAuth2PasswordBearer
from fastapi.types import DecoratedCallable
from handler.auth.base_handler import (
from handler.auth.constants import (
DEFAULT_SCOPES_MAP,
FULL_SCOPES_MAP,
WRITE_SCOPES_MAP,
@@ -49,8 +51,13 @@ oauth.register(
name="openid",
client_id=config.get("OIDC_CLIENT_ID"),
client_secret=config.get("OIDC_CLIENT_SECRET"),
server_metadata_url=f'{config.get("OIDC_SERVER_APPLICATION_URL")}/.well-known/openid-configuration',
client_kwargs={"scope": "openid profile email"},
server_metadata_url=get_well_known_url(
config.get("OIDC_SERVER_APPLICATION_URL"), external=True
),
client_kwargs={
"scope": "openid profile email",
"verify": OIDC_TLS_CACERTFILE,
},
)

View File

@@ -1,7 +1,7 @@
from datetime import datetime, timedelta, timezone
from typing import Annotated, Final
from config import OIDC_ENABLED, OIDC_REDIRECT_URI
from config import DISABLE_USERPASS_LOGIN, OIDC_ENABLED, OIDC_REDIRECT_URI
from decorators.auth import oauth
from endpoints.forms.identity import OAuth2RequestForm
from endpoints.responses import MessageResponse
@@ -11,6 +11,7 @@ from exceptions.auth_exceptions import (
OIDCDisabledException,
OIDCNotConfiguredException,
UserDisabledException,
UserPassDisabledException,
)
from fastapi import Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
@@ -45,6 +46,9 @@ def login(
MessageResponse: Standard message response
"""
if DISABLE_USERPASS_LOGIN:
raise UserPassDisabledException
user = auth_handler.authenticate_user(credentials.username, credentials.password)
if not user:
raise AuthCredentialsException
@@ -247,7 +251,7 @@ async def auth_openid(request: Request):
raise OIDCNotConfiguredException
token = await oauth.openid.authorize_access_token(request)
potential_user, _claims = (
potential_user, _userinfo = (
await oidc_handler.get_current_active_user_from_openid_token(token)
)
if not potential_user:

View File

@@ -13,7 +13,7 @@ from exceptions.endpoint_exceptions import (
CollectionPermissionError,
)
from fastapi import Request, UploadFile
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_collection_handler
from handler.filesystem import fs_resource_handler
from handler.filesystem.base_handler import CoverSize

View File

@@ -7,7 +7,7 @@ from exceptions.config_exceptions import (
ConfigNotWritableException,
)
from fastapi import HTTPException, Request, status
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from logger.logger import log
from utils.router import APIRouter

View File

@@ -14,7 +14,7 @@ from endpoints.responses.feeds import (
WebrcadeFeedSchema,
)
from fastapi import Request
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_platform_handler, db_rom_handler
from handler.metadata import meta_igdb_handler
from handler.metadata.base_hander import SWITCH_TITLEDB_REGEX

View File

@@ -4,7 +4,7 @@ from endpoints.responses import MessageResponse
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
from fastapi import File, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_firmware_handler, db_platform_handler
from handler.filesystem import fs_firmware_handler
from handler.scan_handler import scan_firmware

View File

@@ -1,6 +1,7 @@
from config import (
DISABLE_EMULATOR_JS,
DISABLE_RUFFLE_RS,
DISABLE_USERPASS_LOGIN,
ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
ENABLE_SCHEDULED_RESCAN,
ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB,
@@ -32,15 +33,19 @@ def heartbeat() -> HeartbeatResponse:
"""
return {
"VERSION": get_version(),
"SHOW_SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0,
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED,
"SYSTEM": {
"VERSION": get_version(),
"SHOW_SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0,
},
"METADATA_SOURCES": {
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED,
"IGDB_API_ENABLED": IGDB_API_ENABLED,
"MOBY_API_ENABLED": MOBY_API_ENABLED,
"STEAMGRIDDB_ENABLED": STEAMGRIDDB_API_ENABLED,
},
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
"FILESYSTEM": {
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
},
"WATCHER": {
"ENABLED": ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
"TITLE": "Rescan on filesystem change",
@@ -64,7 +69,10 @@ def heartbeat() -> HeartbeatResponse:
"DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS,
"DISABLE_RUFFLE_RS": DISABLE_RUFFLE_RS,
},
"FRONTEND": {"UPLOAD_TIMEOUT": UPLOAD_TIMEOUT},
"FRONTEND": {
"UPLOAD_TIMEOUT": UPLOAD_TIMEOUT,
"DISABLE_USERPASS_LOGIN": DISABLE_USERPASS_LOGIN,
},
"OIDC": {
"ENABLED": OIDC_ENABLED,
"PROVIDER": OIDC_PROVIDER,

View File

@@ -6,7 +6,7 @@ from endpoints.responses.platform import PlatformSchema
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
from exceptions.fs_exceptions import PlatformAlreadyExistsException
from fastapi import Request
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_platform_handler
from handler.filesystem import fs_platform_handler
from handler.metadata.igdb_handler import IGDB_PLATFORM_LIST

View File

@@ -2,7 +2,7 @@ from config import ASSETS_BASE_PATH
from decorators.auth import protected_route
from fastapi import Request
from fastapi.responses import FileResponse
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from utils.router import APIRouter
router = APIRouter()

View File

@@ -1,7 +1,7 @@
from datetime import datetime
from typing import TypedDict
from pydantic import BaseModel
from .base import BaseModel
class BaseAsset(BaseModel):

View File

@@ -0,0 +1,18 @@
from datetime import datetime, timezone
from pydantic import BaseModel as PydanticBaseModel
from pydantic import ConfigDict
class BaseModel(PydanticBaseModel):
"""Ensures all datetime fields include UTC timezone"""
model_config = ConfigDict(
json_encoders={
datetime: lambda dt: (
dt.isoformat()
if dt.tzinfo
else dt.replace(tzinfo=timezone.utc).isoformat()
)
}
)

View File

@@ -1,7 +1,8 @@
from datetime import datetime
from models.collection import Collection
from pydantic import BaseModel
from .base import BaseModel
class CollectionSchema(BaseModel):

View File

@@ -1,7 +1,7 @@
from datetime import datetime
from typing import TypedDict
from pydantic import BaseModel
from .base import BaseModel
class FirmwareSchema(BaseModel):

View File

@@ -1,6 +1,11 @@
from typing import TypedDict
class SystemDict(TypedDict):
VERSION: str
SHOW_SETUP_WIZARD: bool
class WatcherDict(TypedDict):
ENABLED: bool
TITLE: str
@@ -17,11 +22,16 @@ class SchedulerDict(TypedDict):
class MetadataSourcesDict(TypedDict):
ANY_SOURCE_ENABLED: bool
IGDB_API_ENABLED: bool
MOBY_API_ENABLED: bool
STEAMGRIDDB_ENABLED: bool
class FilesystemDict(TypedDict):
FS_PLATFORMS: list[str]
class EmulationDict(TypedDict):
DISABLE_EMULATOR_JS: bool
DISABLE_RUFFLE_RS: bool
@@ -29,6 +39,7 @@ class EmulationDict(TypedDict):
class FrontendDict(TypedDict):
UPLOAD_TIMEOUT: int
DISABLE_USERPASS_LOGIN: bool
class OIDCDict(TypedDict):
@@ -37,13 +48,11 @@ class OIDCDict(TypedDict):
class HeartbeatResponse(TypedDict):
VERSION: str
SHOW_SETUP_WIZARD: bool
SYSTEM: SystemDict
WATCHER: WatcherDict
SCHEDULER: SchedulerDict
ANY_SOURCE_ENABLED: bool
METADATA_SOURCES: MetadataSourcesDict
FS_PLATFORMS: list
FILESYSTEM: FilesystemDict
EMULATION: EmulationDict
FRONTEND: FrontendDict
OIDC: OIDCDict

View File

@@ -1,7 +1,8 @@
from datetime import datetime
from models.user import Role
from pydantic import BaseModel
from .base import BaseModel
class UserSchema(BaseModel):

View File

@@ -1,8 +1,9 @@
from datetime import datetime
from models.platform import DEFAULT_COVER_ASPECT_RATIO
from pydantic import BaseModel, Field, computed_field
from pydantic import Field, computed_field
from .base import BaseModel
from .firmware import FirmwareSchema

View File

@@ -10,7 +10,9 @@ from fastapi import Request
from handler.metadata.igdb_handler import IGDBMetadata
from handler.metadata.moby_handler import MobyMetadata
from models.rom import Rom, RomUserStatus
from pydantic import BaseModel, computed_field
from pydantic import computed_field
from .base import BaseModel
SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s")
@@ -34,6 +36,7 @@ def rom_user_schema_factory() -> RomUserSchema:
rom_id=-1,
created_at=now,
updated_at=now,
last_played=None,
note_raw_markdown="",
note_is_public=False,
is_main_sibling=False,
@@ -54,6 +57,7 @@ class RomUserSchema(BaseModel):
rom_id: int
created_at: datetime
updated_at: datetime
last_played: datetime | None
note_raw_markdown: str
note_is_public: bool
is_main_sibling: bool
@@ -136,6 +140,7 @@ class RomSchema(BaseModel):
# Metadata fields
first_release_date: int | None
youtube_video_id: str | None
average_rating: float | None
alternative_names: list[str]
genres: list[str]
franchises: list[str]

View File

@@ -1,4 +1,4 @@
from pydantic import BaseModel
from .base import BaseModel
class SearchRomSchema(BaseModel):

View File

@@ -1,5 +1,6 @@
import binascii
from base64 import b64encode
from datetime import datetime, timezone
from io import BytesIO
from shutil import rmtree
from urllib.parse import quote
@@ -18,12 +19,13 @@ from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from exceptions.fs_exceptions import RomAlreadyExistsException
from fastapi import HTTPException, Request, UploadFile, status
from fastapi.responses import Response
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_collection_handler, db_platform_handler, db_rom_handler
from handler.filesystem import fs_resource_handler, fs_rom_handler
from handler.filesystem.base_handler import CoverSize
from handler.metadata import meta_igdb_handler, meta_moby_handler
from logger.logger import log
from models.rom import Rom, RomUser
from PIL import Image
from starlette.requests import ClientDisconnect
from starlette.responses import FileResponse
@@ -114,21 +116,45 @@ def get_roms(
Args:
request (Request): Fastapi Request object
id (int, optional): Rom internal id
platform_id (int, optional): Platform ID to filter ROMs
collection_id (int, optional): Collection ID to filter ROMs
search_term (str, optional): Search term to filter ROMs
limit (int, optional): Limit the number of ROMs returned
offset (int, optional): Offset for pagination
order_by (str, optional): Field to order ROMs by
order_dir (str, optional): Direction to order ROMs (asc or desc)
last_played (bool, optional): Flag to filter ROMs by last played
Returns:
list[SimpleRomSchema]: List of roms stored in the database
list[DetailedRomSchema]: List of ROMs stored in the database
"""
roms = db_rom_handler.get_roms(
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term.lower(),
order_by=order_by.lower(),
order_dir=order_dir.lower(),
limit=limit,
offset=offset,
)
if hasattr(Rom, order_by):
roms = db_rom_handler.get_roms(
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term.lower(),
order_by=order_by.lower(),
order_dir=order_dir.lower(),
limit=limit,
offset=offset,
)
elif hasattr(RomUser, order_by):
roms = db_rom_handler.get_roms_user(
user_id=request.user.id,
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term,
order_by=order_by,
order_dir=order_dir,
limit=limit,
offset=offset,
)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid order_by field",
)
roms = [SimpleRomSchema.from_orm_with_request(rom, request) for rom in roms]
return [rom for rom in roms if rom]
@@ -260,6 +286,18 @@ async def get_rom_content(
log.info(f"User {current_username} is downloading {rom.fs_name}")
if not rom.multi:
# Serve the file directly in development mode for emulatorjs
if DEV_MODE:
return FileResponse(
path=rom_path,
filename=rom.file_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"',
"Content-Type": "application/octet-stream",
"Content-Length": str(rom.file_size_bytes),
},
)
return FileRedirectResponse(
download_path=Path(f"/library/{rom.full_path}"),
filename=rom.fs_name,
@@ -535,6 +573,7 @@ async def delete_roms(
@protected_route(router.put, "/roms/{id}/props", [Scope.ROMS_USER_WRITE])
async def update_rom_user(request: Request, id: int) -> RomUserSchema:
data = await request.json()
data = data.get("data", {})
rom = db_rom_handler.get_rom(id)
@@ -556,9 +595,13 @@ async def update_rom_user(request: Request, id: int) -> RomUserSchema:
"difficulty",
"completion",
"status",
"last_played",
]
cleaned_data = {field: data[field] for field in fields_to_update if field in data}
if data.get("update_last_played", False):
cleaned_data.update({"last_played": datetime.now(timezone.utc)})
rom_user = db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
return RomUserSchema.model_validate(rom_user)

View File

@@ -5,7 +5,7 @@ from endpoints.responses import MessageResponse
from endpoints.responses.assets import SaveSchema, UploadedSavesResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, HTTPException, Request, UploadFile, status
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_rom_handler, db_save_handler, db_screenshot_handler
from handler.filesystem import fs_asset_handler
from handler.scan_handler import scan_save

View File

@@ -1,8 +1,8 @@
from decorators.auth import protected_route
from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, Request, UploadFile
from handler.auth.base_handler import Scope
from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse
from fastapi import File, Request, UploadFile, status
from handler.auth.constants import Scope
from handler.database import db_rom_handler, db_screenshot_handler
from handler.filesystem import fs_asset_handler
from handler.scan_handler import scan_screenshot

View File

@@ -2,7 +2,7 @@ import emoji
from decorators.auth import protected_route
from endpoints.responses.search import SearchCoverSchema, SearchRomSchema
from fastapi import HTTPException, Request, status
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_rom_handler
from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_sgdb_handler
from handler.metadata.igdb_handler import IGDB_API_ENABLED, IGDBRom
@@ -18,7 +18,7 @@ router = APIRouter()
@protected_route(router.get, "/search/roms", [Scope.ROMS_READ])
async def search_rom(
request: Request,
rom_id: str,
rom_id: int,
search_term: str | None = None,
search_by: str = "name",
) -> list[SearchRomSchema]:
@@ -26,7 +26,7 @@ async def search_rom(
Args:
request (Request): FastAPI request
rom_id (str): Rom ID
rom_id (int): Rom ID
source (str): Source of the rom
search_term (str, optional): Search term. Defaults to None.
search_by (str, optional): Search by name or ID. Defaults to "name".
@@ -64,18 +64,17 @@ async def search_rom(
if search_by.lower() == "id":
try:
igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_id(
int(search_term)
)
moby_matched_roms = await meta_moby_handler.get_matched_roms_by_id(
int(search_term)
)
igdb_rom = await meta_igdb_handler.get_matched_rom_by_id(int(search_term))
moby_rom = await meta_moby_handler.get_matched_rom_by_id(int(search_term))
except ValueError as exc:
log.error(f"Search error: invalid ID '{search_term}'")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Tried searching by ID, but '{search_term}' is not a valid ID",
) from exc
else:
igdb_matched_roms = [igdb_rom] if igdb_rom else []
moby_matched_roms = [moby_rom] if moby_rom else []
elif search_by.lower() == "name":
main_platform_igdb_id = await _get_main_platform_igdb_id(rom.platform)
igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_name(

View File

@@ -5,7 +5,7 @@ from endpoints.responses import MessageResponse
from endpoints.responses.assets import StateSchema, UploadedStatesResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, HTTPException, Request, UploadFile, status
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_rom_handler, db_screenshot_handler, db_state_handler
from handler.filesystem import fs_asset_handler
from handler.scan_handler import scan_state

View File

@@ -1,7 +1,7 @@
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
from fastapi import Request
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from tasks.update_switch_titledb import update_switch_titledb_task
from utils.router import APIRouter

View File

@@ -15,7 +15,7 @@ def test_heartbeat(client):
assert response.status_code == 200
heartbeat = response.json()
assert heartbeat.get("VERSION") == get_version()
assert heartbeat.get("SYSTEM").get("VERSION") == get_version()
assert heartbeat.get("WATCHER").get("ENABLED")
assert heartbeat.get("WATCHER").get("TITLE") == "Rescan on filesystem change"
assert heartbeat.get("SCHEDULER").get("RESCAN").get("ENABLED")

View File

@@ -2,7 +2,7 @@ import pytest
from endpoints.auth import ACCESS_TOKEN_EXPIRE_MINUTES
from fastapi.exceptions import HTTPException
from fastapi.testclient import TestClient
from handler.auth.base_handler import WRITE_SCOPES
from handler.auth.constants import WRITE_SCOPES
from main import app

View File

@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Annotated
from typing import Annotated, Any
from anyio import open_file
from config import ASSETS_BASE_PATH
@@ -9,7 +9,7 @@ from endpoints.responses import MessageResponse
from endpoints.responses.identity import UserSchema
from fastapi import Depends, HTTPException, Request, status
from handler.auth import auth_handler
from handler.auth.base_handler import Scope
from handler.auth.constants import Scope
from handler.database import db_user_handler
from handler.filesystem import fs_asset_handler
from logger.logger import log
@@ -51,8 +51,7 @@ def add_user(
detail="Forbidden",
)
existing_user_by_username = db_user_handler.get_user_by_username(username.lower())
if existing_user_by_username:
if db_user_handler.get_user_by_username(username.lower()):
msg = f"Username {username.lower()} already exists"
log.error(msg)
raise HTTPException(
@@ -60,9 +59,8 @@ def add_user(
detail=msg,
)
existing_user_by_email = db_user_handler.get_user_by_email(email.lower())
if existing_user_by_email:
msg = f"Uesr with email {email.lower()} already exists"
if email and db_user_handler.get_user_by_email(email.lower()):
msg = f"User with email {email.lower()} already exists"
log.error(msg)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -72,7 +70,7 @@ def add_user(
user = User(
username=username.lower(),
hashed_password=auth_handler.get_password_hash(password),
email=email.lower(),
email=email.lower() or None,
role=Role[role.upper()],
)
@@ -154,7 +152,7 @@ async def update_user(
if db_user.id != request.user.id and request.user.role != Role.ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
cleaned_data = {}
cleaned_data: dict[str, Any] = {}
if form_data.username and form_data.username != db_user.username:
existing_user = db_user_handler.get_user_by_username(form_data.username.lower())
@@ -173,9 +171,10 @@ async def update_user(
form_data.password
)
if form_data.email and form_data.email != db_user.email:
existing_user = db_user_handler.get_user_by_email(form_data.email.lower())
if existing_user:
if form_data.email is not None and form_data.email != db_user.email:
if form_data.email and db_user_handler.get_user_by_email(
form_data.email.lower()
):
msg = f"User with email {form_data.email} already exists"
log.error(msg)
raise HTTPException(
@@ -183,7 +182,7 @@ async def update_user(
detail=msg,
)
cleaned_data["email"] = form_data.email.lower()
cleaned_data["email"] = form_data.email.lower() or None
# You can't change your own role
if form_data.role and request.user.id != id:

View File

@@ -1,5 +1,10 @@
from fastapi import HTTPException, status
UserPassDisabledException = HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Username/password authentication disabled",
)
AuthCredentialsException = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",

View File

@@ -1,74 +1,18 @@
import asyncio
import enum
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Final, Optional
from typing import Any
import httpx
from config import OIDC_ENABLED, OIDC_SERVER_APPLICATION_URL, ROMM_AUTH_SECRET_KEY
from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY
from decorators.auth import oauth
from exceptions.auth_exceptions import OAuthCredentialsException, UserDisabledException
from fastapi import HTTPException, status
from handler.auth.constants import ALGORITHM, DEFAULT_OAUTH_TOKEN_EXPIRY
from joserfc import jwt
from joserfc.errors import BadSignatureError, ExpiredTokenError, InvalidPayloadError
from joserfc.jwk import OctKey, RSAKey
from joserfc.errors import BadSignatureError
from joserfc.jwk import OctKey
from logger.logger import log
from passlib.context import CryptContext
from starlette.requests import HTTPConnection
from utils.context import ctx_httpx_client
ALGORITHM: Final = "HS256"
DEFAULT_OAUTH_TOKEN_EXPIRY: Final = timedelta(minutes=15)
class Scope(enum.StrEnum):
ME_READ = "me.read"
ME_WRITE = "me.write"
ROMS_READ = "roms.read"
ROMS_WRITE = "roms.write"
ROMS_USER_READ = "roms.user.read"
ROMS_USER_WRITE = "roms.user.write"
PLATFORMS_READ = "platforms.read"
PLATFORMS_WRITE = "platforms.write"
ASSETS_READ = "assets.read"
ASSETS_WRITE = "assets.write"
FIRMWARE_READ = "firmware.read"
FIRMWARE_WRITE = "firmware.write"
COLLECTIONS_READ = "collections.read"
COLLECTIONS_WRITE = "collections.write"
USERS_READ = "users.read"
USERS_WRITE = "users.write"
TASKS_RUN = "tasks.run"
DEFAULT_SCOPES_MAP: Final = {
Scope.ME_READ: "View your profile",
Scope.ME_WRITE: "Modify your profile",
Scope.ROMS_READ: "View ROMs",
Scope.PLATFORMS_READ: "View platforms",
Scope.ASSETS_READ: "View assets",
Scope.ASSETS_WRITE: "Modify assets",
Scope.FIRMWARE_READ: "View firmware",
Scope.ROMS_USER_READ: "View user-rom properties",
Scope.ROMS_USER_WRITE: "Modify user-rom properties",
Scope.COLLECTIONS_READ: "View collections",
Scope.COLLECTIONS_WRITE: "Modify collections",
}
WRITE_SCOPES_MAP: Final = {
Scope.ROMS_WRITE: "Modify ROMs",
Scope.PLATFORMS_WRITE: "Modify platforms",
Scope.FIRMWARE_WRITE: "Modify firmware",
}
FULL_SCOPES_MAP: Final = {
Scope.USERS_READ: "View users",
Scope.USERS_WRITE: "Modify users",
Scope.TASKS_RUN: "Run tasks",
}
DEFAULT_SCOPES: Final = list(DEFAULT_SCOPES_MAP.keys())
WRITE_SCOPES: Final = DEFAULT_SCOPES + list(WRITE_SCOPES_MAP.keys())
FULL_SCOPES: Final = WRITE_SCOPES + list(FULL_SCOPES_MAP.keys())
class AuthHandler:
@@ -159,93 +103,7 @@ class OAuthHandler:
return user, payload.claims
class RSAKeyNotFoundError(Exception): ...
class OpenIDHandler:
RSA_ALGORITHM = "RS256"
def __init__(self) -> None:
self._server_metadata: Optional[dict] = None
self._rsa_key: Optional[RSAKey] = None
self._rsa_key_lock = asyncio.Lock()
async def _fetch_server_metadata(self) -> dict:
"""
Fetch the server metadata from the OIDC server
"""
if self._server_metadata:
return self._server_metadata
server_metadata_url = (
f"{OIDC_SERVER_APPLICATION_URL}/.well-known/openid-configuration"
)
log.info("Fetching server metadata from %s", server_metadata_url)
httpx_client = ctx_httpx_client.get()
try:
response = await httpx_client.get(server_metadata_url, timeout=120)
response.raise_for_status()
json_response = response.json()
self._server_metadata = json_response
return json_response
except httpx.RequestError as exc:
log.error("Unable to fetch server metadata: %s", str(exc))
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Unable to fetch server metadata",
) from exc
async def _fetch_rsa_key(self) -> RSAKey:
"""
Fetch the public key from the OIDC server
JWKS (JSON Web Key Sets) response is a JSON object with a keys array
"""
server_metadata = await self._fetch_server_metadata()
jwks_url = server_metadata.get("jwks_uri", "/jwks")
log.info("Fetching JWKS from %s", jwks_url)
httpx_client = ctx_httpx_client.get()
try:
response = await httpx_client.get(jwks_url, timeout=120)
response.raise_for_status()
keys = response.json().get("keys", [])
if not keys:
raise RSAKeyNotFoundError("No RSA keys found in JWKS response.")
return RSAKey.import_key(keys[0])
except (httpx.RequestError, KeyError, RSAKeyNotFoundError) as exc:
log.error("Unable to fetch RSA public key: %s", str(exc))
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Unable to fetch RSA public key",
) from exc
async def get_rsa_key(self) -> RSAKey:
"""
Retrieves the cached RSA public key, or fetches it if not already cached.
"""
if not self._rsa_key:
async with self._rsa_key_lock:
if not self._rsa_key: # Double-check in case of concurrent calls
self._rsa_key = await self._fetch_rsa_key()
return self._rsa_key
async def validate_token(self, token: str) -> jwt.Token:
"""
Validates a JWT token using the RSA public key.
"""
try:
rsa_key = await self.get_rsa_key()
return jwt.decode(token, rsa_key, algorithms=[self.RSA_ALGORITHM])
except (BadSignatureError, ExpiredTokenError, InvalidPayloadError) as exc:
log.error("Token validation failed: %s", str(exc))
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
) from exc
async def get_current_active_user_from_openid_token(self, token: Any):
from handler.database import db_user_handler
from models.user import Role, User
@@ -253,25 +111,15 @@ class OpenIDHandler:
if not OIDC_ENABLED:
return None, None
id_token = token.get("id_token")
if not id_token:
log.error("ID Token is missing from token.")
userinfo = token.get("userinfo")
if userinfo is None:
log.error("Userinfo is missing from token.")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="ID Token is missing from token.",
detail="Userinfo is missing from token.",
)
payload = await self.validate_token(id_token)
iss = payload.claims.get("iss")
if not iss or OIDC_SERVER_APPLICATION_URL not in str(iss):
log.error("Invalid issuer in token: %s", iss)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid issuer in token.",
)
email = payload.claims.get("email")
email = userinfo.get("email")
if email is None:
log.error("Email is missing from token.")
raise HTTPException(
@@ -279,7 +127,24 @@ class OpenIDHandler:
detail="Email is missing from token.",
)
preferred_username = payload.claims.get("preferred_username")
metadata = await oauth.openid.load_server_metadata()
claims_supported = metadata.get("claims_supported")
is_email_verified = userinfo.get("email_verified", None)
# Fail if email is explicitly unverified, or `email_verified` is a supported claim and
# email is not explicitly verified.
if is_email_verified is False or (
claims_supported
and "email_verified" in claims_supported
and is_email_verified is not True
):
log.error("Email is not verified.")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email is not verified.",
)
preferred_username = userinfo.get("preferred_username")
user = db_user_handler.get_user_by_email(email)
if user is None:
@@ -297,4 +162,4 @@ class OpenIDHandler:
raise UserDisabledException
log.info("User successfully authenticated: %s", email)
return user, payload.claims
return user, userinfo

View File

@@ -0,0 +1,57 @@
import enum
from datetime import timedelta
from typing import Final
ALGORITHM: Final = "HS256"
DEFAULT_OAUTH_TOKEN_EXPIRY: Final = timedelta(minutes=15)
class Scope(enum.StrEnum):
ME_READ = "me.read"
ME_WRITE = "me.write"
ROMS_READ = "roms.read"
ROMS_WRITE = "roms.write"
ROMS_USER_READ = "roms.user.read"
ROMS_USER_WRITE = "roms.user.write"
PLATFORMS_READ = "platforms.read"
PLATFORMS_WRITE = "platforms.write"
ASSETS_READ = "assets.read"
ASSETS_WRITE = "assets.write"
FIRMWARE_READ = "firmware.read"
FIRMWARE_WRITE = "firmware.write"
COLLECTIONS_READ = "collections.read"
COLLECTIONS_WRITE = "collections.write"
USERS_READ = "users.read"
USERS_WRITE = "users.write"
TASKS_RUN = "tasks.run"
DEFAULT_SCOPES_MAP: Final = {
Scope.ME_READ: "View your profile",
Scope.ME_WRITE: "Modify your profile",
Scope.ROMS_READ: "View ROMs",
Scope.PLATFORMS_READ: "View platforms",
Scope.ASSETS_READ: "View assets",
Scope.ASSETS_WRITE: "Modify assets",
Scope.FIRMWARE_READ: "View firmware",
Scope.ROMS_USER_READ: "View user-rom properties",
Scope.ROMS_USER_WRITE: "Modify user-rom properties",
Scope.COLLECTIONS_READ: "View collections",
Scope.COLLECTIONS_WRITE: "Modify collections",
}
WRITE_SCOPES_MAP: Final = {
Scope.ROMS_WRITE: "Modify ROMs",
Scope.PLATFORMS_WRITE: "Modify platforms",
Scope.FIRMWARE_WRITE: "Modify firmware",
}
FULL_SCOPES_MAP: Final = {
Scope.USERS_READ: "View users",
Scope.USERS_WRITE: "Modify users",
Scope.TASKS_RUN: "Run tasks",
}
DEFAULT_SCOPES: Final = list(DEFAULT_SCOPES_MAP.keys())
WRITE_SCOPES: Final = DEFAULT_SCOPES + list(WRITE_SCOPES_MAP.keys())
FULL_SCOPES: Final = WRITE_SCOPES + list(FULL_SCOPES_MAP.keys())

View File

@@ -3,7 +3,7 @@ from base64 import b64encode
import pytest
from fastapi.exceptions import HTTPException
from handler.auth import auth_handler, oauth_handler
from handler.auth.base_handler import WRITE_SCOPES
from handler.auth.constants import WRITE_SCOPES
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.database import db_user_handler
from models.user import User

View File

@@ -1,10 +1,9 @@
from unittest.mock import AsyncMock, MagicMock
from unittest.mock import MagicMock
import pytest
from authlib.integrations.starlette_client.apps import StarletteOAuth2App
from fastapi import HTTPException
from handler.auth.base_handler import OpenIDHandler, ctx_httpx_client
from httpx import Request, RequestError, Response
from joserfc.errors import BadSignatureError
from handler.auth.base_handler import OpenIDHandler
from joserfc.jwt import Token
# Mock constants
@@ -19,93 +18,196 @@ def mock_oidc_disabled(mocker):
@pytest.fixture
def mock_oidc_enabled(mocker):
mocker.patch(
"handler.auth.base_handler.OIDC_SERVER_APPLICATION_URL",
OIDC_SERVER_APPLICATION_URL,
)
mocker.patch("handler.auth.base_handler.OIDC_ENABLED", True)
@pytest.fixture
def mock_httpx_client():
"""Fixture to mock the httpx.AsyncClient and set it in the ContextVar."""
mock_client = AsyncMock()
token = ctx_httpx_client.set(mock_client)
yield mock_client
ctx_httpx_client.reset(token)
def mock_token():
return {
"access_token": "",
"token_type": "Bearer",
"expires_in": 300,
"id_token": "",
"expires_at": 1735397872,
"userinfo": {
"iss": "http://localhost:9000/application/o/romm/",
"sub": "",
"aud": "",
"exp": 1735397871,
"iat": 1735397571,
"auth_time": 1735397571,
"acr": "goauthentik.io/providers/oauth2/default",
"amr": ["pwd"],
"nonce": "",
"sid": "",
"email": "test@example.com",
"email_verified": True,
"name": "Test User",
"given_name": "Test User",
"preferred_username": "testuser",
"nickname": "testuser",
"groups": ["Default Users"],
},
}
@pytest.fixture
def mock_request():
return Request("GET", f"{OIDC_SERVER_APPLICATION_URL}/jwks/")
def mock_openid_configuration():
return {
"issuer": "https://authentik.example.com/application/o/romm/",
"authorization_endpoint": "https://authentik.example.com/application/o/authorize/",
"token_endpoint": "https://authentik.example.com/application/o/token/",
"userinfo_endpoint": "https://authentik.example.com/application/o/userinfo/",
"end_session_endpoint": "https://authentik.example.com/application/o/romm/end-session/",
"introspection_endpoint": "https://authentik.example.com/application/o/introspect/",
"revocation_endpoint": "https://authentik.example.com/application/o/revoke/",
"device_authorization_endpoint": "https://authentik.example.com/application/o/device/",
"response_types_supported": [
"code",
"id_token",
"id_token token",
"code token",
"code id_token",
"code id_token token",
],
"response_modes_supported": ["query", "fragment", "form_post"],
"jwks_uri": "https://authentik.example.com/application/o/romm/jwks/",
"grant_types_supported": [
"authorization_code",
"refresh_token",
"implicit",
"client_credentials",
"password",
"urn:ietf:params:oauth:grant-type:device_code",
],
"id_token_signing_alg_values_supported": ["RS256"],
"subject_types_supported": ["public"],
"token_endpoint_auth_methods_supported": [
"client_secret_post",
"client_secret_basic",
],
"acr_values_supported": ["goauthentik.io/providers/oauth2/default"],
"scopes_supported": ["openid", "email", "profile"],
"request_parameter_supported": False,
"claims_supported": [
"sub",
"iss",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"amr",
"nonce",
"email",
"email_verified",
"name",
"given_name",
"preferred_username",
"nickname",
"groups",
],
"claims_parameter_supported": False,
"code_challenge_methods_supported": ["plain", "S256"],
}
def test_oidc_disabled_initialization(mock_oidc_disabled):
"""Test that the handler initializes correctly when OIDC is disabled."""
async def test_oidc_disabled(mock_oidc_disabled, mock_token):
"""Test that OIDC is disabled."""
oidc_handler = OpenIDHandler()
assert oidc_handler._rsa_key is None
async def test_oidc_enabled_server_unreachable(
mock_httpx_client, mock_request, mock_oidc_enabled
):
"""Test that initialization raises an HTTPException when the OIDC server is unreachable."""
mock_httpx_client.get.side_effect = RequestError(
"Mocked error", request=mock_request
user, userinfo = await oidc_handler.get_current_active_user_from_openid_token(
mock_token
)
oidc_handler = OpenIDHandler()
token = {"id_token": "invalid_signature_token"}
with pytest.raises(HTTPException):
await oidc_handler.get_current_active_user_from_openid_token(token)
assert user is None
assert userinfo is None
async def test_oidc_valid_token_decoding(
mocker, mock_httpx_client, mock_request, mock_oidc_enabled
mocker, mock_oidc_enabled, mock_token, mock_openid_configuration
):
"""Test token decoding with valid RSA key and token."""
mock_httpx_client.get.return_value = Response(
200,
request=mock_request,
json={"keys": [{"kty": "RSA", "n": "fake", "e": "AQAB"}]},
)
mock_rsa_key = MagicMock()
mocker.patch(
"handler.auth.base_handler.RSAKey.import_key", return_value=mock_rsa_key
)
mock_jwt_payload = Token(
header={"alg": "RS256"},
claims={"iss": OIDC_SERVER_APPLICATION_URL, "email": "test@example.com"},
)
mocker.patch("joserfc.jwt.decode", return_value=mock_jwt_payload)
mock_user = MagicMock(enabled=True)
mocker.patch(
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
)
mocker.patch.object(
StarletteOAuth2App,
"load_server_metadata",
return_value=mock_openid_configuration,
)
oidc_handler = OpenIDHandler()
user, userinfo = await oidc_handler.get_current_active_user_from_openid_token(
mock_token
)
assert user is not None
assert userinfo is not None
assert user == mock_user
assert userinfo.get("email") == mock_jwt_payload.claims.get("email")
async def test_oidc_token_unverified_email(
mocker, mock_oidc_enabled, mock_token, mock_openid_configuration
):
"""Test token decoding for unverified email."""
mocker.patch.object(
StarletteOAuth2App,
"load_server_metadata",
return_value=mock_openid_configuration,
)
unverified_token = mock_token
unverified_token["userinfo"]["email_verified"] = False
oidc_handler = OpenIDHandler()
with pytest.raises(HTTPException):
await oidc_handler.get_current_active_user_from_openid_token(unverified_token)
async def test_oidc_token_without_email_verified_claim(
mocker, mock_oidc_enabled, mock_token, mock_openid_configuration
):
"""Test token decoding with server not supporting email_verified claim."""
mock_jwt_payload = Token(
header={"alg": "RS256"},
claims={"iss": OIDC_SERVER_APPLICATION_URL, "email": "test@example.com"},
)
mock_user = MagicMock(enabled=True)
mocker.patch(
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
)
openid_conf = mock_openid_configuration
openid_conf["claims_supported"] = openid_conf["claims_supported"].remove(
"email_verified"
)
mocker.patch.object(
StarletteOAuth2App, "load_server_metadata", return_value=openid_conf
)
unverified_token = mock_token
del unverified_token["userinfo"]["email_verified"]
oidc_handler = OpenIDHandler()
token = {"id_token": "valid_token"}
user, claims = await oidc_handler.get_current_active_user_from_openid_token(token)
user, userinfo = await oidc_handler.get_current_active_user_from_openid_token(
mock_token
)
assert user is not None
assert userinfo is not None
assert user == mock_user
assert claims == mock_jwt_payload.claims
assert userinfo.get("email") == mock_jwt_payload.claims.get("email")
async def test_oidc_invalid_token_signature(
mocker, mock_httpx_client, mock_request, mock_oidc_enabled
):
async def test_oidc_invalid_token_signature(mock_oidc_enabled):
"""Test token decoding raises exception for invalid signature."""
mock_httpx_client.get.return_value = Response(
200,
request=mock_request,
json={"keys": [{"kty": "RSA", "n": "fake", "e": "AQAB"}]},
)
mock_rsa_key = MagicMock()
mocker.patch(
"handler.auth.base_handler.RSAKey.import_key", return_value=mock_rsa_key
)
mocker.patch("joserfc.jwt.decode", side_effect=BadSignatureError)
oidc_handler = OpenIDHandler()
token = {"id_token": "invalid_signature_token"}
with pytest.raises(HTTPException):

View File

@@ -1,9 +1,12 @@
from typing import Sequence
from collections.abc import Sequence
from typing import Any
from decorators.database import begin_session
from models.collection import Collection
from sqlalchemy import delete, select, update
from sqlalchemy.orm import Session
from sqlalchemy.sql import ColumnExpressionArgument
from utils.database import json_array_contains_value
from .base_handler import DBBaseHandler
@@ -40,11 +43,19 @@ class DBCollectionsHandler(DBBaseHandler):
@begin_session
def get_collections_by_rom_id(
self, rom_id: int, session: Session = None
self,
rom_id: int,
*,
order_by: Sequence[str | ColumnExpressionArgument[Any]] | None = None,
session: Session = None,
) -> Sequence[Collection]:
return session.scalars(
select(Collection).filter(Collection.roms.contains(rom_id))
).all()
query = select(Collection).filter(
json_array_contains_value(Collection.roms, rom_id, session=session)
)
if order_by is not None:
query = query.order_by(*order_by)
return session.scalars(query).all()
@begin_session
def update_collection(

View File

@@ -177,20 +177,6 @@ class DBRomsHandler(DBBaseHandler):
) -> Rom | None:
return session.scalar(query.filter_by(fs_name_no_ext=fs_name_no_ext).limit(1))
@begin_session
def get_rom_collections(
self, rom: Rom, session: Session = None
) -> Sequence[Collection]:
return (
session.scalars(
select(Collection)
.filter(func.json_contains(Collection.roms, f"{rom.id}"))
.order_by(Collection.name.asc())
)
.unique()
.all()
)
@begin_session
def update_rom(self, id: int, data: dict, session: Session = None) -> Rom:
session.execute(
@@ -252,6 +238,34 @@ class DBRomsHandler(DBBaseHandler):
select(RomUser).filter_by(rom_id=rom_id, user_id=user_id).limit(1)
)
@begin_session
@with_simple
def get_roms_user(
self,
*,
user_id: int,
platform_id: int | None = None,
collection_id: int | None = None,
search_term: str = "",
order_by: str = "name",
order_dir: str = "asc",
limit: int | None = None,
offset: int | None = None,
query: Query = None,
session: Session = None,
) -> Sequence[Rom]:
filtered_query = (
query.join(RomUser)
.filter(RomUser.user_id == user_id)
.order_by(RomUser.last_played.desc())
)
filtered_query = self._filter(
filtered_query, platform_id, collection_id, search_term, session
)
offset_query = filtered_query.offset(offset)
limited_query = offset_query.limit(limit)
return session.scalars(limited_query).unique().all()
@begin_session
def get_rom_user_by_id(self, id: int, session: Session = None) -> RomUser | None:
return session.scalar(select(RomUser).filter_by(id=id).limit(1))
@@ -265,19 +279,22 @@ class DBRomsHandler(DBBaseHandler):
.execution_options(synchronize_session="evaluate")
)
rom_user = session.query(RomUser).filter_by(id=id).one()
if data.get("is_main_sibling", False):
rom = session.query(Rom).filter_by(id=rom_user.rom_id).one()
session.execute(
update(RomUser)
.where(
and_(
RomUser.rom_id.in_(r.id for r in rom.sibling_roms),
RomUser.user_id == rom_user.user_id,
)
rom_user = self.get_rom_user_by_id(id)
if not data.get("is_main_sibling", False):
return rom_user
rom = self.get_rom(rom_user.rom_id)
session.execute(
update(RomUser)
.where(
and_(
RomUser.rom_id.in_(r.id for r in rom.sibling_roms),
RomUser.user_id == rom_user.user_id,
)
.values(is_main_sibling=False)
)
.values(is_main_sibling=False)
)
return session.query(RomUser).filter_by(id=id).one()

View File

@@ -560,12 +560,12 @@ class IGDBBaseHandler(MetadataHandler):
)
@check_twitch_token
async def get_matched_roms_by_id(self, igdb_id: int) -> list[IGDBRom]:
async def get_matched_rom_by_id(self, igdb_id: int) -> IGDBRom | None:
if not IGDB_API_ENABLED:
return []
return None
rom = await self.get_rom_by_id(igdb_id)
return [rom] if rom["igdb_id"] else []
return rom if rom["igdb_id"] else None
@check_twitch_token
async def get_matched_roms_by_name(

View File

@@ -302,12 +302,12 @@ class MobyGamesHandler(MetadataHandler):
return MobyGamesRom({k: v for k, v in rom.items() if v}) # type: ignore[misc]
async def get_matched_roms_by_id(self, moby_id: int) -> list[MobyGamesRom]:
async def get_matched_rom_by_id(self, moby_id: int) -> MobyGamesRom | None:
if not MOBY_API_ENABLED:
return []
return None
rom = await self.get_rom_by_id(moby_id)
return [rom] if rom["moby_id"] else []
return rom if rom["moby_id"] else None
async def get_matched_roms_by_name(
self, search_term: str, platform_moby_id: int | None

View File

@@ -1,5 +1,6 @@
import socketio # type: ignore
from config import REDIS_URL
from utils import json as json_module
class SocketHandler:
@@ -7,6 +8,7 @@ class SocketHandler:
self.socket_server = socketio.AsyncServer(
cors_allowed_origins="*",
async_mode="asgi",
json=json_module,
logger=False,
engineio_logger=False,
client_manager=socketio.AsyncRedisManager(str(REDIS_URL)),

View File

@@ -4,6 +4,7 @@ from contextlib import asynccontextmanager
import alembic.config
import endpoints.sockets.scan # noqa
import sentry_sdk
import uvicorn
from config import (
DEV_HOST,
@@ -11,6 +12,7 @@ from config import (
DISABLE_CSRF_PROTECTION,
IS_PYTEST_RUN,
ROMM_AUTH_SECRET_KEY,
SENTRY_DSN,
)
from endpoints import (
auth,
@@ -32,7 +34,7 @@ from endpoints import (
)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from handler.auth.base_handler import ALGORITHM
from handler.auth.constants import ALGORITHM
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.auth.middleware import CustomCSRFMiddleware, SessionMiddleware
from handler.socket_handler import socket_handler
@@ -48,6 +50,11 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
yield
sentry_sdk.init(
dsn=SENTRY_DSN,
release="romm@" + get_version(),
)
app = FastAPI(
title="RomM API",
version=get_version(),

View File

@@ -4,8 +4,9 @@ from functools import cached_property
from models.base import BaseModel
from models.user import User
from sqlalchemy import JSON, ForeignKey, String, Text
from sqlalchemy import ForeignKey, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from utils.database import CustomJSON
class Collection(BaseModel):
@@ -24,7 +25,7 @@ class Collection(BaseModel):
)
roms: Mapped[set[int]] = mapped_column(
JSON, default=[], doc="Rom id's that belong to this collection"
CustomJSON(), default=[], doc="Rom id's that belong to this collection"
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))

View File

@@ -8,7 +8,6 @@ from typing import TYPE_CHECKING, Any, Sequence
from config import FRONTEND_RESOURCES_PATH
from models.base import BaseModel
from sqlalchemy import (
JSON,
BigInteger,
DateTime,
Enum,
@@ -18,9 +17,10 @@ from sqlalchemy import (
String,
Text,
UniqueConstraint,
func,
)
from sqlalchemy.dialects.mysql.json import JSON as MySQLJSON
from sqlalchemy.orm import Mapped, mapped_column, relationship
from utils.database import CustomJSON, safe_float, safe_int
if TYPE_CHECKING:
from models.assets import Save, Screenshot, State
@@ -73,10 +73,10 @@ class Rom(BaseModel):
slug: Mapped[str | None] = mapped_column(String(length=400))
summary: Mapped[str | None] = mapped_column(Text)
igdb_metadata: Mapped[dict[str, Any] | None] = mapped_column(
MySQLJSON, default=dict
CustomJSON(), default=dict
)
moby_metadata: Mapped[dict[str, Any] | None] = mapped_column(
MySQLJSON, default=dict
CustomJSON(), default=dict
)
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
@@ -86,13 +86,13 @@ class Rom(BaseModel):
)
revision: Mapped[str | None] = mapped_column(String(100))
regions: Mapped[list[str] | None] = mapped_column(JSON, default=[])
languages: Mapped[list[str] | None] = mapped_column(JSON, default=[])
tags: Mapped[list[str] | None] = mapped_column(JSON, default=[])
regions: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
languages: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
tags: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
path_screenshots: Mapped[list[str] | None] = mapped_column(JSON, default=[])
path_screenshots: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
url_screenshots: Mapped[list[str] | None] = mapped_column(
JSON, default=[], doc="URLs to screenshots stored in IGDB"
CustomJSON(), default=[], doc="URLs to screenshots stored in IGDB"
)
crc_hash: Mapped[str | None] = mapped_column(String(100))
@@ -161,9 +161,12 @@ class Rom(BaseModel):
return sum(f.file_size_bytes for f in self.files)
def get_collections(self) -> Sequence[Collection]:
from handler.database import db_rom_handler
from handler.database import db_collection_handler
return db_rom_handler.get_rom_collections(self)
return db_collection_handler.get_collections_by_rom_id(
self.id,
order_by=[func.lower("name")],
)
# Metadata fields
@property
@@ -181,10 +184,28 @@ class Rom(BaseModel):
)
@property
def first_release_date(self) -> int:
def first_release_date(self) -> int | None:
if self.igdb_metadata:
return self.igdb_metadata.get("first_release_date", 0)
return 0
return safe_int(self.igdb_metadata.get("first_release_date") or 0) * 1000
return None
@property
def average_rating(self) -> float | None:
igdb_rating = (
safe_float(self.igdb_metadata.get("total_rating") or 0)
if self.igdb_metadata
else 0.0
)
moby_rating = (
safe_float(self.moby_metadata.get("moby_score") or 0)
if self.moby_metadata
else 0.0
)
ratings = [r for r in [igdb_rating, moby_rating * 10] if r != 0.0]
return sum(ratings) / len([r for r in ratings if r]) if any(ratings) else None
@property
def genres(self) -> list[str]:

View File

@@ -1,4 +1,4 @@
from handler.auth.base_handler import DEFAULT_SCOPES, FULL_SCOPES, WRITE_SCOPES
from handler.auth.constants import DEFAULT_SCOPES, FULL_SCOPES, WRITE_SCOPES
from models.user import User

View File

@@ -4,13 +4,13 @@ import enum
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from handler.auth.constants import DEFAULT_SCOPES, FULL_SCOPES, WRITE_SCOPES, Scope
from models.base import BaseModel
from sqlalchemy import DateTime, Enum, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from starlette.authentication import SimpleUser
if TYPE_CHECKING:
from handler.auth.base_handler import Scope
from models.assets import Save, Screenshot, State
from models.collection import Collection
from models.rom import RomUser
@@ -47,8 +47,6 @@ class User(BaseModel, SimpleUser):
@property
def oauth_scopes(self) -> list[Scope]:
from handler.auth.base_handler import DEFAULT_SCOPES, FULL_SCOPES, WRITE_SCOPES
if self.role == Role.ADMIN:
return FULL_SCOPES

View File

@@ -1,7 +1,15 @@
import sentry_sdk
from config import SENTRY_DSN
from logger.logger import log
from tasks.scan_library import scan_library_task
from tasks.tasks import tasks_scheduler
from tasks.update_switch_titledb import update_switch_titledb_task
from utils import get_version
sentry_sdk.init(
dsn=SENTRY_DSN,
release="romm@" + get_version(),
)
if __name__ == "__main__":
# Initialize the tasks

View File

@@ -3,7 +3,7 @@ from __version__ import __version__
def get_version() -> str:
"""Returns current version tag"""
if not __version__ == "<version>":
if __version__ != "<version>":
return __version__
return "development"

47
backend/utils/database.py Normal file
View File

@@ -0,0 +1,47 @@
from typing import Any
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as sa_pg
from sqlalchemy.orm import Session
from sqlalchemy.sql import ColumnElement, func
def CustomJSON(**kwargs: Any) -> sa.JSON:
"""Custom SQLAlchemy JSON type that uses JSONB on PostgreSQL."""
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
def is_postgresql(conn: sa.Connection) -> bool:
return conn.engine.name == "postgresql"
def json_array_contains_value(
column: sa.Column, value: Any, *, session: Session
) -> ColumnElement:
"""Check if a JSON array column contains a single value."""
conn = session.get_bind()
if is_postgresql(conn):
# In PostgreSQL, string values can be checked for containment using the `?` operator.
# For other types, we use the `@>` operator.
if isinstance(value, str):
return sa.type_coerce(column, sa_pg.JSONB).has_key(value)
return sa.type_coerce(column, sa_pg.JSONB).contains(
func.cast(value, sa_pg.JSONB)
)
return func.json_contains(column, value)
def safe_float(value: Any, default: float = 0.0) -> float:
"""Safely convert a value to float, returning default if conversion fails."""
try:
return float(value)
except (ValueError, TypeError):
return default
def safe_int(value: Any, default: int = 0) -> int:
"""Safely convert a value to int, returning default if conversion fails."""
try:
return int(value)
except (ValueError, TypeError):
return default

29
backend/utils/json.py Normal file
View File

@@ -0,0 +1,29 @@
"""JSON-compatible module with sane defaults.
Inspiration taken from `python-engineio`.
https://github.com/miguelgrinberg/python-engineio/blob/main/src/engineio/json.py
"""
import datetime
import decimal
import json
import uuid
from json import * # noqa: F401, F403
from json import dumps as __original_dumps
from typing import Any
class DefaultJSONEncoder(json.JSONEncoder):
"""Custom JSON encoder that supports encoding additional types."""
def default(self, o: Any) -> Any:
if isinstance(o, (datetime.date, datetime.datetime, datetime.time)):
return o.isoformat()
if isinstance(o, (decimal.Decimal, uuid.UUID)):
return str(o)
return super().default(o)
def dumps(*args: Any, **kwargs: Any) -> str: # type: ignore[no-redef]
kwargs.setdefault("cls", DefaultJSONEncoder)
return __original_dumps(*args, **kwargs)

View File

@@ -1,10 +1,12 @@
import os
from datetime import timedelta
import sentry_sdk
from config import (
ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
LIBRARY_BASE_PATH,
RESCAN_ON_FILESYSTEM_CHANGE_DELAY,
SENTRY_DSN,
)
from config.config_manager import config_manager as cm
from endpoints.sockets.scan import scan_platforms
@@ -12,9 +14,15 @@ from handler.database import db_platform_handler
from handler.scan_handler import ScanType
from logger.logger import log
from tasks.tasks import tasks_scheduler
from utils import get_version
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
sentry_sdk.init(
dsn=SENTRY_DSN,
release="romm@" + get_version(),
)
path = (
cm.get_config().HIGH_PRIO_STRUCTURE_PATH
if os.path.exists(cm.get_config().HIGH_PRIO_STRUCTURE_PATH)

View File

@@ -1,8 +1,17 @@
import sentry_sdk
from config import SENTRY_DSN
from handler.redis_handler import redis_client
from rq import Connection, Queue, Worker
from utils import get_version
listen = ["high", "default", "low"]
sentry_sdk.init(
dsn=SENTRY_DSN,
release="romm@" + get_version(),
)
if __name__ == "__main__":
# Start the worker
with Connection(redis_client):

View File

@@ -1,10 +1,15 @@
# Stages:
# - frontend-build: Build frontend
# - backend-build: Build backend environment
# - backend-dev-build: Similar to `backend-build`, but also compiles and installs development dependencies
# - rahasher-build: Build RAHasher
# - emulator-stage: Fetch and extract emulators
# - nginx-build: Build nginx modules
# - production-stage: Setup frontend and backend
# - final-stage: Move everything to final stage
# - slim-image: Slim image with only the necessary files
# - full-image: Full image with emulator stage
# - dev-slim: Slim image with development dependencies
# - dev-full: Full image with emulator stage and development dependencies
# Versions:
ARG ALPINE_VERSION=3.20
@@ -25,14 +30,17 @@ RUN npm run build
FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION} AS backend-build
# git is needed to install py7zr fork
# git is needed to install streaming-form-data fork
# libffi-dev is needed to fix poetry dependencies for >= v1.8 on arm64
# libpq-dev is needed to build psycopg-c
# mariadb-connector-c-dev is needed to build mariadb-connector
RUN apk add --no-cache \
gcc \
git \
libffi-dev \
libpq-dev \
mariadb-connector-c-dev \
musl-dev \
libffi-dev
musl-dev
RUN pip install poetry
@@ -42,7 +50,12 @@ ENV POETRY_NO_INTERACTION=1 \
WORKDIR /src
COPY ./pyproject.toml ./poetry.lock /src/
RUN poetry install --no-ansi --no-cache
RUN poetry install --no-ansi --no-cache --only main
FROM backend-build AS backend-dev-build
RUN poetry install --no-ansi --no-cache --all-extras
# TODO: Upgrade Alpine to the same version as the other stages, when RAHasher is updated to work
@@ -66,6 +79,23 @@ RUN git clone --recursive --branch "${RALIBRETRO_VERSION}" --depth 1 https://git
make HAVE_CHD=1 -f ./Makefile.RAHasher
FROM alpine:${ALPINE_VERSION} AS emulator-stage
RUN apk add --no-cache \
7zip \
wget
ARG EMULATORJS_VERSION=4.2.1
RUN wget "https://github.com/EmulatorJS/EmulatorJS/releases/download/v${EMULATORJS_VERSION}/${EMULATORJS_VERSION}.7z" && \
7z x -y "${EMULATORJS_VERSION}.7z" -o/emulatorjs && \
rm -rf "${EMULATORJS_VERSION}.7z";
ARG RUFFLE_VERSION=nightly-2024-12-28
ARG RUFFLE_FILE=ruffle-nightly-2024_12_28-web-selfhosted.zip
RUN wget "https://github.com/ruffle-rs/ruffle/releases/download/${RUFFLE_VERSION}/${RUFFLE_FILE}" && \
unzip -o "${RUFFLE_FILE}" -d /ruffle && \
rm -f "${RUFFLE_FILE}";
FROM alpine:${ALPINE_VERSION} AS nginx-build
RUN apk add --no-cache \
@@ -104,6 +134,7 @@ RUN apk add --no-cache \
bash \
libmagic \
mariadb-connector-c \
libpq \
p7zip \
python3 \
tzdata \
@@ -111,14 +142,15 @@ RUN apk add --no-cache \
COPY --from=rahasher-build /RALibretro/bin64/RAHasher /usr/bin/RAHasher
COPY --from=nginx-build ./nginx/objs/ngx_http_zip_module.so /usr/lib/nginx/modules/
COPY --from=frontend-build /front/dist ${WEBSERVER_FOLDER}
COPY ./frontend/assets/dashboard-icons ${WEBSERVER_FOLDER}/assets/dashboard-icons
COPY ./frontend/assets/default ${WEBSERVER_FOLDER}/assets/default
COPY ./frontend/assets/platforms ${WEBSERVER_FOLDER}/assets/platforms
COPY ./frontend/assets/scrappers ${WEBSERVER_FOLDER}/assets/scrappers
COPY ./frontend/assets/webrcade/feed ${WEBSERVER_FOLDER}/assets/webrcade/feed
COPY ./frontend/assets/emulatorjs ${WEBSERVER_FOLDER}/assets/emulatorjs
COPY ./frontend/assets/ruffle ${WEBSERVER_FOLDER}/assets/ruffle
COPY ./frontend/assets/scrappers ${WEBSERVER_FOLDER}/assets/scrappers
COPY ./frontend/assets/platforms ${WEBSERVER_FOLDER}/assets/platforms
COPY ./frontend/assets/webrcade/feed ${WEBSERVER_FOLDER}/assets/webrcade/feed
RUN mkdir -p ${WEBSERVER_FOLDER}/assets/romm && \
ln -s /romm/resources ${WEBSERVER_FOLDER}/assets/romm/resources && \
ln -s /romm/assets ${WEBSERVER_FOLDER}/assets/romm/assets
@@ -135,13 +167,14 @@ RUN addgroup -g 1000 -S romm && adduser -u 1000 -D -S -G romm romm && \
mkdir /romm /redis-data && chown romm:romm /romm /redis-data
FROM scratch AS final-stage
FROM scratch AS slim-image
COPY --from=production-stage / /
COPY --from=backend-build /src/.venv /src/.venv
# Fix virtualenv link to python binary
RUN ln -sf "$(which python)" /src/.venv/bin/python
ENV PATH="/src/.venv/bin:${PATH}"
# Declare the supported volumes
@@ -153,3 +186,21 @@ WORKDIR /romm
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["/init"]
FROM slim-image AS full-image
ARG WEBSERVER_FOLDER=/var/www/html
COPY --from=emulator-stage /emulatorjs ${WEBSERVER_FOLDER}/assets/emulatorjs
COPY --from=emulator-stage /ruffle ${WEBSERVER_FOLDER}/assets/ruffle
FROM slim-image AS dev-slim
COPY --from=backend-dev-build /src/.venv /src/.venv
# Fix virtualenv link to python binary
RUN ln -sf "$(which python)" /src/.venv/bin/python
FROM full-image AS dev-full
COPY --from=backend-dev-build /src/.venv /src/.venv
# Fix virtualenv link to python binary
RUN ln -sf "$(which python)" /src/.venv/bin/python

View File

@@ -123,7 +123,7 @@ stop_process_pid() {
info_log "stopping ${PROCESS}"
kill "${PID}" || true
# wait for process exit
while [ -e "/proc/${PID}" ]; do sleep 0.1; done
while [[ -e "/proc/${PID}" ]]; do sleep 0.1; done
fi
fi
}

View File

@@ -35,6 +35,14 @@ AUTHENTIK_BOOTSTRAP_PASSWORD=
# Authentication
ROMM_AUTH_SECRET_KEY=
# Disable auth on download endpoint for 3rd party support
DISABLE_DOWNLOAD_ENDPOINT_AUTH=
# Disable CSRF protection for development and testing purposes
DISABLE_CSRF_PROTECTION=
# Disable username + passsword login when using OIDC login
DISABLE_USERPASS_LOGIN=
# OpenID Connect (Authentik, Authelia, etc.)
OIDC_ENABLED=
OIDC_PROVIDER=
OIDC_CLIENT_ID=
@@ -56,8 +64,5 @@ SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON=0 4 * * *
DISABLE_EMULATOR_JS=false
DISABLE_RUFFLE_RS=false
# Disable CSRF protection for development and testing purposes
DISABLE_CSRF_PROTECTION=true
# Logging
LOGLEVEL=DEBUG

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -23,17 +23,14 @@
"build": "npm run typecheck && vite build",
"preview": "vite preview",
"lint": "eslint . --fix",
"postinstall": "cd node_modules/emulatorjs/data/minify/ && npm i && npm run build",
"typecheck": "vue-tsc --noEmit",
"generate": "openapi --input http://127.0.0.1:5000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false"
},
"dependencies": {
"@mdi/font": "7.0.96",
"@ruffle-rs/ruffle": "^0.1.0-nightly.2024.7.29",
"axios": "^1.7.4",
"core-js": "^3.37.1",
"cronstrue": "^2.50.0",
"emulatorjs": "github:emulatorjs/emulatorjs#v4.2.0",
"file-saver": "^2.0.5",
"js-cookie": "^3.0.5",
"jszip": "^3.10.1",
@@ -42,6 +39,7 @@
"mitt": "^3.0.1",
"nanoid": "^5.0.7",
"pinia": "^2.1.7",
"qrcode": "^1.5.4",
"roboto-fontface": "^0.10.0",
"semver": "^7.6.2",
"socket.io-client": "^4.7.5",
@@ -58,6 +56,7 @@
"@types/js-cookie": "^3.0.6",
"@types/lodash": "^4.17.1",
"@types/node": "^20.12.12",
"@types/qrcode": "^1.5.5",
"@types/semver": "^7.5.8",
"@types/webfontloader": "^1.6.38",
"@vitejs/plugin-vue": "^3.2.0",
@@ -67,13 +66,11 @@
"eslint-plugin-vue": "^9.26.0",
"globals": "^15.3.0",
"openapi-typescript-codegen": "^0.25.0",
"sass": "^1.77.1",
"tslib": "^2.6.2",
"typescript": "^5.4.5",
"typescript-eslint": "^7.11.0",
"vite": "^3.2.11",
"vite-plugin-pwa": "^0.14.7",
"vite-plugin-static-copy": "0.17.1",
"vite-plugin-vuetify": "^1.0.2",
"vue-tsc": "^2.1.10"
},

View File

@@ -1,19 +1,10 @@
<script setup lang="ts">
import storeAuth from "@/stores/auth";
import storeConfig from "@/stores/config";
import storeHeartbeat from "@/stores/heartbeat";
import api from "@/services/api/index";
import userApi from "@/services/api/user";
import router from "@/plugins/router";
import languageStore from "@/stores/language";
import { storeToRefs } from "pinia";
import { onBeforeMount, ref } from "vue";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
// Props
const heartbeat = storeHeartbeat();
const auth = storeAuth();
const configStore = storeConfig();
const { locale } = useI18n();
const storeLanguage = languageStore();
const { defaultLanguage, languages } = storeToRefs(storeLanguage);
@@ -24,29 +15,6 @@ const selectedLanguage = ref(
);
locale.value = selectedLanguage.value.value;
storeLanguage.setLanguage(selectedLanguage.value);
// Functions
onBeforeMount(async () => {
await api.get("/heartbeat").then(async ({ data: data }) => {
heartbeat.set(data);
if (heartbeat.value.SHOW_SETUP_WIZARD) {
router.push({ name: "setup" });
} else {
await userApi
.fetchCurrentUser()
.then(({ data: user }) => {
auth.setUser(user);
})
.catch((error) => {
console.error(error);
});
await api.get("/config").then(({ data: data }) => {
configStore.set(data);
});
}
});
});
</script>
<template>
<v-app>

View File

@@ -17,6 +17,7 @@ export type { CollectionSchema } from './models/CollectionSchema';
export type { ConfigResponse } from './models/ConfigResponse';
export type { DetailedRomSchema } from './models/DetailedRomSchema';
export type { EmulationDict } from './models/EmulationDict';
export type { FilesystemDict } from './models/FilesystemDict';
export type { FirmwareSchema } from './models/FirmwareSchema';
export type { FrontendDict } from './models/FrontendDict';
export type { HeartbeatResponse } from './models/HeartbeatResponse';
@@ -44,6 +45,7 @@ export type { SearchRomSchema } from './models/SearchRomSchema';
export type { SimpleRomSchema } from './models/SimpleRomSchema';
export type { StateSchema } from './models/StateSchema';
export type { StatsReturn } from './models/StatsReturn';
export type { SystemDict } from './models/SystemDict';
export type { TaskDict } from './models/TaskDict';
export type { TinfoilFeedFileSchema } from './models/TinfoilFeedFileSchema';
export type { TinfoilFeedSchema } from './models/TinfoilFeedSchema';

View File

@@ -36,6 +36,7 @@ export type DetailedRomSchema = {
summary: (string | null);
first_release_date: (number | null);
youtube_video_id: (string | null);
average_rating: (number | null);
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type FilesystemDict = {
FS_PLATFORMS: Array<string>;
};

View File

@@ -5,5 +5,6 @@
export type FrontendDict = {
UPLOAD_TIMEOUT: number;
DISABLE_USERPASS_LOGIN: boolean;
};

View File

@@ -4,20 +4,20 @@
/* eslint-disable */
import type { EmulationDict } from './EmulationDict';
import type { FilesystemDict } from './FilesystemDict';
import type { FrontendDict } from './FrontendDict';
import type { MetadataSourcesDict } from './MetadataSourcesDict';
import type { OIDCDict } from './OIDCDict';
import type { SchedulerDict } from './SchedulerDict';
import type { SystemDict } from './SystemDict';
import type { WatcherDict } from './WatcherDict';
export type HeartbeatResponse = {
VERSION: string;
SHOW_SETUP_WIZARD: boolean;
SYSTEM: SystemDict;
WATCHER: WatcherDict;
SCHEDULER: SchedulerDict;
ANY_SOURCE_ENABLED: boolean;
METADATA_SOURCES: MetadataSourcesDict;
FS_PLATFORMS: Array<any>;
FILESYSTEM: FilesystemDict;
EMULATION: EmulationDict;
FRONTEND: FrontendDict;
OIDC: OIDCDict;

View File

@@ -4,6 +4,7 @@
/* eslint-disable */
export type MetadataSourcesDict = {
ANY_SOURCE_ENABLED: boolean;
IGDB_API_ENABLED: boolean;
MOBY_API_ENABLED: boolean;
STEAMGRIDDB_ENABLED: boolean;

View File

@@ -29,6 +29,7 @@ export type RomSchema = {
summary: (string | null);
first_release_date: (number | null);
youtube_video_id: (string | null);
average_rating: (number | null);
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;

View File

@@ -11,6 +11,7 @@ export type RomUserSchema = {
rom_id: number;
created_at: string;
updated_at: string;
last_played: (string | null);
note_raw_markdown: string;
note_is_public: boolean;
is_main_sibling: boolean;

View File

@@ -31,6 +31,7 @@ export type SimpleRomSchema = {
summary: (string | null);
first_release_date: (number | null);
youtube_video_id: (string | null);
average_rating: (number | null);
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;

View File

@@ -0,0 +1,10 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type SystemDict = {
VERSION: string;
SHOW_SETUP_WIZARD: boolean;
};

View File

@@ -4,15 +4,18 @@ import CopyRomDownloadLinkDialog from "@/components/common/Game/Dialog/CopyDownl
import romApi from "@/services/api/rom";
import storeDownload from "@/stores/download";
import storeHeartbeat from "@/stores/heartbeat";
import storeConfig from "@/stores/config";
import type { DetailedRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import {
getDownloadLink,
is3DSCIARom,
isEJSEmulationSupported,
isRuffleEmulationSupported,
} from "@/utils";
import type { Emitter } from "mitt";
import { computed, inject, ref } from "vue";
import { storeToRefs } from "pinia";
// Props
const props = defineProps<{ rom: DetailedRom }>();
@@ -20,26 +23,34 @@ const downloadStore = storeDownload();
const heartbeatStore = storeHeartbeat();
const emitter = inject<Emitter<Events>>("emitter");
const playInfoIcon = ref("mdi-play");
const qrCodeIcon = ref("mdi-qrcode");
const configStore = storeConfig();
const { config } = storeToRefs(configStore);
const ejsEmulationSupported = computed(() =>
isEJSEmulationSupported(props.rom.platform_slug, heartbeatStore.value),
);
const ruffleEmulationSupported = computed(() =>
isRuffleEmulationSupported(props.rom.platform_slug, heartbeatStore.value),
const platformSlug = computed(() =>
props.rom.platform_slug in config.value.PLATFORMS_VERSIONS
? config.value.PLATFORMS_VERSIONS[props.rom.platform_slug]
: props.rom.platform_slug,
);
const ejsEmulationSupported = computed(() => {
return isEJSEmulationSupported(platformSlug.value, heartbeatStore.value);
});
const ruffleEmulationSupported = computed(() => {
return isRuffleEmulationSupported(platformSlug.value, heartbeatStore.value);
});
const is3DSRom = computed(() => {
return is3DSCIARom(props.rom);
});
// Functions
async function copyDownloadLink(rom: DetailedRom) {
const downloadLink =
location.protocol +
"//" +
location.host +
encodeURI(
getDownloadLink({
rom,
fileIDs: downloadStore.fileIDsToDownload,
}),
);
const downloadLink = getDownloadLink({
rom,
files: downloadStore.fileIDsToDownload,
});
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(downloadLink);
emitter?.emit("snackbarShow", {
@@ -110,6 +121,13 @@ async function copyDownloadLink(rom: DetailedRom) {
>
<v-icon :icon="playInfoIcon" />
</v-btn>
<v-btn
v-if="is3DSRom"
class="flex-grow-1"
@click="emitter?.emit('showQRCodeDialog', rom)"
>
<v-icon :icon="qrCodeIcon" />
</v-btn>
<v-menu location="bottom">
<template #activator="{ props: menuProps }">
<v-btn class="flex-grow-1" v-bind="menuProps">

View File

@@ -11,7 +11,7 @@ import { useDisplay } from "vuetify";
const props = defineProps<{ rom: DetailedRom }>();
const { smAndDown } = useDisplay();
const releaseDate = new Date(
Number(props.rom.first_release_date) * 1000,
Number(props.rom.first_release_date),
).toLocaleDateString("en-US", {
day: "2-digit",
month: "short",

View File

@@ -14,8 +14,9 @@ const version = ref(props.rom.id);
function formatTitle(rom: RomSchema) {
const langs = rom.languages.map((l) => languageToEmoji(l)).join(" ");
const regions = rom.regions.map((r) => regionToEmoji(r)).join(" ");
const revision = rom.revision ? `[rev-${rom.revision}]` : "";
const tags = rom.tags.map((t) => `(${t})`).join(" ");
return `${langs} ${regions} ${tags}`.trim();
return `${langs} ${regions} ${revision} ${tags}`.trim();
}
function updateVersion() {

View File

@@ -141,41 +141,42 @@ async function updateCollection() {
>
<v-row no-gutters class="justify-center align-center pa-4">
<v-col style="max-width: 240px" cols="12">
<div
v-if="
currentCollection.user__username === auth.user?.username &&
auth.scopes.includes('collections.write')
"
class="text-center justify-center align-center"
>
<div class="text-center justify-center align-center">
<div class="position-absolute append-top-right">
<v-btn
v-if="!isEditable"
:loading="updating"
class="bg-terciary"
@click="showEditable"
size="small"
<template
v-if="
currentCollection.user__username === auth.user?.username &&
auth.scopes.includes('collections.write')
"
>
<template #loader>
<v-progress-circular
color="romm-accent-1"
:width="2"
:size="20"
indeterminate
/>
</template>
<v-icon>mdi-pencil</v-icon></v-btn
>
<template v-else>
<v-btn @click="closeEditable" size="small" class="bg-terciary"
><v-icon color="romm-red">mdi-close</v-icon></v-btn
>
<v-btn
@click="updateCollection()"
v-if="!isEditable"
:loading="updating"
class="bg-terciary"
@click="showEditable"
size="small"
class="bg-terciary ml-1"
><v-icon color="romm-green">mdi-check</v-icon></v-btn
>
<template #loader>
<v-progress-circular
color="romm-accent-1"
:width="2"
:size="20"
indeterminate
/>
</template>
<v-icon>mdi-pencil</v-icon></v-btn
>
<template v-else>
<v-btn @click="closeEditable" size="small" class="bg-terciary"
><v-icon color="romm-red">mdi-close</v-icon></v-btn
>
<v-btn
@click="updateCollection()"
size="small"
class="bg-terciary ml-1"
><v-icon color="romm-green">mdi-check</v-icon></v-btn
>
</template>
</template>
</div>
<collection-card

View File

@@ -182,33 +182,35 @@ watch(
<v-col cols="12">
<div class="text-center justify-center align-center">
<div class="position-absolute append-top-right">
<v-btn
v-if="!isEditable"
:loading="updating"
class="bg-terciary"
@click="showEditable"
size="small"
>
<template #loader>
<v-progress-circular
color="romm-accent-1"
:width="2"
:size="20"
indeterminate
/>
</template>
<v-icon>mdi-pencil</v-icon></v-btn
>
<template v-else>
<v-btn @click="closeEditable" size="small" class="bg-terciary"
><v-icon color="romm-red">mdi-close</v-icon></v-btn
>
<template v-if="auth.scopes.includes('platforms.write')">
<v-btn
@click="updatePlatform()"
v-if="!isEditable"
:loading="updating"
class="bg-terciary"
@click="showEditable"
size="small"
class="bg-terciary ml-1"
><v-icon color="romm-green">mdi-check</v-icon></v-btn
>
<template #loader>
<v-progress-circular
color="romm-accent-1"
:width="2"
:size="20"
indeterminate
/>
</template>
<v-icon>mdi-pencil</v-icon></v-btn
>
<template v-else>
<v-btn @click="closeEditable" size="small" class="bg-terciary"
><v-icon color="romm-red">mdi-close</v-icon></v-btn
>
<v-btn
@click="updatePlatform()"
size="small"
class="bg-terciary ml-1"
><v-icon color="romm-green">mdi-check</v-icon></v-btn
>
</template>
</template>
</div>
<platform-icon

View File

@@ -9,23 +9,22 @@ import type { Platform } from "@/stores/platforms";
import type { Events } from "@/types/emitter";
import type { Emitter } from "mitt";
const romsStore = storeRoms();
const { t } = useI18n();
const searching = ref(false);
const romsStore = storeRoms();
const { gettingRoms } = storeToRefs(romsStore);
const searched = ref(false);
const searchedRoms = ref<Platform[]>([]);
const selectedPlatform = ref<Platform | null>(null);
const emitter = inject<Emitter<Events>>("emitter");
const galleryFilterStore = storeGalleryFilter();
const { searchText, filterPlatforms } = storeToRefs(galleryFilterStore);
const { searchText } = storeToRefs(galleryFilterStore);
async function fetchRoms() {
function fetchRoms() {
if (searchText.value) {
gettingRoms.value = true;
const inputElement = document.getElementById("search-text-field");
inputElement?.blur();
searching.value = true;
searched.value = true;
await romApi
romApi
.getRoms({ searchTerm: searchText.value })
.then(({ data }) => {
data = data.sort((a, b) => {
@@ -44,19 +43,13 @@ async function fetchRoms() {
console.error(`Couldn't fetch roms: ${error}`);
})
.finally(() => {
searching.value = false;
gettingRoms.value = false;
});
searching.value = false;
filterRoms();
galleryFilterStore.activeFilterDrawer = false;
}
}
function clearFilter() {
selectedPlatform.value = null;
fetchRoms();
}
function filterRoms() {
if (selectedPlatform.value) {
romsStore.setFiltered(
@@ -80,6 +73,6 @@ function filterRoms() {
rounded="0"
variant="text"
icon="mdi-magnify"
:disabled="searching || !searchText"
:disabled="gettingRoms || !searchText"
/>
</template>

View File

@@ -5,7 +5,7 @@ import storeGalleryFilter from "@/stores/galleryFilter";
import storePlatforms from "@/stores/platforms";
import type { Events } from "@/types/emitter";
import type { Emitter } from "mitt";
import { inject, ref } from "vue";
import { inject } from "vue";
import { storeToRefs } from "pinia";
import { useDisplay } from "vuetify";
import type { Platform } from "@/stores/platforms";
@@ -15,12 +15,12 @@ import { useI18n } from "vue-i18n";
const { xs } = useDisplay();
const { t } = useI18n();
const romsStore = storeRoms();
const { gettingRoms } = storeToRefs(romsStore);
const emitter = inject<Emitter<Events>>("emitter");
const searching = ref(false);
const platformsStore = storePlatforms();
const { allPlatforms } = storeToRefs(platformsStore);
const galleryFilterStore = storeGalleryFilter();
const { searchText, filterPlatforms } = storeToRefs(galleryFilterStore);
const { searchText } = storeToRefs(galleryFilterStore);
// Functions
function setFilters() {
@@ -61,13 +61,13 @@ function setFilters() {
]);
}
async function fetchRoms() {
function fetchRoms() {
if (searchText.value) {
// Auto hide android keyboard
const inputElement = document.getElementById("search-text-field");
inputElement?.blur();
searching.value = true;
await romApi
gettingRoms.value = true;
romApi
.getRoms({ searchTerm: searchText.value })
.then(({ data }) => {
data = data.sort((a, b) => {
@@ -86,7 +86,7 @@ async function fetchRoms() {
console.error(`Couldn't fetch roms: ${error}`);
})
.finally(() => {
searching.value = false;
gettingRoms.value = false;
});
galleryFilterStore.setFilterPlatforms([
...new Map(
@@ -99,7 +99,6 @@ async function fetchRoms() {
).values(),
] as Platform[]);
setFilters();
searching.value = false;
galleryFilterStore.activeFilterDrawer = false;
}
}
@@ -113,7 +112,7 @@ async function fetchRoms() {
autofocus
@keyup.enter="fetchRoms"
v-model="searchText"
:disabled="searching"
:disabled="gettingRoms"
:label="t('common.search')"
hide-details
class="bg-terciary"

View File

@@ -0,0 +1,53 @@
<script setup lang="ts">
import GameCard from "@/components/common/Game/Card/Base.vue";
import RSection from "@/components/common/RSection.vue";
import storeRoms from "@/stores/roms";
import { views } from "@/utils";
import { storeToRefs } from "pinia";
import { isNull } from "lodash";
import { useI18n } from "vue-i18n";
// Props
const { t } = useI18n();
const romsStore = storeRoms();
const { continuePlayingRoms } = storeToRefs(romsStore);
const gridContinuePlayingRoms = isNull(
localStorage.getItem("settings.gridContinuePlayingRoms"),
)
? false
: localStorage.getItem("settings.gridContinuePlayingRoms") === "true";
</script>
<template>
<r-section icon="mdi-play" :title="t('home.continue-playing')">
<template #content>
<v-row
:class="{ 'flex-nowrap overflow-x-auto': !gridContinuePlayingRoms }"
no-gutters
>
<v-col
v-for="rom in continuePlayingRoms"
:key="rom.id"
class="px-1 pt-1 pb-2 align-self-end"
:cols="views[0]['size-cols']"
:sm="views[0]['size-sm']"
:md="views[0]['size-md']"
:lg="views[0]['size-lg']"
:xl="views[0]['size-xl']"
>
<game-card
:key="rom.updated_at"
:rom="rom"
title-on-hover
pointer-on-hover
with-link
show-flags
show-fav
transform-scale
show-action-bar
show-platform-icon
/>
</v-col>
</v-row>
</template>
</r-section>
</template>

Some files were not shown because too many files have changed in this diff Show More