Merge branch 'rommapp:master' into master
44
.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "ROMM Development",
|
||||
"dockerComposeFile": "docker-compose.yml",
|
||||
"service": "romm-dev",
|
||||
"workspaceFolder": "/app",
|
||||
"shutdownAction": "stopCompose",
|
||||
"forwardPorts": [5000, 3000, 3306, 6379],
|
||||
"portsAttributes": {
|
||||
"5000": {
|
||||
"label": "Backend API",
|
||||
"onAutoForward": "notify"
|
||||
},
|
||||
"3000": {
|
||||
"label": "Frontend Dev Server",
|
||||
"onAutoForward": "notify"
|
||||
},
|
||||
"3306": {
|
||||
"label": "MariaDB",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"6379": {
|
||||
"label": "Valkey/Redis",
|
||||
"onAutoForward": "silent"
|
||||
}
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-python.python",
|
||||
"ms-python.pylint",
|
||||
"ms-python.black-formatter",
|
||||
"bradlc.vscode-tailwindcss",
|
||||
"vue.volar",
|
||||
"ms-vscode.vscode-typescript-next"
|
||||
],
|
||||
"settings": {
|
||||
"python.defaultInterpreterPath": "/usr/local/bin/python",
|
||||
"terminal.integrated.defaultProfile.linux": "bash"
|
||||
}
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "echo 'ROMM development environment ready!'",
|
||||
"remoteUser": "root"
|
||||
}
|
||||
6
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,12 +1,10 @@
|
||||
<!-- trunk-ignore-all(markdownlint/MD041) -->
|
||||
<!-- trunk-ignore-all(markdownlint/MD033) -->
|
||||
|
||||
#### Description
|
||||
|
||||
**Description**
|
||||
<sup>Explain the changes or enhancements you are proposing with this pull request.</sup>
|
||||
|
||||
#### Checklist
|
||||
|
||||
**Checklist**
|
||||
<sup>Please check all that apply.</sup>
|
||||
|
||||
- [ ] I've tested the changes locally
|
||||
|
||||
16
.github/dependabot.yml
vendored
@@ -1,16 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/frontend"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
reviewers:
|
||||
- "gantoine"
|
||||
target-branch: "master"
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
reviewers:
|
||||
- "adamantike"
|
||||
target-branch: "master"
|
||||
BIN
.github/resources/aikido-badge.png
vendored
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
.github/resources/hackernews_badge.svg
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="288.99" height="67"><g fill="none" fill-rule="evenodd"><rect width="286.99" height="65" x="1" y="1" fill="#f60" stroke="#f60" stroke-width="2" rx="8"/><rect width="40" height="40" x="14" y="14" fill="#fff" rx="3"/><path fill="#f60" fill-rule="nonzero" d="M32.684 37.277 26 24h3.055l3.932 8.402q.09.225.211.465.122.24.212.497.06.097.09.177.031.08.061.144.151.32.273.625.12.305.211.562.242-.546.53-1.17.287-.626.59-1.3L39.156 24H42l-6.745 13.437V46h-2.57v-8.723z"/><text fill="#fff" font-family="Arial" font-size="25" font-weight="bold"><tspan x="66" y="51">Hacker News</tspan></text><text fill="#fff" font-family="Arial" font-size="18" font-weight="bold"><tspan x="238.75" y="51">238</tspan></text><text fill="#fff" font-family="Arial" font-size="20" font-weight="bold"><tspan x="244.37" y="30">▲</tspan></text><text fill="#fff" font-family="Arial" font-size="12" font-weight="bold"><tspan x="66" y="26">FEATURED ON</tspan></text></g></svg>
|
||||
|
After Width: | Height: | Size: 988 B |
BIN
.github/resources/isotipo.png
vendored
|
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 661 KiB |
2
.github/resources/isotipo.svg
vendored
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 9.9 KiB |
BIN
.github/resources/logotipo.png
vendored
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 6.8 KiB |
2
.github/resources/logotipo.svg
vendored
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" version="1.0" viewBox="0 0 375 375"><path fill="#553e98" d="M8.828 220.458h25.176c1.41 0 2.52-1.207 2.52-2.618v-23.566a2.49 2.49 0 0 1 2.515-2.516h15.105c1.41 0 2.52 1.106 2.52 2.516v23.664c0 1.41 1.105 2.52 2.516 2.52h25.175c1.41 0 2.52-1.207 2.52-2.618v-24.875c0-5.94-4.332-10.273-10.274-10.273h-.906a2.49 2.49 0 0 1-2.515-2.516c0-1.41 1.105-2.52 2.515-2.52h.906c5.942 0 10.274-4.327 10.274-10.269V156.31c0-9.465-6.95-16.414-16.414-16.414H8.828a2.49 2.49 0 0 0-2.516 2.516v75.527c0 1.41 1.106 2.52 2.516 2.52m30.21-51.864a2.49 2.49 0 0 1-2.515-2.515c0-1.41 1.106-2.52 2.516-2.52h15.105c1.41 0 2.52 1.11 2.52 2.52s-1.11 2.515-2.52 2.515Zm73.382 51.863h24.37c11.883 0 20.543-8.66 20.543-20.543v-39.477c0-11.883-8.66-20.543-20.543-20.543h-24.37c-11.883 0-20.544 8.66-20.544 20.543v39.477c0 11.883 8.66 20.543 20.543 20.543m12.183-23.16a2.493 2.493 0 0 1-2.516-2.52v-29.203c0-1.41 1.106-2.52 2.516-2.52s2.52 1.11 2.52 2.52v29.203c0 1.41-1.11 2.52-2.52 2.52m40.356 23.16h25.074c1.41 0 2.52-1.11 2.52-2.52v-44.812a2.49 2.49 0 0 1 2.515-2.516c1.41 0 2.52 1.105 2.52 2.516v45.015c0 1.309 1.207 2.317 2.516 2.317h25.175c1.309 0 2.52-1.008 2.52-2.317v-45.015a2.49 2.49 0 0 1 2.515-2.516c1.41 0 2.52 1.105 2.52 2.516v44.812c0 1.41 1.207 2.52 2.617 2.52h25.074c1.41 0 2.52-1.11 2.52-2.52v-75.527c0-1.41-1.211-2.516-2.617-2.516h-42.7c-1.41 0-2.519 1.207-2.519 2.617v14a2.49 2.49 0 0 1-2.516 2.516c-1.41 0-2.52-1.11-2.52-2.516v-14.101c0-1.41-1.206-2.516-2.616-2.516h-42.7a2.49 2.49 0 0 0-2.515 2.516v75.527c0 1.41 1.207 2.52 2.617 2.52m105.697 0h25.074c1.41 0 2.52-1.11 2.52-2.52v-44.812a2.49 2.49 0 0 1 2.515-2.516c1.41 0 2.52 1.105 2.52 2.516v45.015c0 1.309 1.207 2.317 2.515 2.317h25.176c1.309 0 2.52-1.008 2.52-2.317v-45.015a2.49 2.49 0 0 1 2.515-2.516c1.41 0 2.52 1.105 2.52 2.516v44.812c0 1.41 1.207 2.52 2.617 2.52h25.074c1.41 0 2.52-1.11 2.52-2.52v-75.527c0-1.41-1.211-2.516-2.618-2.516h-42.699c-1.41 0-2.52 1.207-2.52 2.617v14a2.49 2.49 0 0 1-2.515 2.516c-1.41 0-2.52-1.11-2.52-2.516v-14.101c0-1.41-1.206-2.516-2.617-2.516h-42.699a2.49 2.49 0 0 0-2.515 2.516v75.527c0 1.41 1.207 2.52 2.617 2.52m0 0"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="481.98" height="108.14" data-name="Layer 1" viewBox="0 0 481.98 108.14"><path d="M0 108.14V.15h85.76q6.15 0 11.19 3c3.35 2 6.06 4.71 8.11 8.11s3.08 7.11 3.08 11.11v27.94c0 4.01-1.03 7.71-3.08 11.11s-4.76 6.11-8.11 8.11c-3.36 2-7.08 3-11.19 3l-62.48.15v35.45H0Zm84.56-59.03V23.43H23.28v25.68zm-.6 59.03-31.39-37.4h30.49l24.93 29.44v7.96zm52.87 0c-4.01 0-7.71-1-11.11-3-3.41-2-6.11-4.71-8.11-8.11s-3-7.11-3-11.12V22.23q0-6.15 3-11.19c2-3.35 4.71-6.03 8.11-8.04 3.4-2 7.11-3 11.11-3h63.68q6 0 11.04 3c3.35 2 6.06 4.68 8.11 8.04s3.08 7.08 3.08 11.19v63.68c0 4.01-1.03 7.71-3.08 11.12s-4.76 6.11-8.11 8.11q-5.04 3-11.04 3zm62.33-23.43V23.43h-61.28v61.28zm31.09 23.43V0h24.03l36.65 43.71L327.43 0h24.18v108.14h-23.43V35.6l-37.25 44.46-37.4-44.31v72.39zm130.37 0V0h24.03l36.65 43.71L457.8 0h24.18v108.14h-23.43V35.6L421.3 80.06l-37.4-44.31v72.39z" style="fill:#553e98"/></svg>
|
||||
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 916 B |
BIN
.github/resources/screenshots/preview-desktop.gif
vendored
|
Before Width: | Height: | Size: 24 MiB After Width: | Height: | Size: 44 MiB |
BIN
.github/resources/screenshots/preview-desktop.webp
vendored
Normal file
|
After Width: | Height: | Size: 15 MiB |
BIN
.github/resources/screenshots/preview-mobile.gif
vendored
|
Before Width: | Height: | Size: 30 MiB After Width: | Height: | Size: 27 MiB |
BIN
.github/resources/screenshots/preview-mobile.webp
vendored
Normal file
|
After Width: | Height: | Size: 10 MiB |
2
.github/resources/social_preview.svg
vendored
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 7.6 KiB |
2
.github/workflows/build.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
||||
id: check_tag
|
||||
run: |
|
||||
TAG="${{ github.event.release.tag_name }}"
|
||||
if [[ "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-alpha\.[0-9]+|-beta\.[0-9]+)?$ ]]; then
|
||||
if [[ "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-alpha\.[0-9]+|-beta\.[0-9]+|-rc\.[0-9]+)?$ ]]; then
|
||||
echo "valid=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
|
||||
24
.github/workflows/i18n.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
name: I18N Localization Check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "frontend/src/locales/**/*.json"
|
||||
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
check-translations:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Run localization check
|
||||
run: python frontend/src/locales/check_i18n_locales.py
|
||||
27
.github/workflows/pytest.yml
vendored
@@ -38,19 +38,16 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libmariadb3 libmariadb-dev
|
||||
|
||||
- name: Install poetry
|
||||
run: |
|
||||
pipx install poetry
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "poetry"
|
||||
- name: Install python
|
||||
run: |
|
||||
uv python install 3.13
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
poetry sync --extras test
|
||||
uv sync --extra test
|
||||
|
||||
- name: Initiate database
|
||||
run: |
|
||||
@@ -62,11 +59,17 @@ jobs:
|
||||
DB_PORT: ${{ job.services.mariadb.ports['3306'] }}
|
||||
run: |
|
||||
cd backend
|
||||
poetry run pytest -vv --maxfail=10 --junitxml=pytest-report.xml .
|
||||
uv run pytest -vv --maxfail=10 --junitxml=pytest-report.xml --cov --cov-report xml:coverage.xml --cov-config=.coveragerc .
|
||||
|
||||
- name: Publish test results
|
||||
uses: EnricoMi/publish-unit-test-result-action/composite@v2
|
||||
if: always()
|
||||
uses: EnricoMi/publish-unit-test-result-action/linux@v2
|
||||
if: (!cancelled())
|
||||
with:
|
||||
files: |
|
||||
backend/pytest-report.xml
|
||||
|
||||
- name: Publish coverage report
|
||||
uses: orgoro/coverage@v3.2
|
||||
with:
|
||||
coverageFile: backend/coverage.xml
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
64
.github/workflows/test-build.yml
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
name: Build Experimental Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
# trunk-ignore(checkov/CKV_GHA_7)
|
||||
branch:
|
||||
description: "Git branch to build"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
packages: write
|
||||
actions: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
packages: write
|
||||
steps:
|
||||
- name: Run only once per workflow
|
||||
run: echo "Triggered by ${{ github.event_name }}"
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.branch }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Generate Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
name=rommapp/romm-testing
|
||||
tags: |
|
||||
type=raw,value=${{ github.event.inputs.branch }}
|
||||
|
||||
- name: Build full image
|
||||
id: build-full
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
file: docker/Dockerfile
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/arm64,linux/amd64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
target: full-image
|
||||
4
.gitignore
vendored
@@ -53,9 +53,11 @@ romm_mock
|
||||
# testing
|
||||
backend/romm_test/resources
|
||||
backend/romm_test/logs
|
||||
backend/romm_test/config
|
||||
.pytest_cache
|
||||
/romm_test
|
||||
.coverage
|
||||
pytest-report.xml
|
||||
coverage.xml
|
||||
|
||||
# service worker
|
||||
frontend/dev-dist
|
||||
|
||||
@@ -1 +1 @@
|
||||
3.12
|
||||
3.13
|
||||
|
||||
@@ -2,42 +2,45 @@
|
||||
# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml
|
||||
version: 0.1
|
||||
cli:
|
||||
version: 1.22.10
|
||||
version: 1.24.0
|
||||
# Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins)
|
||||
plugins:
|
||||
sources:
|
||||
- id: trunk
|
||||
ref: v1.6.7
|
||||
ref: v1.7.1
|
||||
uri: https://github.com/trunk-io/plugins
|
||||
# Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes)
|
||||
runtimes:
|
||||
enabled:
|
||||
- go@1.21.0
|
||||
- node@18.20.5
|
||||
- python@3.12.2
|
||||
- node@22.16.0
|
||||
- python@3.13.3
|
||||
# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration)
|
||||
lint:
|
||||
disabled:
|
||||
- pyright
|
||||
enabled:
|
||||
- markdownlint@0.44.0
|
||||
- eslint@9.20.1
|
||||
- hadolint@2.12.1-beta
|
||||
- markdownlint@0.45.0
|
||||
- eslint@9.31.0
|
||||
- actionlint@1.7.7
|
||||
- bandit@1.8.3
|
||||
- bandit@1.8.6
|
||||
- black@25.1.0
|
||||
- checkov@3.2.372
|
||||
- checkov@3.2.451
|
||||
- git-diff-check
|
||||
- isort@6.0.0
|
||||
- mypy@1.15.0
|
||||
- osv-scanner@1.9.2
|
||||
- oxipng@9.1.4
|
||||
- prettier@3.5.1
|
||||
- ruff@0.9.7
|
||||
- isort@6.0.1
|
||||
- mypy@1.17.0
|
||||
- osv-scanner@2.0.3
|
||||
- oxipng@9.1.5
|
||||
- prettier@3.6.2
|
||||
- ruff@0.12.4
|
||||
- shellcheck@0.10.0
|
||||
- shfmt@3.6.0
|
||||
- svgo@3.3.2
|
||||
- svgo@4.0.0
|
||||
- taplo@0.9.3
|
||||
- trivy@0.59.1
|
||||
- trufflehog@3.88.12
|
||||
- yamllint@1.35.1
|
||||
- trivy@0.64.1
|
||||
- trufflehog@3.90.1
|
||||
- yamllint@1.37.1
|
||||
ignore:
|
||||
- linters: [ALL]
|
||||
paths:
|
||||
|
||||
16
.vscode/settings.json
vendored
@@ -3,5 +3,19 @@
|
||||
"python.testing.pytestArgs": ["."],
|
||||
"python.testing.unittestEnabled": false,
|
||||
"python.testing.pytestEnabled": true,
|
||||
"postman.settings.dotenv-detection-notification-visibility": false
|
||||
"sqltools.connections": [
|
||||
{
|
||||
"mysqlOptions": {
|
||||
"authProtocol": "default",
|
||||
"enableSsl": "Disabled"
|
||||
},
|
||||
"previewLimit": 50,
|
||||
"server": "localhost",
|
||||
"port": 3306,
|
||||
"driver": "MariaDB",
|
||||
"name": "romm (dev)",
|
||||
"database": "romm",
|
||||
"username": "root"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
12
.vscode/tasks.json
vendored
@@ -11,19 +11,13 @@
|
||||
{
|
||||
"label": "Launch backend",
|
||||
"type": "shell",
|
||||
"command": "cd backend && poetry run python3 main.py",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Launch worker",
|
||||
"type": "shell",
|
||||
"command": "cd backend && poetry run python3 worker.py",
|
||||
"command": "cd backend && uv run python3 main.py",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Execute tests",
|
||||
"type": "shell",
|
||||
"command": "cd backend && poetry run pytest -vv -c ../pytest.ini",
|
||||
"command": "cd backend && uv run pytest -vv",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
@@ -40,7 +34,7 @@
|
||||
},
|
||||
{
|
||||
"label": "Launch full stack",
|
||||
"dependsOn": ["Launch frontend", "Launch backend", "Launch worker"],
|
||||
"dependsOn": ["Launch frontend", "Launch backend"],
|
||||
"problemMatcher": [],
|
||||
"dependsOrder": "parallel"
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
|
||||
## v3.0.0 (_11-03-2024_)
|
||||
|
||||
- Highlight: [EmulatorJS player](https://github.com/rommapp/romm/wiki/EmulatorJS-Player): Play retro games in your web browser
|
||||
- Highlight: [EmulatorJS player](https://docs.romm.app/latest/Platforms-and-Players/EmulatorJS-Player): Play retro games in your web browser
|
||||
- Highlight: Saves and states: Upload/downlaod game saves, and play them with EmulatorJS
|
||||
- Highlight: More metadata: Extracts more information from IGDB, like release date, genres, related games, etc.
|
||||
- Highlight: New license: Now licensed under AGPL-3.0 to promote community contributions
|
||||
|
||||
@@ -8,9 +8,9 @@ Thank you for considering contributing to RomM! This document outlines some guid
|
||||
|
||||
Please note that this project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). By participating in this project, you are expected to uphold this code.
|
||||
|
||||
## Contributing to the Wiki
|
||||
## Contributing to the Docs
|
||||
|
||||
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).
|
||||
If you would like to contribute to the project's [documentation](https://docs.romm.app), open a pull request against [the docs repo](https://github.com/rommapp/docs). We welcome any contributions that help improve the documentation (new pages, updates, or corrections).
|
||||
|
||||
## Adding Translations
|
||||
|
||||
@@ -51,8 +51,8 @@ If you encounter any bugs or have suggestions for improvements, please [create a
|
||||
|
||||
## Licensing
|
||||
|
||||
By contributing to ROMM, you agree that your contributions will be licensed under the project's [LICENSE](LICENSE).
|
||||
By contributing to RomM, you agree that your contributions will be licensed under the project's [LICENSE](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
Thank you for contributing to ROMM! Your help is greatly appreciated.
|
||||
Thank you for contributing to RomM! Your help is greatly appreciated.
|
||||
|
||||
@@ -1,8 +1,53 @@
|
||||
# Setup for development environment
|
||||
<!-- trunk-ignore-all(markdownlint/MD024) -->
|
||||
|
||||
## Environment setup
|
||||
# Setting up RomM for development
|
||||
|
||||
### Mocking RomM structure
|
||||
## Option 1: Using Docker
|
||||
|
||||
If you prefer to use Docker for development, you can set up RomM using the provided Docker Compose configuration. This method simplifies the setup process by encapsulating all dependencies within Docker containers.
|
||||
|
||||
### Environment setup
|
||||
|
||||
#### Create the mock structure with at least one rom and empty config for manual testing
|
||||
|
||||
```sh
|
||||
mkdir -p romm_mock/library/roms/switch
|
||||
touch romm_mock/library/roms/switch/metroid.xci
|
||||
mkdir -p romm_mock/resources
|
||||
mkdir -p romm_mock/assets
|
||||
mkdir -p romm_mock/config
|
||||
touch romm_mock/config/config.yml
|
||||
```
|
||||
|
||||
#### Copy env.template to .env and fill the variables
|
||||
|
||||
```sh
|
||||
cp env.template .env
|
||||
```
|
||||
|
||||
```dotenv
|
||||
ROMM_BASE_PATH=/app/romm
|
||||
GUNICORN_WORKERS=4
|
||||
DEV_MODE=true
|
||||
```
|
||||
|
||||
#### Build the image
|
||||
|
||||
```sh
|
||||
docker compose build # or `docker compose build --no-cache` to rebuild from scratch
|
||||
```
|
||||
|
||||
#### Spin up the Docker containers
|
||||
|
||||
```sh
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
And you're done! You can access the app at `http://localhost:3000`. Any changes made to the code will be automatically reflected in the app thanks to the volume mounts.
|
||||
|
||||
## Option 2: Manual setup
|
||||
|
||||
### Environment setup
|
||||
|
||||
#### - Create the mock structure with at least one rom and empty config for manual testing
|
||||
|
||||
@@ -15,8 +60,6 @@ mkdir -p romm_mock/config
|
||||
touch romm_mock/config/config.yml
|
||||
```
|
||||
|
||||
### Setting up the backend
|
||||
|
||||
#### - Copy env.template to .env and fill the variables
|
||||
|
||||
```sh
|
||||
@@ -27,35 +70,39 @@ cp env.template .env
|
||||
|
||||
```sh
|
||||
# https://mariadb.com/docs/skysql-previous-release/connect/programming-languages/c/install/#Installation_via_Package_Repository_(Linux):
|
||||
sudo apt install libmariadb3 libmariadb-dev libpq-dev pipx
|
||||
sudo apt install libmariadb3 libmariadb-dev libpq-dev
|
||||
|
||||
# Build and configure RAHasher (optional)
|
||||
# This is only required to calculate RA hashes
|
||||
# Users on macOS can skip this step as RAHasher is not supported
|
||||
git clone --recursive https://github.com/RetroAchievements/RALibretro.git
|
||||
cd ./RALibretro
|
||||
git checkout 1.8.0
|
||||
git submodule update --init --recursive
|
||||
sed -i '22a #include <ctime>' ./src/Util.h
|
||||
make HAVE_CHD=1 -f ./Makefile.RAHasher
|
||||
cp ./bin64/RAHasher /usr/bin/RAHasher
|
||||
```
|
||||
|
||||
#### - Install python dependencies
|
||||
|
||||
You'll need poetry installed
|
||||
You'll need uv installed
|
||||
|
||||
<https://python-poetry.org/docs/#installing-with-the-official-installer>
|
||||
<https://docs.astral.sh/uv/getting-started/installation/>
|
||||
|
||||
```sh
|
||||
pipx install poetry
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
Then create the virtual environment
|
||||
Then create the virtual environment and install the dependencies using uv:
|
||||
|
||||
```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 sync
|
||||
```
|
||||
````sh
|
||||
uv venv
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras --dev
|
||||
``
|
||||
|
||||
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 sync
|
||||
```
|
||||
|
||||
#### - Spin up mariadb in docker
|
||||
#### - Spin up the database and other services
|
||||
|
||||
```sh
|
||||
docker compose up -d
|
||||
@@ -67,14 +114,7 @@ docker compose up -d
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
poetry run python3 main.py
|
||||
```
|
||||
|
||||
#### - Start a worker
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
poetry run python3 worker.py
|
||||
uv run python3 main.py
|
||||
```
|
||||
|
||||
### Setting up the frontend
|
||||
@@ -91,8 +131,8 @@ npm install
|
||||
|
||||
```sh
|
||||
mkdir assets/romm
|
||||
ln -s ../backend/romm_mock/resources assets/romm/resources
|
||||
ln -s ../backend/romm_mock/assets assets/romm/assets
|
||||
ln -s ../romm_mock/resources assets/romm/resources
|
||||
ln -s ../romm_mock/assets assets/romm/assets
|
||||
```
|
||||
|
||||
#### - Run the frontend
|
||||
@@ -101,17 +141,17 @@ ln -s ../backend/romm_mock/assets assets/romm/assets
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Setting up the linter
|
||||
## Setting up the linter
|
||||
|
||||
We use [Trunk](https://trunk.io) for linting, which combines multiple linters and formatters with sensible defaults and a single configuration file. You'll need to install the Trunk CLI to use it.
|
||||
|
||||
#### - Install the Trunk CLI
|
||||
### - Install the Trunk CLI
|
||||
|
||||
```sh
|
||||
curl https://get.trunk.io -fsSL | bash
|
||||
```
|
||||
|
||||
Alternative installation methods can be found [here](https://docs.trunk.io/check/usage#install-the-cli). On commit, the linter will run automatically. To run it manually, use the following commands:
|
||||
Alternative installation methods can be found [in their docs](https://docs.trunk.io/check/usage#install-the-cli). On commit, the linter will run automatically. To run it manually, use the following commands:
|
||||
|
||||
```sh
|
||||
trunk fmt
|
||||
@@ -125,7 +165,7 @@ trunk check
|
||||
### - Create the test user and database with root user
|
||||
|
||||
```sh
|
||||
docker exec -i romm-mariadb-dev mariadb -uroot -p<root password> < backend/romm_test/setup.sql
|
||||
docker exec -i romm-db-dev mariadb -uroot -p<root password> < backend/romm_test/setup.sql
|
||||
```
|
||||
|
||||
### - Run tests
|
||||
@@ -135,5 +175,9 @@ docker exec -i romm-mariadb-dev mariadb -uroot -p<root password> < backend/romm_
|
||||
```sh
|
||||
cd backend
|
||||
# path or test file can be passed as argument to test only a subset
|
||||
poetry run pytest [path/file]
|
||||
uv run pytest [path/file]
|
||||
# or run the following command to run all tests
|
||||
# the -vv switch increases the verbosity of the output, providing more detailed information during test execution.
|
||||
uv run pytest -vv
|
||||
```
|
||||
````
|
||||
|
||||
83
Dockerfile
Normal file
@@ -0,0 +1,83 @@
|
||||
# trunk-ignore-all(trivy)
|
||||
# trunk-ignore-all(checkov)
|
||||
|
||||
FROM ubuntu:22.04
|
||||
|
||||
# Prevent interactive prompts during installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
make \
|
||||
gcc \
|
||||
g++ \
|
||||
libmariadb3 \
|
||||
libmariadb-dev \
|
||||
libpq-dev \
|
||||
libffi-dev \
|
||||
musl-dev \
|
||||
curl \
|
||||
ca-certificates \
|
||||
libmagic-dev \
|
||||
7zip \
|
||||
tzdata \
|
||||
libbz2-dev \
|
||||
libssl-dev \
|
||||
libreadline-dev \
|
||||
libsqlite3-dev \
|
||||
zlib1g-dev \
|
||||
liblzma-dev \
|
||||
libncurses5-dev \
|
||||
libncursesw5-dev \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install nvm
|
||||
ENV NVM_DIR="/root/.nvm"
|
||||
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash \
|
||||
&& . "$NVM_DIR/nvm.sh" \
|
||||
&& nvm install 18.20.8 \
|
||||
&& nvm use 18.20.8 \
|
||||
&& nvm alias default 18.20.8
|
||||
ENV PATH="$NVM_DIR/versions/node/v18.20.8/bin:$PATH"
|
||||
|
||||
# Build and install RAHasher (optional for RA hashes)
|
||||
RUN git clone --recursive --branch 1.8.1 --depth 1 https://github.com/RetroAchievements/RALibretro.git /tmp/RALibretro
|
||||
WORKDIR /tmp/RALibretro
|
||||
RUN sed -i '22a #include <ctime>' ./src/Util.h \
|
||||
&& sed -i '6a #include <unistd.h>' \
|
||||
./src/libchdr/deps/zlib-1.3.1/gzlib.c \
|
||||
./src/libchdr/deps/zlib-1.3.1/gzread.c \
|
||||
./src/libchdr/deps/zlib-1.3.1/gzwrite.c \
|
||||
&& make HAVE_CHD=1 -f ./Makefile.RAHasher \
|
||||
&& cp ./bin64/RAHasher /usr/bin/RAHasher
|
||||
RUN rm -rf /tmp/RALibretro
|
||||
|
||||
# Install frontend dependencies
|
||||
COPY frontend/package.json /app/frontend/
|
||||
WORKDIR /app/frontend
|
||||
RUN npm install
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Install uv for the non-root user
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.19 /uv /uvx /usr/local/bin/
|
||||
|
||||
# Install Python
|
||||
RUN uv python install 3.13
|
||||
|
||||
# Copy project files (including pyproject.toml and uv.lock)
|
||||
COPY pyproject.toml uv.lock* .python-version /app/
|
||||
|
||||
# Install Python dependencies
|
||||
RUN uv sync --all-extras
|
||||
|
||||
ENV PATH="/app/.venv/bin:${PATH}"
|
||||
|
||||
# Copy entrypoint script
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
243
README.md
@@ -1,7 +1,6 @@
|
||||
<!-- trunk-ignore-all(markdownlint/MD033) -->
|
||||
<!-- trunk-ignore(markdownlint/MD041) -->
|
||||
<div align="center">
|
||||
|
||||
<img src=".github/resources/isotipo.png" height="180px" width="auto" alt="romm logo">
|
||||
<br />
|
||||
<img src=".github/resources/logotipo.png" height="45px" width="auto" alt="romm logotype">
|
||||
@@ -16,8 +15,7 @@
|
||||
[![docker-pulls-badge-img]][docker-pulls-badge]
|
||||
|
||||
[![discord-badge-img]][discord-badge]
|
||||
[![unraid-badge-img]][unraid-badge]
|
||||
[![wiki-badge-img]][wiki]
|
||||
[![docs-badge-img]][docs]
|
||||
|
||||
</div>
|
||||
</div>
|
||||
@@ -29,16 +27,11 @@
|
||||
- [Features](#features)
|
||||
- [Preview](#preview)
|
||||
- [Installation](#installation)
|
||||
- [Configuration](#configuration)
|
||||
- [Folder Structure](#folder-structure)
|
||||
- [Configuration File](#configuration-file)
|
||||
- [Scheduler](#scheduler)
|
||||
- [Naming Convention](#naming-convention)
|
||||
- [Platform Support](#platform-support)
|
||||
- [Tag Support](#tag-support)
|
||||
- [Contributing](#contributing)
|
||||
- [Community](#community)
|
||||
- [Support](#support)
|
||||
- [Our Friends](#our-friends)
|
||||
- [Technical Support](#technical-support)
|
||||
- [Project Support](#project-support)
|
||||
- [Our Friends](#our-friends)
|
||||
|
||||
# Overview
|
||||
|
||||
@@ -46,176 +39,55 @@ RomM (ROM Manager) allows you to scan, enrich, browse and play your game collect
|
||||
|
||||
## 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] 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)
|
||||
- Can [parse tags][tag-support] in filenames (e.g. (E), (USA), (rev v1), etc.)
|
||||
- Scan and enhance your game library with metadata from [IGDB][igdb-api], [Screenscraper][screenscraper-api] and [MobyGames][mobygames-api]
|
||||
- Fetch custom artwork from [SteamGridDB][steamgriddb-api]
|
||||
- Display your achievements from [Retroachievements][retroachievements-api]
|
||||
- Metadata available for [400+ platforms][docs-supported-platforms]
|
||||
- Play games directly from the browser using [EmulatorJS][docs-emulatorjs] and [RuffleRS][docs-rufflers]
|
||||
- Share your library with friends with limited access and permissions
|
||||
- Official apps for [Playnite][playnite-app] and [muOS][muos-app]
|
||||
- Supports multi-disk games, DLCs, mods, hacks, patches, and manuals
|
||||
- Parse and filter by [tags][docs-tag-support] in filenames
|
||||
- View, upload, update, and delete games from any modern web browser
|
||||
|
||||
## Preview
|
||||
|
||||
| 🖥 Desktop | 📱 Mobile |
|
||||
| :-----------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------: |
|
||||
| <img src=".github/resources/screenshots/preview-desktop.gif" alt="desktop preview" /> | <img style="width: 325px; aspect-ratio: auto;" src=".github/resources/screenshots/preview-mobile.gif" alt="mobile preview" /> |
|
||||
| 🖥 Desktop | 📱 Mobile |
|
||||
| :------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------: |
|
||||
| <img src=".github/resources/screenshots/preview-desktop.webp" alt="desktop preview" /> | <img style="width: 325px; aspect-ratio: auto;" src=".github/resources/screenshots/preview-mobile.webp" alt="mobile preview" /> |
|
||||
|
||||
# Installation
|
||||
|
||||
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.
|
||||
To start using RomM, check out the [Quick Start Guide][docs-quick-start-guide] in the docs. If you are having issues with RomM, please review the page for [troubleshooting steps][docs-troubleshooting].
|
||||
|
||||
# Configuration
|
||||
# Contributing
|
||||
|
||||
## Folder Structure
|
||||
|
||||
As mentioned in the installation section, RomM requires a specific folder structure. The two supported structures are as follows:
|
||||
|
||||
<table border="0">
|
||||
<tr>
|
||||
<th style="text-align: center"><b>Structure A (recommended)</b></tthd>
|
||||
<th style="text-align: center"><b>Structure B (fallback)</b></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>library/roms/gbc/game_1.gbc</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>library/gbc/roms/game_1.gbc</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<pre>
|
||||
library/
|
||||
├─ roms/
|
||||
│ ├─ gbc/
|
||||
│ │ ├─ game_1.gbc
|
||||
│ │ └─ game_2.gbc
|
||||
│ │
|
||||
│ ├─ gba/
|
||||
│ │ ├─ game_3.gba
|
||||
│ │ └─ game_4/
|
||||
│ │ ├─ game_4.gba
|
||||
│ │ ├─ dlc
|
||||
│ │ │ ├─ game_4_dlc_1.7z
|
||||
│ │ │ └─ game_4_dlc_2.7z
|
||||
│ │ ├─ hacks
|
||||
│ │ │ └─ game_4_hardmode.rar
|
||||
│ │ ├─ manuals
|
||||
│ │ │ └─ game_4_manual.pdf
|
||||
│ │ ├─ mods
|
||||
│ │ │ └─ game_4_crazy_mode.zip
|
||||
│ │ └─ patches
|
||||
│ │ └─ game_4_patch_v1.1.zip
|
||||
│ │
|
||||
│ └─ ps/
|
||||
│ ├─ game_5/
|
||||
│ │ ├─ game_5_cd_1.iso
|
||||
│ │ └─ game_5_cd_2.iso
|
||||
│ │
|
||||
│ └─ game_6.iso
|
||||
│
|
||||
└─ bios/
|
||||
├─ gba/
|
||||
│ └─ gba_bios.bin
|
||||
│
|
||||
└─ ps/
|
||||
├─ scph1001.bin
|
||||
├─ scph5501.bin
|
||||
└─ scph5502.bin
|
||||
</pre>
|
||||
</td>
|
||||
<td>
|
||||
<pre>
|
||||
library/
|
||||
├─ gbc/
|
||||
│ └─ roms/
|
||||
│ ├─ game_1.gbc
|
||||
│ └─ game_2.gbc
|
||||
│
|
||||
├─ gba/
|
||||
│ ├─ roms/
|
||||
│ │ ├─ game_3.gba
|
||||
│ │ └─ game_4/
|
||||
│ │ ├─ game_4.gba
|
||||
│ │ ├─ dlc
|
||||
│ │ │ ├─ game_4_dlc_1.7z
|
||||
│ │ │ └─ game_4_dlc_2.7z
|
||||
│ │ ├─ hacks
|
||||
│ │ │ └─ game_4_hardmode.rar
|
||||
│ │ ├─ manuals
|
||||
│ │ │ └─ game_4_manual.pdf
|
||||
│ │ ├─ mods
|
||||
│ │ │ └─ game_4_crazy_mode.zip
|
||||
│ │ └─ patches
|
||||
│ │ └─ game_4_patch_v1.1.zip
|
||||
│ │
|
||||
│ └─ bios/
|
||||
│ └─ gba_bios.bin
|
||||
│
|
||||
└─ ps/
|
||||
├─ roms/
|
||||
│ ├─ game_5/
|
||||
│ │ ├─ game_5_cd1.iso
|
||||
│ │ └─ game_5_cd2.iso
|
||||
│ │
|
||||
│ └─ game_6.iso
|
||||
│
|
||||
└─ bios/
|
||||
├─ scph1001.bin
|
||||
├─ scph5501.bin
|
||||
└─ scph5502.bin
|
||||
</pre>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
> [!TIP]
|
||||
> For folder naming conventions, review the [Platform Support][platform-support] section. To override default system names in the folder structure (if your directories are named differently), see the [Configuration File][configuration-file] section.
|
||||
|
||||
## Configuration File
|
||||
|
||||
RomM's "understanding" of your library can be configured with a `config.yaml` file or through the `config` tab in the `Control Panel` under the `Settings` section. Refer to the [example config.yml][configuration-file-example] file for guidance on how to configure it and the [example docker-compose.yml][docker-compose-example] file on how to mount it into the container.
|
||||
|
||||
## Scheduler
|
||||
|
||||
The scheduler allows you to schedule async tasks that run in the Redis container at regular intervals. Jobs can be run at a specific time in the future, after a time delta, or at recurring internals using cron notation. The [wiki page on the scheduler][wiki-scheduled-tasks] has more information on which tasks are available and how to enable them.
|
||||
|
||||
# Naming Convention
|
||||
|
||||
## Platform Support
|
||||
|
||||
If you adhere to the [RomM folder structure][folder-structure], RomM supports all platforms listed on the [Supported Platforms][wiki-supported-platforms] page. **The folder is case-sensitive and must be used exactly as it appears on the list.** When scanning your library, RomM will use the folder name to determine the platform and fetch the appropriate game information, metadata, and cover art.
|
||||
|
||||
## Tag Support
|
||||
|
||||
Games can be tagged with region, revision, or other tags by using parentheses in the file name. Additionally, you can set the region and language by adding a prefix: (USA), [reg-J], (French), [De].
|
||||
|
||||
- Revision tags must be prefixed with **"rev "** or **"rev-"** (e.g. **(rev v1)** or **(rev-1)**)
|
||||
- Other tags will also be imported, for example: **my_game [1.0001]\(HACK\)[!].gba**
|
||||
|
||||
Tags can be used to search for games in the search bar. For example, searching for **(USA)** will return all games with the USA tag.
|
||||
To contribute to RomM, please check [Contribution Guide](./CONTRIBUTING.md).
|
||||
|
||||
# Community
|
||||
|
||||
Here are a few projects maintained by members of our community. Please note that the RomM team does not regularly review their source code.
|
||||
|
||||
- [romm-comm][romm-comm-discord-bot]: Discord Bot by @idio-sync
|
||||
- CasaOS app via the [BigBear App Store][big-bear-casaos]
|
||||
- [Helm Chart to deploy on Kubernetes][kubernetes-helm-chart] by @psych0d0g
|
||||
- [DeckRommSync][deck-romm-sync]: SteamOS downloader and sync by @PeriBluGaming
|
||||
- [RommBrowser][romm-browser]: An electron client for RomM by @smurflabs
|
||||
- [RomM Android][romm-android]: An Android app for RomM by @mattsays
|
||||
|
||||
Join us on Discord, where you can ask questions, submit ideas, get help, showcase your collection, and discuss RomM with other users.
|
||||
|
||||
[![discord-invite-img]][discord-invite]
|
||||
|
||||
## Support
|
||||
# Technical Support
|
||||
|
||||
Consider supporting the development of this project on Open Collective.
|
||||
If you have any issues with RomM, please [open an issue](https://github.com/rommapp/romm/issues/new) in this repository.
|
||||
|
||||
# Project Support
|
||||
|
||||
Consider supporting the development of this project on Open Collective. All funds will be used to cover the costs of hosting, development, and maintenance of RomM.
|
||||
|
||||
[![oc-donate-img]][oc-donate]
|
||||
|
||||
## Our Friends
|
||||
# Our Friends
|
||||
|
||||
Here are a few projects that we think you might like:
|
||||
|
||||
@@ -224,29 +96,28 @@ Here are a few projects that we think you might like:
|
||||
- [ES-DE Frontend](https://es-de.org/): Emulator frontend for Linux, macOS and Windows
|
||||
- [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
|
||||
- [Drop](https://droposs.org/): Steam-like experience for DRM-free games
|
||||
- [LanCommander](https://lancommander.app/): Digital game platform for PC games
|
||||
- [Steam ROM Manager](https://steamgriddb.github.io/steam-rom-manager/): An app for managing ROMs in Steam
|
||||
|
||||
<!-- Sections -->
|
||||
<div align="center">
|
||||
<br />
|
||||
<div dir="auto">
|
||||
<a href="https://news.ycombinator.com/item?id=44247964" target="_blank"><img src=".github/resources/hackernews_badge.svg" width="250px" alt="hackernews badge"></a>
|
||||
|
||||
<span><img src=".github/resources/aikido-badge.png" alt="Aikido Security Audit Report" height="58" /></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
[folder-structure]: #folder-structure
|
||||
[platform-support]: #platform-support
|
||||
[tag-support]: #tag-support
|
||||
[configuration-file]: #configuration-file
|
||||
<!-- docs links -->
|
||||
|
||||
<!-- Files -->
|
||||
|
||||
[docker-compose-example]: examples/docker-compose.example.yml
|
||||
[configuration-file-example]: examples/config.example.yml
|
||||
|
||||
<!-- Wiki links -->
|
||||
|
||||
[wiki]: https://docs.romm.app/latest/
|
||||
[wiki-supported-platforms]: https://docs.romm.app/latest/Platforms-and-Players/Supported-Platforms/
|
||||
[wiki-authentication]: https://docs.romm.app/latest/Getting-Started/Authentication/
|
||||
[wiki-troubleshooting]: https://docs.romm.app/latest/Troubleshooting/
|
||||
[wiki-emulatorjs]: https://docs.romm.app/latest/Platforms-and-Players/EmulatorJS-Player/
|
||||
[wiki-scheduled-tasks]: https://docs.romm.app/latest/Maintenance/Scheduled-Tasks/
|
||||
[wiki-quick-start-guide]: https://docs.romm.app/latest/Getting-Started/Quick-Start-Guide/
|
||||
[docs]: https://docs.romm.app/latest/
|
||||
[docs-quick-start-guide]: https://docs.romm.app/latest/Getting-Started/Quick-Start-Guide/
|
||||
[docs-supported-platforms]: https://docs.romm.app/latest/Platforms-and-Players/Supported-Platforms/
|
||||
[docs-emulatorjs]: https://docs.romm.app/latest/Platforms-and-Players/EmulatorJS-Player/
|
||||
[docs-rufflers]: https://docs.romm.app/latest/Platforms-and-Players/RuffleRS-Player/
|
||||
[docs-troubleshooting]: https://docs.romm.app/latest/Troubleshooting/Scanning-Issues/
|
||||
[docs-tag-support]: https://docs.romm.app/latest/Getting-Started/Folder-Structure/#tag-support
|
||||
|
||||
<!-- Badges -->
|
||||
|
||||
@@ -256,9 +127,7 @@ Here are a few projects that we think you might like:
|
||||
[release-badge]: https://github.com/rommapp/romm/releases
|
||||
[discord-badge-img]: https://img.shields.io/badge/discord-7289da?style=for-the-badge
|
||||
[discord-badge]: https://discord.gg/P5HtHnhUDH
|
||||
[unraid-badge-img]: https://img.shields.io/badge/Unraid-f57842?style=for-the-badge&labelColor=ee512b
|
||||
[unraid-badge]: https://forums.unraid.net/topic/149738-support-eurotimmy-romm-rom-manager-by-zurdi15/
|
||||
[wiki-badge-img]: https://img.shields.io/badge/Wiki-736e9b?style=for-the-badge
|
||||
[docs-badge-img]: https://img.shields.io/badge/docs-736e9b?style=for-the-badge
|
||||
[docker-pulls-badge-img]: https://img.shields.io/docker/pulls/rommapp/romm?style=for-the-badge&label=pulls
|
||||
[docker-pulls-badge]: https://hub.docker.com/r/rommapp/romm
|
||||
|
||||
@@ -271,8 +140,14 @@ Here are a few projects that we think you might like:
|
||||
|
||||
<!-- External links -->
|
||||
|
||||
[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
|
||||
[kubernetes-helm-chart]: https://artifacthub.io/packages/helm/crystalnet/romm
|
||||
[igdb-api]: https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#igdb
|
||||
[screenscraper-api]: https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#screenscraper
|
||||
[mobygames-api]: https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#mobygames
|
||||
[steamgriddb-api]: https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#steamgriddb
|
||||
[retroachievements-api]: https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#retroachievements
|
||||
[romm-comm-discord-bot]: https://github.com/idio-sync/romm-comm
|
||||
[deck-romm-sync]: https://github.com/PeriBluGaming/DeckRommSync-Standalone
|
||||
[romm-browser]: https://github.com/smurflabs/RommBrowser/
|
||||
[romm-android]: https://github.com/mattsays/romm-android
|
||||
[playnite-app]: https://github.com/rommapp/playnite-plugin
|
||||
[muos-app]: https://github.com/rommapp/muos-app
|
||||
|
||||
4
backend/.coveragerc
Normal file
@@ -0,0 +1,4 @@
|
||||
[run]
|
||||
omit =
|
||||
alembic/*
|
||||
*/tests/*
|
||||
183
backend/adapters/services/mobygames.py
Normal file
@@ -0,0 +1,183 @@
|
||||
import asyncio
|
||||
import http
|
||||
import json
|
||||
from collections.abc import Collection
|
||||
from typing import Literal, overload
|
||||
|
||||
import aiohttp
|
||||
import yarl
|
||||
from adapters.services.mobygames_types import MobyGame, MobyGameBrief, MobyOutputFormat
|
||||
from aiohttp.client import ClientTimeout
|
||||
from config import MOBYGAMES_API_KEY
|
||||
from fastapi import HTTPException, status
|
||||
from logger.logger import log
|
||||
from utils.context import ctx_aiohttp_session
|
||||
|
||||
|
||||
async def auth_middleware(
|
||||
req: aiohttp.ClientRequest, handler: aiohttp.ClientHandlerType
|
||||
) -> aiohttp.ClientResponse:
|
||||
"""MobyGames API authentication mechanism."""
|
||||
req.url = req.url.update_query({"api_key": MOBYGAMES_API_KEY})
|
||||
return await handler(req)
|
||||
|
||||
|
||||
class MobyGamesService:
|
||||
"""Service to interact with the MobyGames API.
|
||||
|
||||
Reference: https://www.mobygames.com/info/api/
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://api.mobygames.com/v1")
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
|
||||
try:
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return await res.json()
|
||||
except aiohttp.ServerTimeoutError:
|
||||
# Retry the request once if it times out
|
||||
log.debug("Request to URL=%s timed out. Retrying...", url)
|
||||
except aiohttp.ClientConnectionError as exc:
|
||||
log.critical("Connection error: can't connect to MobyGames", exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Can't connect to MobyGames, check your internet connection",
|
||||
) from exc
|
||||
except aiohttp.ClientResponseError as exc:
|
||||
if exc.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
# Sometimes MobyGames returns 401 even with a valid API key
|
||||
log.error(exc)
|
||||
return {}
|
||||
elif exc.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Retry after 2 seconds if rate limit hit
|
||||
await asyncio.sleep(2)
|
||||
else:
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(exc)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
# Retry the request once if it times out
|
||||
try:
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return await res.json()
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as exc:
|
||||
if (
|
||||
isinstance(exc, aiohttp.ClientResponseError)
|
||||
and exc.status == http.HTTPStatus.UNAUTHORIZED
|
||||
):
|
||||
return {}
|
||||
|
||||
log.error(exc)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
@overload
|
||||
async def list_games(
|
||||
self,
|
||||
*,
|
||||
game_id: int | None = ...,
|
||||
platform_ids: Collection[int] | None = ...,
|
||||
genre_ids: Collection[int] | None = ...,
|
||||
group_ids: Collection[int] | None = ...,
|
||||
title: str | None = ...,
|
||||
output_format: Literal["id"],
|
||||
limit: int | None = ...,
|
||||
offset: int | None = ...,
|
||||
) -> list[int]: ...
|
||||
|
||||
@overload
|
||||
async def list_games(
|
||||
self,
|
||||
*,
|
||||
game_id: int | None = ...,
|
||||
platform_ids: Collection[int] | None = ...,
|
||||
genre_ids: Collection[int] | None = ...,
|
||||
group_ids: Collection[int] | None = ...,
|
||||
title: str | None = ...,
|
||||
output_format: Literal["brief"],
|
||||
limit: int | None = ...,
|
||||
offset: int | None = ...,
|
||||
) -> list[MobyGameBrief]: ...
|
||||
|
||||
@overload
|
||||
async def list_games(
|
||||
self,
|
||||
*,
|
||||
game_id: int | None = ...,
|
||||
platform_ids: Collection[int] | None = ...,
|
||||
genre_ids: Collection[int] | None = ...,
|
||||
group_ids: Collection[int] | None = ...,
|
||||
title: str | None = ...,
|
||||
output_format: Literal["normal"] = "normal",
|
||||
limit: int | None = ...,
|
||||
offset: int | None = ...,
|
||||
) -> list[MobyGame]: ...
|
||||
|
||||
async def list_games(
|
||||
self,
|
||||
*,
|
||||
game_id: int | None = None,
|
||||
platform_ids: Collection[int] | None = None,
|
||||
genre_ids: Collection[int] | None = None,
|
||||
group_ids: Collection[int] | None = None,
|
||||
title: str | None = None,
|
||||
output_format: MobyOutputFormat = "normal",
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
) -> list[int] | list[MobyGameBrief] | list[MobyGame]:
|
||||
"""Provides a list of games matching the filters given in the query parameters, ordered by ID.
|
||||
|
||||
Reference: https://www.mobygames.com/info/api/#games
|
||||
"""
|
||||
params: dict[str, list[str]] = {}
|
||||
if game_id:
|
||||
params["id"] = [str(game_id)]
|
||||
if platform_ids:
|
||||
params["platform"] = [str(id_) for id_ in platform_ids]
|
||||
if genre_ids:
|
||||
params["genre"] = [str(id_) for id_ in genre_ids]
|
||||
if group_ids:
|
||||
params["group"] = [str(id_) for id_ in group_ids]
|
||||
if title:
|
||||
params["title"] = [title]
|
||||
if output_format:
|
||||
params["format"] = [output_format]
|
||||
if limit is not None:
|
||||
params["limit"] = [str(limit)]
|
||||
if offset is not None:
|
||||
params["offset"] = [str(offset)]
|
||||
|
||||
url = self.url.joinpath("games").with_query(**params)
|
||||
response = await self._request(str(url))
|
||||
return response.get("games", [])
|
||||
60
backend/adapters/services/mobygames_types.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from typing import Literal, TypedDict
|
||||
|
||||
MobyOutputFormat = Literal["id", "brief", "normal"]
|
||||
|
||||
|
||||
class MobyGameAlternateTitle(TypedDict):
|
||||
description: str
|
||||
title: str
|
||||
|
||||
|
||||
class MobyGenre(TypedDict):
|
||||
genre_category: str
|
||||
genre_category_id: int
|
||||
genre_id: int
|
||||
genre_name: str
|
||||
|
||||
|
||||
class MobyPlatform(TypedDict):
|
||||
first_release_date: str
|
||||
platform_id: int
|
||||
platform_name: str
|
||||
|
||||
|
||||
class MobyGameCover(TypedDict):
|
||||
height: int
|
||||
image: str
|
||||
platforms: list[str]
|
||||
thumbnail_image: str
|
||||
width: int
|
||||
|
||||
|
||||
class MobyGameScreenshot(TypedDict):
|
||||
caption: str
|
||||
height: int
|
||||
image: str
|
||||
thumbnail_image: str
|
||||
width: int
|
||||
|
||||
|
||||
# https://www.mobygames.com/info/api/#games
|
||||
class MobyGameBrief(TypedDict):
|
||||
game_id: int
|
||||
moby_url: str
|
||||
title: str
|
||||
|
||||
|
||||
# https://www.mobygames.com/info/api/#games
|
||||
class MobyGame(TypedDict):
|
||||
alternate_titles: list[MobyGameAlternateTitle]
|
||||
description: str
|
||||
game_id: int
|
||||
genres: list[MobyGenre]
|
||||
moby_score: float
|
||||
moby_url: str
|
||||
num_votes: int
|
||||
official_url: str | None
|
||||
platforms: list[MobyPlatform]
|
||||
sample_cover: MobyGameCover
|
||||
sample_screenshots: list[MobyGameScreenshot]
|
||||
title: str
|
||||
@@ -1,83 +1,72 @@
|
||||
import asyncio
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from handler.metadata.base_hander import UniversalPlatformSlug as UPS
|
||||
from logger.formatter import LIGHTMAGENTA
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
|
||||
RAHASHER_VALID_HASH_REGEX = re.compile(r"^[0-9a-f]{32}$")
|
||||
RAHASHER_VALID_HASH_REGEX = re.compile(r"[0-9a-f]{32}")
|
||||
|
||||
# TODO: Centralize standarized platform slugs using StrEnum.
|
||||
PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID: dict[str, int] = {
|
||||
"3do": 43,
|
||||
"cpc": 37,
|
||||
"acpc": 37,
|
||||
"apple2": 38,
|
||||
"appleii": 38,
|
||||
"arcade": 27,
|
||||
"arcadia-2001": 73,
|
||||
"arduboy": 71,
|
||||
"atari-2600": 25,
|
||||
"atari2600": 25,
|
||||
"atari-7800": 51,
|
||||
"atari7800": 51,
|
||||
"atari-jaguar-cd": 77,
|
||||
"colecovision": 44,
|
||||
"dreamcast": 40,
|
||||
"dc": 40,
|
||||
"gameboy": 4,
|
||||
"gb": 4,
|
||||
"gameboy-advance": 5,
|
||||
"gba": 5,
|
||||
"gameboy-color": 6,
|
||||
"gbc": 6,
|
||||
"game-gear": 15,
|
||||
"gamegear": 15,
|
||||
"gamecube": 16,
|
||||
"ngc": 14,
|
||||
"genesis": 1,
|
||||
"genesis-slash-megadrive": 16,
|
||||
"intellivision": 45,
|
||||
"jaguar": 17,
|
||||
"lynx": 13,
|
||||
"msx": 29,
|
||||
"mega-duck-slash-cougar-boy": 69,
|
||||
"nes": 7,
|
||||
"famicom": 7,
|
||||
"neo-geo-cd": 56,
|
||||
"neo-geo-pocket": 14,
|
||||
"neo-geo-pocket-color": 14,
|
||||
"n64": 2,
|
||||
"nintendo-ds": 18,
|
||||
"nds": 18,
|
||||
"nintendo-dsi": 78,
|
||||
"odyssey-2": 23,
|
||||
"pc-8000": 47,
|
||||
"pc-8800-series": 47,
|
||||
"pc-fx": 49,
|
||||
"psp": 41,
|
||||
"playstation": 12,
|
||||
"ps": 12,
|
||||
"ps2": 21,
|
||||
"pokemon-mini": 24,
|
||||
"saturn": 39,
|
||||
"sega-32x": 10,
|
||||
"sega32": 10,
|
||||
"sega-cd": 9,
|
||||
"segacd": 9,
|
||||
"sega-master-system": 11,
|
||||
"sms": 11,
|
||||
"sg-1000": 33,
|
||||
"snes": 3,
|
||||
"turbografx-cd": 76,
|
||||
"turbografx-16-slash-pc-engine-cd": 76,
|
||||
"turbo-grafx": 8,
|
||||
"turbografx16--1": 8,
|
||||
"vectrex": 26,
|
||||
"virtual-boy": 28,
|
||||
"virtualboy": 28,
|
||||
"watara-slash-quickshot-supervision": 63,
|
||||
"wonderswan": 53,
|
||||
"wonderswan-color": 53,
|
||||
PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID: dict[UPS, int] = {
|
||||
UPS._3DO: 43,
|
||||
UPS.ACPC: 37,
|
||||
UPS.APPLEII: 38,
|
||||
UPS.ARCADE: 27,
|
||||
UPS.ARCADIA_2001: 73,
|
||||
UPS.ARDUBOY: 71,
|
||||
UPS.ATARI_JAGUAR_CD: 77,
|
||||
UPS.ATARI2600: 25,
|
||||
UPS.ATARI7800: 51,
|
||||
UPS.COLECOVISION: 44,
|
||||
UPS.DC: 40,
|
||||
UPS.ELEKTOR: 75,
|
||||
UPS.FAIRCHILD_CHANNEL_F: 57,
|
||||
UPS.FAMICOM: 7,
|
||||
UPS.GAMEGEAR: 15,
|
||||
UPS.GB: 4,
|
||||
UPS.GBA: 5,
|
||||
UPS.GBC: 6,
|
||||
UPS.GENESIS: 1,
|
||||
UPS.INTELLIVISION: 45,
|
||||
UPS.INTERTON_VC_4000: 74,
|
||||
UPS.JAGUAR: 17,
|
||||
UPS.LYNX: 13,
|
||||
UPS.MEGA_DUCK_SLASH_COUGAR_BOY: 69,
|
||||
UPS.MSX: 29,
|
||||
UPS.N64: 2,
|
||||
UPS.NDS: 18,
|
||||
UPS.NEO_GEO_CD: 56,
|
||||
UPS.NEO_GEO_POCKET: 14,
|
||||
UPS.NEO_GEO_POCKET_COLOR: 14,
|
||||
UPS.NES: 7,
|
||||
UPS.NGC: 16,
|
||||
UPS.NINTENDO_DSI: 78,
|
||||
UPS.ODYSSEY_2: 23,
|
||||
UPS.PC_8000: 47,
|
||||
UPS.PC_8800_SERIES: 47,
|
||||
UPS.PC_FX: 49,
|
||||
UPS.POKEMON_MINI: 24,
|
||||
UPS.PSX: 12,
|
||||
UPS.PS2: 21,
|
||||
UPS.PSP: 41,
|
||||
UPS.SATURN: 39,
|
||||
UPS.SEGACD: 9,
|
||||
UPS.SEGA32: 10,
|
||||
UPS.SFAM: 3,
|
||||
UPS.SG1000: 33,
|
||||
UPS.SMS: 11,
|
||||
UPS.SNES: 3,
|
||||
UPS.TURBOGRAFX_CD: 76,
|
||||
UPS.TG16: 8,
|
||||
UPS.UZEBOX: 80,
|
||||
UPS.VECTREX: 46,
|
||||
UPS.VIRTUALBOY: 28,
|
||||
UPS.WASM_4: 72,
|
||||
UPS.SUPERVISION: 63,
|
||||
UPS.WIN: 102,
|
||||
UPS.WONDERSWAN: 53,
|
||||
UPS.WONDERSWAN_COLOR: 53,
|
||||
}
|
||||
|
||||
|
||||
@@ -87,41 +76,50 @@ class RAHasherError(Exception): ...
|
||||
class RAHasherService:
|
||||
"""Service to calculate RetroAchievements hashes using RAHasher."""
|
||||
|
||||
async def calculate_hash(self, platform_slug: str, file_path: Path) -> str:
|
||||
platform_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID.get(platform_slug)
|
||||
if not platform_id:
|
||||
raise RAHasherError(
|
||||
f"Platform not supported by RetroAchievements. {platform_slug=}"
|
||||
)
|
||||
async def calculate_hash(self, platform_id: int, file_path: str) -> str:
|
||||
from handler.metadata.ra_handler import RA_ID_TO_SLUG
|
||||
|
||||
args = (str(platform_id), str(file_path))
|
||||
log.debug("Executing RAHasher with args: %s", args)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"RAHasher",
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
log.debug(
|
||||
f"Executing {hl('RAHasher', color=LIGHTMAGENTA)} for platform: {hl(RA_ID_TO_SLUG[platform_id])} - file: {hl(file_path.split('/')[-1])}"
|
||||
)
|
||||
args = (str(platform_id), file_path)
|
||||
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"RAHasher",
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
log.error("RAHasher executable not found in PATH")
|
||||
return ""
|
||||
|
||||
return_code = await proc.wait()
|
||||
if return_code != 1:
|
||||
if proc.stderr is not None:
|
||||
stderr = (await proc.stderr.read()).decode("utf-8")
|
||||
else:
|
||||
stderr = None
|
||||
raise RAHasherError(f"RAHasher failed with code {return_code}. {stderr=}")
|
||||
log.error(f"RAHasher failed with code {return_code}. {stderr=}")
|
||||
return ""
|
||||
|
||||
if proc.stdout is None:
|
||||
raise RAHasherError("RAHasher did not return a hash.")
|
||||
log.error("RAHasher did not return a hash.")
|
||||
return ""
|
||||
|
||||
file_hash = (await proc.stdout.read()).decode("utf-8").strip()
|
||||
if not file_hash:
|
||||
raise RAHasherError(
|
||||
f"RAHasher returned an empty hash. {platform_id=}, {file_path=}"
|
||||
)
|
||||
if not RAHASHER_VALID_HASH_REGEX.match(file_hash):
|
||||
raise RAHasherError(
|
||||
f"RAHasher returned an invalid hash: {file_hash=}, {platform_id=}, {file_path=}"
|
||||
log.error(
|
||||
f"RAHasher returned an empty hash for file {file_path} (platform ID: {platform_id})"
|
||||
)
|
||||
return ""
|
||||
|
||||
return file_hash
|
||||
match = RAHASHER_VALID_HASH_REGEX.search(file_hash)
|
||||
if not match:
|
||||
log.error(
|
||||
f"RAHasher returned invalid hash {file_hash} for file {file_path} (platform ID: {platform_id}"
|
||||
)
|
||||
return ""
|
||||
|
||||
return match.group(0)
|
||||
|
||||
218
backend/adapters/services/retroachievements.py
Normal file
@@ -0,0 +1,218 @@
|
||||
import asyncio
|
||||
import http
|
||||
import json
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import cast
|
||||
|
||||
import aiohttp
|
||||
import yarl
|
||||
from adapters.services.retroachievements_types import (
|
||||
RAGameExtendedDetails,
|
||||
RAGameInfoAndUserProgress,
|
||||
RAGameListItem,
|
||||
RAUserCompletionProgress,
|
||||
RAUserCompletionProgressResult,
|
||||
)
|
||||
from aiohttp.client import ClientTimeout
|
||||
from config import RETROACHIEVEMENTS_API_KEY
|
||||
from fastapi import HTTPException, status
|
||||
from logger.logger import log
|
||||
from utils.context import ctx_aiohttp_session
|
||||
|
||||
|
||||
async def auth_middleware(
|
||||
req: aiohttp.ClientRequest, handler: aiohttp.ClientHandlerType
|
||||
) -> aiohttp.ClientResponse:
|
||||
"""RetroAchievements API authentication mechanism.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/getting-started.html#quick-start-http-requests
|
||||
"""
|
||||
req.url = req.url.update_query({"y": RETROACHIEVEMENTS_API_KEY})
|
||||
return await handler(req)
|
||||
|
||||
|
||||
class RetroAchievementsService:
|
||||
"""Service to interact with the RetroAchievements API.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://retroachievements.org/API")
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
try:
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return await res.json()
|
||||
except aiohttp.ServerTimeoutError:
|
||||
# Retry the request once if it times out
|
||||
pass
|
||||
except aiohttp.ClientConnectionError as exc:
|
||||
log.critical(
|
||||
"Connection error: can't connect to RetroAchievements", exc_info=True
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Can't connect to RetroAchievements, check your internet connection",
|
||||
) from exc
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Retry after 2 seconds if rate limit hit
|
||||
await asyncio.sleep(2)
|
||||
else:
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(err)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return await res.json()
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err:
|
||||
if (
|
||||
isinstance(err, aiohttp.ClientResponseError)
|
||||
and err.status == http.HTTPStatus.UNAUTHORIZED
|
||||
):
|
||||
return {}
|
||||
|
||||
log.error(err)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
async def get_game_extended_details(self, game_id: int) -> RAGameExtendedDetails:
|
||||
"""Retrieve extended metadata about a game, targeted via its unique ID.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-extended.html
|
||||
"""
|
||||
url = self.url.joinpath("API_GetGameExtended.php").with_query(
|
||||
i=[game_id],
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAGameExtendedDetails, response)
|
||||
|
||||
async def get_game_list(
|
||||
self,
|
||||
system_id: int,
|
||||
*,
|
||||
only_games_with_achievements: bool = False,
|
||||
include_hashes: bool = False,
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
) -> list[RAGameListItem]:
|
||||
"""Retrieve the complete list of games for a specified console on the site, targeted by the console ID.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-list.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {"i": [str(system_id)]}
|
||||
if only_games_with_achievements:
|
||||
params["f"] = ["1"]
|
||||
if include_hashes:
|
||||
params["h"] = ["1"]
|
||||
if limit is not None:
|
||||
params["c"] = [str(limit)]
|
||||
if offset is not None:
|
||||
params["o"] = [str(offset)]
|
||||
|
||||
url = self.url.joinpath("API_GetGameList.php").with_query(**params)
|
||||
response = await self._request(str(url))
|
||||
return cast(list[RAGameListItem], response)
|
||||
|
||||
async def get_user_completion_progress(
|
||||
self,
|
||||
username: str,
|
||||
*,
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
) -> RAUserCompletionProgress:
|
||||
"""Retrieve a given user's completion progress, targeted by their username.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-user-completion-progress.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {"u": [username]}
|
||||
if limit is not None:
|
||||
params["c"] = [str(limit)]
|
||||
if offset is not None:
|
||||
params["o"] = [str(offset)]
|
||||
|
||||
url = self.url.joinpath("API_GetUserCompletionProgress.php").with_query(
|
||||
**params
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAUserCompletionProgress, response)
|
||||
|
||||
async def iter_user_completion_progress(
|
||||
self,
|
||||
username: str,
|
||||
) -> AsyncIterator[RAUserCompletionProgressResult]:
|
||||
"""Iterate through a given user's completion progress, targeted by their username.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-user-completion-progress.html
|
||||
"""
|
||||
page_size = 500 # Maximum page size for this endpoint.
|
||||
offset = 0
|
||||
|
||||
while True:
|
||||
response = await self.get_user_completion_progress(
|
||||
username,
|
||||
limit=page_size,
|
||||
offset=offset or None,
|
||||
)
|
||||
results = response["Results"]
|
||||
for result in results:
|
||||
yield result
|
||||
|
||||
offset += len(results)
|
||||
if len(results) < page_size or offset >= response["Total"]:
|
||||
break
|
||||
|
||||
async def get_user_game_progress(
|
||||
self,
|
||||
username: str,
|
||||
game_id: int,
|
||||
*,
|
||||
include_award_metadata: bool = False,
|
||||
) -> RAGameInfoAndUserProgress:
|
||||
"""Retrieve extended metadata about a game, in addition to a user's progress about that game.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-info-and-user-progress.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {
|
||||
"u": [username],
|
||||
"g": [str(game_id)],
|
||||
}
|
||||
if include_award_metadata:
|
||||
params["a"] = ["1"]
|
||||
|
||||
url = self.url.joinpath("API_GetGameInfoAndUserProgress.php").with_query(
|
||||
**params
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAGameInfoAndUserProgress, response)
|
||||
168
backend/adapters/services/retroachievements_types.py
Normal file
@@ -0,0 +1,168 @@
|
||||
import enum
|
||||
from collections.abc import Mapping
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
|
||||
class PaginatedResponse[T: Mapping](TypedDict):
|
||||
Count: int
|
||||
Total: int
|
||||
Results: list[T]
|
||||
|
||||
|
||||
# https://github.com/RetroAchievements/RAWeb/blob/master/app/Platform/Enums/AchievementType.php
|
||||
class RAGameAchievementType(enum.StrEnum):
|
||||
PROGRESSION = "progression"
|
||||
WIN_CONDITION = "win_condition"
|
||||
MISSABLE = "missable"
|
||||
|
||||
|
||||
# https://github.com/RetroAchievements/RAWeb/blob/master/app/Platform/Enums/ReleasedAtGranularity.php
|
||||
class RAGameReleasedAtGranularity(enum.StrEnum):
|
||||
DAY = "day"
|
||||
MONTH = "month"
|
||||
YEAR = "year"
|
||||
|
||||
|
||||
# https://github.com/RetroAchievements/RAWeb/blob/master/resources/js/common/components/AwardIndicator/AwardIndicator.tsx
|
||||
class RAUserCompletionProgressKind(enum.StrEnum):
|
||||
COMPLETED = "completed"
|
||||
MASTERED = "mastered"
|
||||
BEATEN_HARDCORE = "beaten-hardcore"
|
||||
BEATEN_SOFTCORE = "beaten-softcore"
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-game-extended.html#response
|
||||
class RAGameExtendedDetailsAchievement(TypedDict):
|
||||
ID: int
|
||||
NumAwarded: int
|
||||
NumAwardedHardcore: int
|
||||
Title: str
|
||||
Description: str
|
||||
Points: int
|
||||
TrueRatio: int
|
||||
Author: str
|
||||
AuthorULID: str
|
||||
DateModified: str # ISO 8601 datetime format
|
||||
DateCreated: str # ISO 8601 datetime format
|
||||
BadgeName: str
|
||||
DisplayOrder: int
|
||||
MemAddr: str
|
||||
type: RAGameAchievementType | None
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-game-extended.html#response
|
||||
class RAGameExtendedDetails(TypedDict):
|
||||
ID: int
|
||||
Title: str
|
||||
ConsoleID: int
|
||||
ForumTopicID: int | None
|
||||
ImageIcon: str
|
||||
ImageTitle: str
|
||||
ImageIngame: str
|
||||
ImageBoxArt: str
|
||||
Publisher: str
|
||||
Developer: str
|
||||
Genre: str
|
||||
Released: str # ISO 8601 date format
|
||||
ReleasedAtGranularity: RAGameReleasedAtGranularity
|
||||
RichPresencePatch: str
|
||||
GuideURL: str | None
|
||||
Updated: str # ISO 8601 datetime format
|
||||
ConsoleName: str
|
||||
ParentGameID: int | None
|
||||
NumDistinctPlayers: int
|
||||
NumAchievements: int
|
||||
Achievements: dict[
|
||||
str, RAGameExtendedDetailsAchievement
|
||||
] # Key is achievement ID as string
|
||||
NumDistinctPlayersCasual: int
|
||||
NumDistinctPlayersHardcore: int
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-user-completion-progress.html#response
|
||||
class RAUserCompletionProgressResult(TypedDict):
|
||||
GameID: int
|
||||
Title: str
|
||||
ImageIcon: str
|
||||
ConsoleID: int
|
||||
ConsoleName: str
|
||||
MaxPossible: int
|
||||
NumAwarded: int
|
||||
NumAwardedHardcore: int
|
||||
MostRecentAwardedDate: str # ISO 8601 datetime format
|
||||
HighestAwardKind: RAUserCompletionProgressKind # e.g., "beaten-hardcore"
|
||||
HighestAwardDate: str # ISO 8601 datetime format
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-user-completion-progress.html#response
|
||||
RAUserCompletionProgress = PaginatedResponse[RAUserCompletionProgressResult]
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-game-info-and-user-progress.html#response
|
||||
class RAGameInfoAndUserProgressAchievement(TypedDict):
|
||||
ID: int
|
||||
NumAwarded: int
|
||||
NumAwardedHardcore: int
|
||||
Title: str
|
||||
Description: str
|
||||
Points: int
|
||||
TrueRatio: int
|
||||
Author: str
|
||||
AuthorULID: str
|
||||
DateModified: str # ISO 8601 datetime format
|
||||
DateCreated: str # ISO 8601 datetime format
|
||||
BadgeName: str
|
||||
DisplayOrder: int
|
||||
MemAddr: str
|
||||
type: RAGameAchievementType | None
|
||||
DateEarnedHardcore: NotRequired[str] # ISO 8601 datetime format
|
||||
DateEarned: NotRequired[str] # ISO 8601 datetime format
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-game-info-and-user-progress.html#response
|
||||
class RAGameInfoAndUserProgress(TypedDict):
|
||||
ID: int
|
||||
Title: str
|
||||
ConsoleID: int
|
||||
ForumTopicID: int | None
|
||||
ImageIcon: str
|
||||
ImageTitle: str
|
||||
ImageIngame: str
|
||||
ImageBoxArt: str
|
||||
Publisher: str
|
||||
Developer: str
|
||||
Genre: str
|
||||
Released: str # ISO 8601 date format
|
||||
ReleasedAtGranularity: RAGameReleasedAtGranularity
|
||||
RichPresencePatch: str
|
||||
GuideURL: str | None
|
||||
ConsoleName: str
|
||||
ParentGameID: int | None
|
||||
NumDistinctPlayers: int
|
||||
NumAchievements: int
|
||||
Achievements: dict[
|
||||
str, RAGameInfoAndUserProgressAchievement
|
||||
] # Key is achievement ID as string
|
||||
NumAwardedToUser: int
|
||||
NumAwardedToUserHardcore: int
|
||||
NumDistinctPlayersCasual: int
|
||||
NumDistinctPlayersHardcore: int
|
||||
UserCompletion: str # e.g., "100.00%"
|
||||
UserCompletionHardcore: str # e.g., "100.00%"
|
||||
HighestAwardKind: NotRequired[RAUserCompletionProgressKind]
|
||||
HighestAwardDate: NotRequired[str] # ISO 8601 datetime format
|
||||
|
||||
|
||||
# https://api-docs.retroachievements.org/v1/get-game-list.html#response
|
||||
class RAGameListItem(TypedDict):
|
||||
Title: str
|
||||
ID: int
|
||||
ConsoleID: int
|
||||
ConsoleName: str
|
||||
ImageIcon: str
|
||||
NumAchievements: int
|
||||
NumLeaderboards: int
|
||||
Points: int
|
||||
DateModified: str # ISO 8601 datetime format
|
||||
ForumTopicID: int | None
|
||||
Hashes: NotRequired[list[str]]
|
||||
192
backend/adapters/services/screenscraper.py
Normal file
@@ -0,0 +1,192 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import http
|
||||
import json
|
||||
from typing import Final, cast
|
||||
|
||||
import aiohttp
|
||||
import yarl
|
||||
from adapters.services.screenscraper_types import SSGame
|
||||
from aiohttp.client import ClientTimeout
|
||||
from config import SCREENSCRAPER_PASSWORD, SCREENSCRAPER_USER
|
||||
from fastapi import HTTPException, status
|
||||
from logger.logger import log
|
||||
from utils.context import ctx_aiohttp_session
|
||||
|
||||
SS_DEV_ID: Final = base64.b64decode("enVyZGkxNQ==").decode()
|
||||
SS_DEV_PASSWORD: Final = base64.b64decode("eFRKd29PRmpPUUc=").decode()
|
||||
LOGIN_ERROR_CHECK: Final = "Erreur de login"
|
||||
|
||||
|
||||
async def auth_middleware(
|
||||
req: aiohttp.ClientRequest, handler: aiohttp.ClientHandlerType
|
||||
) -> aiohttp.ClientResponse:
|
||||
"""ScreenScraper API authentication mechanism."""
|
||||
req.url = req.url.update_query(
|
||||
{
|
||||
"devid": SS_DEV_ID,
|
||||
"devpassword": SS_DEV_PASSWORD,
|
||||
"output": "json",
|
||||
"softname": "romm",
|
||||
"ssid": SCREENSCRAPER_USER,
|
||||
"sspassword": SCREENSCRAPER_PASSWORD,
|
||||
},
|
||||
)
|
||||
return await handler(req)
|
||||
|
||||
|
||||
class ScreenScraperService:
|
||||
"""Service to interact with the ScreenScraper API.
|
||||
|
||||
Reference: https://api.screenscraper.fr/webapi2.php
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://api.screenscraper.fr/api2")
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
try:
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
res_text = await res.text()
|
||||
if LOGIN_ERROR_CHECK in res_text:
|
||||
log.error("Invalid ScreenScraper credentials")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
return await res.json()
|
||||
except aiohttp.ServerTimeoutError:
|
||||
# Retry the request once if it times out
|
||||
pass
|
||||
except aiohttp.ClientConnectionError as exc:
|
||||
log.critical(
|
||||
"Connection error: can't connect to ScreenScraper", exc_info=True
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Can't connect to ScreenScraper, check your internet connection",
|
||||
) from exc
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Retry after 2 seconds if rate limit hit
|
||||
await asyncio.sleep(2)
|
||||
else:
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(err)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
res_text = await res.text()
|
||||
if LOGIN_ERROR_CHECK in res_text:
|
||||
log.error("Invalid ScreenScraper credentials")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
return await res.json()
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err:
|
||||
if (
|
||||
isinstance(err, aiohttp.ClientResponseError)
|
||||
and err.status == http.HTTPStatus.UNAUTHORIZED
|
||||
):
|
||||
return {}
|
||||
|
||||
log.error(err)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
async def get_game_info(
|
||||
self,
|
||||
*,
|
||||
crc: str | None = None,
|
||||
md5: str | None = None,
|
||||
sha1: str | None = None,
|
||||
system_id: int | None = None,
|
||||
rom_type: str | None = None,
|
||||
rom_name: str | None = None,
|
||||
rom_size_bytes: int | None = None,
|
||||
serial_number: str | None = None,
|
||||
game_id: int | None = None,
|
||||
) -> SSGame | None:
|
||||
"""Retrieve information about a game.
|
||||
|
||||
Reference: https://api.screenscraper.fr/webapi2.php#jeuInfos
|
||||
"""
|
||||
params: dict[str, list[str]] = {}
|
||||
if crc:
|
||||
params["crc"] = [crc]
|
||||
if md5:
|
||||
params["md5"] = [md5]
|
||||
if sha1:
|
||||
params["sha1"] = [sha1]
|
||||
if system_id is not None:
|
||||
params["systemeid"] = [str(system_id)]
|
||||
if rom_type:
|
||||
params["romtype"] = [rom_type]
|
||||
if rom_name:
|
||||
params["romnom"] = [rom_name]
|
||||
if rom_size_bytes is not None:
|
||||
params["romtaille"] = [str(rom_size_bytes)]
|
||||
if serial_number:
|
||||
params["serialnum"] = [serial_number]
|
||||
if game_id is not None:
|
||||
params["gameid"] = [str(game_id)]
|
||||
|
||||
url = self.url.joinpath("jeuInfos.php").with_query(**params)
|
||||
response = await self._request(str(url))
|
||||
data = response.get("response", {}).get("jeu", {})
|
||||
if not data:
|
||||
return None
|
||||
return cast(SSGame, data)
|
||||
|
||||
async def search_games(
|
||||
self,
|
||||
*,
|
||||
term: str,
|
||||
system_id: int | None = None,
|
||||
) -> list[SSGame]:
|
||||
"""Search games by name. Returns games sorted by relevance (limited to 30 results).
|
||||
|
||||
Reference: https://api.screenscraper.fr/webapi2.php#jeuRecherche
|
||||
"""
|
||||
params: dict[str, list[str]] = {"recherche": [term]}
|
||||
if system_id is not None:
|
||||
params["systemeid"] = [str(system_id)]
|
||||
|
||||
url = self.url.joinpath("jeuRecherche.php").with_query(**params)
|
||||
response = await self._request(str(url))
|
||||
data = response.get("response", {}).get("jeux", [])
|
||||
# If no roms are returned, "jeux" is a list with an empty dict.
|
||||
if len(data) == 1 and not data[0]:
|
||||
data = []
|
||||
return cast(list[SSGame], data)
|
||||
89
backend/adapters/services/screenscraper_types.py
Normal file
@@ -0,0 +1,89 @@
|
||||
from typing import Literal, TypedDict
|
||||
|
||||
|
||||
class SSText(TypedDict):
|
||||
text: str
|
||||
|
||||
|
||||
class SSTextID(TypedDict):
|
||||
id: str
|
||||
text: str
|
||||
|
||||
|
||||
class SSRegionalText(TypedDict):
|
||||
region: str
|
||||
text: str
|
||||
|
||||
|
||||
class SSLanguageText(TypedDict):
|
||||
langue: str
|
||||
text: str
|
||||
|
||||
|
||||
class SSGameClassification(TypedDict):
|
||||
type: str
|
||||
text: str
|
||||
|
||||
|
||||
class SSGameDate(TypedDict):
|
||||
region: str
|
||||
text: str
|
||||
|
||||
|
||||
class SSGameGenre(TypedDict):
|
||||
id: str
|
||||
nomcourt: str
|
||||
principale: str
|
||||
parentid: str
|
||||
noms: list[SSLanguageText]
|
||||
|
||||
|
||||
class SSGameMode(TypedDict):
|
||||
id: str
|
||||
nomcourt: str
|
||||
principale: str
|
||||
parentid: str
|
||||
noms: list[SSLanguageText]
|
||||
|
||||
|
||||
class SSGameFranchise(TypedDict):
|
||||
id: str
|
||||
nomcourt: str
|
||||
principale: str
|
||||
parentid: str
|
||||
noms: list[SSLanguageText]
|
||||
|
||||
|
||||
class SSGameMedia(TypedDict):
|
||||
type: str
|
||||
parent: str
|
||||
url: str
|
||||
region: str
|
||||
crc: str
|
||||
md5: str
|
||||
sha1: str
|
||||
size: str
|
||||
format: str
|
||||
|
||||
|
||||
# https://api.screenscraper.fr/webapi2.php#jeuInfos
|
||||
class SSGame(TypedDict):
|
||||
id: int
|
||||
romid: str
|
||||
notgame: Literal["true", "false"]
|
||||
noms: list[SSRegionalText]
|
||||
cloneof: str
|
||||
systeme: SSTextID
|
||||
editeur: SSTextID
|
||||
developpeur: SSTextID
|
||||
joueurs: SSText
|
||||
note: SSText
|
||||
topstaff: str
|
||||
rotation: str
|
||||
synopsis: list[SSLanguageText]
|
||||
classifications: list[SSGameClassification]
|
||||
dates: list[SSGameDate]
|
||||
genres: list[SSGameGenre]
|
||||
modes: list[SSGameMode]
|
||||
familles: list[SSGameFranchise]
|
||||
medias: list[SSGameMedia]
|
||||
179
backend/adapters/services/steamgriddb.py
Normal file
@@ -0,0 +1,179 @@
|
||||
import http
|
||||
import itertools
|
||||
import json
|
||||
from collections.abc import AsyncIterator, Collection
|
||||
from typing import Literal, cast
|
||||
|
||||
import aiohttp
|
||||
import aiohttp.client_exceptions
|
||||
import yarl
|
||||
from adapters.services.steamgriddb_types import (
|
||||
SGDBDimension,
|
||||
SGDBGame,
|
||||
SGDBGrid,
|
||||
SGDBGridList,
|
||||
SGDBMime,
|
||||
SGDBStyle,
|
||||
SGDBTag,
|
||||
SGDBType,
|
||||
)
|
||||
from aiohttp.client import ClientTimeout
|
||||
from config import STEAMGRIDDB_API_KEY
|
||||
from exceptions.endpoint_exceptions import SGDBInvalidAPIKeyException
|
||||
from logger.logger import log
|
||||
from utils.context import ctx_aiohttp_session
|
||||
|
||||
|
||||
async def auth_middleware(
|
||||
req: aiohttp.ClientRequest, handler: aiohttp.ClientHandlerType
|
||||
) -> aiohttp.ClientResponse:
|
||||
"""SteamGridDB API authentication mechanism."""
|
||||
req.headers["Authorization"] = f"Bearer {STEAMGRIDDB_API_KEY}"
|
||||
return await handler(req)
|
||||
|
||||
|
||||
class SteamGridDBService:
|
||||
"""Service to interact with the SteamGridDB API.
|
||||
|
||||
Reference: https://www.steamgriddb.com/api/v2
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://steamgriddb.com/api/v2")
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
try:
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return await res.json()
|
||||
except aiohttp.client_exceptions.ClientResponseError as exc:
|
||||
print(f"Request failed with status {exc.status} for URL: {url}")
|
||||
if exc.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
print("Invalid API key or unauthorized access.")
|
||||
raise SGDBInvalidAPIKeyException from exc
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(exc)
|
||||
return {}
|
||||
except json.decoder.JSONDecodeError as exc:
|
||||
log.error(
|
||||
"Failed to decode JSON response from SteamGridDB: %s",
|
||||
str(exc),
|
||||
)
|
||||
return {}
|
||||
|
||||
async def get_grids_for_game(
|
||||
self,
|
||||
game_id: int,
|
||||
*,
|
||||
styles: Collection[SGDBStyle] | None = None,
|
||||
dimensions: Collection[SGDBDimension] | None = None,
|
||||
mimes: Collection[SGDBMime] | None = None,
|
||||
types: Collection[SGDBType] | None = None,
|
||||
any_of_tags: Collection[SGDBTag] | None = None,
|
||||
is_nsfw: bool | Literal["any"] | None = None,
|
||||
is_humor: bool | Literal["any"] | None = None,
|
||||
is_epilepsy: bool | Literal["any"] | None = None,
|
||||
limit: int | None = None,
|
||||
page_number: int | None = None,
|
||||
) -> SGDBGridList:
|
||||
"""Retrieve grids by game ID.
|
||||
|
||||
Reference: https://www.steamgriddb.com/api/v2#tag/GRIDS/operation/getGridsByGameId
|
||||
"""
|
||||
params: dict[str, list[str]] = {}
|
||||
if styles:
|
||||
params["styles"] = [",".join(styles)]
|
||||
if dimensions:
|
||||
params["dimensions"] = [",".join(dimensions)]
|
||||
if mimes:
|
||||
params["mimes"] = [",".join(mimes)]
|
||||
if types:
|
||||
params["types"] = [",".join(types)]
|
||||
if any_of_tags:
|
||||
params["oneoftag"] = [",".join(any_of_tags)]
|
||||
if is_nsfw is not None:
|
||||
params["nsfw"] = [str(is_nsfw).lower()]
|
||||
if is_humor is not None:
|
||||
params["humor"] = [str(is_humor).lower()]
|
||||
if is_epilepsy is not None:
|
||||
params["epilepsy"] = [str(is_epilepsy).lower()]
|
||||
if limit is not None:
|
||||
params["limit"] = [str(limit)]
|
||||
if page_number is not None:
|
||||
params["page"] = [str(page_number)]
|
||||
|
||||
base_url = self.url.joinpath("grids/game", str(game_id))
|
||||
url = base_url.with_query(**params) if params else base_url
|
||||
response = await self._request(str(url))
|
||||
if not response:
|
||||
return SGDBGridList(
|
||||
page=0,
|
||||
total=0,
|
||||
limit=limit or 50,
|
||||
data=[],
|
||||
)
|
||||
return cast(SGDBGridList, response)
|
||||
|
||||
async def iter_grids_for_game(
|
||||
self,
|
||||
game_id: int,
|
||||
*,
|
||||
styles: Collection[SGDBStyle] | None = None,
|
||||
dimensions: Collection[SGDBDimension] | None = None,
|
||||
mimes: Collection[SGDBMime] | None = None,
|
||||
types: Collection[SGDBType] | None = None,
|
||||
any_of_tags: Collection[SGDBTag] | None = None,
|
||||
is_nsfw: bool | Literal["any"] | None = None,
|
||||
is_humor: bool | Literal["any"] | None = None,
|
||||
is_epilepsy: bool | Literal["any"] | None = None,
|
||||
) -> AsyncIterator[SGDBGrid]:
|
||||
"""Iterate through grids by game ID.
|
||||
|
||||
Reference: https://www.steamgriddb.com/api/v2#tag/GRIDS/operation/getGridsByGameId
|
||||
"""
|
||||
page_size = 50 # Maximum page size for this endpoint.
|
||||
offset = 0
|
||||
|
||||
for page_number in itertools.count(start=0):
|
||||
response = await self.get_grids_for_game(
|
||||
game_id,
|
||||
styles=styles,
|
||||
dimensions=dimensions,
|
||||
mimes=mimes,
|
||||
types=types,
|
||||
any_of_tags=any_of_tags,
|
||||
is_nsfw=is_nsfw,
|
||||
is_humor=is_humor,
|
||||
is_epilepsy=is_epilepsy,
|
||||
limit=page_size,
|
||||
page_number=page_number,
|
||||
)
|
||||
results = response["data"]
|
||||
for result in results:
|
||||
yield result
|
||||
|
||||
offset += len(results)
|
||||
if len(results) < page_size or offset >= response["total"]:
|
||||
break
|
||||
|
||||
async def search_games(self, term: str) -> list[SGDBGame]:
|
||||
"""Search for games by name.
|
||||
|
||||
Reference: https://www.steamgriddb.com/api/v2#tag/SEARCH/operation/searchGrids
|
||||
"""
|
||||
url = self.url.joinpath("search/autocomplete", term)
|
||||
response = await self._request(str(url))
|
||||
return cast(list[SGDBGame], response.get("data", []))
|
||||
76
backend/adapters/services/steamgriddb_types.py
Normal file
@@ -0,0 +1,76 @@
|
||||
import enum
|
||||
from collections.abc import Mapping
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
@enum.unique
|
||||
class SGDBStyle(enum.StrEnum):
|
||||
ALTERNATE = "alternate"
|
||||
BLURRED = "blurred"
|
||||
WHITE_LOGO = "white_logo"
|
||||
MATERIAL = "material"
|
||||
NO_LOGO = "no_logo"
|
||||
|
||||
|
||||
@enum.unique
|
||||
class SGDBDimension(enum.StrEnum):
|
||||
STEAM_HORIZONTAL = "460x215"
|
||||
STEAM_HORIZONTAL_2X = "920x430"
|
||||
STEAM_VERTICAL = "600x900"
|
||||
GOG_GALAXY_TILE = "342x482"
|
||||
GOG_GALAXY_COVER = "660x930"
|
||||
SQUARE_512 = "512x512"
|
||||
SQUARE_1024 = "1024x1024"
|
||||
|
||||
|
||||
@enum.unique
|
||||
class SGDBMime(enum.StrEnum):
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
WEBP = "image/webp"
|
||||
|
||||
|
||||
@enum.unique
|
||||
class SGDBType(enum.StrEnum):
|
||||
STATIC = "static"
|
||||
ANIMATED = "animated"
|
||||
|
||||
|
||||
@enum.unique
|
||||
class SGDBTag(enum.StrEnum):
|
||||
HUMOR = "humor"
|
||||
NSFW = "nsfw"
|
||||
EPILEPSY = "epilepsy"
|
||||
|
||||
|
||||
class PaginatedResponse[T: Mapping](TypedDict):
|
||||
page: int
|
||||
total: int
|
||||
limit: int
|
||||
data: list[T]
|
||||
|
||||
|
||||
class SGDBGridAuthor(TypedDict):
|
||||
name: str
|
||||
steam64: str
|
||||
avatar: str
|
||||
|
||||
|
||||
class SGDBGrid(TypedDict):
|
||||
id: int
|
||||
score: int
|
||||
style: SGDBStyle
|
||||
url: str
|
||||
thumb: str
|
||||
tags: list[str]
|
||||
author: SGDBGridAuthor
|
||||
|
||||
|
||||
class SGDBGame(TypedDict):
|
||||
id: int
|
||||
name: str
|
||||
types: list[str]
|
||||
verified: bool
|
||||
|
||||
|
||||
SGDBGridList = PaginatedResponse[SGDBGrid]
|
||||
@@ -63,7 +63,7 @@ version_path_separator = os # Use os.pathsep. Default configuration used for ne
|
||||
sqlalchemy.url = ''
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# [post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
@@ -73,38 +73,3 @@ sqlalchemy.url = ''
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)s: [RomM][%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import context
|
||||
from config.config_manager import ConfigManager
|
||||
from logger.logger import unify_logger
|
||||
from models.assets import Save, Screenshot, State # noqa
|
||||
from models.base import BaseModel
|
||||
from models.collection import VirtualCollection
|
||||
from models.firmware import Firmware # noqa
|
||||
from models.platform import Platform # noqa
|
||||
from models.rom import Rom, SiblingRom # noqa
|
||||
from models.rom import Rom, RomMetadata, SiblingRom # noqa
|
||||
from models.user import User # noqa
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
@@ -17,10 +17,7 @@ from sqlalchemy import create_engine
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name, disable_existing_loggers=False)
|
||||
unify_logger("alembic")
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
@@ -39,6 +36,7 @@ def include_object(object, name, type_, reflected, compare_to):
|
||||
if type_ == "table" and name in [
|
||||
SiblingRom.__tablename__,
|
||||
VirtualCollection.__tablename__,
|
||||
RomMetadata.__tablename__,
|
||||
]: # Virtual table
|
||||
return False
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ def migrate_to_supported_engine() -> None:
|
||||
|
||||
# Skip if sqlite database is not mounted
|
||||
if not os.path.exists(f"{SQLITE_DB_BASE_PATH}/romm.db"):
|
||||
return
|
||||
return None
|
||||
|
||||
engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
|
||||
session = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
@@ -8,7 +8,7 @@ Create Date: 2025-01-02 18:58:55.557123
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from handler.metadata.ss_handler import SLUG_TO_SS_ID
|
||||
from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0036_screenscraper_platforms_id"
|
||||
@@ -20,10 +20,10 @@ depends_on = None
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
connection = op.get_bind()
|
||||
for slug, ss_id in SLUG_TO_SS_ID.items():
|
||||
for slug, ss_platform in SCREENSAVER_PLATFORM_LIST.items():
|
||||
connection.execute(
|
||||
sa.text("UPDATE platforms SET ss_id = :ss_id WHERE slug = :slug"),
|
||||
{"ss_id": ss_id["id"], "slug": slug},
|
||||
{"ss_id": ss_platform["id"], "slug": slug.value},
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
228
backend/alembic/versions/0037_virtual_rom_columns.py
Normal file
@@ -0,0 +1,228 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0037_virtual_rom_columns
|
||||
Revises: 0036_screenscraper_platforms_id
|
||||
Create Date: 2025-03-17 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0037_virtual_rom_columns"
|
||||
down_revision = "0036_screenscraper_platforms_id"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
connection = op.get_bind()
|
||||
if is_postgresql(connection):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
CREATE OR REPLACE VIEW roms_metadata AS
|
||||
SELECT
|
||||
r.id AS rom_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'genres'),
|
||||
(r.moby_metadata -> 'genres'),
|
||||
(r.ss_metadata -> 'genres'),
|
||||
'[]'::jsonb
|
||||
) AS genres,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'franchises' THEN r.igdb_metadata -> 'franchises'
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'franchises' THEN r.ss_metadata -> 'franchises'
|
||||
ELSE '[]'::jsonb
|
||||
END AS franchises,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'collections' THEN r.igdb_metadata -> 'collections'
|
||||
ELSE '[]'::jsonb
|
||||
END AS collections,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'companies' THEN r.igdb_metadata -> 'companies'
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'companies' THEN r.ss_metadata -> 'companies'
|
||||
ELSE '[]'::jsonb
|
||||
END AS companies,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'game_modes' THEN r.igdb_metadata -> 'game_modes'
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'game_modes' THEN r.ss_metadata -> 'game_modes'
|
||||
ELSE '[]'::jsonb
|
||||
END AS game_modes,
|
||||
|
||||
COALESCE(
|
||||
jsonb_path_query_array(
|
||||
r.igdb_metadata,
|
||||
'$.age_ratings[*].rating'
|
||||
),
|
||||
'[]'::jsonb
|
||||
) AS age_ratings,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'first_release_date' AND
|
||||
r.igdb_metadata ->> 'first_release_date' NOT IN ('null', 'None', '') AND
|
||||
r.igdb_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.igdb_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'first_release_date' AND
|
||||
r.ss_metadata ->> 'first_release_date' NOT IN ('null', 'None', '') AND
|
||||
r.ss_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.ss_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
ELSE NULL
|
||||
END AS first_release_date,
|
||||
|
||||
CASE
|
||||
WHEN (igdb_rating IS NOT NULL OR moby_rating IS NOT NULL OR ss_rating IS NOT NULL) THEN
|
||||
(COALESCE(igdb_rating, 0) + COALESCE(moby_rating, 0) + COALESCE(ss_rating, 0)) /
|
||||
(CASE WHEN igdb_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN moby_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN ss_rating IS NOT NULL THEN 1 ELSE 0 END)
|
||||
ELSE NULL
|
||||
END AS average_rating
|
||||
FROM (
|
||||
SELECT
|
||||
r.id,
|
||||
r.igdb_metadata,
|
||||
r.moby_metadata,
|
||||
r.ss_metadata,
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'total_rating' AND
|
||||
r.igdb_metadata ->> 'total_rating' NOT IN ('null', 'None', '') AND
|
||||
r.igdb_metadata ->> 'total_rating' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.igdb_metadata ->> 'total_rating')::float
|
||||
ELSE NULL
|
||||
END AS igdb_rating,
|
||||
CASE
|
||||
WHEN r.moby_metadata IS NOT NULL AND r.moby_metadata ? 'moby_score' AND
|
||||
r.moby_metadata ->> 'moby_score' NOT IN ('null', 'None', '') AND
|
||||
r.moby_metadata ->> 'moby_score' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.moby_metadata ->> 'moby_score')::float * 10
|
||||
ELSE NULL
|
||||
END AS moby_rating,
|
||||
CASE
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'ss_score' AND
|
||||
r.ss_metadata ->> 'ss_score' NOT IN ('null', 'None', '') AND
|
||||
r.ss_metadata ->> 'ss_score' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.ss_metadata ->> 'ss_score')::float
|
||||
ELSE NULL
|
||||
END AS ss_rating
|
||||
FROM roms r
|
||||
) AS r;
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""CREATE OR REPLACE VIEW roms_metadata AS
|
||||
SELECT
|
||||
r.id as rom_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.moby_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.ss_metadata, '$.genres'),
|
||||
JSON_ARRAY()
|
||||
) AS genres,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.franchises') THEN JSON_EXTRACT(r.igdb_metadata, '$.franchises')
|
||||
WHEN JSON_CONTAINS_PATH(r.ss_metadata, 'one', '$.franchises') THEN JSON_EXTRACT(r.ss_metadata, '$.franchises')
|
||||
ELSE JSON_ARRAY()
|
||||
END AS franchises,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.collections') THEN JSON_EXTRACT(r.igdb_metadata, '$.collections')
|
||||
ELSE JSON_ARRAY()
|
||||
END AS collections,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.companies') THEN JSON_EXTRACT(r.igdb_metadata, '$.companies')
|
||||
WHEN JSON_CONTAINS_PATH(r.ss_metadata, 'one', '$.companies') THEN JSON_EXTRACT(r.ss_metadata, '$.companies')
|
||||
ELSE JSON_ARRAY()
|
||||
END AS companies,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.game_modes') THEN JSON_EXTRACT(r.igdb_metadata, '$.game_modes')
|
||||
WHEN JSON_CONTAINS_PATH(r.ss_metadata, 'one', '$.game_modes') THEN JSON_EXTRACT(r.ss_metadata, '$.game_modes')
|
||||
ELSE JSON_ARRAY()
|
||||
END AS game_modes,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.age_ratings')
|
||||
AND JSON_LENGTH(JSON_EXTRACT(r.igdb_metadata, '$.age_ratings')) > 0
|
||||
THEN
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.age_ratings[*].rating')
|
||||
ELSE
|
||||
JSON_ARRAY()
|
||||
END AS age_ratings,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date')) NOT IN ('null', 'None', '') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
WHEN JSON_CONTAINS_PATH(r.ss_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ss_metadata, '$.first_release_date')) NOT IN ('null', 'None', '') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ss_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.ss_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
ELSE NULL
|
||||
END AS first_release_date,
|
||||
|
||||
CASE
|
||||
WHEN (igdb_rating IS NOT NULL OR moby_rating IS NOT NULL OR ss_rating IS NOT NULL) THEN
|
||||
(COALESCE(igdb_rating, 0) + COALESCE(moby_rating, 0) + COALESCE(ss_rating, 0)) /
|
||||
(CASE WHEN igdb_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN moby_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN ss_rating IS NOT NULL THEN 1 ELSE 0 END)
|
||||
ELSE NULL
|
||||
END AS average_rating
|
||||
|
||||
FROM (
|
||||
SELECT
|
||||
id,
|
||||
igdb_metadata,
|
||||
moby_metadata,
|
||||
ss_metadata,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(igdb_metadata, 'one', '$.total_rating') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(igdb_metadata, '$.total_rating')) NOT IN ('null', 'None', '') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(igdb_metadata, '$.total_rating')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(igdb_metadata, '$.total_rating') AS DECIMAL(10,2))
|
||||
ELSE NULL
|
||||
END AS igdb_rating,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(moby_metadata, 'one', '$.moby_score') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(moby_metadata, '$.moby_score')) NOT IN ('null', 'None', '') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(moby_metadata, '$.moby_score')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(moby_metadata, '$.moby_score') AS DECIMAL(10,2)) * 10
|
||||
ELSE NULL
|
||||
END AS moby_rating,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(ss_metadata, 'one', '$.ss_score') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(ss_metadata, '$.ss_score')) NOT IN ('null', 'None', '') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(ss_metadata, '$.ss_score')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(ss_metadata, '$.ss_score') AS DECIMAL(10,2)) * 10
|
||||
ELSE NULL
|
||||
END AS ss_rating
|
||||
FROM roms
|
||||
) AS r;
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute("DROP VIEW IF EXISTS roms_metadata")
|
||||
92
backend/alembic/versions/0038_add_ssid_to_sibling_roms.py
Normal file
@@ -0,0 +1,92 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0038_add_ssid_to_sibling_roms
|
||||
Revises: 0037_virtual_rom_columns
|
||||
Create Date: 2025-04-23 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0038_add_ssid_to_sibling_roms"
|
||||
down_revision = "0037_virtual_rom_columns"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
null_safe_equal_operator = (
|
||||
"IS NOT DISTINCT FROM" if is_postgresql(connection) else "<=>"
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
CREATE OR REPLACE VIEW sibling_roms AS
|
||||
SELECT
|
||||
r1.id AS rom_id,
|
||||
r2.id AS sibling_rom_id,
|
||||
r1.platform_id AS platform_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
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,
|
||||
CASE WHEN r1.ss_id {null_safe_equal_operator} r2.ss_id THEN r1.ss_id END AS ss_id
|
||||
FROM
|
||||
roms r1
|
||||
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)
|
||||
OR
|
||||
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
|
||||
OR
|
||||
(r1.ss_id = r2.ss_id AND r1.ss_id IS NOT NULL)
|
||||
);
|
||||
""" # nosec B608
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
null_safe_equal_operator = (
|
||||
"IS NOT DISTINCT FROM" if is_postgresql(connection) else "<=>"
|
||||
)
|
||||
|
||||
connection.execute(sa.text("DROP VIEW IF EXISTS sibling_roms;"))
|
||||
|
||||
connection.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
CREATE VIEW sibling_roms AS
|
||||
SELECT
|
||||
r1.id AS rom_id,
|
||||
r2.id AS sibling_rom_id,
|
||||
r1.platform_id AS platform_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
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
|
||||
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)
|
||||
OR
|
||||
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
|
||||
);
|
||||
""" # nosec B608
|
||||
),
|
||||
)
|
||||
59
backend/alembic/versions/0039_add_retro_achievements.py
Normal file
@@ -0,0 +1,59 @@
|
||||
"""add retro achievements data
|
||||
|
||||
Revision ID: 0039_add_retro_achievements
|
||||
Revises: 0038_add_ssid_to_sibling_roms
|
||||
Create Date: 2025-04-11 00:59:30.772416
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import CustomJSON
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0039_add_retro_achievements"
|
||||
down_revision = "0038_add_ssid_to_sibling_roms"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True))
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("ra_hash", sa.String(length=100), nullable=True))
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("ra_id", sa.Integer(), nullable=True))
|
||||
|
||||
with op.batch_alter_table("users", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("ra_username", sa.String(length=100), nullable=True)
|
||||
)
|
||||
batch_op.add_column(sa.Column("ra_progression", CustomJSON(), nullable=True))
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("ra_id", sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column("ra_hash", sa.String(length=100), nullable=True))
|
||||
batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_metadata")
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_id")
|
||||
|
||||
with op.batch_alter_table("users", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_username")
|
||||
batch_op.drop_column("ra_progression")
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_id")
|
||||
batch_op.drop_column("ra_hash")
|
||||
batch_op.drop_column("ra_metadata")
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_hash")
|
||||
117
backend/alembic/versions/0040_migrate_assets_paths.py
Normal file
@@ -0,0 +1,117 @@
|
||||
"""migrate asset file paths to include rom_id
|
||||
|
||||
Revision ID: 0040_migrate_assets_paths
|
||||
Revises: 0039_add_retro_achievements
|
||||
Create Date: 2025-05-14 18:10:23.522345
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from config import ASSETS_BASE_PATH
|
||||
from logger.logger import log
|
||||
from sqlalchemy.sql import text
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0040_migrate_assets_paths"
|
||||
down_revision = "0039_add_retro_achievements"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
# Table configuration: whether each table has an emulator column
|
||||
tables_with_emulator_column = {
|
||||
"saves": True,
|
||||
"states": True,
|
||||
"screenshots": False,
|
||||
}
|
||||
|
||||
for table, has_emulator in tables_with_emulator_column.items():
|
||||
log.info(f"Processing table: {table}")
|
||||
|
||||
# Database-specific LIKE clause
|
||||
like_clause = (
|
||||
"file_path NOT LIKE '%%/' || rom_id::text || '/%%'"
|
||||
if is_postgresql(conn)
|
||||
else "file_path NOT LIKE CONCAT('%/', rom_id, '/%')"
|
||||
)
|
||||
|
||||
# Build query based on whether emulator exists
|
||||
select_cols = "id, file_path, rom_id" + (", emulator" if has_emulator else "")
|
||||
results = conn.execute(
|
||||
text(
|
||||
f"""
|
||||
SELECT {select_cols}
|
||||
FROM {table}
|
||||
WHERE {like_clause}
|
||||
""" # nosec B608
|
||||
)
|
||||
).fetchall()
|
||||
|
||||
for row in results:
|
||||
item_id = row.id
|
||||
old_path = row.file_path
|
||||
rom_id = row.rom_id
|
||||
emulator = row.emulator if has_emulator else None
|
||||
|
||||
if not old_path or not rom_id:
|
||||
continue # Skip incomplete records
|
||||
|
||||
parts = old_path.split("/")
|
||||
try:
|
||||
user_id = parts[1]
|
||||
platform = parts[3]
|
||||
except IndexError:
|
||||
log.info(f"[{table}] Skipping malformed path: {old_path}")
|
||||
continue
|
||||
|
||||
# Always include rom_id in the path
|
||||
path_parts = ["users", user_id, table, platform, str(rom_id)]
|
||||
if emulator:
|
||||
path_parts.append(emulator)
|
||||
new_path = "/".join(path_parts)
|
||||
|
||||
old_abs = os.path.join(ASSETS_BASE_PATH, *old_path.split("/"))
|
||||
new_abs = os.path.join(ASSETS_BASE_PATH, *new_path.split("/"))
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(new_abs), exist_ok=True)
|
||||
|
||||
if os.path.exists(old_abs):
|
||||
if table == "screenshots" and os.path.isdir(old_abs):
|
||||
# Move files individually to avoid moving directory into itself
|
||||
for filename in os.listdir(old_abs):
|
||||
src = os.path.join(old_abs, filename)
|
||||
dst = os.path.join(new_abs, filename)
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
os.rename(src, dst)
|
||||
log.info(f"[{table}] Moved file: {src} -> {dst}")
|
||||
else:
|
||||
os.rename(old_abs, new_abs)
|
||||
log.info(f"[{table}] Moved: {old_abs} -> {new_abs}")
|
||||
else:
|
||||
log.info(f"[{table}] Old path does not exist: {old_abs}")
|
||||
except Exception as e:
|
||||
log.error(f"[{table}] Error moving {old_abs} to {new_abs}: {e}")
|
||||
continue
|
||||
|
||||
# Update DB
|
||||
conn.execute(
|
||||
text(
|
||||
f"""
|
||||
UPDATE {table}
|
||||
SET file_path = :new_path
|
||||
WHERE id = :item_id
|
||||
""" # nosec B608
|
||||
),
|
||||
{"new_path": new_path, "item_id": item_id},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Optional: implement reverse logic if desired
|
||||
pass
|
||||
94
backend/alembic/versions/0041_assets_t_thumb_cleanup.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0041_assets_t_thumb_cleanup
|
||||
Revises: 0040_migrate_assets_paths
|
||||
Create Date: 2025-06-06 16:22:08.361524
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.sql import text
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0041_assets_t_thumb_cleanup"
|
||||
down_revision = "0040_migrate_assets_paths"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE roms
|
||||
SET url_cover = replace(url_cover, 't_thumb', 't_1080p')
|
||||
WHERE url_cover LIKE '%t_thumb%'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
if is_postgresql(conn):
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE roms
|
||||
SET url_screenshots = (
|
||||
SELECT jsonb_agg(
|
||||
to_jsonb(replace(value, 't_thumb', 't_720p'))
|
||||
)
|
||||
FROM jsonb_array_elements_text(url_screenshots) AS value
|
||||
)
|
||||
WHERE url_screenshots IS NOT NULL
|
||||
AND url_screenshots::text LIKE '%t_thumb%';
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
result = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, url_screenshots
|
||||
FROM roms
|
||||
WHERE JSON_SEARCH(url_screenshots, 'one', '%t_thumb%') IS NOT NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
for row in result:
|
||||
row_id, screenshots_json = row
|
||||
if screenshots_json:
|
||||
try:
|
||||
screenshots = json.loads(screenshots_json)
|
||||
if isinstance(screenshots, list):
|
||||
updated_screenshots = [
|
||||
(
|
||||
url.replace("t_thumb", "t_720p")
|
||||
if isinstance(url, str)
|
||||
else url
|
||||
)
|
||||
for url in screenshots
|
||||
]
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE roms
|
||||
SET url_screenshots = :screenshots
|
||||
WHERE id = :id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"screenshots": json.dumps(updated_screenshots),
|
||||
"id": row_id,
|
||||
},
|
||||
)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
90
backend/alembic/versions/0042_add_missing_from_fs.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0042_add_missing_from_fs
|
||||
Revises: 0041_assets_t_thumb_cleanup
|
||||
Create Date: 2025-06-11
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0042_add_missing_from_fs"
|
||||
down_revision = "0041_assets_t_thumb_cleanup"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("firmware", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("saves", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("states", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("screenshots", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"missing_from_fs", sa.Boolean(), nullable=False, server_default="0"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("firmware", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("saves", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("states", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
|
||||
with op.batch_alter_table("screenshots", schema=None) as batch_op:
|
||||
batch_op.drop_column("missing_from_fs")
|
||||
55
backend/alembic/versions/0043_launchbox_id.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0043_launchbox_id
|
||||
Revises: 0042_add_missing_from_fs
|
||||
Create Date: 2025-05-20 22:39:16.993191
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
from utils.database import CustomJSON
|
||||
|
||||
revision = "0043_launchbox_id"
|
||||
down_revision = "0042_add_missing_from_fs"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.drop_column("ra_metadata")
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("launchbox_id", sa.Integer(), nullable=True))
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("launchbox_id", sa.Integer(), nullable=True))
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"launchbox_metadata",
|
||||
sa.JSON().with_variant(
|
||||
postgresql.JSONB(astext_type=sa.Text()), "postgresql"
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
batch_op.create_index("idx_roms_launchbox_id", ["launchbox_id"], unique=False)
|
||||
batch_op.create_index("idx_roms_ra_id", ["ra_id"], unique=False)
|
||||
batch_op.create_index("idx_roms_sgdb_id", ["sgdb_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_index("idx_roms_sgdb_id")
|
||||
batch_op.drop_index("idx_roms_ra_id")
|
||||
batch_op.drop_index("idx_roms_launchbox_id")
|
||||
batch_op.drop_column("launchbox_metadata")
|
||||
batch_op.drop_column("launchbox_id")
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.drop_column("launchbox_id")
|
||||
|
||||
with op.batch_alter_table("rom_user", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True))
|
||||
51
backend/alembic/versions/0044_hasheous_id.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0044_hasheous_id
|
||||
Revises: 0043_launchbox_id
|
||||
Create Date: 2025-06-16 03:15:42.692551
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0044_hasheous_id"
|
||||
down_revision = "0043_launchbox_id"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("hasheous_id", sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column("tgdb_id", sa.Integer(), nullable=True))
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"hasheous_metadata",
|
||||
sa.JSON().with_variant(
|
||||
postgresql.JSONB(astext_type=sa.Text()), "postgresql"
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
batch_op.create_index("idx_roms_hasheous_id", ["hasheous_id"], unique=False)
|
||||
batch_op.create_index("idx_roms_tgdb_id", ["tgdb_id"], unique=False)
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("hasheous_id", sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column("tgdb_id", sa.Integer(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.drop_column("hasheous_id")
|
||||
batch_op.drop_column("tgdb_id")
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_index("idx_roms_tgdb_id")
|
||||
batch_op.drop_index("idx_roms_hasheous_id")
|
||||
batch_op.drop_column("hasheous_metadata")
|
||||
batch_op.drop_column("tgdb_id")
|
||||
batch_op.drop_column("hasheous_id")
|
||||
302
backend/alembic/versions/0045_roms_metadata_update.py
Normal file
@@ -0,0 +1,302 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0045_roms_metadata_update
|
||||
Revises: 0044_hasheous_id
|
||||
Create Date: 2025-03-17 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0045_roms_metadata_update"
|
||||
down_revision = "0044_hasheous_id"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
connection = op.get_bind()
|
||||
if is_postgresql(connection):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
CREATE OR REPLACE VIEW roms_metadata AS
|
||||
SELECT
|
||||
r.id AS rom_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'genres'),
|
||||
(r.moby_metadata -> 'genres'),
|
||||
(r.ss_metadata -> 'genres'),
|
||||
(r.launchbox_metadata -> 'genres'),
|
||||
(r.ra_metadata -> 'genres'),
|
||||
'[]'::jsonb
|
||||
) AS genres,
|
||||
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'franchises'),
|
||||
(r.ss_metadata -> 'franchises'),
|
||||
'[]'::jsonb
|
||||
) AS franchises,
|
||||
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'collections'),
|
||||
'[]'::jsonb
|
||||
) AS collections,
|
||||
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'companies'),
|
||||
(r.ss_metadata -> 'companies'),
|
||||
(r.ra_metadata -> 'companies'),
|
||||
(r.launchbox_metadata -> 'companies'),
|
||||
'[]'::jsonb
|
||||
) AS companies,
|
||||
|
||||
COALESCE(
|
||||
(r.igdb_metadata -> 'game_modes'),
|
||||
(r.ss_metadata -> 'game_modes'),
|
||||
'[]'::jsonb
|
||||
) AS game_modes,
|
||||
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL
|
||||
AND r.igdb_metadata ? 'age_ratings'
|
||||
AND jsonb_array_length(r.igdb_metadata -> 'age_ratings') > 0
|
||||
THEN
|
||||
jsonb_path_query_array(r.igdb_metadata, '$.age_ratings[*].rating')
|
||||
ELSE
|
||||
'[]'::jsonb
|
||||
END,
|
||||
CASE
|
||||
WHEN r.launchbox_metadata IS NOT NULL
|
||||
AND r.launchbox_metadata ? 'esrb'
|
||||
AND r.launchbox_metadata ->> 'esrb' IS NOT NULL
|
||||
AND r.launchbox_metadata ->> 'esrb' != ''
|
||||
THEN
|
||||
jsonb_build_array(r.launchbox_metadata ->> 'esrb')
|
||||
ELSE
|
||||
'[]'::jsonb
|
||||
END,
|
||||
'[]'::jsonb
|
||||
) AS age_ratings,
|
||||
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'first_release_date' AND
|
||||
r.igdb_metadata ->> 'first_release_date' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.igdb_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.igdb_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'first_release_date' AND
|
||||
r.ss_metadata ->> 'first_release_date' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.ss_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.ss_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
WHEN r.ra_metadata IS NOT NULL AND r.ra_metadata ? 'first_release_date' AND
|
||||
r.ra_metadata ->> 'first_release_date' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.ra_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.ra_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
WHEN r.launchbox_metadata IS NOT NULL AND r.launchbox_metadata ? 'first_release_date' AND
|
||||
r.launchbox_metadata ->> 'first_release_date' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.launchbox_metadata ->> 'first_release_date' ~ '^[0-9]+$'
|
||||
THEN (r.launchbox_metadata ->> 'first_release_date')::bigint * 1000
|
||||
|
||||
ELSE NULL
|
||||
END AS first_release_date,
|
||||
|
||||
CASE
|
||||
WHEN (igdb_rating IS NOT NULL OR moby_rating IS NOT NULL OR ss_rating IS NOT NULL OR launchbox_rating IS NOT NULL) THEN
|
||||
(COALESCE(igdb_rating, 0) + COALESCE(moby_rating, 0) + COALESCE(ss_rating, 0) + COALESCE(launchbox_rating, 0)) /
|
||||
(CASE WHEN igdb_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN moby_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN ss_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN launchbox_rating IS NOT NULL THEN 1 ELSE 0 END)
|
||||
ELSE NULL
|
||||
END AS average_rating
|
||||
FROM (
|
||||
SELECT
|
||||
r.id,
|
||||
r.igdb_metadata,
|
||||
r.moby_metadata,
|
||||
r.ss_metadata,
|
||||
r.ra_metadata,
|
||||
r.launchbox_metadata,
|
||||
CASE
|
||||
WHEN r.igdb_metadata IS NOT NULL AND r.igdb_metadata ? 'total_rating' AND
|
||||
r.igdb_metadata ->> 'total_rating' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.igdb_metadata ->> 'total_rating' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.igdb_metadata ->> 'total_rating')::float
|
||||
ELSE NULL
|
||||
END AS igdb_rating,
|
||||
CASE
|
||||
WHEN r.moby_metadata IS NOT NULL AND r.moby_metadata ? 'moby_score' AND
|
||||
r.moby_metadata ->> 'moby_score' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.moby_metadata ->> 'moby_score' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.moby_metadata ->> 'moby_score')::float * 10
|
||||
ELSE NULL
|
||||
END AS moby_rating,
|
||||
CASE
|
||||
WHEN r.ss_metadata IS NOT NULL AND r.ss_metadata ? 'ss_score' AND
|
||||
r.ss_metadata ->> 'ss_score' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.ss_metadata ->> 'ss_score' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.ss_metadata ->> 'ss_score')::float * 10
|
||||
ELSE NULL
|
||||
END AS ss_rating,
|
||||
CASE
|
||||
WHEN r.launchbox_metadata IS NOT NULL AND r.launchbox_metadata ? 'community_rating' AND
|
||||
r.launchbox_metadata ->> 'community_rating' NOT IN ('null', 'None', '0', '0.0') AND
|
||||
r.launchbox_metadata ->> 'community_rating' ~ '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN (r.launchbox_metadata ->> 'community_rating')::float * 20
|
||||
ELSE NULL
|
||||
END AS launchbox_rating
|
||||
FROM roms r
|
||||
) AS r;
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""CREATE OR REPLACE VIEW roms_metadata AS
|
||||
SELECT
|
||||
r.id as rom_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.moby_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.ss_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.launchbox_metadata, '$.genres'),
|
||||
JSON_EXTRACT(r.ra_metadata, '$.genres'),
|
||||
JSON_ARRAY()
|
||||
) AS genres,
|
||||
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.franchises'),
|
||||
JSON_EXTRACT(r.ss_metadata, '$.franchises'),
|
||||
JSON_ARRAY()
|
||||
) AS franchises,
|
||||
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.collections'),
|
||||
JSON_ARRAY()
|
||||
) AS collections,
|
||||
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.companies'),
|
||||
JSON_EXTRACT(r.ss_metadata, '$.companies'),
|
||||
JSON_EXTRACT(r.ra_metadata, '$.companies'),
|
||||
JSON_EXTRACT(r.launchbox_metadata, '$.companies'),
|
||||
JSON_ARRAY()
|
||||
) AS companies,
|
||||
|
||||
COALESCE(
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.game_modes'),
|
||||
JSON_EXTRACT(r.ss_metadata, '$.game_modes'),
|
||||
JSON_ARRAY()
|
||||
) AS game_modes,
|
||||
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.age_ratings')
|
||||
AND JSON_LENGTH(JSON_EXTRACT(r.igdb_metadata, '$.age_ratings')) > 0
|
||||
THEN
|
||||
JSON_EXTRACT(r.igdb_metadata, '$.age_ratings[*].rating')
|
||||
ELSE
|
||||
JSON_ARRAY()
|
||||
END,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.launchbox_metadata, 'one', '$.esrb')
|
||||
AND JSON_EXTRACT(r.launchbox_metadata, '$.esrb') IS NOT NULL
|
||||
AND JSON_EXTRACT(r.launchbox_metadata, '$.esrb') != ''
|
||||
THEN
|
||||
JSON_ARRAY(JSON_EXTRACT(r.launchbox_metadata, '$.esrb'))
|
||||
ELSE
|
||||
JSON_ARRAY()
|
||||
END,
|
||||
JSON_ARRAY()
|
||||
) AS age_ratings,
|
||||
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(r.igdb_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.igdb_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
WHEN JSON_CONTAINS_PATH(r.ss_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ss_metadata, '$.first_release_date')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ss_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.ss_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
WHEN JSON_CONTAINS_PATH(r.ra_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ra_metadata, '$.first_release_date')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.ra_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.ra_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
WHEN JSON_CONTAINS_PATH(r.launchbox_metadata, 'one', '$.first_release_date') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.launchbox_metadata, '$.first_release_date')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.launchbox_metadata, '$.first_release_date')) REGEXP '^[0-9]+$'
|
||||
THEN CAST(JSON_EXTRACT(r.launchbox_metadata, '$.first_release_date') AS SIGNED) * 1000
|
||||
|
||||
ELSE NULL
|
||||
END AS first_release_date,
|
||||
|
||||
CASE
|
||||
WHEN (igdb_rating IS NOT NULL OR moby_rating IS NOT NULL OR ss_rating IS NOT NULL OR launchbox_rating IS NOT NULL) THEN
|
||||
(COALESCE(igdb_rating, 0) + COALESCE(moby_rating, 0) + COALESCE(ss_rating, 0) + COALESCE(launchbox_rating, 0)) /
|
||||
(CASE WHEN igdb_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN moby_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN ss_rating IS NOT NULL THEN 1 ELSE 0 END +
|
||||
CASE WHEN launchbox_rating IS NOT NULL THEN 1 ELSE 0 END)
|
||||
ELSE NULL
|
||||
END AS average_rating
|
||||
FROM (
|
||||
SELECT
|
||||
id,
|
||||
igdb_metadata,
|
||||
moby_metadata,
|
||||
ss_metadata,
|
||||
ra_metadata,
|
||||
launchbox_metadata,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(igdb_metadata, 'one', '$.total_rating') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(igdb_metadata, '$.total_rating')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(igdb_metadata, '$.total_rating')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(igdb_metadata, '$.total_rating') AS DECIMAL(10,2))
|
||||
ELSE NULL
|
||||
END AS igdb_rating,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(moby_metadata, 'one', '$.moby_score') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(moby_metadata, '$.moby_score')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(moby_metadata, '$.moby_score')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(moby_metadata, '$.moby_score') AS DECIMAL(10,2)) * 10
|
||||
ELSE NULL
|
||||
END AS moby_rating,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(ss_metadata, 'one', '$.ss_score') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(ss_metadata, '$.ss_score')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(ss_metadata, '$.ss_score')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(ss_metadata, '$.ss_score') AS DECIMAL(10,2)) * 10
|
||||
ELSE NULL
|
||||
END AS ss_rating,
|
||||
CASE
|
||||
WHEN JSON_CONTAINS_PATH(launchbox_metadata, 'one', '$.community_rating') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(launchbox_metadata, '$.community_rating')) NOT IN ('null', 'None', '0', '0.0') AND
|
||||
JSON_UNQUOTE(JSON_EXTRACT(launchbox_metadata, '$.community_rating')) REGEXP '^[0-9]+(\\.[0-9]+)?$'
|
||||
THEN CAST(JSON_EXTRACT(launchbox_metadata, '$.community_rating') AS DECIMAL(10,2)) * 20
|
||||
ELSE NULL
|
||||
END AS launchbox_rating
|
||||
FROM roms
|
||||
) AS r;
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute("DROP VIEW IF EXISTS roms_metadata")
|
||||
226
backend/alembic/versions/0046_migrate_platform_slugs.py
Normal file
@@ -0,0 +1,226 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0046_migrate_platform_slugs
|
||||
Revises: 0045_roms_metadata_update
|
||||
Create Date: 2025-07-24 15:24:04.331946
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.metadata.base_hander import UniversalPlatformSlug as UPS
|
||||
|
||||
revision = "0046_migrate_platform_slugs"
|
||||
down_revision = "0045_roms_metadata_update"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("temp_old_slug", sa.String(length=100), nullable=True)
|
||||
)
|
||||
batch_op.drop_column("logo_path")
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"created_at",
|
||||
existing_type=sa.DATETIME(),
|
||||
type_=sa.TIMESTAMP(timezone=True),
|
||||
existing_nullable=False,
|
||||
existing_server_default=sa.text("now()"),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"updated_at",
|
||||
existing_type=sa.DATETIME(),
|
||||
type_=sa.TIMESTAMP(timezone=True),
|
||||
existing_nullable=False,
|
||||
existing_server_default=sa.text("now()"),
|
||||
)
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"fs_name", existing_type=sa.VARCHAR(length=450), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_tags", existing_type=sa.VARCHAR(length=450), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_ext", existing_type=sa.VARCHAR(length=450), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_extension", existing_type=sa.VARCHAR(length=100), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_path", existing_type=sa.VARCHAR(length=1000), nullable=False
|
||||
)
|
||||
|
||||
with op.batch_alter_table("users", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"role", existing_type=sa.Enum("VIEWER", "EDITOR", "ADMIN"), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"avatar_path", existing_type=sa.VARCHAR(length=255), nullable=False
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"ra_username",
|
||||
existing_type=sa.VARCHAR(length=100),
|
||||
type_=sa.String(length=255),
|
||||
existing_nullable=True,
|
||||
)
|
||||
|
||||
# Update slugs already in the database
|
||||
connection = op.get_bind()
|
||||
for old_slug, new_slug in OLD_SLUGS_TO_NEW_MAP.items():
|
||||
result = connection.execute(
|
||||
sa.text(
|
||||
"UPDATE platforms SET slug = :new_slug, temp_old_slug = :old_slug WHERE slug = :old_slug"
|
||||
),
|
||||
{"new_slug": new_slug.value, "old_slug": old_slug},
|
||||
)
|
||||
if result.rowcount > 0:
|
||||
try:
|
||||
cm.add_platform_binding(old_slug, new_slug.value)
|
||||
except OSError as e:
|
||||
print(
|
||||
f"Error adding platform binding for {old_slug} to {new_slug.value}: {e}"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
for old_slug, new_slug in OLD_SLUGS_TO_NEW_MAP.items():
|
||||
result = connection.execute(
|
||||
sa.text(
|
||||
"UPDATE platforms SET slug = temp_old_slug WHERE temp_old_slug = :old_slug AND slug = :new_slug"
|
||||
),
|
||||
{"old_slug": old_slug, "new_slug": new_slug.value},
|
||||
)
|
||||
if result.rowcount > 0:
|
||||
try:
|
||||
cm.remove_platform_binding(old_slug)
|
||||
except OSError as e:
|
||||
print(f"Error removing platform binding for {old_slug}: {e}")
|
||||
|
||||
with op.batch_alter_table("users", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"ra_username",
|
||||
existing_type=sa.String(length=255),
|
||||
type_=sa.VARCHAR(length=100),
|
||||
existing_nullable=True,
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"avatar_path", existing_type=sa.VARCHAR(length=255), nullable=True
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"role", existing_type=sa.Enum("VIEWER", "EDITOR", "ADMIN"), nullable=True
|
||||
)
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"fs_path", existing_type=sa.VARCHAR(length=1000), nullable=True
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_extension", existing_type=sa.VARCHAR(length=100), nullable=True
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_ext", existing_type=sa.VARCHAR(length=450), nullable=True
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name_no_tags", existing_type=sa.VARCHAR(length=450), nullable=True
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"fs_name", existing_type=sa.VARCHAR(length=450), nullable=True
|
||||
)
|
||||
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"updated_at",
|
||||
existing_type=sa.TIMESTAMP(timezone=True),
|
||||
type_=sa.DATETIME(),
|
||||
existing_nullable=False,
|
||||
existing_server_default=sa.text("now()"),
|
||||
)
|
||||
batch_op.alter_column(
|
||||
"created_at",
|
||||
existing_type=sa.TIMESTAMP(timezone=True),
|
||||
type_=sa.DATETIME(),
|
||||
existing_nullable=False,
|
||||
existing_server_default=sa.text("now()"),
|
||||
)
|
||||
|
||||
with op.batch_alter_table("platforms", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("logo_path", sa.VARCHAR(length=1000), nullable=True)
|
||||
)
|
||||
batch_op.drop_column("temp_old_slug")
|
||||
|
||||
|
||||
OLD_SLUGS_TO_NEW_MAP = {
|
||||
"cpc": UPS.ACPC,
|
||||
"apple-i": UPS.APPLE,
|
||||
"apple2": UPS.APPLEII,
|
||||
"apple2gs": UPS.APPLE_IIGS,
|
||||
"apple3": UPS.APPLEIII,
|
||||
"mattel-aquarius": UPS.AQUARIUS,
|
||||
"atari-2600": UPS.ATARI2600,
|
||||
"atari-5200": UPS.ATARI5200,
|
||||
"atari-7800": UPS.ATARI7800,
|
||||
"atari-8-bit": UPS.ATARI8BIT,
|
||||
"bally-astrocade": UPS.ASTROCADE,
|
||||
"bbc-micro": UPS.BBCMICRO,
|
||||
"cd-i": UPS.PHILIPS_CD_I,
|
||||
"cdtv": UPS.COMMODORE_CDTV,
|
||||
"channel-f": UPS.FAIRCHILD_CHANNEL_F,
|
||||
"commodore-16-plus4": UPS.C_PLUS_4,
|
||||
"dragon-3264": UPS.DRAGON_32_SLASH_64,
|
||||
"dreamcast": UPS.DC,
|
||||
"edsac--1": UPS.EDSAC,
|
||||
"electron": UPS.ACORN_ELECTRON,
|
||||
"elektor-tv-games-computer": UPS.ELEKTOR,
|
||||
"fmtowns": UPS.FM_TOWNS,
|
||||
"game-com": UPS.GAME_DOT_COM,
|
||||
"gameboy": UPS.GB,
|
||||
"gameboy-color": UPS.GBC,
|
||||
"gameboy-advance": UPS.GBA,
|
||||
"game-gear": UPS.GAMEGEAR,
|
||||
"gamecube": UPS.NGC,
|
||||
"genesis-slash-megadrive": UPS.GENESIS,
|
||||
"macintosh": UPS.MAC,
|
||||
"microcomputer--1": UPS.MICROCOMPUTER,
|
||||
"microvision--1": UPS.MICROVISION,
|
||||
"neo-geo": UPS.NEOGEOAES,
|
||||
"odyssey--1": UPS.ODYSSEY,
|
||||
"nintendo-ds": UPS.NDS,
|
||||
"palmos": UPS.PALM_OS,
|
||||
"pc88": UPS.PC_8800_SERIES,
|
||||
"pc98": UPS.PC_9800_SERIES,
|
||||
"pet": UPS.CPET,
|
||||
"pdp-7--1": UPS.PDP_7,
|
||||
"pdp-8--1": UPS.PDP_8,
|
||||
"playstation": UPS.PSX,
|
||||
"ps": UPS.PSX,
|
||||
"ps4--1": UPS.PS4,
|
||||
"playstation-4": UPS.PS4,
|
||||
"playstation-5": UPS.PS5,
|
||||
"ps-vita": UPS.PSVITA,
|
||||
"sega-32x": UPS.SEGA32,
|
||||
"sega-cd": UPS.SEGACD,
|
||||
"sega-cd-32x": UPS.SEGACD32,
|
||||
"sega-master-system": UPS.SMS,
|
||||
"sega-saturn": UPS.SATURN,
|
||||
"sharp-x1": UPS.X1,
|
||||
"sinclair-zx81": UPS.ZX81,
|
||||
"sg-1000": UPS.SG1000,
|
||||
"switch2": UPS.SWITCH_2,
|
||||
"thomson-mo": UPS.THOMSON_MO5,
|
||||
"trs-80-coco": UPS.TRS_80_COLOR_COMPUTER,
|
||||
"turbografx-16-slash-pc-engine-cd": UPS.TURBOGRAFX_CD,
|
||||
"turbo-grafx": UPS.TG16,
|
||||
"turbografx16--1": UPS.TG16,
|
||||
"watara-slash-quickshot-supervision": UPS.SUPERVISION,
|
||||
"windows": UPS.WIN,
|
||||
"zx-spectrum": UPS.ZXS,
|
||||
}
|
||||
61
backend/alembic/versions/0047_smart_collections.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""Add smart collections table
|
||||
|
||||
Revision ID: 0047_smart_collections
|
||||
Revises: 0046_migrate_platform_slugs
|
||||
Create Date: 2024-12-19 12:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import CustomJSON
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0047_smart_collections"
|
||||
down_revision = "0046_migrate_platform_slugs"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Create smart collections table (no association table - purely computed)."""
|
||||
|
||||
# Create the smart collections table
|
||||
op.create_table(
|
||||
"smart_collections",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("name", sa.String(length=400), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("is_public", sa.Boolean(), nullable=False, default=False),
|
||||
sa.Column("filter_criteria", CustomJSON(), nullable=False, default={}),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("rom_count", sa.Integer(), nullable=False, default=0),
|
||||
sa.Column(
|
||||
"rom_ids",
|
||||
CustomJSON(),
|
||||
nullable=False,
|
||||
default=[],
|
||||
),
|
||||
sa.Column("path_covers_small", CustomJSON(), nullable=False, default=[]),
|
||||
sa.Column("path_covers_large", CustomJSON(), nullable=False, default=[]),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Drop smart collections table."""
|
||||
|
||||
op.drop_table("smart_collections")
|
||||
107
backend/alembic/versions/0048_sibling_roms_more_ids.py
Normal file
@@ -0,0 +1,107 @@
|
||||
"""Add additional metadata IDs to sibling_roms view
|
||||
|
||||
Revision ID: 0048_sibling_roms_more_ids
|
||||
Revises: 0047_smart_collections
|
||||
Create Date: 2025-01-27 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0048_sibling_roms_more_ids"
|
||||
down_revision = "0047_smart_collections"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
null_safe_equal_operator = (
|
||||
"IS NOT DISTINCT FROM" if is_postgresql(connection) else "<=>"
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
CREATE OR REPLACE VIEW sibling_roms AS
|
||||
SELECT
|
||||
r1.id AS rom_id,
|
||||
r2.id AS sibling_rom_id,
|
||||
r1.platform_id AS platform_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
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,
|
||||
CASE WHEN r1.ss_id {null_safe_equal_operator} r2.ss_id THEN r1.ss_id END AS ss_id,
|
||||
CASE WHEN r1.launchbox_id {null_safe_equal_operator} r2.launchbox_id THEN r1.launchbox_id END AS launchbox_id,
|
||||
CASE WHEN r1.ra_id {null_safe_equal_operator} r2.ra_id THEN r1.ra_id END AS ra_id,
|
||||
CASE WHEN r1.hasheous_id {null_safe_equal_operator} r2.hasheous_id THEN r1.hasheous_id END AS hasheous_id,
|
||||
CASE WHEN r1.tgdb_id {null_safe_equal_operator} r2.tgdb_id THEN r1.tgdb_id END AS tgdb_id
|
||||
FROM
|
||||
roms r1
|
||||
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)
|
||||
OR
|
||||
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
|
||||
OR
|
||||
(r1.ss_id = r2.ss_id AND r1.ss_id IS NOT NULL)
|
||||
OR
|
||||
(r1.launchbox_id = r2.launchbox_id AND r1.launchbox_id IS NOT NULL)
|
||||
OR
|
||||
(r1.ra_id = r2.ra_id AND r1.ra_id IS NOT NULL)
|
||||
OR
|
||||
(r1.hasheous_id = r2.hasheous_id AND r1.hasheous_id IS NOT NULL)
|
||||
OR
|
||||
(r1.tgdb_id = r2.tgdb_id AND r1.tgdb_id IS NOT NULL)
|
||||
);
|
||||
""" # nosec B608
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
null_safe_equal_operator = (
|
||||
"IS NOT DISTINCT FROM" if is_postgresql(connection) else "<=>"
|
||||
)
|
||||
|
||||
connection.execute(sa.text("DROP VIEW IF EXISTS sibling_roms;"))
|
||||
|
||||
connection.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
CREATE VIEW sibling_roms AS
|
||||
SELECT
|
||||
r1.id AS rom_id,
|
||||
r2.id AS sibling_rom_id,
|
||||
r1.platform_id AS platform_id,
|
||||
NOW() AS created_at,
|
||||
NOW() AS updated_at,
|
||||
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,
|
||||
CASE WHEN r1.ss_id {null_safe_equal_operator} r2.ss_id THEN r1.ss_id END AS ss_id
|
||||
FROM
|
||||
roms r1
|
||||
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)
|
||||
OR
|
||||
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
|
||||
OR
|
||||
(r1.ss_id = r2.ss_id AND r1.ss_id IS NOT NULL)
|
||||
);
|
||||
""" # nosec B608
|
||||
),
|
||||
)
|
||||
38
backend/alembic/versions/0049_add_fs_size_bytes.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0049_add_fs_size_bytes
|
||||
Revises: 0048_sibling_roms_more_ids
|
||||
Create Date: 2025-08-20 01:14:05.164201
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0049_add_fs_size_bytes"
|
||||
down_revision = "0048_sibling_roms_more_ids"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("fs_size_bytes", sa.BigInteger(), nullable=True))
|
||||
|
||||
# Set fs_size_bytes for all roms
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE roms SET fs_size_bytes = COALESCE((SELECT SUM(file_size_bytes) FROM rom_files WHERE roms.id = rom_files.rom_id), 0)"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"fs_size_bytes", existing_type=sa.BigInteger(), nullable=False
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_column("fs_size_bytes")
|
||||
@@ -1,5 +1,4 @@
|
||||
import os
|
||||
import secrets
|
||||
from typing import Final
|
||||
|
||||
import yarl
|
||||
@@ -9,13 +8,17 @@ load_dotenv()
|
||||
|
||||
|
||||
def str_to_bool(value: str) -> bool:
|
||||
return value.lower() in ("true", "1")
|
||||
return value.strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
ROMM_BASE_URL = os.environ.get("ROMM_BASE_URL", "http://0.0.0.0")
|
||||
ROMM_PORT = int(os.environ.get("ROMM_PORT", 8080))
|
||||
|
||||
# GUNICORN
|
||||
DEV_MODE: Final = str_to_bool(os.environ.get("DEV_MODE", "false"))
|
||||
DEV_HOST: Final = os.environ.get("DEV_HOST", "127.0.0.1")
|
||||
DEV_PORT: Final = int(os.environ.get("DEV_PORT", "5000"))
|
||||
DEV_SQL_ECHO: Final = str_to_bool(os.environ.get("DEV_SQL_ECHO", "false"))
|
||||
|
||||
# PATHS
|
||||
ROMM_BASE_PATH: Final = os.environ.get("ROMM_BASE_PATH", "/romm")
|
||||
@@ -25,12 +28,15 @@ ASSETS_BASE_PATH: Final = f"{ROMM_BASE_PATH}/assets"
|
||||
FRONTEND_RESOURCES_PATH: Final = "/assets/romm/resources"
|
||||
|
||||
# DATABASE
|
||||
DB_HOST: Final = os.environ.get("DB_HOST", "127.0.0.1")
|
||||
DB_PORT: Final = int(os.environ.get("DB_PORT", 3306))
|
||||
DB_USER: Final = os.environ.get("DB_USER")
|
||||
DB_PASSWD: Final = os.environ.get("DB_PASSWD")
|
||||
DB_NAME: Final = os.environ.get("DB_NAME", "romm")
|
||||
ROMM_DB_DRIVER: Final = os.environ.get("ROMM_DB_DRIVER", "mariadb")
|
||||
DB_HOST: Final[str | None] = os.environ.get("DB_HOST", "127.0.0.1") or None
|
||||
DB_PORT: Final[int | None] = (
|
||||
int(os.environ.get("DB_PORT", 3306)) if os.environ.get("DB_PORT") != "" else None
|
||||
)
|
||||
DB_USER: Final[str | None] = os.environ.get("DB_USER")
|
||||
DB_PASSWD: Final[str | None] = os.environ.get("DB_PASSWD")
|
||||
DB_NAME: Final[str] = os.environ.get("DB_NAME", "romm")
|
||||
DB_QUERY_JSON: Final[str | None] = os.environ.get("DB_QUERY_JSON")
|
||||
ROMM_DB_DRIVER: Final[str] = os.environ.get("ROMM_DB_DRIVER", "mariadb")
|
||||
|
||||
# REDIS
|
||||
REDIS_HOST: Final = os.environ.get("REDIS_HOST", "127.0.0.1")
|
||||
@@ -56,6 +62,9 @@ IGDB_CLIENT_SECRET: Final = os.environ.get(
|
||||
"IGDB_CLIENT_SECRET", os.environ.get("CLIENT_SECRET", "")
|
||||
).strip()
|
||||
|
||||
# MOBYGAMES
|
||||
MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip()
|
||||
|
||||
# SCREENSCRAPER
|
||||
SCREENSCRAPER_USER: Final = os.environ.get("SCREENSCRAPER_USER", "")
|
||||
SCREENSCRAPER_PASSWORD: Final = os.environ.get("SCREENSCRAPER_PASSWORD", "")
|
||||
@@ -63,13 +72,36 @@ SCREENSCRAPER_PASSWORD: Final = os.environ.get("SCREENSCRAPER_PASSWORD", "")
|
||||
# STEAMGRIDDB
|
||||
STEAMGRIDDB_API_KEY: Final = os.environ.get("STEAMGRIDDB_API_KEY", "").strip()
|
||||
|
||||
# MOBYGAMES
|
||||
MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip()
|
||||
# RETROACHIEVEMENTS
|
||||
RETROACHIEVEMENTS_API_KEY: Final = os.environ.get("RETROACHIEVEMENTS_API_KEY", "")
|
||||
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final = int(
|
||||
os.environ.get("REFRESH_RETROACHIEVEMENTS_CACHE_DAYS", 30)
|
||||
)
|
||||
|
||||
# LAUNCHBOX
|
||||
LAUNCHBOX_API_ENABLED: Final = str_to_bool(
|
||||
os.environ.get("LAUNCHBOX_API_ENABLED", "false")
|
||||
)
|
||||
|
||||
# PLAYMATCH
|
||||
PLAYMATCH_API_ENABLED: Final = str_to_bool(
|
||||
os.environ.get("PLAYMATCH_API_ENABLED", "false")
|
||||
)
|
||||
|
||||
# HASHEOUS
|
||||
HASHEOUS_API_ENABLED: Final = str_to_bool(
|
||||
os.environ.get("HASHEOUS_API_ENABLED", "false")
|
||||
)
|
||||
|
||||
# THEGAMESDB
|
||||
TGDB_API_ENABLED: Final = str_to_bool(os.environ.get("TGDB_API_ENABLED", "false"))
|
||||
|
||||
# AUTH
|
||||
ROMM_AUTH_SECRET_KEY: Final = os.environ.get(
|
||||
"ROMM_AUTH_SECRET_KEY", secrets.token_hex(32)
|
||||
)
|
||||
ROMM_AUTH_SECRET_KEY: Final = os.environ.get("ROMM_AUTH_SECRET_KEY")
|
||||
|
||||
SESSION_MAX_AGE_SECONDS: Final = int(
|
||||
os.environ.get("SESSION_MAX_AGE_SECONDS", 14 * 24 * 60 * 60)
|
||||
) # 14 days, in seconds
|
||||
DISABLE_CSRF_PROTECTION = str_to_bool(
|
||||
os.environ.get("DISABLE_CSRF_PROTECTION", "false")
|
||||
)
|
||||
@@ -111,6 +143,13 @@ SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON: Final = os.environ.get(
|
||||
"SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON",
|
||||
"0 4 * * *", # At 4:00 AM every day
|
||||
)
|
||||
ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA: Final = str_to_bool(
|
||||
os.environ.get("ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA", "false")
|
||||
)
|
||||
SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON: Final = os.environ.get(
|
||||
"SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON",
|
||||
"0 5 * * *", # At 5:00 AM every day
|
||||
)
|
||||
|
||||
# EMULATION
|
||||
DISABLE_EMULATOR_JS = str_to_bool(os.environ.get("DISABLE_EMULATOR_JS", "false"))
|
||||
@@ -125,6 +164,11 @@ LOGLEVEL: Final = os.environ.get("LOGLEVEL", "INFO").upper()
|
||||
FORCE_COLOR: Final = str_to_bool(os.environ.get("FORCE_COLOR", "false"))
|
||||
NO_COLOR: Final = str_to_bool(os.environ.get("NO_COLOR", "false"))
|
||||
|
||||
# YOUTUBE
|
||||
YOUTUBE_BASE_URL: Final = os.environ.get(
|
||||
"YOUTUBE_BASE_URL", "https://www.youtube.com"
|
||||
).rstrip("/")
|
||||
|
||||
# SENTRY
|
||||
SENTRY_DSN: Final = os.environ.get("SENTRY_DSN", None)
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import pydash
|
||||
@@ -10,6 +9,7 @@ from config import (
|
||||
DB_NAME,
|
||||
DB_PASSWD,
|
||||
DB_PORT,
|
||||
DB_QUERY_JSON,
|
||||
DB_USER,
|
||||
LIBRARY_BASE_PATH,
|
||||
ROMM_BASE_PATH,
|
||||
@@ -19,6 +19,8 @@ from exceptions.config_exceptions import (
|
||||
ConfigNotReadableException,
|
||||
ConfigNotWritableException,
|
||||
)
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from sqlalchemy import URL
|
||||
from yaml.loader import SafeLoader
|
||||
@@ -64,11 +66,7 @@ class ConfigManager:
|
||||
# Tests require custom config path
|
||||
def __init__(self, config_file: str = ROMM_USER_CONFIG_FILE):
|
||||
self.config_file = config_file
|
||||
# If config file doesn't exists, create an empty one
|
||||
if not os.path.exists(config_file):
|
||||
Path(ROMM_USER_CONFIG_PATH).mkdir(parents=True, exist_ok=True)
|
||||
with open(config_file, "w") as file:
|
||||
file.write("")
|
||||
|
||||
try:
|
||||
self.get_config()
|
||||
except ConfigNotReadableException as e:
|
||||
@@ -83,12 +81,6 @@ class ConfigManager:
|
||||
str: database connection string
|
||||
"""
|
||||
|
||||
# DEPRECATED
|
||||
if ROMM_DB_DRIVER == "sqlite":
|
||||
log.critical("Sqlite is not supported anymore, migrate to mariaDB")
|
||||
sys.exit(6)
|
||||
# DEPRECATED
|
||||
|
||||
if ROMM_DB_DRIVER == "mariadb":
|
||||
driver = "mariadb+mariadbconnector"
|
||||
elif ROMM_DB_DRIVER == "mysql":
|
||||
@@ -96,7 +88,7 @@ class ConfigManager:
|
||||
elif ROMM_DB_DRIVER == "postgresql":
|
||||
driver = "postgresql+psycopg"
|
||||
else:
|
||||
log.critical(f"{ROMM_DB_DRIVER} database not supported")
|
||||
log.critical(f"{hl(ROMM_DB_DRIVER)} database not supported")
|
||||
sys.exit(3)
|
||||
|
||||
if not DB_USER or not DB_PASSWD:
|
||||
@@ -105,6 +97,14 @@ class ConfigManager:
|
||||
)
|
||||
sys.exit(3)
|
||||
|
||||
query: dict[str, str] = {}
|
||||
if DB_QUERY_JSON:
|
||||
try:
|
||||
query = json.loads(DB_QUERY_JSON)
|
||||
except ValueError as exc:
|
||||
log.critical(f"Invalid JSON in DB_QUERY_JSON: {exc}")
|
||||
sys.exit(3)
|
||||
|
||||
return URL.create(
|
||||
drivername=driver,
|
||||
username=DB_USER,
|
||||
@@ -112,6 +112,7 @@ class ConfigManager:
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
database=DB_NAME,
|
||||
query=query,
|
||||
)
|
||||
|
||||
def _parse_config(self):
|
||||
@@ -119,18 +120,24 @@ class ConfigManager:
|
||||
|
||||
self.config = Config(
|
||||
EXCLUDED_PLATFORMS=pydash.get(self._raw_config, "exclude.platforms", []),
|
||||
EXCLUDED_SINGLE_EXT=pydash.get(
|
||||
self._raw_config, "exclude.roms.single_file.extensions", []
|
||||
),
|
||||
EXCLUDED_SINGLE_EXT=[
|
||||
e.lower()
|
||||
for e in pydash.get(
|
||||
self._raw_config, "exclude.roms.single_file.extensions", []
|
||||
)
|
||||
],
|
||||
EXCLUDED_SINGLE_FILES=pydash.get(
|
||||
self._raw_config, "exclude.roms.single_file.names", []
|
||||
),
|
||||
EXCLUDED_MULTI_FILES=pydash.get(
|
||||
self._raw_config, "exclude.roms.multi_file.names", []
|
||||
),
|
||||
EXCLUDED_MULTI_PARTS_EXT=pydash.get(
|
||||
self._raw_config, "exclude.roms.multi_file.parts.extensions", []
|
||||
),
|
||||
EXCLUDED_MULTI_PARTS_EXT=[
|
||||
e.lower()
|
||||
for e in pydash.get(
|
||||
self._raw_config, "exclude.roms.multi_file.parts.extensions", []
|
||||
)
|
||||
],
|
||||
EXCLUDED_MULTI_PARTS_FILES=pydash.get(
|
||||
self._raw_config, "exclude.roms.multi_file.parts.names", []
|
||||
),
|
||||
@@ -225,14 +232,8 @@ class ConfigManager:
|
||||
sys.exit(3)
|
||||
|
||||
def get_config(self) -> Config:
|
||||
try:
|
||||
with open(self.config_file) as config_file:
|
||||
self._raw_config = yaml.load(config_file, Loader=SafeLoader) or {}
|
||||
except FileNotFoundError:
|
||||
self._raw_config = {}
|
||||
except PermissionError as exc:
|
||||
self._raw_config = {}
|
||||
raise ConfigNotReadableException from exc
|
||||
with open(self.config_file) as config_file:
|
||||
self._raw_config = yaml.load(config_file, Loader=SafeLoader) or {}
|
||||
|
||||
self._parse_config()
|
||||
self._validate_config()
|
||||
@@ -279,8 +280,8 @@ class ConfigManager:
|
||||
def add_platform_binding(self, fs_slug: str, slug: str) -> None:
|
||||
platform_bindings = self.config.PLATFORMS_BINDING
|
||||
if fs_slug in platform_bindings:
|
||||
log.warning(f"Binding for {fs_slug} already exists")
|
||||
return
|
||||
log.warning(f"Binding for {hl(fs_slug)} already exists")
|
||||
return None
|
||||
|
||||
platform_bindings[fs_slug] = slug
|
||||
self.config.PLATFORMS_BINDING = platform_bindings
|
||||
@@ -300,8 +301,8 @@ class ConfigManager:
|
||||
def add_platform_version(self, fs_slug: str, slug: str) -> None:
|
||||
platform_versions = self.config.PLATFORMS_VERSIONS
|
||||
if fs_slug in platform_versions:
|
||||
log.warning(f"Version for {fs_slug} already exists")
|
||||
return
|
||||
log.warning(f"Version for {hl(fs_slug)} already exists")
|
||||
return None
|
||||
|
||||
platform_versions[fs_slug] = slug
|
||||
self.config.PLATFORMS_VERSIONS = platform_versions
|
||||
@@ -321,8 +322,10 @@ class ConfigManager:
|
||||
def add_exclusion(self, exclusion_type: str, exclusion_value: str):
|
||||
config_item = self.config.__getattribute__(exclusion_type)
|
||||
if exclusion_value in config_item:
|
||||
log.warning(f"{exclusion_value} already excluded in {exclusion_type}")
|
||||
return
|
||||
log.warning(
|
||||
f"{hl(exclusion_value)} already excluded in {hl(exclusion_type, color=BLUE)}"
|
||||
)
|
||||
return None
|
||||
|
||||
config_item.append(exclusion_value)
|
||||
self.config.__setattr__(exclusion_type, config_item)
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated, Final
|
||||
|
||||
from config import DISABLE_USERPASS_LOGIN, OIDC_ENABLED, OIDC_REDIRECT_URI
|
||||
from config import OIDC_ENABLED, OIDC_REDIRECT_URI
|
||||
from decorators.auth import oauth
|
||||
from endpoints.forms.identity import OAuth2RequestForm
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.oauth import TokenResponse
|
||||
from exceptions.auth_exceptions import (
|
||||
AuthCredentialsException,
|
||||
OIDCDisabledException,
|
||||
OIDCNotConfiguredException,
|
||||
UserDisabledException,
|
||||
UserPassDisabledException,
|
||||
)
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi import Body, Depends, HTTPException, Request, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.security.http import HTTPBasic
|
||||
from handler.auth import auth_handler, oauth_handler, oidc_handler
|
||||
from handler.database import db_user_handler
|
||||
from logger.formatter import CYAN
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: Final = 30
|
||||
@@ -33,7 +34,7 @@ router = APIRouter(
|
||||
def login(
|
||||
request: Request,
|
||||
credentials=Depends(HTTPBasic()), # noqa
|
||||
) -> MessageResponse:
|
||||
) -> None:
|
||||
"""Session login endpoint
|
||||
|
||||
Args:
|
||||
@@ -43,14 +44,8 @@ def login(
|
||||
Raises:
|
||||
CredentialsException: Invalid credentials
|
||||
UserDisabledException: Auth is disabled
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
|
||||
if DISABLE_USERPASS_LOGIN:
|
||||
raise UserPassDisabledException
|
||||
|
||||
user = auth_handler.authenticate_user(credentials.username, credentials.password)
|
||||
if not user:
|
||||
raise AuthCredentialsException
|
||||
@@ -64,24 +59,17 @@ def login(
|
||||
now = datetime.now(timezone.utc)
|
||||
db_user_handler.update_user(user.id, {"last_login": now, "last_active": now})
|
||||
|
||||
return {"msg": "Successfully logged in"}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(request: Request) -> MessageResponse:
|
||||
@router.post("/logout", status_code=status.HTTP_200_OK)
|
||||
def logout(request: Request) -> None:
|
||||
"""Session logout endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
|
||||
request.session.clear()
|
||||
|
||||
return {"msg": "Successfully logged out"}
|
||||
|
||||
|
||||
@router.post("/token")
|
||||
async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResponse:
|
||||
@@ -256,8 +244,6 @@ async def auth_openid(request: Request):
|
||||
potential_user, _userinfo = (
|
||||
await oidc_handler.get_current_active_user_from_openid_token(token)
|
||||
)
|
||||
if not potential_user:
|
||||
raise AuthCredentialsException
|
||||
|
||||
if not potential_user:
|
||||
raise AuthCredentialsException
|
||||
@@ -274,3 +260,45 @@ async def auth_openid(request: Request):
|
||||
)
|
||||
|
||||
return RedirectResponse(url="/")
|
||||
|
||||
|
||||
@router.post("/forgot-password", status_code=status.HTTP_200_OK)
|
||||
def request_password_reset(username: str = Body(..., embed=True)) -> None:
|
||||
"""Request a password reset link for the user.
|
||||
|
||||
Args:
|
||||
username (str): Username of the user requesting the reset
|
||||
Returns:
|
||||
None: Returns 200 OK status
|
||||
"""
|
||||
user = db_user_handler.get_user_by_username(username)
|
||||
|
||||
if user:
|
||||
auth_handler.generate_password_reset_token(user)
|
||||
else:
|
||||
log.warning(
|
||||
f"Reset password link requested for a user {hl(username, color=CYAN)}, but that username does not exist."
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reset-password", status_code=status.HTTP_200_OK)
|
||||
def reset_password(
|
||||
token: str = Body(..., embed=True),
|
||||
new_password: str = Body(..., embed=True),
|
||||
) -> None:
|
||||
"""Reset password using the token.
|
||||
|
||||
Args:
|
||||
token (str): Reset token from the URL
|
||||
new_password (str): New user password
|
||||
|
||||
Returns:
|
||||
None: Returns 200 OK status
|
||||
"""
|
||||
user = auth_handler.verify_password_reset_token(token)
|
||||
|
||||
auth_handler.set_user_new_password(user, new_password)
|
||||
|
||||
log.info(
|
||||
f"Password was successfully reset for user {hl(user.username, color=CYAN)}."
|
||||
)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import json
|
||||
from io import BytesIO
|
||||
from shutil import rmtree
|
||||
|
||||
from anyio import Path
|
||||
from config import RESOURCES_BASE_PATH
|
||||
from config import str_to_bool
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.collection import CollectionSchema, VirtualCollectionSchema
|
||||
from endpoints.responses.collection import (
|
||||
CollectionSchema,
|
||||
SmartCollectionSchema,
|
||||
VirtualCollectionSchema,
|
||||
)
|
||||
from exceptions.endpoint_exceptions import (
|
||||
CollectionAlreadyExistsException,
|
||||
CollectionNotFoundInDatabaseException,
|
||||
@@ -17,10 +18,10 @@ 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
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.collection import Collection
|
||||
from PIL import Image
|
||||
from sqlalchemy.inspection import inspect
|
||||
from models.collection import Collection, SmartCollection
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -62,20 +63,13 @@ async def add_collection(
|
||||
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
(
|
||||
path_cover_l,
|
||||
path_cover_s,
|
||||
artwork_path,
|
||||
) = await fs_resource_handler.build_artwork_path(_added_collection, file_ext)
|
||||
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
file_location_small = Path(f"{artwork_path}/small.{file_ext}")
|
||||
file_location_large = Path(f"{artwork_path}/big.{file_ext}")
|
||||
with Image.open(artwork_content) as img:
|
||||
img.save(file_location_large)
|
||||
fs_resource_handler.resize_cover_to_small(
|
||||
img, save_path=file_location_small
|
||||
)
|
||||
) = await fs_resource_handler.store_artwork(
|
||||
_added_collection, artwork_content, file_ext
|
||||
)
|
||||
else:
|
||||
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
||||
entity=_added_collection,
|
||||
@@ -90,14 +84,58 @@ async def add_collection(
|
||||
created_collection = db_collection_handler.update_collection(
|
||||
_added_collection.id,
|
||||
{
|
||||
c: getattr(_added_collection, c)
|
||||
for c in inspect(_added_collection).mapper.column_attrs.keys()
|
||||
"path_cover_s": path_cover_s,
|
||||
"path_cover_l": path_cover_l,
|
||||
},
|
||||
)
|
||||
|
||||
return CollectionSchema.model_validate(created_collection)
|
||||
|
||||
|
||||
@protected_route(router.post, "/smart", [Scope.COLLECTIONS_WRITE])
|
||||
async def add_smart_collection(request: Request) -> SmartCollectionSchema:
|
||||
"""Create smart collection endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
SmartCollectionSchema: Just created smart collection
|
||||
"""
|
||||
|
||||
data = await request.form()
|
||||
|
||||
# Parse filter criteria from JSON string
|
||||
try:
|
||||
filter_criteria = json.loads(str(data.get("filter_criteria", "{}")))
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError("Invalid JSON for filter_criteria field") from e
|
||||
|
||||
cleaned_data = {
|
||||
"name": str(data.get("name", "")),
|
||||
"description": str(data.get("description", "")),
|
||||
"filter_criteria": filter_criteria,
|
||||
"is_public": str_to_bool(str(data.get("is_public", "false"))),
|
||||
"user_id": request.user.id,
|
||||
}
|
||||
|
||||
db_smart_collection = db_collection_handler.get_smart_collection_by_name(
|
||||
cleaned_data["name"], request.user.id
|
||||
)
|
||||
|
||||
if db_smart_collection:
|
||||
raise CollectionAlreadyExistsException(cleaned_data["name"])
|
||||
|
||||
created_smart_collection = db_collection_handler.add_smart_collection(
|
||||
SmartCollection(**cleaned_data)
|
||||
)
|
||||
|
||||
# Fetch the ROMs to update the database model
|
||||
smart_collection = created_smart_collection.update_properties(request.user.id)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.COLLECTIONS_READ])
|
||||
def get_collections(request: Request) -> list[CollectionSchema]:
|
||||
"""Get collections endpoint
|
||||
@@ -135,6 +173,24 @@ def get_virtual_collections(
|
||||
return [VirtualCollectionSchema.model_validate(vc) for vc in virtual_collections]
|
||||
|
||||
|
||||
@protected_route(router.get, "/smart", [Scope.COLLECTIONS_READ])
|
||||
def get_smart_collections(request: Request) -> list[SmartCollectionSchema]:
|
||||
"""Get smart collections endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
list[SmartCollectionSchema]: List of smart collections
|
||||
"""
|
||||
|
||||
smart_collections = db_collection_handler.get_smart_collections(request.user.id)
|
||||
|
||||
return SmartCollectionSchema.for_user(
|
||||
request.user.id, [s for s in smart_collections]
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/{id}", [Scope.COLLECTIONS_READ])
|
||||
def get_collection(request: Request, id: int) -> CollectionSchema:
|
||||
"""Get collections endpoint
|
||||
@@ -173,6 +229,25 @@ def get_virtual_collection(request: Request, id: str) -> VirtualCollectionSchema
|
||||
return VirtualCollectionSchema.model_validate(virtual_collection)
|
||||
|
||||
|
||||
@protected_route(router.get, "/smart/{id}", [Scope.COLLECTIONS_READ])
|
||||
def get_smart_collection(request: Request, id: int) -> SmartCollectionSchema:
|
||||
"""Get smart collection endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Smart collection id
|
||||
|
||||
Returns:
|
||||
SmartCollectionSchema: Smart collection
|
||||
"""
|
||||
|
||||
smart_collection = db_collection_handler.get_smart_collection(id)
|
||||
if not smart_collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
async def update_collection(
|
||||
request: Request,
|
||||
@@ -187,7 +262,7 @@ async def update_collection(
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
CollectionSchema: Updated collection
|
||||
"""
|
||||
|
||||
data = await request.form()
|
||||
@@ -215,44 +290,43 @@ async def update_collection(
|
||||
}
|
||||
|
||||
if remove_cover:
|
||||
cleaned_data.update(fs_resource_handler.remove_cover(collection))
|
||||
cleaned_data.update(await fs_resource_handler.remove_cover(collection))
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
else:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
(
|
||||
path_cover_l,
|
||||
path_cover_s,
|
||||
artwork_path,
|
||||
) = await fs_resource_handler.build_artwork_path(collection, file_ext)
|
||||
) = await fs_resource_handler.store_artwork(
|
||||
collection, artwork_content, file_ext
|
||||
)
|
||||
|
||||
cleaned_data["path_cover_l"] = path_cover_l
|
||||
cleaned_data["path_cover_s"] = path_cover_s
|
||||
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
file_location_small = Path(f"{artwork_path}/small.{file_ext}")
|
||||
file_location_large = Path(f"{artwork_path}/big.{file_ext}")
|
||||
with Image.open(artwork_content) as img:
|
||||
img.save(file_location_large)
|
||||
fs_resource_handler.resize_cover_to_small(
|
||||
img, save_path=file_location_small
|
||||
)
|
||||
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
cleaned_data.update(
|
||||
{
|
||||
"url_cover": "",
|
||||
"path_cover_s": path_cover_s,
|
||||
"path_cover_l": path_cover_l,
|
||||
}
|
||||
)
|
||||
else:
|
||||
if data.get("url_cover", "") != collection.url_cover or not (
|
||||
await fs_resource_handler.cover_exists(collection, CoverSize.BIG)
|
||||
if data.get(
|
||||
"url_cover", ""
|
||||
) != collection.url_cover or not fs_resource_handler.cover_exists(
|
||||
collection, CoverSize.BIG
|
||||
):
|
||||
cleaned_data.update(
|
||||
{"url_cover": data.get("url_cover", collection.url_cover)}
|
||||
)
|
||||
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
||||
entity=collection,
|
||||
overwrite=True,
|
||||
url_cover=data.get("url_cover", ""), # type: ignore
|
||||
)
|
||||
cleaned_data.update(
|
||||
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
|
||||
{
|
||||
"url_cover": data.get("url_cover", collection.url_cover),
|
||||
"path_cover_s": path_cover_s,
|
||||
"path_cover_l": path_cover_l,
|
||||
}
|
||||
)
|
||||
|
||||
updated_collection = db_collection_handler.update_collection(
|
||||
@@ -262,8 +336,59 @@ async def update_collection(
|
||||
return CollectionSchema.model_validate(updated_collection)
|
||||
|
||||
|
||||
@protected_route(router.put, "/smart/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
async def update_smart_collection(
|
||||
request: Request,
|
||||
id: int,
|
||||
is_public: bool | None = None,
|
||||
) -> SmartCollectionSchema:
|
||||
"""Update smart collection endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Smart collection id
|
||||
|
||||
Returns:
|
||||
SmartCollectionSchema: Updated smart collection
|
||||
"""
|
||||
|
||||
data = await request.form()
|
||||
|
||||
smart_collection = db_collection_handler.get_smart_collection(id)
|
||||
if not smart_collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
if smart_collection.user_id != request.user.id:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
# Parse filter criteria if provided
|
||||
filter_criteria = smart_collection.filter_criteria
|
||||
if "filter_criteria" in data:
|
||||
try:
|
||||
filter_criteria = json.loads(str(data["filter_criteria"]))
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError("Invalid JSON for filter_criteria field") from e
|
||||
|
||||
cleaned_data = {
|
||||
"name": str(data.get("name", smart_collection.name)),
|
||||
"description": str(data.get("description", smart_collection.description)),
|
||||
"filter_criteria": filter_criteria,
|
||||
"is_public": is_public if is_public is not None else smart_collection.is_public,
|
||||
"user_id": request.user.id,
|
||||
}
|
||||
|
||||
updated_smart_collection = db_collection_handler.update_smart_collection(
|
||||
id, cleaned_data
|
||||
)
|
||||
|
||||
# Fetch the ROMs to update the database model
|
||||
smart_collection = updated_smart_collection.update_properties(request.user.id)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
async def delete_collections(request: Request, id: int) -> MessageResponse:
|
||||
async def delete_collection(request: Request, id: int) -> None:
|
||||
"""Delete collections endpoint
|
||||
|
||||
Args:
|
||||
@@ -274,9 +399,6 @@ async def delete_collections(request: Request, id: int) -> MessageResponse:
|
||||
|
||||
Raises:
|
||||
HTTPException: Collection not found
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
|
||||
collection = db_collection_handler.get_collection(id)
|
||||
@@ -284,12 +406,33 @@ async def delete_collections(request: Request, id: int) -> MessageResponse:
|
||||
if not collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
log.info(f"Deleting {collection.name} from database")
|
||||
log.info(f"Deleting {hl(collection.name, color=BLUE)} from database")
|
||||
db_collection_handler.delete_collection(id)
|
||||
|
||||
try:
|
||||
rmtree(f"{RESOURCES_BASE_PATH}/{collection.fs_resources_path}")
|
||||
await fs_resource_handler.remove_directory(collection.fs_resources_path)
|
||||
except FileNotFoundError:
|
||||
log.error(f"Couldn't find resources to delete for {collection.name}")
|
||||
log.error(
|
||||
f"Couldn't find resources to delete for {hl(collection.name, color=BLUE)}"
|
||||
)
|
||||
|
||||
return {"msg": f"{collection.name} deleted successfully!"}
|
||||
|
||||
@protected_route(router.delete, "/smart/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
async def delete_smart_collection(request: Request, id: int) -> None:
|
||||
"""Delete smart collection endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Smart collection id
|
||||
"""
|
||||
|
||||
smart_collection = db_collection_handler.get_smart_collection(id)
|
||||
|
||||
if not smart_collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
if smart_collection.user_id != request.user.id:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
log.info(f"Deleting {hl(smart_collection.name, color=BLUE)} from database")
|
||||
db_collection_handler.delete_smart_collection(id)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from config.config_manager import config_manager as cm
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.config import ConfigResponse
|
||||
from exceptions.config_exceptions import (
|
||||
ConfigNotReadableException,
|
||||
@@ -45,7 +44,7 @@ def get_config() -> ConfigResponse:
|
||||
|
||||
|
||||
@protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE])
|
||||
async def add_platform_binding(request: Request) -> MessageResponse:
|
||||
async def add_platform_binding(request: Request) -> None:
|
||||
"""Add platform binding to the configuration"""
|
||||
|
||||
data = await request.json()
|
||||
@@ -60,11 +59,9 @@ async def add_platform_binding(request: Request) -> MessageResponse:
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {"msg": f"{fs_slug} binded to: {slug} successfully!"}
|
||||
|
||||
|
||||
@protected_route(router.delete, "/system/platforms/{fs_slug}", [Scope.PLATFORMS_WRITE])
|
||||
async def delete_platform_binding(request: Request, fs_slug: str) -> MessageResponse:
|
||||
async def delete_platform_binding(request: Request, fs_slug: str) -> None:
|
||||
"""Delete platform binding from the configuration"""
|
||||
|
||||
try:
|
||||
@@ -75,11 +72,9 @@ async def delete_platform_binding(request: Request, fs_slug: str) -> MessageResp
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {"msg": f"{fs_slug} bind removed successfully!"}
|
||||
|
||||
|
||||
@protected_route(router.post, "/system/versions", [Scope.PLATFORMS_WRITE])
|
||||
async def add_platform_version(request: Request) -> MessageResponse:
|
||||
async def add_platform_version(request: Request) -> None:
|
||||
"""Add platform version to the configuration"""
|
||||
|
||||
data = await request.json()
|
||||
@@ -94,11 +89,9 @@ async def add_platform_version(request: Request) -> MessageResponse:
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {"msg": f"Added {fs_slug} as version of: {slug} successfully!"}
|
||||
|
||||
|
||||
@protected_route(router.delete, "/system/versions/{fs_slug}", [Scope.PLATFORMS_WRITE])
|
||||
async def delete_platform_version(request: Request, fs_slug: str) -> MessageResponse:
|
||||
async def delete_platform_version(request: Request, fs_slug: str) -> None:
|
||||
"""Delete platform version from the configuration"""
|
||||
|
||||
try:
|
||||
@@ -109,11 +102,9 @@ async def delete_platform_version(request: Request, fs_slug: str) -> MessageResp
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {"msg": f"{fs_slug} version removed successfully!"}
|
||||
|
||||
|
||||
@protected_route(router.post, "/exclude", [Scope.PLATFORMS_WRITE])
|
||||
async def add_exclusion(request: Request) -> MessageResponse:
|
||||
async def add_exclusion(request: Request) -> None:
|
||||
"""Add platform exclusion to the configuration"""
|
||||
|
||||
data = await request.json()
|
||||
@@ -127,10 +118,6 @@ async def add_exclusion(request: Request) -> MessageResponse:
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {
|
||||
"msg": f"Exclusion {exclusion_value} added to {exclusion_type} successfully!"
|
||||
}
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.delete,
|
||||
@@ -139,7 +126,7 @@ async def add_exclusion(request: Request) -> MessageResponse:
|
||||
)
|
||||
async def delete_exclusion(
|
||||
request: Request, exclusion_type: str, exclusion_value: str
|
||||
) -> MessageResponse:
|
||||
) -> None:
|
||||
"""Delete platform binding from the configuration"""
|
||||
|
||||
try:
|
||||
@@ -149,7 +136,3 @@ async def delete_exclusion(
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
return {
|
||||
"msg": f"Exclusion {exclusion_value} removed from {exclusion_type} successfully!"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Sequence
|
||||
from collections.abc import Sequence
|
||||
|
||||
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH, FRONTEND_RESOURCES_PATH
|
||||
from decorators.auth import protected_route
|
||||
@@ -17,7 +17,7 @@ from fastapi import Request
|
||||
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
|
||||
from handler.metadata.base_hander import SWITCH_PRODUCT_ID_REGEX, SWITCH_TITLEDB_REGEX
|
||||
from models.rom import Rom
|
||||
from starlette.datastructures import URLPath
|
||||
from utils.router import APIRouter
|
||||
@@ -51,7 +51,8 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
continue
|
||||
|
||||
category_items = []
|
||||
for rom in db_rom_handler.get_roms(platform_id=p.id):
|
||||
roms = db_rom_handler.get_roms_scalar(platform_id=p.id)
|
||||
for rom in roms:
|
||||
category_item = WebrcadeFeedItemSchema(
|
||||
title=rom.name or "",
|
||||
description=rom.summary or "",
|
||||
@@ -102,7 +103,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
title="RomM Feed",
|
||||
longTitle="Custom RomM Feed",
|
||||
description="Custom feed from your RomM library",
|
||||
thumbnail="https://raw.githubusercontent.com/rommapp/romm/f2dd425d87ad8e21bf47f8258ae5dcf90f56fbc2/frontend/assets/isotipo.svg",
|
||||
thumbnail="https://raw.githubusercontent.com/rommapp/romm/release/.github/resources/isotipo.svg",
|
||||
background="https://raw.githubusercontent.com/rommapp/romm/release/.github/resources/screenshots/gallery.png",
|
||||
categories=categories,
|
||||
)
|
||||
@@ -134,17 +135,37 @@ async def tinfoil_index_feed(
|
||||
error="Nintendo Switch platform not found",
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms(platform_id=switch.id)
|
||||
|
||||
async def extract_titledb(
|
||||
roms: Sequence[Rom],
|
||||
) -> dict[str, TinfoilFeedTitleDBSchema]:
|
||||
titledb = {}
|
||||
for rom in roms:
|
||||
match = SWITCH_TITLEDB_REGEX.search(rom.fs_name)
|
||||
if match:
|
||||
tdb_match = SWITCH_TITLEDB_REGEX.search(rom.fs_name)
|
||||
pid_match = SWITCH_PRODUCT_ID_REGEX.search(rom.fs_name)
|
||||
if tdb_match:
|
||||
_search_term, index_entry = (
|
||||
await meta_igdb_handler._switch_titledb_format(match, rom.fs_name)
|
||||
await meta_igdb_handler._switch_titledb_format(
|
||||
tdb_match, rom.fs_name
|
||||
)
|
||||
)
|
||||
if index_entry:
|
||||
titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema(
|
||||
id=str(index_entry["nsuId"]),
|
||||
name=index_entry["name"],
|
||||
description=index_entry["description"],
|
||||
size=index_entry["size"],
|
||||
version=index_entry["version"] or 0,
|
||||
region=index_entry["region"] or "US",
|
||||
releaseDate=index_entry["releaseDate"] or 19700101,
|
||||
rating=index_entry["rating"] or 0,
|
||||
publisher=index_entry["publisher"] or "",
|
||||
rank=0,
|
||||
)
|
||||
elif pid_match:
|
||||
_search_term, index_entry = (
|
||||
await meta_igdb_handler._switch_productid_format(
|
||||
pid_match, rom.fs_name
|
||||
)
|
||||
)
|
||||
if index_entry:
|
||||
titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema(
|
||||
@@ -162,15 +183,23 @@ async def tinfoil_index_feed(
|
||||
|
||||
return titledb
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(platform_id=switch.id)
|
||||
|
||||
return TinfoilFeedSchema(
|
||||
files=[
|
||||
TinfoilFeedFileSchema(
|
||||
url=str(
|
||||
request.url_for("get_rom_content", id=rom.id, file_name=rom.fs_name)
|
||||
request.url_for(
|
||||
"get_romfile_content",
|
||||
id=rom_file.id,
|
||||
file_name=rom_file.file_name,
|
||||
)
|
||||
),
|
||||
size=rom.fs_size_bytes,
|
||||
size=rom_file.file_size_bytes,
|
||||
)
|
||||
for rom in roms
|
||||
for rom_file in rom.files
|
||||
if rom_file.file_extension in ["xci", "nsp", "nsz", "xcz", "nro"]
|
||||
],
|
||||
directories=[],
|
||||
success="RomM Switch Library",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH, LIBRARY_BASE_PATH
|
||||
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses import BulkOperationResponse
|
||||
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -8,6 +8,8 @@ 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
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -18,7 +20,7 @@ router = APIRouter(
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.FIRMWARE_WRITE])
|
||||
def add_firmware(
|
||||
async def add_firmware(
|
||||
request: Request,
|
||||
platform_id: int,
|
||||
files: list[UploadFile] = File(...), # noqa: B008
|
||||
@@ -43,23 +45,25 @@ def add_firmware(
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
log.info(f"Uploading firmware to {db_platform.fs_slug}")
|
||||
|
||||
uploaded_firmware = []
|
||||
firmware_path = fs_firmware_handler.build_upload_file_path(db_platform.fs_slug)
|
||||
firmware_path = fs_firmware_handler.get_firmware_fs_structure(db_platform.fs_slug)
|
||||
|
||||
for file in files:
|
||||
if not file.filename:
|
||||
log.warning("Empty filename, skipping")
|
||||
continue
|
||||
|
||||
fs_firmware_handler.write_file(file=file, path=firmware_path)
|
||||
log.info(
|
||||
f"Uploading firmware {hl(file.filename)} to {hl(db_platform.custom_name or db_platform.name, color=BLUE)}"
|
||||
)
|
||||
|
||||
await fs_firmware_handler.write_file(file=file, path=firmware_path)
|
||||
|
||||
db_firmware = db_firmware_handler.get_firmware_by_filename(
|
||||
platform_id=db_platform.id, file_name=file.filename
|
||||
)
|
||||
# Scan or update firmware
|
||||
scanned_firmware = scan_firmware(
|
||||
scanned_firmware = await scan_firmware(
|
||||
platform=db_platform,
|
||||
file_name=file.filename,
|
||||
firmware=db_firmware,
|
||||
@@ -150,7 +154,7 @@ def head_firmware_content(request: Request, id: int, file_name: str):
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(
|
||||
path=firmware_path,
|
||||
@@ -188,7 +192,7 @@ def get_firmware_content(
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(path=firmware_path, filename=firmware.file_name)
|
||||
|
||||
@@ -196,7 +200,7 @@ def get_firmware_content(
|
||||
@protected_route(router.post, "/delete", [Scope.FIRMWARE_WRITE])
|
||||
async def delete_firmware(
|
||||
request: Request,
|
||||
) -> MessageResponse:
|
||||
) -> BulkOperationResponse:
|
||||
"""Delete firmware endpoint
|
||||
|
||||
Args:
|
||||
@@ -207,34 +211,47 @@ async def delete_firmware(
|
||||
delete_from_fs (bool, optional): Flag to delete rom from filesystem. Defaults to False.
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
BulkOperationResponse: Bulk operation response with details
|
||||
"""
|
||||
|
||||
data: dict = await request.json()
|
||||
firmare_ids: list = data["firmware"]
|
||||
firmware_ids: list = data["firmware"]
|
||||
delete_from_fs: list = data["delete_from_fs"]
|
||||
|
||||
for id in firmare_ids:
|
||||
successful_items = 0
|
||||
failed_items = 0
|
||||
errors = []
|
||||
|
||||
for id in firmware_ids:
|
||||
firmware = db_firmware_handler.get_firmware(id)
|
||||
if not firmware:
|
||||
error = f"Firmware with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
failed_items += 1
|
||||
errors.append(f"Firmware with ID {id} not found")
|
||||
continue
|
||||
|
||||
log.info(f"Deleting {firmware.file_name} from database")
|
||||
db_firmware_handler.delete_firmware(id)
|
||||
try:
|
||||
log.info(f"Deleting {hl(firmware.file_name)} from database")
|
||||
db_firmware_handler.delete_firmware(id)
|
||||
|
||||
if id in delete_from_fs:
|
||||
log.info(f"Deleting {firmware.file_name} from filesystem")
|
||||
try:
|
||||
fs_firmware_handler.remove_file(
|
||||
file_name=firmware.file_name, file_path=firmware.file_path
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
error = f"Firmware file {firmware.file_name} not found for platform {firmware.platform_slug}"
|
||||
log.error(error)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=error
|
||||
) from exc
|
||||
if id in delete_from_fs:
|
||||
log.info(f"Deleting {hl(firmware.file_name)} from filesystem")
|
||||
try:
|
||||
file_path = f"{firmware.file_path}/{firmware.file_name}"
|
||||
await fs_firmware_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"Firmware file {hl(firmware.file_name)} not found for platform {hl(firmware.platform_slug)}"
|
||||
log.error(error)
|
||||
errors.append(error)
|
||||
failed_items += 1
|
||||
continue
|
||||
|
||||
return {"msg": f"{len(firmare_ids)} firmware files deleted successfully!"}
|
||||
successful_items += 1
|
||||
except Exception as e:
|
||||
failed_items += 1
|
||||
errors.append(f"Failed to delete firmware {id}: {str(e)}")
|
||||
|
||||
return {
|
||||
"successful_items": successful_items,
|
||||
"failed_items": failed_items,
|
||||
"errors": errors,
|
||||
}
|
||||
|
||||
@@ -1,23 +1,16 @@
|
||||
from fastapi import UploadFile
|
||||
from fastapi.param_functions import Form
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class UserForm:
|
||||
def __init__(
|
||||
self,
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
email: str | None = None,
|
||||
role: str | None = None,
|
||||
enabled: bool | None = None,
|
||||
avatar: UploadFile | None = None,
|
||||
):
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.email = email
|
||||
self.role = role
|
||||
self.enabled = enabled
|
||||
self.avatar = avatar
|
||||
class UserForm(BaseModel):
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
email: str | None = None
|
||||
role: str | None = None
|
||||
enabled: bool | None = None
|
||||
ra_username: str | None = None
|
||||
avatar: UploadFile | None = None
|
||||
|
||||
|
||||
class OAuth2RequestForm:
|
||||
|
||||
@@ -2,21 +2,21 @@ 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,
|
||||
HASHEOUS_API_ENABLED,
|
||||
LAUNCHBOX_API_ENABLED,
|
||||
OIDC_ENABLED,
|
||||
OIDC_PROVIDER,
|
||||
RESCAN_ON_FILESYSTEM_CHANGE_DELAY,
|
||||
SCHEDULED_RESCAN_CRON,
|
||||
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
|
||||
PLAYMATCH_API_ENABLED,
|
||||
TGDB_API_ENABLED,
|
||||
UPLOAD_TIMEOUT,
|
||||
YOUTUBE_BASE_URL,
|
||||
)
|
||||
from endpoints.responses.heartbeat import HeartbeatResponse
|
||||
from handler.database import db_user_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from handler.metadata.igdb_handler import IGDB_API_ENABLED
|
||||
from handler.metadata.moby_handler import MOBY_API_ENABLED
|
||||
from handler.metadata.ra_handler import RA_API_ENABLED
|
||||
from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED
|
||||
from handler.metadata.ss_handler import SS_API_ENABLED
|
||||
from utils import get_version
|
||||
@@ -28,7 +28,7 @@ router = APIRouter(
|
||||
|
||||
|
||||
@router.get("/heartbeat")
|
||||
def heartbeat() -> HeartbeatResponse:
|
||||
async def heartbeat() -> HeartbeatResponse:
|
||||
"""Endpoint to set the CSRF token in cache and return all the basic RomM config
|
||||
|
||||
Returns:
|
||||
@@ -42,34 +42,24 @@ def heartbeat() -> HeartbeatResponse:
|
||||
},
|
||||
"METADATA_SOURCES": {
|
||||
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED
|
||||
or SS_API_ENABLED
|
||||
or MOBY_API_ENABLED
|
||||
or SS_API_ENABLED,
|
||||
or RA_API_ENABLED
|
||||
or LAUNCHBOX_API_ENABLED
|
||||
or HASHEOUS_API_ENABLED
|
||||
or TGDB_API_ENABLED,
|
||||
"IGDB_API_ENABLED": IGDB_API_ENABLED,
|
||||
"MOBY_API_ENABLED": MOBY_API_ENABLED,
|
||||
"SS_API_ENABLED": SS_API_ENABLED,
|
||||
"STEAMGRIDDB_ENABLED": STEAMGRIDDB_API_ENABLED,
|
||||
"MOBY_API_ENABLED": MOBY_API_ENABLED,
|
||||
"STEAMGRIDDB_API_ENABLED": STEAMGRIDDB_API_ENABLED,
|
||||
"RA_API_ENABLED": RA_API_ENABLED,
|
||||
"LAUNCHBOX_API_ENABLED": LAUNCHBOX_API_ENABLED,
|
||||
"HASHEOUS_API_ENABLED": HASHEOUS_API_ENABLED,
|
||||
"PLAYMATCH_API_ENABLED": PLAYMATCH_API_ENABLED,
|
||||
"TGDB_API_ENABLED": TGDB_API_ENABLED,
|
||||
},
|
||||
"FILESYSTEM": {
|
||||
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
|
||||
},
|
||||
"WATCHER": {
|
||||
"ENABLED": ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
|
||||
"TITLE": "Rescan on filesystem change",
|
||||
"MESSAGE": f"Runs a scan when a change is detected in the library path, with a {RESCAN_ON_FILESYSTEM_CHANGE_DELAY} minute delay",
|
||||
},
|
||||
"SCHEDULER": {
|
||||
"RESCAN": {
|
||||
"ENABLED": ENABLE_SCHEDULED_RESCAN,
|
||||
"CRON": SCHEDULED_RESCAN_CRON,
|
||||
"TITLE": "Scheduled rescan",
|
||||
"MESSAGE": "Rescans the entire library",
|
||||
},
|
||||
"SWITCH_TITLEDB": {
|
||||
"ENABLED": ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB, # noqa
|
||||
"CRON": SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
|
||||
"TITLE": "Scheduled Switch TitleDB update",
|
||||
"MESSAGE": "Updates the Nintendo Switch TitleDB file",
|
||||
},
|
||||
"FS_PLATFORMS": await fs_platform_handler.get_platforms(),
|
||||
},
|
||||
"EMULATION": {
|
||||
"DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS,
|
||||
@@ -78,6 +68,7 @@ def heartbeat() -> HeartbeatResponse:
|
||||
"FRONTEND": {
|
||||
"UPLOAD_TIMEOUT": UPLOAD_TIMEOUT,
|
||||
"DISABLE_USERPASS_LOGIN": DISABLE_USERPASS_LOGIN,
|
||||
"YOUTUBE_BASE_URL": YOUTUBE_BASE_URL,
|
||||
},
|
||||
"OIDC": {
|
||||
"ENABLED": OIDC_ENABLED,
|
||||
|
||||
@@ -1,17 +1,31 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.platform import PlatformSchema
|
||||
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
||||
from fastapi import Request
|
||||
from fastapi import Body
|
||||
from fastapi import Path as PathVar
|
||||
from fastapi import Request, status
|
||||
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
|
||||
from handler.metadata import (
|
||||
meta_hasheous_handler,
|
||||
meta_igdb_handler,
|
||||
meta_launchbox_handler,
|
||||
meta_moby_handler,
|
||||
meta_ra_handler,
|
||||
meta_ss_handler,
|
||||
meta_tgdb_handler,
|
||||
)
|
||||
from handler.metadata.base_hander import UniversalPlatformSlug as UPS
|
||||
from handler.scan_handler import scan_platform
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.platform import DEFAULT_COVER_ASPECT_RATIO, Platform
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -20,23 +34,23 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.PLATFORMS_WRITE])
|
||||
async def add_platforms(request: Request) -> PlatformSchema:
|
||||
"""Create platform endpoint
|
||||
@protected_route(
|
||||
router.post,
|
||||
"",
|
||||
[Scope.PLATFORMS_WRITE],
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def add_platform(
|
||||
request: Request,
|
||||
fs_slug: Annotated[str, Body(description="Platform slug.", embed=True)],
|
||||
) -> PlatformSchema:
|
||||
"""Create a platform."""
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
PlatformSchema: Just created platform
|
||||
"""
|
||||
|
||||
data = await request.json()
|
||||
fs_slug = data["fs_slug"]
|
||||
try:
|
||||
fs_platform_handler.add_platforms(fs_slug=fs_slug)
|
||||
await fs_platform_handler.add_platform(fs_slug=fs_slug)
|
||||
except PlatformAlreadyExistsException:
|
||||
log.info(f"Detected platform: {fs_slug}")
|
||||
log.info(f"Detected platform: {hl(fs_slug)}")
|
||||
|
||||
scanned_platform = await scan_platform(fs_slug, [fs_slug])
|
||||
return PlatformSchema.model_validate(
|
||||
db_platform_handler.add_platform(scanned_platform)
|
||||
@@ -45,15 +59,7 @@ async def add_platforms(request: Request) -> PlatformSchema:
|
||||
|
||||
@protected_route(router.get, "", [Scope.PLATFORMS_READ])
|
||||
def get_platforms(request: Request) -> list[PlatformSchema]:
|
||||
"""Get platforms endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int, optional): Platform id. Defaults to None.
|
||||
|
||||
Returns:
|
||||
list[PlatformSchema]: List of platforms
|
||||
"""
|
||||
"""Retrieve platforms."""
|
||||
|
||||
return [
|
||||
PlatformSchema.model_validate(p) for p in db_platform_handler.get_platforms()
|
||||
@@ -62,108 +68,148 @@ def get_platforms(request: Request) -> list[PlatformSchema]:
|
||||
|
||||
@protected_route(router.get, "/supported", [Scope.PLATFORMS_READ])
|
||||
def get_supported_platforms(request: Request) -> list[PlatformSchema]:
|
||||
"""Get list of supported platforms endpoint
|
||||
"""Retrieve the list of supported platforms."""
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
|
||||
Returns:
|
||||
list[PlatformSchema]: List of supported platforms
|
||||
"""
|
||||
|
||||
supported_platforms = []
|
||||
db_platforms = db_platform_handler.get_platforms()
|
||||
db_platforms_map = {p.name: p.id for p in db_platforms}
|
||||
db_platforms_map = {p.slug: p for p in db_platforms}
|
||||
|
||||
for platform in IGDB_PLATFORM_LIST:
|
||||
now = datetime.now(timezone.utc)
|
||||
sup_plat = {
|
||||
now = datetime.now(timezone.utc)
|
||||
supported_platforms = []
|
||||
|
||||
for upslug in UPS:
|
||||
slug = upslug.value
|
||||
|
||||
db_platform = db_platforms_map.get(slug, None)
|
||||
if db_platform:
|
||||
supported_platforms.append(
|
||||
PlatformSchema.model_validate(db_platform).model_dump()
|
||||
)
|
||||
continue
|
||||
|
||||
igdb_platform = meta_igdb_handler.get_platform(slug)
|
||||
moby_platform = meta_moby_handler.get_platform(slug)
|
||||
ss_platform = meta_ss_handler.get_platform(slug)
|
||||
ra_platform = meta_ra_handler.get_platform(slug)
|
||||
launchbox_platform = meta_launchbox_handler.get_platform(slug)
|
||||
hasheous_platform = meta_hasheous_handler.get_platform(slug)
|
||||
tgdb_platform = meta_tgdb_handler.get_platform(slug)
|
||||
|
||||
platform_attrs = {
|
||||
"id": -1,
|
||||
"name": platform["name"],
|
||||
"fs_slug": platform["slug"],
|
||||
"slug": platform["slug"],
|
||||
"logo_path": "",
|
||||
"name": slug.replace("-", " ").title(),
|
||||
"fs_slug": slug,
|
||||
"slug": slug,
|
||||
"roms": [],
|
||||
"rom_count": 0,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
"fs_size_bytes": 0,
|
||||
"missing_from_fs": False,
|
||||
"aspect_ratio": DEFAULT_COVER_ASPECT_RATIO,
|
||||
}
|
||||
|
||||
if platform["name"] in db_platforms_map:
|
||||
sup_plat["id"] = db_platforms_map[platform["name"]]
|
||||
platform_attrs.update(
|
||||
{
|
||||
**hasheous_platform,
|
||||
**tgdb_platform,
|
||||
**launchbox_platform,
|
||||
**ra_platform,
|
||||
**moby_platform,
|
||||
**ss_platform,
|
||||
**igdb_platform,
|
||||
"igdb_id": igdb_platform.get("igdb_id")
|
||||
or hasheous_platform.get("igdb_id")
|
||||
or None,
|
||||
"ra_id": ra_platform.get("ra_id")
|
||||
or hasheous_platform.get("ra_id")
|
||||
or None,
|
||||
"tgdb_id": moby_platform.get("tgdb_id")
|
||||
or hasheous_platform.get("tgdb_id")
|
||||
or None,
|
||||
"name": igdb_platform.get("name")
|
||||
or ss_platform.get("name")
|
||||
or moby_platform.get("name")
|
||||
or ra_platform.get("name")
|
||||
or launchbox_platform.get("name")
|
||||
or hasheous_platform.get("name")
|
||||
or tgdb_platform.get("name")
|
||||
or slug.replace("-", " ").title(),
|
||||
"url_logo": igdb_platform.get("url_logo")
|
||||
or tgdb_platform.get("url_logo")
|
||||
or "",
|
||||
}
|
||||
)
|
||||
|
||||
supported_platforms.append(PlatformSchema.model_validate(sup_plat).model_dump())
|
||||
platform = Platform(**platform_attrs)
|
||||
supported_platforms.append(PlatformSchema.model_validate(platform).model_dump())
|
||||
|
||||
return supported_platforms
|
||||
|
||||
|
||||
@protected_route(router.get, "/{id}", [Scope.PLATFORMS_READ])
|
||||
def get_platform(request: Request, id: int) -> PlatformSchema:
|
||||
"""Get platforms endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int, optional): Platform id. Defaults to None.
|
||||
|
||||
Returns:
|
||||
PlatformSchema: Platform
|
||||
"""
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/{id}",
|
||||
[Scope.PLATFORMS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
def get_platform(
|
||||
request: Request,
|
||||
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
||||
) -> PlatformSchema:
|
||||
"""Retrieve a platform by ID."""
|
||||
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
|
||||
if not platform:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
|
||||
return PlatformSchema.model_validate(platform)
|
||||
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.PLATFORMS_WRITE])
|
||||
async def update_platform(request: Request, id: int) -> PlatformSchema:
|
||||
"""Update platform endpoint
|
||||
@protected_route(
|
||||
router.put,
|
||||
"/{id}",
|
||||
[Scope.PLATFORMS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def update_platform(
|
||||
request: Request,
|
||||
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
||||
aspect_ratio: Annotated[str | None, Body(description="Cover aspect ratio.")] = None,
|
||||
custom_name: Annotated[
|
||||
str | None, Body(description="Custom platform name.")
|
||||
] = None,
|
||||
) -> PlatformSchema:
|
||||
"""Update a platform."""
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
id (int): Platform id
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
data = await request.json()
|
||||
platform_db = db_platform_handler.get_platform(id)
|
||||
|
||||
if not platform_db:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
|
||||
platform_db.aspect_ratio = data.get("aspect_ratio", platform_db.aspect_ratio)
|
||||
platform_db.custom_name = data.get("custom_name", platform_db.custom_name)
|
||||
if aspect_ratio is not None:
|
||||
platform_db.aspect_ratio = aspect_ratio
|
||||
if custom_name is not None:
|
||||
platform_db.custom_name = custom_name
|
||||
platform_db = db_platform_handler.add_platform(platform_db)
|
||||
|
||||
return PlatformSchema.model_validate(platform_db)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/{id}", [Scope.PLATFORMS_WRITE])
|
||||
async def delete_platforms(request: Request, id: int) -> MessageResponse:
|
||||
"""Delete platforms endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
{
|
||||
"platforms": List of rom's ids to delete
|
||||
}
|
||||
|
||||
Raises:
|
||||
HTTPException: Platform not found
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
@protected_route(
|
||||
router.delete,
|
||||
"/{id}",
|
||||
[Scope.PLATFORMS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def delete_platform(
|
||||
request: Request,
|
||||
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
||||
) -> None:
|
||||
"""Delete a platform."""
|
||||
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
|
||||
if not platform:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
|
||||
log.info(f"Deleting {platform.name} [{platform.fs_slug}] from database")
|
||||
log.info(
|
||||
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
|
||||
)
|
||||
db_platform_handler.delete_platform(id)
|
||||
|
||||
return {"msg": f"{platform.name} - [{platform.fs_slug}] deleted successfully!"}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from config import ASSETS_BASE_PATH
|
||||
from decorators.auth import protected_route
|
||||
from fastapi import Request
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
from handler.auth.constants import Scope
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -13,8 +13,16 @@ router = APIRouter(
|
||||
|
||||
@protected_route(router.head, "/assets/{path:path}", [Scope.ASSETS_READ])
|
||||
def head_raw_asset(request: Request, path: str):
|
||||
asset_path = f"{ASSETS_BASE_PATH}/{path}"
|
||||
return FileResponse(path=asset_path, filename=path.split("/")[-1])
|
||||
try:
|
||||
resolved_path = fs_asset_handler.validate_path(path)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail="Asset not found") from exc
|
||||
|
||||
# Check if file exists and is a file (not directory)
|
||||
if not resolved_path.exists() or not resolved_path.is_file():
|
||||
return HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
return FileResponse(path=str(resolved_path), filename=resolved_path.name)
|
||||
|
||||
|
||||
@protected_route(router.get, "/assets/{path:path}", [Scope.ASSETS_READ])
|
||||
@@ -23,10 +31,24 @@ def get_raw_asset(request: Request, path: str):
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
path (str): Relative path to the asset file
|
||||
|
||||
Returns:
|
||||
FileResponse: Returns a single asset file
|
||||
"""
|
||||
|
||||
asset_path = f"{ASSETS_BASE_PATH}/{path}"
|
||||
return FileResponse(path=asset_path, filename=path.split("/")[-1])
|
||||
Raises:
|
||||
HTTPException: 404 if asset not found or access denied
|
||||
"""
|
||||
try:
|
||||
resolved_path = fs_asset_handler.validate_path(path)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail="Asset not found") from exc
|
||||
|
||||
# Check if file exists and is a file (not directory)
|
||||
if not resolved_path.exists() or not resolved_path.is_file():
|
||||
return HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
if not resolved_path:
|
||||
raise HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
return FileResponse(path=str(resolved_path), filename=resolved_path.name)
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
from typing import TypedDict
|
||||
|
||||
from rq_scheduler.scheduler import JobStatus
|
||||
|
||||
class MessageResponse(TypedDict):
|
||||
msg: str
|
||||
|
||||
class TaskExecutionResponse(TypedDict):
|
||||
task_name: str
|
||||
task_id: str
|
||||
status: JobStatus | None
|
||||
queued_at: str
|
||||
|
||||
|
||||
class TaskStatusResponse(TaskExecutionResponse):
|
||||
started_at: str | None
|
||||
ended_at: str | None
|
||||
|
||||
|
||||
class BulkOperationResponse(TypedDict):
|
||||
successful_items: int
|
||||
failed_items: int
|
||||
errors: list[str]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from datetime import datetime
|
||||
from typing import TypedDict
|
||||
|
||||
from .base import BaseModel
|
||||
|
||||
@@ -16,6 +15,9 @@ class BaseAsset(BaseModel):
|
||||
file_size_bytes: int
|
||||
full_path: str
|
||||
download_path: str
|
||||
|
||||
missing_from_fs: bool
|
||||
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -27,27 +29,11 @@ class ScreenshotSchema(BaseAsset):
|
||||
pass
|
||||
|
||||
|
||||
class UploadedScreenshotsResponse(TypedDict):
|
||||
uploaded: int
|
||||
screenshots: list[ScreenshotSchema]
|
||||
merged_screenshots: list[str]
|
||||
|
||||
|
||||
class SaveSchema(BaseAsset):
|
||||
emulator: str | None
|
||||
screenshot: ScreenshotSchema | None
|
||||
|
||||
|
||||
class UploadedSavesResponse(TypedDict):
|
||||
uploaded: int
|
||||
saves: list[SaveSchema]
|
||||
|
||||
|
||||
class StateSchema(BaseAsset):
|
||||
emulator: str | None
|
||||
screenshot: ScreenshotSchema | None
|
||||
|
||||
|
||||
class UploadedStatesResponse(TypedDict):
|
||||
uploaded: int
|
||||
states: list[StateSchema]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from models.collection import Collection
|
||||
from models.collection import Collection, SmartCollection
|
||||
|
||||
from .base import BaseModel
|
||||
|
||||
@@ -14,21 +15,19 @@ class BaseCollectionSchema(BaseModel):
|
||||
path_cover_large: str | None
|
||||
path_covers_small: list[str]
|
||||
path_covers_large: list[str]
|
||||
is_public: bool = False
|
||||
is_favorite: bool = False
|
||||
is_virtual: bool = False
|
||||
is_smart: bool = False
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class CollectionSchema(BaseCollectionSchema):
|
||||
id: int
|
||||
url_cover: str | None
|
||||
rom_ids: set[int]
|
||||
rom_count: int
|
||||
user_id: int
|
||||
user__username: str
|
||||
is_public: bool
|
||||
is_favorite: bool
|
||||
is_virtual: bool = False
|
||||
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@@ -47,12 +46,32 @@ class CollectionSchema(BaseCollectionSchema):
|
||||
class VirtualCollectionSchema(BaseCollectionSchema):
|
||||
id: str
|
||||
type: str
|
||||
is_public: bool = True
|
||||
is_favorite: bool = False
|
||||
is_virtual: bool = True
|
||||
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class SmartCollectionSchema(BaseCollectionSchema):
|
||||
id: int
|
||||
name: str
|
||||
description: str = ""
|
||||
filter_criteria: dict[str, Any]
|
||||
filter_summary: str
|
||||
user_id: int
|
||||
user__username: str
|
||||
is_smart: bool = True
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@classmethod
|
||||
def for_user(
|
||||
cls, user_id: int, smart_collections: list["SmartCollection"]
|
||||
) -> list["SmartCollectionSchema"]:
|
||||
"""Filter smart collections visible to user and create schemas."""
|
||||
return [
|
||||
cls.model_validate(c)
|
||||
for c in smart_collections
|
||||
if c.user_id == user_id or c.is_public
|
||||
]
|
||||
|
||||
@@ -1,59 +1,62 @@
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
from handler.metadata.base_hander import UniversalPlatformSlug as UPS
|
||||
|
||||
WEBRCADE_SUPPORTED_PLATFORM_SLUGS = frozenset(
|
||||
(
|
||||
"3do",
|
||||
"arcade",
|
||||
"atari2600",
|
||||
"atari5200",
|
||||
"atari7800",
|
||||
"colecovision",
|
||||
"gamegear",
|
||||
"gb",
|
||||
"gba",
|
||||
"gbc",
|
||||
"genesis-slash-megadrive",
|
||||
"lynx",
|
||||
"n64",
|
||||
"neo-geo-cd",
|
||||
"neo-geo-pocket",
|
||||
"neo-geo-pocket-color",
|
||||
"neogeoaes",
|
||||
"neogeomvs",
|
||||
"nes",
|
||||
"pc-fx",
|
||||
"ps",
|
||||
"segacd",
|
||||
"sg1000",
|
||||
"sms",
|
||||
"snes",
|
||||
"supergrafx",
|
||||
"turbografx-16-slash-pc-engine-cd",
|
||||
"turbografx16--1",
|
||||
"virtualboy",
|
||||
"wonderswan",
|
||||
"wonderswan-color",
|
||||
UPS._3DO,
|
||||
UPS.ARCADE,
|
||||
UPS.ATARI2600,
|
||||
UPS.ATARI5200,
|
||||
UPS.ATARI7800,
|
||||
UPS.C64,
|
||||
UPS.COLECOVISION,
|
||||
UPS.DOS,
|
||||
UPS.GAMEGEAR,
|
||||
UPS.GB,
|
||||
UPS.GBA,
|
||||
UPS.GBC,
|
||||
UPS.GENESIS,
|
||||
UPS.LYNX,
|
||||
UPS.N64,
|
||||
UPS.NEO_GEO_CD,
|
||||
UPS.NEO_GEO_POCKET,
|
||||
UPS.NEO_GEO_POCKET_COLOR,
|
||||
UPS.NEOGEOAES,
|
||||
UPS.NEOGEOMVS,
|
||||
UPS.NES,
|
||||
UPS.PC_FX,
|
||||
UPS.PSX,
|
||||
UPS.SEGACD,
|
||||
UPS.SG1000,
|
||||
UPS.SMS,
|
||||
UPS.SNES,
|
||||
UPS.SUPERGRAFX,
|
||||
UPS.TURBOGRAFX_CD,
|
||||
UPS.TG16,
|
||||
UPS.VIRTUALBOY,
|
||||
UPS.WONDERSWAN,
|
||||
UPS.WONDERSWAN_COLOR,
|
||||
)
|
||||
)
|
||||
|
||||
WEBRCADE_SLUG_TO_TYPE_MAP = {
|
||||
"atari2600": "2600",
|
||||
"atari5200": "5200",
|
||||
"atari7800": "7800",
|
||||
"lynx": "lnx",
|
||||
"turbografx16--1": "pce",
|
||||
"turbografx-16-slash-pc-engine-cd": "pce",
|
||||
"supergrafx": "sgx",
|
||||
"pc-fx": "pcfx",
|
||||
"virtualboy": "vb",
|
||||
"genesis-slash-megadrive": "genesis",
|
||||
"gamegear": "gg",
|
||||
"neogeoaes": "neogeo",
|
||||
"neogeomvs": "neogeo",
|
||||
"neo-geo-cd": "neogeocd",
|
||||
"neo-geo-pocket": "ngp",
|
||||
"neo-geo-pocket-color": "ngc",
|
||||
"ps": "psx",
|
||||
UPS.ATARI2600: "2600",
|
||||
UPS.ATARI5200: "5200",
|
||||
UPS.ATARI7800: "7800",
|
||||
UPS.C64: "commodore-c64",
|
||||
UPS.LYNX: "lnx",
|
||||
UPS.TG16: "pce",
|
||||
UPS.TURBOGRAFX_CD: "pce",
|
||||
UPS.SUPERGRAFX: "sgx",
|
||||
UPS.PC_FX: "pcfx",
|
||||
UPS.VIRTUALBOY: "vb",
|
||||
UPS.GAMEGEAR: "gg",
|
||||
UPS.NEOGEOAES: "neogeo",
|
||||
UPS.NEOGEOMVS: "neogeo",
|
||||
UPS.NEO_GEO_CD: "neogeocd",
|
||||
UPS.NEO_GEO_POCKET: "ngp",
|
||||
UPS.NEO_GEO_POCKET_COLOR: "ngc",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ class FirmwareSchema(BaseModel):
|
||||
md5_hash: str
|
||||
sha1_hash: str
|
||||
|
||||
missing_from_fs: bool
|
||||
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
@@ -6,27 +6,17 @@ class SystemDict(TypedDict):
|
||||
SHOW_SETUP_WIZARD: bool
|
||||
|
||||
|
||||
class WatcherDict(TypedDict):
|
||||
ENABLED: bool
|
||||
TITLE: str
|
||||
MESSAGE: str
|
||||
|
||||
|
||||
class TaskDict(WatcherDict):
|
||||
CRON: str
|
||||
|
||||
|
||||
class SchedulerDict(TypedDict):
|
||||
RESCAN: TaskDict
|
||||
SWITCH_TITLEDB: TaskDict
|
||||
|
||||
|
||||
class MetadataSourcesDict(TypedDict):
|
||||
ANY_SOURCE_ENABLED: bool
|
||||
IGDB_API_ENABLED: bool
|
||||
MOBY_API_ENABLED: bool
|
||||
SS_API_ENABLED: bool
|
||||
STEAMGRIDDB_ENABLED: bool
|
||||
STEAMGRIDDB_API_ENABLED: bool
|
||||
RA_API_ENABLED: bool
|
||||
LAUNCHBOX_API_ENABLED: bool
|
||||
PLAYMATCH_API_ENABLED: bool
|
||||
HASHEOUS_API_ENABLED: bool
|
||||
TGDB_API_ENABLED: bool
|
||||
|
||||
|
||||
class FilesystemDict(TypedDict):
|
||||
@@ -41,6 +31,7 @@ class EmulationDict(TypedDict):
|
||||
class FrontendDict(TypedDict):
|
||||
UPLOAD_TIMEOUT: int
|
||||
DISABLE_USERPASS_LOGIN: bool
|
||||
YOUTUBE_BASE_URL: str
|
||||
|
||||
|
||||
class OIDCDict(TypedDict):
|
||||
@@ -50,8 +41,6 @@ class OIDCDict(TypedDict):
|
||||
|
||||
class HeartbeatResponse(TypedDict):
|
||||
SYSTEM: SystemDict
|
||||
WATCHER: WatcherDict
|
||||
SCHEDULER: SchedulerDict
|
||||
METADATA_SOURCES: MetadataSourcesDict
|
||||
FILESYSTEM: FilesystemDict
|
||||
EMULATION: EmulationDict
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
from datetime import datetime
|
||||
from typing import NotRequired, TypedDict, get_type_hints
|
||||
|
||||
from handler.metadata.ra_handler import RAUserProgression
|
||||
from models.user import Role
|
||||
|
||||
from .base import BaseModel
|
||||
|
||||
RAProgression = TypedDict( # type: ignore[misc]
|
||||
"RAProgression",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(RAUserProgression).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
|
||||
|
||||
class UserSchema(BaseModel):
|
||||
id: int
|
||||
@@ -15,9 +23,15 @@ class UserSchema(BaseModel):
|
||||
avatar_path: str
|
||||
last_login: datetime | None
|
||||
last_active: datetime | None
|
||||
ra_username: str | None = None
|
||||
ra_progression: RAProgression | None = None
|
||||
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class InviteLinkSchema(BaseModel):
|
||||
token: str
|
||||
|
||||
@@ -13,22 +13,31 @@ class PlatformSchema(BaseModel):
|
||||
fs_slug: str
|
||||
rom_count: int
|
||||
name: str
|
||||
igdb_slug: str | None
|
||||
moby_slug: str | None
|
||||
custom_name: str | None = None
|
||||
igdb_id: int | None = None
|
||||
sgdb_id: int | None = None
|
||||
moby_id: int | None = None
|
||||
launchbox_id: int | None = None
|
||||
ss_id: int | None = None
|
||||
ra_id: int | None = None
|
||||
hasheous_id: int | None = None
|
||||
tgdb_id: int | None = None
|
||||
category: str | None = None
|
||||
generation: int | None = None
|
||||
family_name: str | None = None
|
||||
family_slug: str | None = None
|
||||
url: str | None = None
|
||||
url_logo: str | None = None
|
||||
logo_path: str | None = None
|
||||
firmware: list[FirmwareSchema] = Field(default_factory=list)
|
||||
aspect_ratio: str = DEFAULT_COVER_ASPECT_RATIO
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
fs_size_bytes: int
|
||||
is_unidentified: bool
|
||||
is_identified: bool
|
||||
missing_from_fs: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@@ -5,11 +5,14 @@ from datetime import datetime, timezone
|
||||
from typing import NotRequired, TypedDict, get_type_hints
|
||||
|
||||
from endpoints.responses.assets import SaveSchema, ScreenshotSchema, StateSchema
|
||||
from endpoints.responses.collection import CollectionSchema
|
||||
from fastapi import Request
|
||||
from handler.metadata.hasheous_handler import HasheousMetadata
|
||||
from handler.metadata.igdb_handler import IGDBMetadata
|
||||
from handler.metadata.launchbox_handler import LaunchboxMetadata
|
||||
from handler.metadata.moby_handler import MobyMetadata
|
||||
from handler.metadata.ra_handler import RAMetadata
|
||||
from handler.metadata.ss_handler import SSMetadata
|
||||
from models.collection import Collection
|
||||
from models.rom import Rom, RomFileCategory, RomUserStatus
|
||||
from pydantic import computed_field, field_validator
|
||||
|
||||
@@ -19,17 +22,32 @@ SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s")
|
||||
|
||||
RomIGDBMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomIGDBMetadata",
|
||||
dict((k, NotRequired[v]) for k, v in get_type_hints(IGDBMetadata).items()),
|
||||
{k: NotRequired[v] for k, v in get_type_hints(IGDBMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
RomMobyMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomMobyMetadata",
|
||||
dict((k, NotRequired[v]) for k, v in get_type_hints(MobyMetadata).items()),
|
||||
{k: NotRequired[v] for k, v in get_type_hints(MobyMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
RomSSMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomSSMetadata",
|
||||
dict((k, NotRequired[v]) for k, v in get_type_hints(SSMetadata).items()),
|
||||
{k: NotRequired[v] for k, v in get_type_hints(SSMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
RomRAMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomRAMetadata",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(RAMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
RomLaunchboxMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomLaunchboxMetadata",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(LaunchboxMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
RomHasheousMetadata = TypedDict( # type: ignore[misc]
|
||||
"RomHasheousMetadata",
|
||||
{k: NotRequired[v] for k, v in get_type_hints(HasheousMetadata).items()}, # type: ignore[misc]
|
||||
total=False,
|
||||
)
|
||||
|
||||
@@ -121,12 +139,55 @@ class RomFileSchema(BaseModel):
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RomMetadataSchema(BaseModel):
|
||||
rom_id: int
|
||||
genres: list[str]
|
||||
franchises: list[str]
|
||||
collections: list[str]
|
||||
companies: list[str]
|
||||
game_modes: list[str]
|
||||
age_ratings: list[str]
|
||||
first_release_date: int | None
|
||||
average_rating: float | None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@field_validator("genres")
|
||||
def sort_genres(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("franchises")
|
||||
def sort_franchises(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("collections")
|
||||
def sort_collections(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("companies")
|
||||
def sort_companies(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("game_modes")
|
||||
def sort_game_modes(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("age_ratings")
|
||||
def sort_age_ratings(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
|
||||
class RomSchema(BaseModel):
|
||||
id: int
|
||||
igdb_id: int | None
|
||||
sgdb_id: int | None
|
||||
moby_id: int | None
|
||||
ss_id: int | None
|
||||
ra_id: int | None
|
||||
launchbox_id: int | None
|
||||
hasheous_id: int | None
|
||||
tgdb_id: int | None
|
||||
|
||||
platform_id: int
|
||||
platform_slug: str
|
||||
@@ -147,19 +208,14 @@ class RomSchema(BaseModel):
|
||||
summary: str | None
|
||||
|
||||
# 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]
|
||||
meta_collections: list[str]
|
||||
companies: list[str]
|
||||
game_modes: list[str]
|
||||
age_ratings: list[str]
|
||||
youtube_video_id: str | None
|
||||
metadatum: RomMetadataSchema
|
||||
igdb_metadata: RomIGDBMetadata | None
|
||||
moby_metadata: RomMobyMetadata | None
|
||||
ss_metadata: RomSSMetadata | None
|
||||
launchbox_metadata: RomLaunchboxMetadata | None
|
||||
hasheous_metadata: RomHasheousMetadata | None
|
||||
|
||||
path_cover_small: str | None
|
||||
path_cover_large: str | None
|
||||
@@ -170,6 +226,7 @@ class RomSchema(BaseModel):
|
||||
url_manual: str | None
|
||||
|
||||
is_unidentified: bool
|
||||
is_identified: bool
|
||||
|
||||
revision: str | None
|
||||
regions: list[str]
|
||||
@@ -185,10 +242,51 @@ class RomSchema(BaseModel):
|
||||
full_path: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
missing_from_fs: bool
|
||||
|
||||
siblings: list[SiblingRomSchema]
|
||||
rom_user: RomUserSchema
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@classmethod
|
||||
def populate_properties(cls, db_rom: Rom, request: Request) -> Rom:
|
||||
db_rom.rom_user = RomUserSchema.for_user(request.user.id, db_rom) # type: ignore
|
||||
db_rom.siblings = [ # type: ignore
|
||||
SiblingRomSchema(
|
||||
id=s.id,
|
||||
name=s.name,
|
||||
fs_name_no_tags=s.fs_name_no_tags,
|
||||
fs_name_no_ext=s.fs_name_no_ext,
|
||||
)
|
||||
for s in db_rom.sibling_roms
|
||||
]
|
||||
return db_rom
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, _request: Request) -> RomSchema:
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@field_validator("alternative_names")
|
||||
def sort_alternative_names(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("files")
|
||||
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
|
||||
return sorted(v, key=lambda x: x.file_name)
|
||||
|
||||
@field_validator("siblings")
|
||||
def sort_siblings(cls, v: list[SiblingRomSchema]) -> list[SiblingRomSchema]:
|
||||
return sorted(v, key=lambda x: x.sort_comparator)
|
||||
|
||||
|
||||
class SiblingRomSchema(BaseModel):
|
||||
id: int
|
||||
name: str | None
|
||||
fs_name_no_tags: str
|
||||
fs_name_no_ext: str
|
||||
|
||||
@computed_field # type: ignore
|
||||
@property
|
||||
def sort_comparator(self) -> str:
|
||||
@@ -201,78 +299,52 @@ class RomSchema(BaseModel):
|
||||
.lower()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, _request: Request) -> RomSchema:
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@field_validator("alternative_names")
|
||||
def sort_alternative_names(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("genres")
|
||||
def sort_genres(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("franchises")
|
||||
def sort_franchises(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("meta_collections")
|
||||
def sort_meta_collections(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("companies")
|
||||
def sort_companies(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("game_modes")
|
||||
def sort_game_modes(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("age_ratings")
|
||||
def sort_age_ratings(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("files")
|
||||
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
|
||||
return sorted(v, key=lambda x: x.file_name)
|
||||
|
||||
|
||||
class SimpleRomSchema(RomSchema):
|
||||
sibling_roms: list[RomSchema]
|
||||
rom_user: RomUserSchema
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> SimpleRomSchema:
|
||||
user_id = request.user.id
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # type: ignore
|
||||
db_rom = cls.populate_properties(db_rom, request)
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_factory(cls, db_rom: Rom) -> SimpleRomSchema:
|
||||
db_rom.rom_user = rom_user_schema_factory() # type: ignore
|
||||
db_rom.siblings = [] # type: ignore
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@field_validator("sibling_roms")
|
||||
def sort_sibling_roms(cls, v: list[RomSchema]) -> list[RomSchema]:
|
||||
return sorted(v, key=lambda x: x.sort_comparator)
|
||||
|
||||
class UserCollectionSchema(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
|
||||
@classmethod
|
||||
def for_user(
|
||||
cls, user_id: int, collections: list[Collection]
|
||||
) -> list["UserCollectionSchema"]:
|
||||
return [
|
||||
UserCollectionSchema(
|
||||
id=c.id,
|
||||
name=c.name,
|
||||
)
|
||||
for c in collections
|
||||
if c.user_id == user_id or c.is_public
|
||||
]
|
||||
|
||||
|
||||
class DetailedRomSchema(RomSchema):
|
||||
merged_ra_metadata: RomRAMetadata | None
|
||||
merged_screenshots: list[str]
|
||||
sibling_roms: list[RomSchema]
|
||||
rom_user: RomUserSchema
|
||||
user_saves: list[SaveSchema]
|
||||
user_states: list[StateSchema]
|
||||
user_screenshots: list[ScreenshotSchema]
|
||||
user_notes: list[UserNotesSchema]
|
||||
user_collections: list[CollectionSchema]
|
||||
user_collections: list[UserCollectionSchema]
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
|
||||
user_id = request.user.id
|
||||
db_rom = cls.populate_properties(db_rom, request)
|
||||
|
||||
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # type: ignore
|
||||
db_rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom) # type: ignore
|
||||
db_rom.user_saves = [ # type: ignore
|
||||
SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id
|
||||
@@ -285,16 +357,11 @@ class DetailedRomSchema(RomSchema):
|
||||
for s in db_rom.screenshots
|
||||
if s.user_id == user_id
|
||||
]
|
||||
db_rom.user_collections = CollectionSchema.for_user( # type: ignore
|
||||
db_rom.user_collections = UserCollectionSchema.for_user( # type: ignore
|
||||
user_id, db_rom.collections
|
||||
)
|
||||
|
||||
return cls.model_validate(db_rom)
|
||||
|
||||
@field_validator("sibling_roms")
|
||||
def sort_sibling_roms(cls, v: list[RomSchema]) -> list[RomSchema]:
|
||||
return sorted(v, key=lambda x: x.sort_comparator)
|
||||
|
||||
@field_validator("user_saves")
|
||||
def sort_user_saves(cls, v: list[SaveSchema]) -> list[SaveSchema]:
|
||||
return sorted(v, key=lambda x: x.updated_at, reverse=True)
|
||||
|
||||
@@ -2,16 +2,19 @@ from .base import BaseModel
|
||||
|
||||
|
||||
class SearchRomSchema(BaseModel):
|
||||
id: int | None = None
|
||||
igdb_id: int | None = None
|
||||
moby_id: int | None = None
|
||||
ss_id: int | None = None
|
||||
slug: str
|
||||
sgdb_id: int | None = None
|
||||
platform_id: int
|
||||
name: str
|
||||
summary: str
|
||||
slug: str = ""
|
||||
summary: str = ""
|
||||
igdb_url_cover: str = ""
|
||||
moby_url_cover: str = ""
|
||||
ss_url_cover: str = ""
|
||||
platform_id: int
|
||||
sgdb_url_cover: str = ""
|
||||
|
||||
|
||||
class SearchCoverSchema(BaseModel):
|
||||
|
||||
@@ -7,4 +7,4 @@ class StatsReturn(TypedDict):
|
||||
SAVES: int
|
||||
STATES: int
|
||||
SCREENSHOTS: int
|
||||
FILESIZE: int
|
||||
TOTAL_FILESIZE_BYTES: int
|
||||
|
||||
14
backend/endpoints/responses/tasks.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from typing import Dict, List, TypedDict
|
||||
|
||||
|
||||
class TaskInfo(TypedDict):
|
||||
name: str
|
||||
manual_run: bool
|
||||
title: str
|
||||
description: str
|
||||
enabled: bool
|
||||
cron_string: str
|
||||
|
||||
|
||||
# Use a more flexible type for grouped tasks
|
||||
GroupedTasksDict = Dict[str, List[TaskInfo]]
|
||||
@@ -1,14 +1,15 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.assets import SaveSchema, UploadedSavesResponse
|
||||
from endpoints.responses.assets import SaveSchema
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from fastapi import HTTPException, Request, UploadFile, status
|
||||
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
|
||||
from handler.scan_handler import scan_save, scan_screenshot
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -19,123 +20,212 @@ router = APIRouter(
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
||||
def add_saves(
|
||||
async def add_save(
|
||||
request: Request,
|
||||
rom_id: int,
|
||||
saves: list[UploadFile] = File(...), # noqa: B008
|
||||
emulator: str | None = None,
|
||||
) -> UploadedSavesResponse:
|
||||
) -> SaveSchema:
|
||||
data = await request.form()
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading saves to {rom.name}")
|
||||
log.info(f"Uploading save of {rom.name}")
|
||||
|
||||
saves_path = fs_asset_handler.build_saves_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom_id,
|
||||
emulator=emulator,
|
||||
)
|
||||
|
||||
for save in saves:
|
||||
if not save.filename:
|
||||
log.error("Save file has no filename")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=save, path=saves_path)
|
||||
|
||||
# Scan or update save
|
||||
scanned_save = scan_save(
|
||||
file_name=save.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
emulator=emulator,
|
||||
if "saveFile" not in data:
|
||||
log.error("No save file provided")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="No save file provided"
|
||||
)
|
||||
db_save = db_save_handler.get_save_by_filename(
|
||||
rom_id=rom.id, user_id=current_user.id, file_name=save.filename
|
||||
)
|
||||
if db_save:
|
||||
db_save_handler.update_save(
|
||||
db_save.id, {"file_size_bytes": scanned_save.file_size_bytes}
|
||||
)
|
||||
continue
|
||||
|
||||
saveFile: UploadFile = data["saveFile"] # type: ignore
|
||||
|
||||
if not saveFile.filename:
|
||||
log.error("Save file has no filename")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Save file has no filename"
|
||||
)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
log.info(
|
||||
f"Uploading save {hl(saveFile.filename)} for {hl(str(rom.name), color=BLUE)}"
|
||||
)
|
||||
|
||||
saves_path = fs_asset_handler.build_saves_file_path(
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom.id,
|
||||
emulator=emulator,
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=saveFile, path=saves_path)
|
||||
|
||||
# Scan or update save
|
||||
scanned_save = await scan_save(
|
||||
file_name=saveFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom_id,
|
||||
emulator=emulator,
|
||||
)
|
||||
db_save = db_save_handler.get_save_by_filename(
|
||||
user_id=request.user.id, rom_id=rom.id, file_name=saveFile.filename
|
||||
)
|
||||
if db_save:
|
||||
db_save = db_save_handler.update_save(
|
||||
db_save.id, {"file_size_bytes": scanned_save.file_size_bytes}
|
||||
)
|
||||
else:
|
||||
scanned_save.rom_id = rom.id
|
||||
scanned_save.user_id = current_user.id
|
||||
scanned_save.user_id = request.user.id
|
||||
scanned_save.emulator = emulator
|
||||
db_save_handler.add_save(scanned_save)
|
||||
db_save = db_save_handler.add_save(save=scanned_save)
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = await scan_screenshot(
|
||||
file_name=screenshotFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform_slug,
|
||||
rom_id=rom.id,
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot(
|
||||
filename=screenshotFile.filename,
|
||||
rom_id=rom.id,
|
||||
user_id=request.user.id,
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot = db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
else:
|
||||
scanned_screenshot.rom_id = rom.id
|
||||
scanned_screenshot.user_id = request.user.id
|
||||
db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot)
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=request.user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom_id=rom.id, user_id=request.user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
# Refetch the rom to get updated saves
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(saves),
|
||||
"saves": [
|
||||
SaveSchema.model_validate(s)
|
||||
for s in rom.saves
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
}
|
||||
return SaveSchema.model_validate(db_save)
|
||||
|
||||
|
||||
# @protected_route(router.get, "", [Scope.ASSETS_READ])
|
||||
# def get_saves(request: Request) -> MessageResponse:
|
||||
# pass
|
||||
@protected_route(router.get, "", [Scope.ASSETS_READ])
|
||||
def get_saves(
|
||||
request: Request, rom_id: int | None = None, platform_id: int | None = None
|
||||
) -> list[SaveSchema]:
|
||||
saves = db_save_handler.get_saves(
|
||||
user_id=request.user.id, rom_id=rom_id, platform_id=platform_id
|
||||
)
|
||||
|
||||
return [SaveSchema.model_validate(save) for save in saves]
|
||||
|
||||
|
||||
# @protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
||||
# def get_save(request: Request, id: int) -> MessageResponse:
|
||||
# pass
|
||||
@protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
||||
def get_save(request: Request, id: int) -> SaveSchema:
|
||||
save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
||||
|
||||
if not save:
|
||||
error = f"Save with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
return SaveSchema.model_validate(save)
|
||||
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
|
||||
async def update_save(request: Request, id: int) -> SaveSchema:
|
||||
data = await request.form()
|
||||
|
||||
db_save = db_save_handler.get_save(id)
|
||||
db_save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
||||
if not db_save:
|
||||
error = f"Save with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
if db_save.user_id != request.user.id:
|
||||
error = "You are not authorized to update this save"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
if "saveFile" in data:
|
||||
saveFile: UploadFile = data["saveFile"] # type: ignore
|
||||
await fs_asset_handler.write_file(file=saveFile, path=db_save.file_path)
|
||||
db_save = db_save_handler.update_save(
|
||||
db_save.id, {"file_size_bytes": saveFile.size}
|
||||
)
|
||||
|
||||
if "file" in data:
|
||||
file: UploadFile = data["file"] # type: ignore
|
||||
fs_asset_handler.write_file(file=file, path=db_save.file_path)
|
||||
db_save_handler.update_save(db_save.id, {"file_size_bytes": file.size})
|
||||
screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user,
|
||||
platform_fs_slug=db_save.rom.platform_slug,
|
||||
rom_id=db_save.rom.id,
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = await scan_screenshot(
|
||||
file_name=screenshotFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=db_save.rom.platform_slug,
|
||||
rom_id=db_save.rom.id,
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot(
|
||||
filename=screenshotFile.filename,
|
||||
rom_id=db_save.rom.id,
|
||||
user_id=request.user.id,
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot = db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
else:
|
||||
scanned_screenshot.rom_id = db_save.rom.id
|
||||
scanned_screenshot.user_id = request.user.id
|
||||
db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot)
|
||||
|
||||
# Set the last played time for the current user
|
||||
current_user = request.user
|
||||
rom_user = db_rom_handler.get_rom_user(db_save.rom_id, current_user.id)
|
||||
rom_user = db_rom_handler.get_rom_user(db_save.rom_id, request.user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(db_save.rom_id, current_user.id)
|
||||
rom_user = db_rom_handler.add_rom_user(db_save.rom_id, request.user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
# Refetch the save to get updated fields
|
||||
db_save = db_save_handler.get_save(id)
|
||||
return SaveSchema.model_validate(db_save)
|
||||
|
||||
|
||||
@protected_route(router.post, "/delete", [Scope.ASSETS_WRITE])
|
||||
async def delete_saves(request: Request) -> MessageResponse:
|
||||
async def delete_saves(request: Request) -> list[int]:
|
||||
data: dict = await request.json()
|
||||
save_ids: list = data["saves"]
|
||||
delete_from_fs: list = data["delete_from_fs"]
|
||||
|
||||
if not save_ids:
|
||||
error = "No saves were provided"
|
||||
@@ -143,44 +233,32 @@ async def delete_saves(request: Request) -> MessageResponse:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
|
||||
|
||||
for save_id in save_ids:
|
||||
save = db_save_handler.get_save(save_id)
|
||||
save = db_save_handler.get_save(user_id=request.user.id, id=save_id)
|
||||
if not save:
|
||||
error = f"Save with ID {save_id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
if save.user_id != request.user.id:
|
||||
error = "You are not authorized to delete this save"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
|
||||
db_save_handler.delete_save(save_id)
|
||||
|
||||
if save_id in delete_from_fs:
|
||||
log.info(f"Deleting {save.file_name} from filesystem")
|
||||
|
||||
try:
|
||||
fs_asset_handler.remove_file(
|
||||
file_name=save.file_name, file_path=save.file_path
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
error = f"Save file {save.file_name} not found for platform {save.rom.platform_slug}"
|
||||
log.error(error)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=error
|
||||
) from exc
|
||||
log.info(
|
||||
f"Deleting save {hl(save.file_name)} [{save.rom.platform_slug}] from filesystem"
|
||||
)
|
||||
try:
|
||||
file_path = f"{save.file_path}/{save.file_name}"
|
||||
await fs_asset_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"Save file {hl(save.file_name)} not found for platform {hl(save.rom.platform_display_name, color=BLUE)}[{hl(save.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
|
||||
if save.screenshot:
|
||||
db_screenshot_handler.delete_screenshot(save.screenshot.id)
|
||||
|
||||
if delete_from_fs:
|
||||
try:
|
||||
fs_asset_handler.remove_file(
|
||||
file_name=save.screenshot.file_name,
|
||||
file_path=save.screenshot.file_path,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
error = f"Screenshot file {save.screenshot.file_name} not found for save {save.file_name}"
|
||||
log.error(error)
|
||||
try:
|
||||
file_path = f"{save.screenshot.file_path}/{save.screenshot.file_name}"
|
||||
await fs_asset_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"Screenshot file {hl(save.screenshot.file_name)} not found for save {hl(save.file_name)}[{hl(save.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
|
||||
return {"msg": f"Successfully deleted {len(save_ids)} saves"}
|
||||
return save_ids
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse
|
||||
from endpoints.responses.assets import ScreenshotSchema
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, Request, UploadFile
|
||||
from fastapi import HTTPException, 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
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -16,59 +18,72 @@ router = APIRouter(
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
||||
def add_screenshots(
|
||||
async def add_screenshot(
|
||||
request: Request,
|
||||
rom_id: int,
|
||||
screenshots: list[UploadFile] = File(...), # noqa: B008
|
||||
) -> UploadedScreenshotsResponse:
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
) -> ScreenshotSchema:
|
||||
data = await request.form()
|
||||
|
||||
rom = db_rom_handler.get_rom(id=rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading screenshots to {rom.name}")
|
||||
log.info(f"Uploading screenshots to {hl(str(rom.name), color=BLUE)}")
|
||||
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform_slug
|
||||
user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id
|
||||
)
|
||||
|
||||
for screenshot in screenshots:
|
||||
if not screenshot.filename:
|
||||
log.warning("Skipping empty screenshot")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=screenshot, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = scan_screenshot(
|
||||
file_name=screenshot.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform_slug,
|
||||
if "screenshotFile" not in data:
|
||||
log.error("No screenshot file provided")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No screenshot file provided",
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot_by_filename(
|
||||
rom_id=rom.id, user_id=current_user.id, file_name=screenshot.filename
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
continue
|
||||
|
||||
screenshotFile: UploadFile = data["screenshotFile"] # type: ignore
|
||||
if not screenshotFile.filename:
|
||||
log.error("Screenshot file has no filename")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Screenshot file has no filename",
|
||||
)
|
||||
|
||||
if not screenshotFile.filename:
|
||||
log.warning("Skipping empty screenshot")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Screenshot has no filename"
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = await scan_screenshot(
|
||||
file_name=screenshotFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform_slug,
|
||||
rom_id=rom.id,
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot(
|
||||
filename=screenshotFile.filename,
|
||||
rom_id=rom.id,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot = db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
else:
|
||||
scanned_screenshot.rom_id = rom.id
|
||||
scanned_screenshot.user_id = current_user.id
|
||||
db_screenshot_handler.add_screenshot(scanned_screenshot)
|
||||
db_screenshot = db_screenshot_handler.add_screenshot(
|
||||
screenshot=scanned_screenshot
|
||||
)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
rom = db_rom_handler.get_rom(id=rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(screenshots),
|
||||
"screenshots": [
|
||||
ScreenshotSchema.model_validate(s)
|
||||
for s in rom.screenshots
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
"merged_screenshots": rom.merged_screenshots,
|
||||
}
|
||||
return ScreenshotSchema.model_validate(db_screenshot)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
|
||||
import emoji
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.search import SearchCoverSchema, SearchRomSchema
|
||||
from exceptions.endpoint_exceptions import SGDBInvalidAPIKeyException
|
||||
from fastapi import HTTPException, Request, status
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
@@ -14,10 +14,13 @@ from handler.metadata import (
|
||||
)
|
||||
from handler.metadata.igdb_handler import IGDB_API_ENABLED, IGDBRom
|
||||
from handler.metadata.moby_handler import MOBY_API_ENABLED, MobyGamesRom
|
||||
from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED
|
||||
from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED, SGDBRom
|
||||
from handler.metadata.ss_handler import SS_API_ENABLED, SSRom
|
||||
from handler.scan_handler import _get_main_platform_igdb_id
|
||||
from handler.scan_handler import get_main_platform_igdb_id
|
||||
from logger.formatter import BLUE, CYAN
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils import emoji
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -63,12 +66,14 @@ async def search_rom(
|
||||
return []
|
||||
|
||||
log.info(
|
||||
emoji.emojize(":magnifying_glass_tilted_right: Searching metadata providers...")
|
||||
f"{emoji.EMOJI_MAGNIFYING_GLASS_TILTED_RIGHT} Searching metadata providers..."
|
||||
)
|
||||
matched_roms: list = []
|
||||
|
||||
log.info(f"Searching by {search_by.lower()}: {search_term}")
|
||||
log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.fs_name}"))
|
||||
log.info(f"Searching by {hl(search_by.lower(), color=CYAN)}:")
|
||||
log.info(
|
||||
f"{emoji.EMOJI_VIDEO_GAME} {hl(rom.platform_display_name, color=BLUE)} [{rom.platform_fs_slug}]: {hl(search_term)}[{rom.fs_name}]"
|
||||
)
|
||||
|
||||
igdb_matched_roms: list[IGDBRom] = []
|
||||
moby_matched_roms: list[MobyGamesRom] = []
|
||||
@@ -92,9 +97,13 @@ async def search_rom(
|
||||
moby_matched_roms = [moby_rom] if moby_rom else []
|
||||
ss_matched_roms = [ss_rom] if ss_rom else []
|
||||
elif search_by.lower() == "name":
|
||||
igdb_matched_roms, moby_matched_roms, ss_matched_roms = await asyncio.gather(
|
||||
(
|
||||
igdb_matched_roms,
|
||||
moby_matched_roms,
|
||||
ss_matched_roms,
|
||||
) = await asyncio.gather(
|
||||
meta_igdb_handler.get_matched_roms_by_name(
|
||||
search_term, (await _get_main_platform_igdb_id(rom.platform))
|
||||
search_term, get_main_platform_igdb_id(rom.platform)
|
||||
),
|
||||
meta_moby_handler.get_matched_roms_by_name(
|
||||
search_term, rom.platform.moby_id
|
||||
@@ -105,41 +114,60 @@ async def search_rom(
|
||||
merged_dict: dict[str, dict] = {}
|
||||
|
||||
for igdb_rom in igdb_matched_roms:
|
||||
merged_dict[igdb_rom["name"]] = {
|
||||
**igdb_rom,
|
||||
"igdb_url_cover": igdb_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(igdb_rom.get("name", ""), {}),
|
||||
}
|
||||
if igdb_rom["igdb_id"]:
|
||||
igdb_name = meta_igdb_handler.normalize_search_term(
|
||||
igdb_rom.get("name", ""),
|
||||
remove_articles=False,
|
||||
)
|
||||
merged_dict[igdb_name] = {
|
||||
**igdb_rom,
|
||||
"platform_id": rom.platform_id,
|
||||
"igdb_url_cover": igdb_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(igdb_name, {}),
|
||||
}
|
||||
|
||||
for moby_rom in moby_matched_roms:
|
||||
merged_dict[moby_rom["name"]] = { # type: ignore
|
||||
**moby_rom,
|
||||
"moby_url_cover": moby_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(moby_rom.get("name", ""), {}),
|
||||
}
|
||||
if moby_rom["moby_id"]:
|
||||
moby_name = meta_moby_handler.normalize_search_term(
|
||||
moby_rom.get("name", ""),
|
||||
remove_articles=False,
|
||||
)
|
||||
merged_dict[moby_name] = {
|
||||
**moby_rom,
|
||||
"platform_id": rom.platform_id,
|
||||
"moby_url_cover": moby_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(moby_name, {}),
|
||||
}
|
||||
|
||||
for ss_rom in ss_matched_roms:
|
||||
merged_dict[ss_rom["name"]] = {
|
||||
**ss_rom,
|
||||
"ss_url_cover": ss_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(ss_rom.get("name", ""), {}),
|
||||
}
|
||||
|
||||
matched_roms = [
|
||||
{
|
||||
**{
|
||||
"slug": "",
|
||||
"name": "",
|
||||
"summary": "",
|
||||
"igdb_url_cover": "",
|
||||
"moby_url_cover": "",
|
||||
"ss_url_cover": "",
|
||||
if ss_rom["ss_id"]:
|
||||
ss_name = meta_ss_handler.normalize_search_term(
|
||||
ss_rom.get("name", ""),
|
||||
remove_articles=False,
|
||||
)
|
||||
merged_dict[ss_name] = {
|
||||
**ss_rom,
|
||||
"platform_id": rom.platform_id,
|
||||
},
|
||||
**item,
|
||||
}
|
||||
for item in list(merged_dict.values())
|
||||
]
|
||||
"ss_url_cover": ss_rom.pop("url_cover", ""),
|
||||
**merged_dict.get(ss_name, {}),
|
||||
}
|
||||
|
||||
async def get_sgdb_rom(name: str) -> tuple[str, SGDBRom]:
|
||||
return name, await meta_sgdb_handler.get_details_by_names([name])
|
||||
|
||||
sgdb_roms = await asyncio.gather(
|
||||
*[get_sgdb_rom(name) for name in list(merged_dict.keys())]
|
||||
)
|
||||
|
||||
for name, sgdb_rom in sgdb_roms:
|
||||
if sgdb_rom["sgdb_id"]:
|
||||
merged_dict[name] = {
|
||||
**merged_dict[name],
|
||||
"sgdb_id": sgdb_rom.get("sgdb_id", ""),
|
||||
"sgdb_url_cover": sgdb_rom.get("url_cover", ""),
|
||||
}
|
||||
|
||||
matched_roms = list(merged_dict.values())
|
||||
|
||||
log.info("Results:")
|
||||
for m_rom in matched_roms:
|
||||
@@ -161,6 +189,11 @@ async def search_cover(
|
||||
detail="No SteamGridDB enabled",
|
||||
)
|
||||
|
||||
covers = await meta_sgdb_handler.get_details(search_term=search_term)
|
||||
try:
|
||||
covers = await meta_sgdb_handler.get_details(search_term=search_term)
|
||||
except SGDBInvalidAPIKeyException as err:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid SGDB API key"
|
||||
) from err
|
||||
|
||||
return [SearchCoverSchema.model_validate(cover) for cover in covers]
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from itertools import batched
|
||||
from typing import Any, Final
|
||||
|
||||
import emoji
|
||||
import socketio # type: ignore
|
||||
from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT
|
||||
from endpoints.responses.platform import PlatformSchema
|
||||
@@ -26,55 +24,23 @@ from handler.filesystem import (
|
||||
from handler.filesystem.roms_handler import FSRom
|
||||
from handler.redis_handler import high_prio_queue, redis_client
|
||||
from handler.scan_handler import (
|
||||
MetadataSource,
|
||||
ScanType,
|
||||
scan_firmware,
|
||||
scan_platform,
|
||||
scan_rom,
|
||||
)
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.formatter import LIGHTYELLOW, RED
|
||||
from logger.formatter import BLUE, LIGHTYELLOW
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile
|
||||
from rq import Worker
|
||||
from rq.job import Job
|
||||
from sqlalchemy.inspection import inspect
|
||||
from utils import emoji
|
||||
from utils.context import initialize_context
|
||||
|
||||
STOP_SCAN_FLAG: Final = "scan:stop"
|
||||
NON_HASHABLE_PLATFORMS = frozenset(
|
||||
(
|
||||
"amazon-alexa",
|
||||
"amazon-fire-tv",
|
||||
"android",
|
||||
"gear-vr",
|
||||
"ios",
|
||||
"ipad",
|
||||
"linux",
|
||||
"mac",
|
||||
"meta-quest-2",
|
||||
"meta-quest-3",
|
||||
"oculus-go",
|
||||
"oculus-quest",
|
||||
"oculus-rift",
|
||||
"pc",
|
||||
"ps3",
|
||||
"ps4",
|
||||
"ps4--1",
|
||||
"ps5",
|
||||
"psvr",
|
||||
"psvr2",
|
||||
"series-x",
|
||||
"switch",
|
||||
"wiiu",
|
||||
"win",
|
||||
"xbox-360",
|
||||
"xbox360",
|
||||
"xboxone",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -90,7 +56,10 @@ class ScanStats:
|
||||
|
||||
def __add__(self, other: Any) -> ScanStats:
|
||||
if not isinstance(other, ScanStats):
|
||||
return NotImplemented
|
||||
raise NotImplementedError(
|
||||
f"Addition not implemented between ScanStats and {type(other)}"
|
||||
)
|
||||
|
||||
return ScanStats(
|
||||
scanned_platforms=self.scanned_platforms + other.scanned_platforms,
|
||||
added_platforms=self.added_platforms + other.added_platforms,
|
||||
@@ -108,241 +77,6 @@ def _get_socket_manager() -> socketio.AsyncRedisManager:
|
||||
return socketio.AsyncRedisManager(str(REDIS_URL), write_only=True)
|
||||
|
||||
|
||||
def _should_scan_rom(scan_type: ScanType, rom: Rom | None, roms_ids: list[str]) -> bool:
|
||||
"""Decide if a rom should be scanned or not
|
||||
|
||||
Args:
|
||||
scan_type (str): Type of scan to be performed.
|
||||
roms_ids (list[str], optional): List of selected roms to be scanned.
|
||||
metadata_sources (list[str], optional): List of metadata sources to be used
|
||||
"""
|
||||
|
||||
# This logic is tricky so only touch it if you know what you're doing"""
|
||||
return bool(
|
||||
(scan_type in {ScanType.NEW_PLATFORMS, ScanType.QUICK} and not rom)
|
||||
or (scan_type == ScanType.COMPLETE)
|
||||
or (scan_type == ScanType.HASHES)
|
||||
or (
|
||||
rom
|
||||
and (
|
||||
(scan_type == ScanType.UNIDENTIFIED and rom.is_unidentified)
|
||||
or (scan_type == ScanType.PARTIAL and rom.is_partially_identified)
|
||||
or (rom.id in roms_ids)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@initialize_context()
|
||||
async def scan_platforms(
|
||||
platform_ids: list[int],
|
||||
scan_type: ScanType = ScanType.QUICK,
|
||||
roms_ids: list[str] | None = None,
|
||||
metadata_sources: list[str] | None = None,
|
||||
):
|
||||
"""Scan all the listed platforms and fetch metadata from different sources
|
||||
|
||||
Args:
|
||||
platform_slugs (list[str]): List of platform slugs to be scanned
|
||||
scan_type (str): Type of scan to be performed. Defaults to "quick".
|
||||
roms_ids (list[str], optional): List of selected roms to be scanned. Defaults to [].
|
||||
metadata_sources (list[str], optional): List of metadata sources to be used. Defaults to all sources.
|
||||
"""
|
||||
|
||||
if not roms_ids:
|
||||
roms_ids = []
|
||||
|
||||
if not metadata_sources:
|
||||
metadata_sources = [MetadataSource.IGDB, MetadataSource.MOBY, MetadataSource.SS]
|
||||
|
||||
sm = _get_socket_manager()
|
||||
|
||||
try:
|
||||
fs_platforms: list[str] = fs_platform_handler.get_platforms()
|
||||
except FolderStructureNotMatchException as e:
|
||||
log.error(e)
|
||||
await sm.emit("scan:done_ko", e.message)
|
||||
return
|
||||
|
||||
scan_stats = ScanStats()
|
||||
|
||||
async def stop_scan():
|
||||
log.info(emoji.emojize(":stop_sign: Scan stopped manually"))
|
||||
await sm.emit("scan:done", scan_stats.__dict__)
|
||||
redis_client.delete(STOP_SCAN_FLAG)
|
||||
|
||||
try:
|
||||
platform_list = [
|
||||
platform.fs_slug
|
||||
for s in platform_ids
|
||||
if (platform := db_platform_handler.get_platform(s)) is not None
|
||||
] or fs_platforms
|
||||
|
||||
if len(platform_list) == 0:
|
||||
log.warning(
|
||||
emoji.emojize(
|
||||
f"{hl(':warning:', color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly. \
|
||||
Check https://github.com/rommapp/romm?tab=readme-ov-file#folder-structure for more details."
|
||||
)
|
||||
)
|
||||
else:
|
||||
log.info(f"Found {len(platform_list)} platforms in the file system")
|
||||
|
||||
for platform_slug in platform_list:
|
||||
scan_stats += await _identify_platform(
|
||||
platform_slug=platform_slug,
|
||||
scan_type=scan_type,
|
||||
fs_platforms=fs_platforms,
|
||||
roms_ids=roms_ids,
|
||||
metadata_sources=metadata_sources,
|
||||
socket_manager=sm,
|
||||
)
|
||||
|
||||
# Only purge platforms if there are some platforms remaining in the library
|
||||
# This protects against accidental deletion of entries when
|
||||
# the folder structure is not correct or the drive is not mounted
|
||||
if len(fs_platforms) > 0:
|
||||
purged_platforms = db_platform_handler.purge_platforms(fs_platforms)
|
||||
if len(purged_platforms) > 0:
|
||||
log.info("Purging platforms not found in the filesystem:")
|
||||
for p in purged_platforms:
|
||||
log.info(f" - {p.slug}")
|
||||
|
||||
log.info(emoji.emojize(":check_mark: Scan completed "))
|
||||
await sm.emit("scan:done", scan_stats.__dict__)
|
||||
except ScanStoppedException:
|
||||
await stop_scan()
|
||||
return
|
||||
except Exception as e:
|
||||
log.error(f"Error in scan_platform: {e}")
|
||||
# Catch all exceptions and emit error to the client
|
||||
await sm.emit("scan:done_ko", str(e))
|
||||
# Re-raise the exception to be caught by the error handler
|
||||
raise e
|
||||
|
||||
|
||||
async def _identify_platform(
|
||||
platform_slug: str,
|
||||
scan_type: ScanType,
|
||||
fs_platforms: list[str],
|
||||
roms_ids: list[str],
|
||||
metadata_sources: list[str],
|
||||
socket_manager: socketio.AsyncRedisManager,
|
||||
) -> ScanStats:
|
||||
# Stop the scan if the flag is set
|
||||
if redis_client.get(STOP_SCAN_FLAG):
|
||||
raise ScanStoppedException()
|
||||
|
||||
scan_stats = ScanStats()
|
||||
|
||||
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
|
||||
if platform and scan_type == ScanType.NEW_PLATFORMS:
|
||||
return scan_stats
|
||||
|
||||
scanned_platform = await scan_platform(
|
||||
platform_slug, fs_platforms, metadata_sources=metadata_sources
|
||||
)
|
||||
if platform:
|
||||
scanned_platform.id = platform.id
|
||||
# Keep the existing ids if they exist on the platform
|
||||
scanned_platform.igdb_id = scanned_platform.igdb_id or platform.igdb_id
|
||||
scanned_platform.moby_id = scanned_platform.moby_id or platform.moby_id
|
||||
|
||||
scan_stats.scanned_platforms += 1
|
||||
scan_stats.added_platforms += 1 if not platform else 0
|
||||
scan_stats.metadata_platforms += (
|
||||
1 if scanned_platform.igdb_id or scanned_platform.moby_id else 0
|
||||
)
|
||||
|
||||
platform = db_platform_handler.add_platform(scanned_platform)
|
||||
|
||||
await socket_manager.emit(
|
||||
"scan:scanning_platform",
|
||||
PlatformSchema.model_validate(platform).model_dump(
|
||||
include={"id", "name", "slug", "fs_slug"}
|
||||
),
|
||||
)
|
||||
await socket_manager.emit("", None)
|
||||
|
||||
# Scanning firmware
|
||||
try:
|
||||
fs_firmware = fs_firmware_handler.get_firmware(platform.fs_slug)
|
||||
except FirmwareNotFoundException:
|
||||
fs_firmware = []
|
||||
|
||||
if len(fs_firmware) == 0:
|
||||
log.warning(
|
||||
emoji.emojize(
|
||||
f" {hl(':warning:', color=LIGHTYELLOW)} No firmware found, skipping firmware scan for this platform"
|
||||
)
|
||||
)
|
||||
else:
|
||||
log.info(f" {len(fs_firmware)} firmware files found")
|
||||
|
||||
for fs_fw in fs_firmware:
|
||||
scan_stats += await _identify_firmware(
|
||||
platform=platform,
|
||||
fs_fw=fs_fw,
|
||||
)
|
||||
|
||||
# Scanning roms
|
||||
try:
|
||||
fs_roms = fs_rom_handler.get_roms(platform.fs_slug)
|
||||
except RomsNotFoundException as e:
|
||||
log.error(e)
|
||||
return scan_stats
|
||||
|
||||
if len(fs_roms) == 0:
|
||||
log.warning(
|
||||
emoji.emojize(
|
||||
f" {hl(':warning:', color=LIGHTYELLOW)} No roms found, verify that the folder structure is correct"
|
||||
)
|
||||
)
|
||||
else:
|
||||
log.info(f" {len(fs_roms)} roms found in the file system")
|
||||
|
||||
for fs_roms_batch in batched(fs_roms, 200):
|
||||
rom_by_filename_map = db_rom_handler.get_roms_by_fs_name(
|
||||
platform_id=platform.id,
|
||||
fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch},
|
||||
)
|
||||
|
||||
for fs_rom in fs_roms_batch:
|
||||
scan_stats += await _identify_rom(
|
||||
platform=platform,
|
||||
fs_rom=fs_rom,
|
||||
rom=rom_by_filename_map.get(fs_rom["fs_name"]),
|
||||
scan_type=scan_type,
|
||||
roms_ids=roms_ids,
|
||||
metadata_sources=metadata_sources,
|
||||
socket_manager=socket_manager,
|
||||
)
|
||||
|
||||
# Only purge entries if there are some file remaining in the library
|
||||
# This protects against accidental deletion of entries when
|
||||
# the folder structure is not correct or the drive is not mounted
|
||||
if len(fs_roms) > 0:
|
||||
purged_roms = db_rom_handler.purge_roms(
|
||||
platform.id, [rom["fs_name"] for rom in fs_roms]
|
||||
)
|
||||
if len(purged_roms) > 0:
|
||||
log.info("Purging roms not found in the filesystem:")
|
||||
for r in purged_roms:
|
||||
log.info(f" - {r.fs_name}")
|
||||
|
||||
# Same protection for firmware
|
||||
if len(fs_firmware) > 0:
|
||||
purged_firmware = db_firmware_handler.purge_firmware(
|
||||
platform.id, [fw for fw in fs_firmware]
|
||||
)
|
||||
if len(purged_firmware) > 0:
|
||||
log.info("Purging firmware not found in the filesystem:")
|
||||
for f in purged_firmware:
|
||||
log.info(f" - {f}")
|
||||
|
||||
return scan_stats
|
||||
|
||||
|
||||
async def _identify_firmware(
|
||||
platform: Platform,
|
||||
fs_fw: str,
|
||||
@@ -355,7 +89,7 @@ async def _identify_firmware(
|
||||
|
||||
firmware = db_firmware_handler.get_firmware_by_filename(platform.id, fs_fw)
|
||||
|
||||
scanned_firmware = scan_firmware(
|
||||
scanned_firmware = await scan_firmware(
|
||||
platform=platform,
|
||||
file_name=fs_fw,
|
||||
firmware=firmware,
|
||||
@@ -364,61 +98,48 @@ async def _identify_firmware(
|
||||
scan_stats.scanned_firmware += 1
|
||||
scan_stats.added_firmware += 1 if not firmware else 0
|
||||
|
||||
scanned_firmware.missing_from_fs = False
|
||||
db_firmware_handler.add_firmware(scanned_firmware)
|
||||
return scan_stats
|
||||
|
||||
|
||||
def _set_rom_hashes(rom_id: int):
|
||||
"""Set the hashes for the given rom
|
||||
def _should_scan_rom(scan_type: ScanType, rom: Rom | None, roms_ids: list[int]) -> bool:
|
||||
"""Decide if a rom should be scanned or not
|
||||
|
||||
Args:
|
||||
rom_id (int): Rom id
|
||||
scan_type (str): Type of scan to be performed.
|
||||
roms_ids (list[int], optional): List of selected roms to be scanned.
|
||||
metadata_sources (list[str], optional): List of metadata sources to be used
|
||||
"""
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
return
|
||||
|
||||
try:
|
||||
rom_hash, rom_file_hashes = fs_rom_handler.get_rom_hashes(rom)
|
||||
except zlib.error as e:
|
||||
# Set empty hashes if calculating them fails for corrupted files
|
||||
log.error(
|
||||
f"Hashes of {rom.fs_name} couldn't be calculated: {hl(str(e), color=RED)}"
|
||||
)
|
||||
db_rom_handler.update_rom(
|
||||
rom_id,
|
||||
{
|
||||
"crc_hash": "",
|
||||
"md5_hash": "",
|
||||
"sha1_hash": "",
|
||||
},
|
||||
)
|
||||
else:
|
||||
db_rom_handler.update_rom(
|
||||
rom_id,
|
||||
{
|
||||
"crc_hash": rom_hash["crc_hash"],
|
||||
"md5_hash": rom_hash["md5_hash"],
|
||||
"sha1_hash": rom_hash["sha1_hash"],
|
||||
},
|
||||
)
|
||||
for file_hash in rom_file_hashes:
|
||||
db_rom_handler.update_rom_file(
|
||||
file_hash["id"],
|
||||
{
|
||||
"crc_hash": file_hash["crc_hash"],
|
||||
"md5_hash": file_hash["md5_hash"],
|
||||
"sha1_hash": file_hash["sha1_hash"],
|
||||
},
|
||||
# This logic is tricky so only touch it if you know what you're doing"""
|
||||
return bool(
|
||||
(scan_type in {ScanType.NEW_PLATFORMS, ScanType.QUICK} and not rom)
|
||||
or (scan_type == ScanType.COMPLETE)
|
||||
or (scan_type == ScanType.HASHES)
|
||||
or (
|
||||
rom
|
||||
and (
|
||||
(scan_type == ScanType.UNIDENTIFIED and rom.is_unidentified)
|
||||
or (scan_type == ScanType.PARTIAL and rom.is_identified)
|
||||
or (rom.id in roms_ids)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# There's an order of operations here that is important:
|
||||
# 1. Read the list of roms from the filesystem
|
||||
# 2. Check if ROM should be scanned based on the scan type
|
||||
# 3. Create a new ROM entry if it doesn't exist
|
||||
# 4. Build the ROM files and calculate the hashes
|
||||
# 4. Scan the ROM and update its metadata
|
||||
async def _identify_rom(
|
||||
platform: Platform,
|
||||
fs_rom: FSRom,
|
||||
rom: Rom | None,
|
||||
scan_type: ScanType,
|
||||
roms_ids: list[str],
|
||||
roms_ids: list[int],
|
||||
metadata_sources: list[str],
|
||||
socket_manager: socketio.AsyncRedisManager,
|
||||
) -> ScanStats:
|
||||
@@ -429,24 +150,80 @@ async def _identify_rom(
|
||||
return scan_stats
|
||||
|
||||
if not _should_scan_rom(scan_type=scan_type, rom=rom, roms_ids=roms_ids):
|
||||
if rom and rom.fs_name != fs_rom["fs_name"]:
|
||||
# Just to update the filesystem data
|
||||
rom.fs_name = fs_rom["fs_name"]
|
||||
db_rom_handler.add_rom(rom)
|
||||
if rom:
|
||||
if rom.fs_name != fs_rom["fs_name"]:
|
||||
# Just to update the filesystem data
|
||||
rom.fs_name = fs_rom["fs_name"]
|
||||
db_rom_handler.add_rom(rom)
|
||||
|
||||
if rom.missing_from_fs:
|
||||
db_rom_handler.update_rom(rom.id, {"missing_from_fs": False})
|
||||
|
||||
return scan_stats
|
||||
|
||||
# Update properties that don't require metadata
|
||||
fs_regions, fs_revisions, fs_languages, fs_other_tags = fs_rom_handler.parse_tags(
|
||||
fs_rom["fs_name"]
|
||||
)
|
||||
roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug)
|
||||
|
||||
# Create the entry early so we have the ID
|
||||
newly_added: bool = rom is None
|
||||
if not rom:
|
||||
rom = db_rom_handler.add_rom(
|
||||
Rom(
|
||||
fs_name=fs_rom["fs_name"],
|
||||
fs_path=roms_path,
|
||||
fs_name_no_tags=fs_rom_handler.get_file_name_with_no_tags(
|
||||
fs_rom["fs_name"]
|
||||
),
|
||||
fs_name_no_ext=fs_rom_handler.get_file_name_with_no_extension(
|
||||
fs_rom["fs_name"]
|
||||
),
|
||||
fs_extension=fs_rom_handler.parse_file_extension(fs_rom["fs_name"]),
|
||||
regions=fs_regions,
|
||||
revision=fs_revisions,
|
||||
languages=fs_languages,
|
||||
tags=fs_other_tags,
|
||||
platform_id=platform.id,
|
||||
name=fs_rom["fs_name"],
|
||||
multi=fs_rom["multi"],
|
||||
url_cover="",
|
||||
url_manual="",
|
||||
url_screenshots=[],
|
||||
)
|
||||
)
|
||||
|
||||
# Silly checks to make the type checker happy
|
||||
if not rom:
|
||||
return scan_stats
|
||||
|
||||
# Build rom files object before scanning
|
||||
rom_files, rom_crc_c, rom_md5_h, rom_sha1_h, rom_ra_h = (
|
||||
await fs_rom_handler.get_rom_files(rom)
|
||||
)
|
||||
fs_rom.update(
|
||||
{
|
||||
"files": rom_files,
|
||||
"crc_hash": rom_crc_c,
|
||||
"md5_hash": rom_md5_h,
|
||||
"sha1_hash": rom_sha1_h,
|
||||
"ra_hash": rom_ra_h,
|
||||
}
|
||||
)
|
||||
|
||||
scanned_rom = await scan_rom(
|
||||
platform=platform,
|
||||
fs_rom=fs_rom,
|
||||
scan_type=scan_type,
|
||||
platform=platform,
|
||||
rom=rom,
|
||||
fs_rom=fs_rom,
|
||||
metadata_sources=metadata_sources,
|
||||
newly_added=newly_added,
|
||||
)
|
||||
|
||||
scan_stats.scanned_roms += 1
|
||||
scan_stats.added_roms += 1 if not rom else 0
|
||||
scan_stats.metadata_roms += 1 if scanned_rom.igdb_id or scanned_rom.moby_id else 0
|
||||
scan_stats.metadata_roms += 1 if scanned_rom.is_identified else 0
|
||||
|
||||
_added_rom = db_rom_handler.add_rom(scanned_rom)
|
||||
|
||||
@@ -462,28 +239,32 @@ async def _identify_rom(
|
||||
file_size_bytes=file.file_size_bytes,
|
||||
last_modified=file.last_modified,
|
||||
category=file.category,
|
||||
crc_hash=file.crc_hash,
|
||||
md5_hash=file.md5_hash,
|
||||
sha1_hash=file.sha1_hash,
|
||||
ra_hash=file.ra_hash,
|
||||
)
|
||||
for file in fs_rom["files"]
|
||||
for file in rom_files
|
||||
]
|
||||
for new_rom_file in new_rom_files:
|
||||
db_rom_handler.add_rom_file(new_rom_file)
|
||||
|
||||
# Calculating hashes is expensive, so we only do it if necessary
|
||||
if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES:
|
||||
# Skip hashing games for platforms that don't have a hash database
|
||||
if platform.slug not in NON_HASHABLE_PLATFORMS:
|
||||
_set_rom_hashes(_added_rom.id)
|
||||
if _added_rom.ra_metadata:
|
||||
await fs_resource_handler.create_ra_resources_path(platform.id, _added_rom.id)
|
||||
|
||||
# Uncomment this to run scan in a background process
|
||||
# low_prio_queue.enqueue(
|
||||
# _set_rom_hashes,
|
||||
# _added_rom.id,
|
||||
# job_timeout=60 * 15, # Timeout (15 minutes)
|
||||
# )
|
||||
|
||||
# Return early if we're only scanning for hashes
|
||||
if scan_type == ScanType.HASHES:
|
||||
return scan_stats
|
||||
# Store the achievements badges
|
||||
for ach in _added_rom.ra_metadata.get("achievements", []):
|
||||
# Store both normal and locked version
|
||||
badge_url_lock = ach.get("badge_url_lock", None)
|
||||
badge_path_lock = ach.get("badge_path_lock", None)
|
||||
if badge_url_lock and badge_path_lock:
|
||||
await fs_resource_handler.store_ra_badge(
|
||||
badge_url_lock, badge_path_lock
|
||||
)
|
||||
badge_url = ach.get("badge_url", None)
|
||||
badge_path = ach.get("badge_path", None)
|
||||
if badge_url and badge_path:
|
||||
await fs_resource_handler.store_ra_badge(badge_url, badge_path)
|
||||
|
||||
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
|
||||
entity=_added_rom,
|
||||
@@ -506,12 +287,15 @@ async def _identify_rom(
|
||||
_added_rom.path_cover_l = path_cover_l
|
||||
_added_rom.path_screenshots = path_screenshots
|
||||
_added_rom.path_manual = path_manual
|
||||
|
||||
# Update the scanned rom with the cover and screenshots paths and update database
|
||||
db_rom_handler.update_rom(
|
||||
_added_rom.id,
|
||||
{
|
||||
c: getattr(_added_rom, c)
|
||||
for c in inspect(_added_rom).mapper.column_attrs.keys()
|
||||
"path_cover_s": path_cover_s,
|
||||
"path_cover_l": path_cover_l,
|
||||
"path_screenshots": path_screenshots,
|
||||
"path_manual": path_manual,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -531,15 +315,212 @@ async def _identify_rom(
|
||||
return scan_stats
|
||||
|
||||
|
||||
@socket_handler.socket_server.on("scan")
|
||||
async def scan_handler(_sid: str, options: dict):
|
||||
async def _identify_platform(
|
||||
platform_slug: str,
|
||||
scan_type: ScanType,
|
||||
fs_platforms: list[str],
|
||||
roms_ids: list[int],
|
||||
metadata_sources: list[str],
|
||||
socket_manager: socketio.AsyncRedisManager,
|
||||
) -> ScanStats:
|
||||
# Stop the scan if the flag is set
|
||||
if redis_client.get(STOP_SCAN_FLAG):
|
||||
raise ScanStoppedException()
|
||||
|
||||
scan_stats = ScanStats()
|
||||
|
||||
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
|
||||
if platform and scan_type == ScanType.NEW_PLATFORMS:
|
||||
return scan_stats
|
||||
|
||||
scanned_platform = await scan_platform(platform_slug, fs_platforms)
|
||||
if platform:
|
||||
scanned_platform.id = platform.id
|
||||
# Keep the existing ids if they exist on the platform
|
||||
scanned_platform.igdb_id = scanned_platform.igdb_id or platform.igdb_id
|
||||
scanned_platform.moby_id = scanned_platform.moby_id or platform.moby_id
|
||||
scanned_platform.launchbox_id = (
|
||||
scanned_platform.launchbox_id or platform.launchbox_id
|
||||
)
|
||||
|
||||
scan_stats.scanned_platforms += 1
|
||||
scan_stats.added_platforms += 1 if not platform else 0
|
||||
scan_stats.metadata_platforms += 1 if scanned_platform.is_identified else 0
|
||||
|
||||
platform = db_platform_handler.add_platform(scanned_platform)
|
||||
|
||||
await socket_manager.emit(
|
||||
"scan:scanning_platform",
|
||||
PlatformSchema.model_validate(platform).model_dump(
|
||||
include={"id", "name", "slug", "fs_slug"}
|
||||
),
|
||||
)
|
||||
await socket_manager.emit("", None)
|
||||
|
||||
# Scanning firmware
|
||||
try:
|
||||
fs_firmware = await fs_firmware_handler.get_firmware(platform.fs_slug)
|
||||
except FirmwareNotFoundException:
|
||||
fs_firmware = []
|
||||
|
||||
if len(fs_firmware) == 0:
|
||||
log.warning(
|
||||
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} No firmware found for {hl(platform.custom_name or platform.name, color=BLUE)}[{hl(platform.fs_slug)}]"
|
||||
)
|
||||
else:
|
||||
log.info(f"{hl(str(len(fs_firmware)))} firmware files found")
|
||||
|
||||
for fs_fw in fs_firmware:
|
||||
scan_stats += await _identify_firmware(
|
||||
platform=platform,
|
||||
fs_fw=fs_fw,
|
||||
)
|
||||
|
||||
# Scanning roms
|
||||
try:
|
||||
fs_roms = await fs_rom_handler.get_roms(platform)
|
||||
except RomsNotFoundException as e:
|
||||
log.error(e)
|
||||
return scan_stats
|
||||
|
||||
if len(fs_roms) == 0:
|
||||
log.warning(
|
||||
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} No roms found, verify that the folder structure is correct"
|
||||
)
|
||||
else:
|
||||
log.info(f"{hl(str(len(fs_roms)))} roms found in the file system")
|
||||
|
||||
for fs_roms_batch in batched(fs_roms, 200, strict=False):
|
||||
rom_by_filename_map = db_rom_handler.get_roms_by_fs_name(
|
||||
platform_id=platform.id,
|
||||
fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch},
|
||||
)
|
||||
|
||||
for fs_rom in fs_roms_batch:
|
||||
scan_stats += await _identify_rom(
|
||||
platform=platform,
|
||||
fs_rom=fs_rom,
|
||||
rom=rom_by_filename_map.get(fs_rom["fs_name"]),
|
||||
scan_type=scan_type,
|
||||
roms_ids=roms_ids,
|
||||
metadata_sources=metadata_sources,
|
||||
socket_manager=socket_manager,
|
||||
)
|
||||
|
||||
missing_roms = db_rom_handler.mark_missing_roms(
|
||||
platform.id, [rom["fs_name"] for rom in fs_roms]
|
||||
)
|
||||
if len(missing_roms) > 0:
|
||||
log.warning(f"{hl('Missing')} roms from filesystem:")
|
||||
for r in missing_roms:
|
||||
log.warning(f" - {r.fs_name}")
|
||||
|
||||
missing_firmware = db_firmware_handler.mark_missing_firmware(
|
||||
platform.id, [fw for fw in fs_firmware]
|
||||
)
|
||||
if len(missing_firmware) > 0:
|
||||
log.warning(f"{hl('Missing')} firmware from filesystem:")
|
||||
for f in missing_firmware:
|
||||
log.warning(f" - {f}")
|
||||
|
||||
return scan_stats
|
||||
|
||||
|
||||
@initialize_context()
|
||||
async def scan_platforms(
|
||||
platform_ids: list[int],
|
||||
scan_type: ScanType = ScanType.QUICK,
|
||||
roms_ids: list[int] | None = None,
|
||||
metadata_sources: list[str] | None = None,
|
||||
):
|
||||
"""Scan all the listed platforms and fetch metadata from different sources
|
||||
|
||||
Args:
|
||||
platform_slugs (list[str]): List of platform slugs to be scanned
|
||||
scan_type (str): Type of scan to be performed. Defaults to "quick".
|
||||
roms_ids (list[int], optional): List of selected roms to be scanned. Defaults to [].
|
||||
metadata_sources (list[str], optional): List of metadata sources to be used. Defaults to all sources.
|
||||
"""
|
||||
|
||||
if not roms_ids:
|
||||
roms_ids = []
|
||||
|
||||
sm = _get_socket_manager()
|
||||
|
||||
if not metadata_sources:
|
||||
log.error("No metadata sources provided")
|
||||
await sm.emit("scan:done_ko", "No metadata sources provided")
|
||||
return None
|
||||
|
||||
try:
|
||||
fs_platforms: list[str] = await fs_platform_handler.get_platforms()
|
||||
except FolderStructureNotMatchException as e:
|
||||
log.error(e)
|
||||
await sm.emit("scan:done_ko", e.message)
|
||||
return None
|
||||
|
||||
scan_stats = ScanStats()
|
||||
|
||||
async def stop_scan():
|
||||
log.info(f"{emoji.EMOJI_STOP_SIGN} Scan stopped manually")
|
||||
await sm.emit("scan:done", scan_stats.__dict__)
|
||||
redis_client.delete(STOP_SCAN_FLAG)
|
||||
|
||||
try:
|
||||
platform_list = [
|
||||
platform.fs_slug
|
||||
for s in platform_ids
|
||||
if (platform := db_platform_handler.get_platform(s)) is not None
|
||||
] or fs_platforms
|
||||
platform_list = sorted(platform_list)
|
||||
|
||||
if len(platform_list) == 0:
|
||||
log.warning(
|
||||
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly."
|
||||
"Check https://github.com/rommapp/romm?tab=readme-ov-file#folder-structure for more details."
|
||||
)
|
||||
else:
|
||||
log.info(
|
||||
f"Found {hl(str(len(platform_list)))} platforms in the file system"
|
||||
)
|
||||
|
||||
for platform_slug in platform_list:
|
||||
scan_stats += await _identify_platform(
|
||||
platform_slug=platform_slug,
|
||||
scan_type=scan_type,
|
||||
fs_platforms=fs_platforms,
|
||||
roms_ids=roms_ids,
|
||||
metadata_sources=metadata_sources,
|
||||
socket_manager=sm,
|
||||
)
|
||||
|
||||
missed_platforms = db_platform_handler.mark_missing_platforms(fs_platforms)
|
||||
if len(missed_platforms) > 0:
|
||||
log.warning(f"{hl('Missing')} platforms from filesystem:")
|
||||
for p in missed_platforms:
|
||||
log.warning(f" - {p.slug}")
|
||||
|
||||
log.info(f"{emoji.EMOJI_CHECK_MARK} Scan completed")
|
||||
await sm.emit("scan:done", scan_stats.__dict__)
|
||||
except ScanStoppedException:
|
||||
await stop_scan()
|
||||
except Exception as e:
|
||||
log.error(f"Error in scan_platform: {e}")
|
||||
# Catch all exceptions and emit error to the client
|
||||
await sm.emit("scan:done_ko", str(e))
|
||||
# Re-raise the exception to be caught by the error handler
|
||||
raise e
|
||||
|
||||
|
||||
@socket_handler.socket_server.on("scan") # type: ignore
|
||||
async def scan_handler(_sid: str, options: dict[str, Any]):
|
||||
"""Scan socket endpoint
|
||||
|
||||
Args:
|
||||
options (dict): Socket options
|
||||
"""
|
||||
|
||||
log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning "))
|
||||
log.info(f"{emoji.EMOJI_MAGNIFYING_GLASS_TILTED_RIGHT} Scanning")
|
||||
|
||||
platform_ids = options.get("platforms", [])
|
||||
scan_type = ScanType[options.get("type", "quick").upper()]
|
||||
@@ -564,16 +545,16 @@ async def scan_handler(_sid: str, options: dict):
|
||||
)
|
||||
|
||||
|
||||
@socket_handler.socket_server.on("scan:stop")
|
||||
@socket_handler.socket_server.on("scan:stop") # type: ignore
|
||||
async def stop_scan_handler(_sid: str):
|
||||
"""Stop scan socket endpoint"""
|
||||
|
||||
log.info(emoji.emojize(":stop_button: Stop scan requested..."))
|
||||
log.info(f"{emoji.EMOJI_STOP_BUTTON} Stop scan requested...")
|
||||
|
||||
async def cancel_job(job: Job):
|
||||
job.cancel()
|
||||
redis_client.set(STOP_SCAN_FLAG, 1)
|
||||
log.info(emoji.emojize(":stop_button: Job found, stopping scan..."))
|
||||
log.info(f"{emoji.EMOJI_STOP_BUTTON} Job found, stopping scan...")
|
||||
|
||||
existing_jobs = high_prio_queue.get_jobs()
|
||||
for job in existing_jobs:
|
||||
@@ -590,4 +571,4 @@ async def stop_scan_handler(_sid: str):
|
||||
):
|
||||
return await cancel_job(current_job)
|
||||
|
||||
log.info(emoji.emojize(":stop_button: No running scan to stop"))
|
||||
log.info(f"{emoji.EMOJI_STOP_BUTTON} No running scan to stop")
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.assets import StateSchema, UploadedStatesResponse
|
||||
from endpoints.responses.assets import StateSchema
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from fastapi import File, HTTPException, Request, UploadFile, status
|
||||
from fastapi import HTTPException, Request, UploadFile, status
|
||||
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
|
||||
from handler.scan_handler import scan_screenshot, scan_state
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -19,121 +20,216 @@ router = APIRouter(
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
||||
def add_states(
|
||||
async def add_state(
|
||||
request: Request,
|
||||
rom_id: int,
|
||||
states: list[UploadFile] = File(...), # noqa: B008
|
||||
emulator: str | None = None,
|
||||
) -> UploadedStatesResponse:
|
||||
) -> StateSchema:
|
||||
data = await request.form()
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
current_user = request.user
|
||||
log.info(f"Uploading states to {rom.name}")
|
||||
log.info(f"Uploading state of {rom.name}")
|
||||
|
||||
states_path = fs_asset_handler.build_states_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom_id,
|
||||
emulator=emulator,
|
||||
)
|
||||
|
||||
for state in states:
|
||||
if not state.filename:
|
||||
log.warning("Skipping file with no filename")
|
||||
continue
|
||||
|
||||
fs_asset_handler.write_file(file=state, path=states_path)
|
||||
|
||||
# Scan or update state
|
||||
scanned_state = scan_state(
|
||||
file_name=state.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
emulator=emulator,
|
||||
if "stateFile" not in data:
|
||||
log.error("No state file provided")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="No state file provided"
|
||||
)
|
||||
db_state = db_state_handler.get_state_by_filename(
|
||||
rom_id=rom.id, user_id=current_user.id, file_name=state.filename
|
||||
)
|
||||
if db_state:
|
||||
db_state_handler.update_state(
|
||||
db_state.id, {"file_size_bytes": scanned_state.file_size_bytes}
|
||||
)
|
||||
continue
|
||||
|
||||
scanned_state.rom_id = rom.id
|
||||
scanned_state.user_id = current_user.id
|
||||
scanned_state.emulator = emulator
|
||||
db_state_handler.add_state(scanned_state)
|
||||
stateFile: UploadFile = data["stateFile"] # type: ignore
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
if not stateFile.filename:
|
||||
log.error("State file has no filename")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="State file has no filename"
|
||||
)
|
||||
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return {
|
||||
"uploaded": len(states),
|
||||
"states": [
|
||||
StateSchema.model_validate(s)
|
||||
for s in rom.states
|
||||
if s.user_id == current_user.id
|
||||
],
|
||||
}
|
||||
log.info(
|
||||
f"Uploading state {hl(stateFile.filename)} for {hl(str(rom.name), color=BLUE)}"
|
||||
)
|
||||
|
||||
states_path = fs_asset_handler.build_states_file_path(
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom.id,
|
||||
emulator=emulator,
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=stateFile, path=states_path)
|
||||
|
||||
# Scan or update state
|
||||
scanned_state = await scan_state(
|
||||
file_name=stateFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform.fs_slug,
|
||||
rom_id=rom_id,
|
||||
emulator=emulator,
|
||||
)
|
||||
db_state = db_state_handler.get_state_by_filename(
|
||||
user_id=request.user.id, rom_id=rom.id, file_name=stateFile.filename
|
||||
)
|
||||
if db_state:
|
||||
db_state = db_state_handler.update_state(
|
||||
db_state.id, {"file_size_bytes": scanned_state.file_size_bytes}
|
||||
)
|
||||
else:
|
||||
scanned_state.rom_id = rom.id
|
||||
scanned_state.user_id = request.user.id
|
||||
scanned_state.emulator = emulator
|
||||
db_state = db_state_handler.add_state(state=scanned_state)
|
||||
|
||||
screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = await scan_screenshot(
|
||||
file_name=screenshotFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=rom.platform_slug,
|
||||
rom_id=rom.id,
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot(
|
||||
filename=screenshotFile.filename,
|
||||
rom_id=rom.id,
|
||||
user_id=request.user.id,
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot = db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
else:
|
||||
scanned_screenshot.rom_id = rom.id
|
||||
scanned_screenshot.user_id = request.user.id
|
||||
db_screenshot = db_screenshot_handler.add_screenshot(
|
||||
screenshot=scanned_screenshot
|
||||
)
|
||||
|
||||
# Set the last played time for the current user
|
||||
rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=request.user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(rom_id=rom.id, user_id=request.user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
# Refetch the rom to get updated states
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(rom_id)
|
||||
|
||||
return StateSchema.model_validate(db_state)
|
||||
|
||||
|
||||
# @protected_route(router.get, "", [Scope.ASSETS_READ])
|
||||
# def get_states(request: Request) -> MessageResponse:
|
||||
# pass
|
||||
@protected_route(router.get, "", [Scope.ASSETS_READ])
|
||||
def get_states(
|
||||
request: Request, rom_id: int | None = None, platform_id: int | None = None
|
||||
) -> list[StateSchema]:
|
||||
states = db_state_handler.get_states(
|
||||
user_id=request.user.id, rom_id=rom_id, platform_id=platform_id
|
||||
)
|
||||
|
||||
return [StateSchema.model_validate(state) for state in states]
|
||||
|
||||
|
||||
# @protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
||||
# def get_state(request: Request, id: int) -> MessageResponse:
|
||||
# pass
|
||||
@protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
||||
def get_state(request: Request, id: int) -> StateSchema:
|
||||
state = db_state_handler.get_state(user_id=request.user.id, id=id)
|
||||
|
||||
if not state:
|
||||
error = f"State with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
return StateSchema.model_validate(state)
|
||||
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
|
||||
async def update_state(request: Request, id: int) -> StateSchema:
|
||||
data = await request.form()
|
||||
|
||||
db_state = db_state_handler.get_state(id)
|
||||
db_state = db_state_handler.get_state(user_id=request.user.id, id=id)
|
||||
if not db_state:
|
||||
error = f"Save with ID {id} not found"
|
||||
error = f"State with ID {id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
if db_state.user_id != request.user.id:
|
||||
error = "You are not authorized to update this save state"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
if "stateFile" in data:
|
||||
stateFile: UploadFile = data["stateFile"] # type: ignore
|
||||
await fs_asset_handler.write_file(file=stateFile, path=db_state.file_path)
|
||||
db_state = db_state_handler.update_state(
|
||||
db_state.id, {"file_size_bytes": stateFile.size}
|
||||
)
|
||||
|
||||
if "file" in data:
|
||||
file: UploadFile = data["file"] # type: ignore
|
||||
fs_asset_handler.write_file(file=file, path=db_state.file_path)
|
||||
db_state_handler.update_state(db_state.id, {"file_size_bytes": file.size})
|
||||
screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
||||
user=request.user,
|
||||
platform_fs_slug=db_state.rom.platform_slug,
|
||||
rom_id=db_state.rom.id,
|
||||
)
|
||||
|
||||
await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path)
|
||||
|
||||
# Scan or update screenshot
|
||||
scanned_screenshot = await scan_screenshot(
|
||||
file_name=screenshotFile.filename,
|
||||
user=request.user,
|
||||
platform_fs_slug=db_state.rom.platform_slug,
|
||||
rom_id=db_state.rom.id,
|
||||
)
|
||||
db_screenshot = db_screenshot_handler.get_screenshot(
|
||||
filename=screenshotFile.filename,
|
||||
rom_id=db_state.rom.id,
|
||||
user_id=request.user.id,
|
||||
)
|
||||
if db_screenshot:
|
||||
db_screenshot = db_screenshot_handler.update_screenshot(
|
||||
db_screenshot.id,
|
||||
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
||||
)
|
||||
else:
|
||||
scanned_screenshot.rom_id = db_state.rom.id
|
||||
scanned_screenshot.user_id = request.user.id
|
||||
db_screenshot = db_screenshot_handler.add_screenshot(
|
||||
screenshot=scanned_screenshot
|
||||
)
|
||||
|
||||
# Set the last played time for the current user
|
||||
current_user = request.user
|
||||
rom_user = db_rom_handler.get_rom_user(db_state.rom_id, current_user.id)
|
||||
rom_user = db_rom_handler.get_rom_user(db_state.rom_id, request.user.id)
|
||||
if not rom_user:
|
||||
rom_user = db_rom_handler.add_rom_user(db_state.rom_id, current_user.id)
|
||||
rom_user = db_rom_handler.add_rom_user(db_state.rom_id, request.user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
||||
)
|
||||
|
||||
db_state = db_state_handler.get_state(id)
|
||||
# Refetch the state to get updated fields
|
||||
return StateSchema.model_validate(db_state)
|
||||
|
||||
|
||||
@protected_route(router.post, "/delete", [Scope.ASSETS_WRITE])
|
||||
async def delete_states(request: Request) -> MessageResponse:
|
||||
async def delete_states(request: Request) -> list[int]:
|
||||
data: dict = await request.json()
|
||||
state_ids: list = data["states"]
|
||||
delete_from_fs: list = data["delete_from_fs"]
|
||||
|
||||
if not state_ids:
|
||||
error = "No states were provided"
|
||||
@@ -141,43 +237,32 @@ async def delete_states(request: Request) -> MessageResponse:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
|
||||
|
||||
for state_id in state_ids:
|
||||
state = db_state_handler.get_state(state_id)
|
||||
state = db_state_handler.get_state(user_id=request.user.id, id=state_id)
|
||||
if not state:
|
||||
error = f"Save with ID {state_id} not found"
|
||||
error = f"State with ID {state_id} not found"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
if state.user_id != request.user.id:
|
||||
error = "You are not authorized to delete this save state"
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
|
||||
|
||||
db_state_handler.delete_state(state_id)
|
||||
log.info(
|
||||
f"Deleting state {hl(state.file_name)} [{state.rom.platform_slug}] from filesystem"
|
||||
)
|
||||
|
||||
if state_id in delete_from_fs:
|
||||
log.info(f"Deleting {state.file_name} from filesystem")
|
||||
try:
|
||||
fs_asset_handler.remove_file(
|
||||
file_name=state.file_name, file_path=state.file_path
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
error = f"Save file {state.file_name} not found for platform {state.rom.platform_slug}"
|
||||
log.error(error)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=error
|
||||
) from exc
|
||||
try:
|
||||
file_path = f"{state.file_path}/{state.file_name}"
|
||||
await fs_asset_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"State file {hl(state.file_name)} not found for platform {hl(state.rom.platform_display_name, color=BLUE)}[{hl(state.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
|
||||
if state.screenshot:
|
||||
db_screenshot_handler.delete_screenshot(state.screenshot.id)
|
||||
|
||||
if delete_from_fs:
|
||||
try:
|
||||
fs_asset_handler.remove_file(
|
||||
file_name=state.screenshot.file_name,
|
||||
file_path=state.screenshot.file_path,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
error = f"Screenshot file {state.screenshot.file_name} not found for state {state.file_name}"
|
||||
log.error(error)
|
||||
try:
|
||||
file_path = f"{state.screenshot.file_path}/{state.screenshot.file_name}"
|
||||
await fs_asset_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"Screenshot file {hl(state.screenshot.file_name)} not found for state {hl(state.file_name)}[{hl(state.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
|
||||
return {"msg": f"Successfully deleted {len(state_ids)} states"}
|
||||
return state_ids
|
||||
|
||||
@@ -22,5 +22,5 @@ def stats() -> StatsReturn:
|
||||
"SAVES": db_stats_handler.get_saves_count(),
|
||||
"STATES": db_stats_handler.get_states_count(),
|
||||
"SCREENSHOTS": db_stats_handler.get_screenshots_count(),
|
||||
"FILESIZE": db_stats_handler.get_total_filesize(),
|
||||
"TOTAL_FILESIZE_BYTES": db_stats_handler.get_total_filesize(),
|
||||
}
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from config import (
|
||||
ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
|
||||
RESCAN_ON_FILESYSTEM_CHANGE_DELAY,
|
||||
)
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import MessageResponse
|
||||
from fastapi import Request
|
||||
from endpoints.responses import TaskExecutionResponse, TaskStatusResponse
|
||||
from endpoints.responses.tasks import GroupedTasksDict, TaskInfo
|
||||
from fastapi import HTTPException, Request
|
||||
from handler.auth.constants import Scope
|
||||
from tasks.update_switch_titledb import update_switch_titledb_task
|
||||
from handler.redis_handler import low_prio_queue
|
||||
from rq.job import Job
|
||||
from tasks.manual.cleanup_orphaned_resources import cleanup_orphaned_resources_task
|
||||
from tasks.scheduled.scan_library import scan_library_task
|
||||
from tasks.scheduled.update_launchbox_metadata import update_launchbox_metadata_task
|
||||
from tasks.scheduled.update_switch_titledb import update_switch_titledb_task
|
||||
from tasks.tasks import Task
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -10,32 +23,173 @@ router = APIRouter(
|
||||
tags=["tasks"],
|
||||
)
|
||||
|
||||
scheduled_tasks: dict[str, Task] = {
|
||||
"scan_library": scan_library_task,
|
||||
"update_launchbox_metadata": update_launchbox_metadata_task,
|
||||
"update_switch_titledb": update_switch_titledb_task,
|
||||
}
|
||||
|
||||
manual_tasks: dict[str, Task] = {
|
||||
"cleanup_orphaned_resources": cleanup_orphaned_resources_task,
|
||||
}
|
||||
|
||||
|
||||
def _build_task_info(name: str, task: Task) -> TaskInfo:
|
||||
"""Builds a TaskInfo object from task details."""
|
||||
return TaskInfo(
|
||||
name=name,
|
||||
title=task.title,
|
||||
description=task.description,
|
||||
enabled=task.enabled,
|
||||
manual_run=task.manual_run,
|
||||
cron_string=task.cron_string or "",
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.TASKS_RUN])
|
||||
async def list_tasks(request: Request) -> GroupedTasksDict:
|
||||
"""List all available tasks grouped by task type.
|
||||
|
||||
Args:
|
||||
request (Request): FastAPI Request object
|
||||
Returns:
|
||||
Dictionary with tasks grouped by their type (scheduled, manual, watcher)
|
||||
"""
|
||||
# Initialize the grouped tasks dictionary
|
||||
grouped_tasks: GroupedTasksDict = {
|
||||
"scheduled": [],
|
||||
"manual": [],
|
||||
"watcher": [],
|
||||
}
|
||||
|
||||
for name, task in manual_tasks.items():
|
||||
grouped_tasks["manual"].append(_build_task_info(name, task))
|
||||
|
||||
for name, task in scheduled_tasks.items():
|
||||
grouped_tasks["scheduled"].append(_build_task_info(name, task))
|
||||
|
||||
# Add the adhoc watcher task
|
||||
grouped_tasks["watcher"].append(
|
||||
TaskInfo(
|
||||
name="filesystem_watcher",
|
||||
title="Rescan on filesystem change",
|
||||
description=f"Runs a scan when a change is detected in the library path, with a {RESCAN_ON_FILESYSTEM_CHANGE_DELAY} minute delay",
|
||||
enabled=ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
|
||||
manual_run=False,
|
||||
cron_string="",
|
||||
)
|
||||
)
|
||||
|
||||
return grouped_tasks
|
||||
|
||||
|
||||
@protected_route(router.get, "/{task_id}", [Scope.TASKS_RUN])
|
||||
async def get_task_by_id(request: Request, task_id: str) -> TaskStatusResponse:
|
||||
"""Get the status of a task by its job ID.
|
||||
|
||||
Args:
|
||||
request (Request): FastAPI Request object
|
||||
task_id (str): Job ID of the task to retrieve status for
|
||||
Returns:
|
||||
TaskStatusResponse: Task status information
|
||||
"""
|
||||
try:
|
||||
job = Job.fetch(task_id, connection=low_prio_queue.connection)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Task with ID '{task_id}' not found",
|
||||
) from e
|
||||
|
||||
# Convert datetime objects to ISO format strings
|
||||
queued_at = job.created_at.isoformat() if job.created_at else None
|
||||
started_at = job.started_at.isoformat() if job.started_at else None
|
||||
ended_at = job.ended_at.isoformat() if job.ended_at else None
|
||||
|
||||
# Get task name from job metadata or function name
|
||||
task_name = (
|
||||
job.meta.get("task_name") or job.func_name if job.meta else job.func_name
|
||||
)
|
||||
|
||||
return TaskStatusResponse(
|
||||
task_name=str(task_name),
|
||||
task_id=task_id,
|
||||
status=job.get_status(),
|
||||
queued_at=queued_at or "",
|
||||
started_at=started_at,
|
||||
ended_at=ended_at,
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.post, "/run", [Scope.TASKS_RUN])
|
||||
async def run_tasks(request: Request) -> MessageResponse:
|
||||
"""Run all tasks endpoint
|
||||
async def run_all_tasks(request: Request) -> list[TaskExecutionResponse]:
|
||||
"""Run all runnable tasks endpoint
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
request (Request): FastAPI Request object
|
||||
Returns:
|
||||
RunTasksResponse: Standard message response
|
||||
TaskExecutionResponse: Task execution response with details
|
||||
"""
|
||||
# Filter only runnable tasks
|
||||
runnable_tasks = {
|
||||
name: task
|
||||
for name, task in {**manual_tasks, **scheduled_tasks}.items()
|
||||
if task.enabled and task.manual_run
|
||||
}
|
||||
|
||||
await update_switch_titledb_task.run()
|
||||
return {"msg": "All tasks ran successfully!"}
|
||||
if not runnable_tasks:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No runnable tasks available to run",
|
||||
)
|
||||
|
||||
jobs = [
|
||||
(task_name, low_prio_queue.enqueue(task_instance.run))
|
||||
for task_name, task_instance in runnable_tasks.items()
|
||||
]
|
||||
|
||||
return [
|
||||
{
|
||||
"task_name": task_name,
|
||||
"task_id": job.get_id(),
|
||||
"status": job.get_status(),
|
||||
"queued_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
for (task_name, job) in jobs
|
||||
]
|
||||
|
||||
|
||||
@protected_route(router.post, "/{task}/run", [Scope.TASKS_RUN])
|
||||
async def run_task(request: Request, task: str) -> MessageResponse:
|
||||
"""Run all tasks endpoint
|
||||
@protected_route(router.post, "/run/{task_name}", [Scope.TASKS_RUN])
|
||||
async def run_single_task(request: Request, task_name: str) -> TaskExecutionResponse:
|
||||
"""Run a single task endpoint.
|
||||
|
||||
Args:
|
||||
request (Request): Fastapi Request object
|
||||
request (Request): FastAPI Request object
|
||||
task_name (str): Name of the task to run
|
||||
Returns:
|
||||
RunTasksResponse: Standard message response
|
||||
TaskExecutionResponse: Task execution response with details
|
||||
"""
|
||||
all_tasks = {**manual_tasks, **scheduled_tasks}
|
||||
|
||||
tasks = {"switch_titledb": update_switch_titledb_task}
|
||||
if task_name not in all_tasks:
|
||||
available_tasks = list(all_tasks.keys())
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Task '{task_name}' not found, available tasks are {', '.join(available_tasks)}",
|
||||
)
|
||||
|
||||
await tasks[task].run()
|
||||
return {"msg": f"Task {task} run successfully!"}
|
||||
task_instance = all_tasks[task_name]
|
||||
if not task_instance.enabled or not task_instance.manual_run:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Task '{task_name}' cannot be run",
|
||||
)
|
||||
|
||||
job = low_prio_queue.enqueue(task_instance.run)
|
||||
|
||||
return {
|
||||
"task_name": task_name,
|
||||
"task_id": job.get_id(),
|
||||
"status": job.get_status(),
|
||||
"queued_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
from utils import get_version
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
with TestClient(app) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_heartbeat(client):
|
||||
response = client.get("/api/heartbeat")
|
||||
assert response.status_code == 200
|
||||
|
||||
heartbeat = response.json()
|
||||
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")
|
||||
assert heartbeat.get("SCHEDULER").get("RESCAN").get("CRON") == "0 3 * * *"
|
||||
assert heartbeat.get("SCHEDULER").get("RESCAN").get("TITLE") == "Scheduled rescan"
|
||||
assert heartbeat.get("SCHEDULER").get("SWITCH_TITLEDB").get("ENABLED")
|
||||
assert heartbeat.get("SCHEDULER").get("SWITCH_TITLEDB").get("CRON") == "0 4 * * *"
|
||||
assert (
|
||||
heartbeat.get("SCHEDULER").get("SWITCH_TITLEDB").get("TITLE")
|
||||
== "Scheduled Switch TitleDB update"
|
||||
)
|
||||
assert heartbeat.get("FRONTEND").get("UPLOAD_TIMEOUT") == 20
|
||||
@@ -1,17 +1,14 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any
|
||||
|
||||
from anyio import open_file
|
||||
from config import ASSETS_BASE_PATH
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.forms.identity import UserForm
|
||||
from endpoints.responses import MessageResponse
|
||||
from endpoints.responses.identity import UserSchema
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from endpoints.responses.identity import InviteLinkSchema, UserSchema
|
||||
from fastapi import Body, Form, HTTPException, Request, status
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_user_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.metadata import meta_ra_handler
|
||||
from logger.logger import log
|
||||
from models.user import Role, User
|
||||
from utils.router import APIRouter
|
||||
@@ -29,7 +26,11 @@ router = APIRouter(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def add_user(
|
||||
request: Request, username: str, password: str, email: str, role: str
|
||||
request: Request,
|
||||
username: str = Body(..., embed=True),
|
||||
email: str = Body(..., embed=True),
|
||||
password: str = Body(..., embed=True),
|
||||
role: str = Body(..., embed=True),
|
||||
) -> UserSchema:
|
||||
"""Create user endpoint
|
||||
|
||||
@@ -80,6 +81,95 @@ def add_user(
|
||||
return UserSchema.model_validate(db_user_handler.add_user(user))
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post,
|
||||
"/invite-link",
|
||||
[],
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def create_invite_link(request: Request, role: str) -> InviteLinkSchema:
|
||||
"""Create an invite link for a user.
|
||||
|
||||
Args:
|
||||
request (Request): FastAPI Request object
|
||||
role (str): The role of the user
|
||||
|
||||
Returns:
|
||||
InviteLinkSchema: Invite link
|
||||
"""
|
||||
|
||||
if (
|
||||
Scope.USERS_WRITE not in request.auth.scopes
|
||||
and len(db_user_handler.get_admin_users()) > 0
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Forbidden",
|
||||
)
|
||||
|
||||
if role not in [r.value for r in Role]:
|
||||
msg = f"Role {role} is not valid"
|
||||
log.error(msg)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=msg,
|
||||
)
|
||||
|
||||
token = auth_handler.generate_invite_link_token(request.user, role=role)
|
||||
return InviteLinkSchema.model_validate({"token": token})
|
||||
|
||||
|
||||
@router.post("/register", status_code=status.HTTP_201_CREATED)
|
||||
def create_user_from_invite(
|
||||
username: str = Body(..., embed=True),
|
||||
email: str = Body(..., embed=True),
|
||||
password: str = Body(..., embed=True),
|
||||
token: str = Body(..., embed=True),
|
||||
) -> UserSchema:
|
||||
"""Create user endpoint with invite link
|
||||
|
||||
Args:
|
||||
username (str): User username
|
||||
email (str): User email
|
||||
password (str): User password
|
||||
token (str): Invite link token
|
||||
|
||||
Returns:
|
||||
UserSchema: Newly created user
|
||||
"""
|
||||
|
||||
jti, role = auth_handler.verify_invite_link_token(token)
|
||||
|
||||
if db_user_handler.get_user_by_username(username):
|
||||
msg = f"Username {username} already exists"
|
||||
log.error(msg)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=msg,
|
||||
)
|
||||
|
||||
if email and db_user_handler.get_user_by_email(email):
|
||||
msg = f"User with email {email} already exists"
|
||||
log.error(msg)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=msg,
|
||||
)
|
||||
|
||||
user = User(
|
||||
username=username.lower(),
|
||||
hashed_password=auth_handler.get_password_hash(password),
|
||||
email=email.lower() or None,
|
||||
role=Role[role.upper()],
|
||||
)
|
||||
|
||||
created_user = db_user_handler.add_user(user)
|
||||
|
||||
auth_handler.invalidate_invite_link_token(jti)
|
||||
|
||||
return UserSchema.model_validate(created_user)
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.USERS_READ])
|
||||
def get_users(request: Request) -> list[UserSchema]:
|
||||
"""Get all users endpoint
|
||||
@@ -128,7 +218,7 @@ def get_user(request: Request, id: int) -> UserSchema:
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.ME_WRITE])
|
||||
async def update_user(
|
||||
request: Request, id: int, form_data: Annotated[UserForm, Depends()]
|
||||
request: Request, id: int, form_data: Annotated[UserForm, Form()]
|
||||
) -> UserSchema:
|
||||
"""Update user endpoint
|
||||
|
||||
@@ -192,17 +282,19 @@ async def update_user(
|
||||
if form_data.enabled is not None and request.user.id != id:
|
||||
cleaned_data["enabled"] = form_data.enabled # type: ignore[assignment]
|
||||
|
||||
if form_data.avatar is not None:
|
||||
if form_data.ra_username:
|
||||
cleaned_data["ra_username"] = form_data.ra_username # type: ignore[assignment]
|
||||
|
||||
if form_data.avatar is not None and form_data.avatar.filename is not None:
|
||||
user_avatar_path = fs_asset_handler.build_avatar_path(user=db_user)
|
||||
file_location = f"{user_avatar_path}/{form_data.avatar.filename}"
|
||||
cleaned_data["avatar_path"] = file_location
|
||||
Path(f"{ASSETS_BASE_PATH}/{user_avatar_path}").mkdir(
|
||||
parents=True, exist_ok=True
|
||||
file_extension = form_data.avatar.filename.split(".")[-1]
|
||||
file_name = f"avatar.{file_extension}"
|
||||
|
||||
await fs_asset_handler.write_file(
|
||||
file=form_data.avatar.file, path=user_avatar_path, filename=file_name
|
||||
)
|
||||
async with await open_file(
|
||||
f"{ASSETS_BASE_PATH}/{file_location}", "wb+"
|
||||
) as file_object:
|
||||
await file_object.write(form_data.avatar.file.read())
|
||||
file_location = f"{user_avatar_path}/{file_name}"
|
||||
cleaned_data["avatar_path"] = file_location
|
||||
|
||||
if cleaned_data:
|
||||
db_user_handler.update_user(id, cleaned_data)
|
||||
@@ -224,7 +316,7 @@ async def update_user(
|
||||
|
||||
|
||||
@protected_route(router.delete, "/{id}", [Scope.USERS_WRITE])
|
||||
def delete_user(request: Request, id: int) -> MessageResponse:
|
||||
async def delete_user(request: Request, id: int) -> None:
|
||||
"""Delete user endpoint
|
||||
|
||||
Args:
|
||||
@@ -235,9 +327,6 @@ def delete_user(request: Request, id: int) -> MessageResponse:
|
||||
HTTPException: User is not found in database
|
||||
HTTPException: User deleting itself
|
||||
HTTPException: User is the last admin user
|
||||
|
||||
Returns:
|
||||
MessageResponse: Standard message response
|
||||
"""
|
||||
|
||||
user = db_user_handler.get_user(id)
|
||||
@@ -256,4 +345,42 @@ def delete_user(request: Request, id: int) -> MessageResponse:
|
||||
|
||||
db_user_handler.delete_user(id)
|
||||
|
||||
return {"msg": "User successfully deleted"}
|
||||
# Remove the user's folder
|
||||
user_avatar_path = fs_asset_handler.build_avatar_path(user=user)
|
||||
try:
|
||||
await fs_asset_handler.remove_directory(user_avatar_path)
|
||||
except FileNotFoundError:
|
||||
log.warning(f"Couldn't find avatar directory to delete for {user.username}")
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post, "/{id}/ra/refresh", [Scope.ME_WRITE], status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def refresh_retro_achievements(request: Request, id: int) -> None:
|
||||
"""Refresh RetroAchievements data for a user.
|
||||
|
||||
Args:
|
||||
request (Request): FastAPI Request object
|
||||
id (int): User ID
|
||||
|
||||
Raises:
|
||||
HTTPException: User not found or no RetroAchievements username set
|
||||
|
||||
Returns:
|
||||
None: Returns 200 OK status
|
||||
"""
|
||||
user = db_user_handler.get_user(id)
|
||||
if user and user.ra_username:
|
||||
user_progression = await meta_ra_handler.get_user_progression(user.ra_username)
|
||||
db_user_handler.update_user(
|
||||
id,
|
||||
{
|
||||
"ra_progression": user_progression,
|
||||
},
|
||||
)
|
||||
return None
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="User does not have a RetroAchievements username set",
|
||||
)
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
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",
|
||||
|
||||
@@ -6,7 +6,6 @@ class PlatformNotFoundInDatabaseException(Exception):
|
||||
def __init__(self, id):
|
||||
self.message = f"Platform with id '{id}' not found"
|
||||
super().__init__(self.message)
|
||||
log.critical(self.message)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -17,7 +16,6 @@ class RomNotFoundInDatabaseException(Exception):
|
||||
def __init__(self, id):
|
||||
self.message = f"Rom with id '{id}' not found"
|
||||
super().__init__(self.message)
|
||||
log.critical(self.message)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -28,7 +26,6 @@ class CollectionNotFoundInDatabaseException(Exception):
|
||||
def __init__(self, id):
|
||||
self.message = f"Collection with id '{id}' not found"
|
||||
super().__init__(self.message)
|
||||
log.critical(self.message)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -39,7 +36,6 @@ class CollectionPermissionError(Exception):
|
||||
def __init__(self, id):
|
||||
self.message = f"Permission denied for collection with id '{id}'"
|
||||
super().__init__(self.message)
|
||||
log.critical(self.message)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -57,3 +53,23 @@ class CollectionAlreadyExistsException(Exception):
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.message
|
||||
|
||||
|
||||
class RomNotFoundInRetroAchievementsException(Exception):
|
||||
def __init__(self, id):
|
||||
self.message = f"Rom with id '{id}' does not exist on RetroAchievements"
|
||||
super().__init__(self.message)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
|
||||
|
||||
|
||||
class SGDBInvalidAPIKeyException(Exception):
|
||||
def __init__(self):
|
||||
self.message = "Invalid SGDB API key"
|
||||
super().__init__(self.message)
|
||||
log.critical(self.message)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail=self.message
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.message
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
|
||||
folder_struct_msg = "Check RomM folder structure here: https://github.com/rommapp/romm?tab=readme-ov-file#folder-structure"
|
||||
|
||||
|
||||
@@ -30,7 +33,7 @@ class PlatformAlreadyExistsException(Exception):
|
||||
|
||||
class RomsNotFoundException(Exception):
|
||||
def __init__(self, platform: str):
|
||||
self.message = f"Roms not found for platform {platform}. {folder_struct_msg}"
|
||||
self.message = f"Roms not found for platform {hl(platform, color=BLUE)}. {folder_struct_msg}"
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self):
|
||||
@@ -39,7 +42,7 @@ class RomsNotFoundException(Exception):
|
||||
|
||||
class RomAlreadyExistsException(Exception):
|
||||
def __init__(self, rom_name: str):
|
||||
self.message = f"Can't rename: {rom_name} already exists"
|
||||
self.message = f"Can't rename: {hl(rom_name)} already exists"
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self):
|
||||
@@ -48,18 +51,7 @@ class RomAlreadyExistsException(Exception):
|
||||
|
||||
class FirmwareNotFoundException(Exception):
|
||||
def __init__(self, platform: str):
|
||||
self.message = (
|
||||
f"Firmware not found for platform {platform}. {folder_struct_msg}"
|
||||
)
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self):
|
||||
return self.message
|
||||
|
||||
|
||||
class FirmwareAlreadyExistsException(Exception):
|
||||
def __init__(self, firmware_name: str):
|
||||
self.message = f"Can't rename: {firmware_name} already exists"
|
||||
self.message = f"Firmware not found for platform {hl(platform, color=BLUE)}. {folder_struct_msg}"
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
@@ -2,14 +2,17 @@ import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY
|
||||
from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY, ROMM_BASE_URL
|
||||
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 handler.auth.constants import ALGORITHM, DEFAULT_OAUTH_TOKEN_EXPIRY, TokenPurpose
|
||||
from handler.redis_handler import redis_client
|
||||
from joserfc import jwt
|
||||
from joserfc.errors import BadSignatureError
|
||||
from joserfc.errors import BadSignatureError, DecodeError
|
||||
from joserfc.jwk import OctKey
|
||||
from logger.formatter import CYAN
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from passlib.context import CryptContext
|
||||
from starlette.requests import HTTPConnection
|
||||
@@ -18,6 +21,8 @@ from starlette.requests import HTTPConnection
|
||||
class AuthHandler:
|
||||
def __init__(self) -> None:
|
||||
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
self.reset_passwd_token_expires_in_minutes = 10
|
||||
self.invite_link_token_expires_in_minutes = 10
|
||||
|
||||
def verify_password(self, plain_password, hashed_password):
|
||||
return self.pwd_context.verify(plain_password, hashed_password)
|
||||
@@ -54,13 +59,173 @@ class AuthHandler:
|
||||
conn.session.clear()
|
||||
log.error(
|
||||
"User '%s' %s",
|
||||
username,
|
||||
hl(username, color=CYAN),
|
||||
"not found" if user is None else "not enabled",
|
||||
)
|
||||
return None
|
||||
|
||||
return user
|
||||
|
||||
def generate_password_reset_token(self, user: Any) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
jti = str(uuid.uuid4())
|
||||
|
||||
to_encode = {
|
||||
"sub": user.username,
|
||||
"email": user.email,
|
||||
"type": TokenPurpose.RESET,
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int(
|
||||
(
|
||||
now + timedelta(minutes=self.reset_passwd_token_expires_in_minutes)
|
||||
).timestamp()
|
||||
),
|
||||
"jti": jti,
|
||||
}
|
||||
token = jwt.encode(
|
||||
{"alg": ALGORITHM}, to_encode, OctKey.import_key(ROMM_AUTH_SECRET_KEY)
|
||||
)
|
||||
log.info(
|
||||
f"Reset password link requested for {hl(user.username, color=CYAN)}. Reset link: {hl(f'{ROMM_BASE_URL}/reset-password?token={token}')}"
|
||||
)
|
||||
redis_client.setex(
|
||||
f"reset-jti:{jti}", self.reset_passwd_token_expires_in_minutes * 60, "valid"
|
||||
)
|
||||
|
||||
def verify_password_reset_token(self, token: str) -> Any:
|
||||
"""Verify the password reset token.
|
||||
|
||||
Args:
|
||||
token (str): The token to verify.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the token is invalid or expired.
|
||||
HTTPException: If the token is missing or malformed.
|
||||
HTTPException: If the user is not found.
|
||||
HTTPException: If the token is not for password reset.
|
||||
"""
|
||||
from handler.database import db_user_handler
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, ROMM_AUTH_SECRET_KEY, algorithms=[ALGORITHM])
|
||||
except (BadSignatureError, DecodeError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid token") from exc
|
||||
|
||||
if payload.claims.get("type") != TokenPurpose.RESET:
|
||||
raise HTTPException(status_code=400, detail="Invalid token purpose")
|
||||
|
||||
username = payload.claims.get("sub")
|
||||
jti = payload.claims.get("jti")
|
||||
if not username or not jti:
|
||||
raise HTTPException(status_code=400, detail="Invalid token payload")
|
||||
|
||||
# Check JTI in Redis
|
||||
redis_jti_key = f"reset-jti:{jti}"
|
||||
if not redis_client.exists(redis_jti_key):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="This token has already been used or is invalid"
|
||||
)
|
||||
|
||||
# Delete it to enforce one-time use
|
||||
redis_client.delete(redis_jti_key)
|
||||
|
||||
user = db_user_handler.get_user_by_username(username)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
now = datetime.now(timezone.utc).timestamp()
|
||||
if now > payload.claims.get("exp"):
|
||||
raise HTTPException(status_code=400, detail="Token has expired")
|
||||
|
||||
return user
|
||||
|
||||
def set_user_new_password(self, user: Any, new_password: str) -> None:
|
||||
"""
|
||||
Set the new password for the user.
|
||||
Args:
|
||||
user (Any): The user object.
|
||||
new_password (str): The new password to set.
|
||||
"""
|
||||
from handler.database import db_user_handler
|
||||
|
||||
db_user_handler.update_user(
|
||||
user.id, {"hashed_password": self.get_password_hash(new_password)}
|
||||
)
|
||||
|
||||
def generate_invite_link_token(self, user: Any, role: str) -> str:
|
||||
"""
|
||||
Generate an invite link token for the user.
|
||||
Args:
|
||||
user (Any): The user object.
|
||||
role (str): The role of the user.
|
||||
Returns:
|
||||
str: The generated invite link token.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
jti = str(uuid.uuid4())
|
||||
|
||||
to_encode = {
|
||||
"sub": user.username,
|
||||
"type": TokenPurpose.INVITE,
|
||||
"role": role.upper(),
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int(
|
||||
(
|
||||
now + timedelta(minutes=self.invite_link_token_expires_in_minutes)
|
||||
).timestamp()
|
||||
),
|
||||
"jti": jti,
|
||||
}
|
||||
token = jwt.encode(
|
||||
{"alg": ALGORITHM}, to_encode, OctKey.import_key(ROMM_AUTH_SECRET_KEY)
|
||||
)
|
||||
invite_link = f"{ROMM_BASE_URL}/register?token={token}"
|
||||
log.info(
|
||||
f"Invite link created by {hl(user.username, color=CYAN)}: {hl(invite_link)}"
|
||||
)
|
||||
redis_client.setex(
|
||||
f"invite-jti:{jti}", self.invite_link_token_expires_in_minutes * 60, "valid"
|
||||
)
|
||||
return token
|
||||
|
||||
def verify_invite_link_token(self, token: str) -> tuple[str, str]:
|
||||
"""
|
||||
Verify the invite link token.
|
||||
Args:
|
||||
token (str): The token to verify.
|
||||
Returns:
|
||||
str: The JTI (JWT ID) of the token.
|
||||
"""
|
||||
try:
|
||||
payload = jwt.decode(token, OctKey.import_key(ROMM_AUTH_SECRET_KEY))
|
||||
except (BadSignatureError, DecodeError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid token") from exc
|
||||
|
||||
if payload.claims.get("type") != TokenPurpose.INVITE:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid token type.",
|
||||
)
|
||||
|
||||
jti = payload.claims.get("jti")
|
||||
role = payload.claims.get("role", "USER").upper()
|
||||
if not jti or redis_client.get(f"invite-jti:{jti}") != b"valid":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invite token has already been used or is invalid.",
|
||||
)
|
||||
return jti, role
|
||||
|
||||
def invalidate_invite_link_token(self, jti: str) -> None:
|
||||
"""
|
||||
Invalidate the invite link token.
|
||||
Args:
|
||||
jti (str): The JTI (JWT ID) of the token to invalidate.
|
||||
"""
|
||||
redis_client.delete(f"invite-jti:{jti}")
|
||||
|
||||
|
||||
class OAuthHandler:
|
||||
def __init__(self) -> None:
|
||||
@@ -82,7 +247,7 @@ class OAuthHandler:
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, OctKey.import_key(ROMM_AUTH_SECRET_KEY))
|
||||
except (BadSignatureError, ValueError) as exc:
|
||||
except (BadSignatureError, DecodeError, ValueError) as exc:
|
||||
raise OAuthCredentialsException from exc
|
||||
|
||||
issuer = payload.claims.get("iss")
|
||||
@@ -148,18 +313,21 @@ class OpenIDHandler:
|
||||
|
||||
user = db_user_handler.get_user_by_email(email)
|
||||
if user is None:
|
||||
log.info("User with email '%s' not found, creating new user", email)
|
||||
user = User(
|
||||
log.info(
|
||||
"User with email '%s' not found, creating new user",
|
||||
hl(email, color=CYAN),
|
||||
)
|
||||
new_user = User(
|
||||
username=preferred_username,
|
||||
hashed_password=str(uuid.uuid4()),
|
||||
email=email,
|
||||
enabled=True,
|
||||
role=Role.VIEWER,
|
||||
)
|
||||
db_user_handler.add_user(user)
|
||||
user = db_user_handler.add_user(new_user)
|
||||
|
||||
if not user.enabled:
|
||||
raise UserDisabledException
|
||||
|
||||
log.info("User successfully authenticated: %s", email)
|
||||
log.info("User successfully authenticated: %s", hl(email, color=CYAN))
|
||||
return user, userinfo
|
||||
|
||||
@@ -59,3 +59,8 @@ READ_SCOPES: Final = list(READ_SCOPES_MAP.keys())
|
||||
WRITE_SCOPES: Final = READ_SCOPES + list(WRITE_SCOPES_MAP.keys())
|
||||
EDIT_SCOPES: Final = WRITE_SCOPES + list(EDIT_SCOPES_MAP.keys())
|
||||
FULL_SCOPES: Final = EDIT_SCOPES + list(FULL_SCOPES_MAP.keys())
|
||||
|
||||
|
||||
class TokenPurpose(enum.StrEnum):
|
||||
INVITE = "invite"
|
||||
RESET = "reset"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import time
|
||||
from collections import namedtuple
|
||||
|
||||
from config import SESSION_MAX_AGE_SECONDS
|
||||
from joserfc import jwt
|
||||
from joserfc.errors import BadSignatureError
|
||||
from joserfc.jwk import OctKey
|
||||
@@ -15,7 +16,7 @@ class CustomCSRFMiddleware(CSRFMiddleware):
|
||||
# Skip CSRF check if not an HTTP request, like websockets
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
return None
|
||||
|
||||
request = Request(scope, receive)
|
||||
|
||||
@@ -23,7 +24,7 @@ class CustomCSRFMiddleware(CSRFMiddleware):
|
||||
auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower()
|
||||
if auth_scheme == "bearer" or auth_scheme == "basic":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
return None
|
||||
|
||||
await super().__call__(scope, receive, send)
|
||||
|
||||
@@ -37,7 +38,7 @@ class SessionMiddleware:
|
||||
app: ASGIApp,
|
||||
secret_key: str | Secret | SecretKey,
|
||||
session_cookie: str = "session",
|
||||
max_age: int = 14 * 24 * 60 * 60, # 14 days, in seconds
|
||||
max_age: int = SESSION_MAX_AGE_SECONDS,
|
||||
same_site: str = "lax",
|
||||
https_only: bool = False,
|
||||
jwt_alg: str = "HS256",
|
||||
@@ -66,8 +67,10 @@ class SessionMiddleware:
|
||||
)
|
||||
),
|
||||
)
|
||||
assert token.claims == {"1": 2}, "wrong crypto setup"
|
||||
assert token.header == {"typ": "JWT", "alg": jwt_alg}, "wrong crypto setup"
|
||||
if token.claims != {"1": 2} or token.header != {"typ": "JWT", "alg": jwt_alg}:
|
||||
raise ValueError(
|
||||
"Invalid crypto setup, check your secret key and algorithm configuration"
|
||||
)
|
||||
|
||||
self.session_cookie = session_cookie
|
||||
self.max_age = max_age
|
||||
@@ -94,7 +97,7 @@ class SessionMiddleware:
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] not in ("http", "websocket"): # pragma: no cover
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
return None
|
||||
|
||||
connection = HTTPConnection(scope)
|
||||
initial_session_was_empty = True
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
from handler.tests.conftest import ( # noqa
|
||||
admin_user,
|
||||
clear_database,
|
||||
editor_user,
|
||||
setup_database,
|
||||
viewer_user,
|
||||
)
|
||||
@@ -1,9 +1,30 @@
|
||||
import time
|
||||
|
||||
from config import DEV_SQL_ECHO
|
||||
from config.config_manager import ConfigManager
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
sync_engine = create_engine(ConfigManager.get_db_engine(), pool_pre_ping=True)
|
||||
sync_engine = create_engine(
|
||||
ConfigManager.get_db_engine(), pool_pre_ping=True, echo=DEV_SQL_ECHO
|
||||
)
|
||||
sync_session = sessionmaker(bind=sync_engine, expire_on_commit=False)
|
||||
|
||||
|
||||
if DEV_SQL_ECHO:
|
||||
|
||||
@event.listens_for(sync_engine, "before_cursor_execute")
|
||||
def before_cursor_execute(
|
||||
conn, cursor, statement, parameters, context, executemany
|
||||
):
|
||||
context._query_start_time = time.time()
|
||||
print(f"SQL: {statement}")
|
||||
print(f"Parameters: {parameters}")
|
||||
|
||||
@event.listens_for(sync_engine, "after_cursor_execute")
|
||||
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
total_time = time.time() - context._query_start_time
|
||||
print(f"Execution time: {total_time:.4f} seconds")
|
||||
|
||||
|
||||
class DBBaseHandler: ...
|
||||
|
||||
@@ -1,73 +1,72 @@
|
||||
from typing import Sequence
|
||||
import functools
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import Collection, CollectionRom, VirtualCollection
|
||||
from models.collection import (
|
||||
Collection,
|
||||
CollectionRom,
|
||||
SmartCollection,
|
||||
VirtualCollection,
|
||||
)
|
||||
from models.rom import Rom
|
||||
from sqlalchemy import delete, insert, literal, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Query, Session, selectinload
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def with_roms(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
kwargs["query"] = select(Collection).options(
|
||||
selectinload(Collection.roms),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class DBCollectionsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
@with_roms
|
||||
def add_collection(
|
||||
self, collection: Collection, session: Session = None
|
||||
self, collection: Collection, query: Query = None, session: Session = None
|
||||
) -> Collection:
|
||||
collection = session.merge(collection)
|
||||
session.flush()
|
||||
|
||||
return session.query(Collection).filter_by(id=collection.id).one()
|
||||
return session.scalar(query.filter_by(id=collection.id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_collection(self, id: int, session: Session = None) -> Collection | None:
|
||||
return session.scalar(select(Collection).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_virtual_collection(
|
||||
self, id: str, session: Session = None
|
||||
) -> VirtualCollection | None:
|
||||
name, type = VirtualCollection.from_id(id)
|
||||
return session.scalar(
|
||||
select(VirtualCollection).filter_by(name=name, type=type).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_collection_by_name(
|
||||
self, name: str, user_id: int, session: Session = None
|
||||
@with_roms
|
||||
def get_collection(
|
||||
self, id: int, query: Query = None, session: Session = None
|
||||
) -> Collection | None:
|
||||
return session.scalar(
|
||||
select(Collection).filter_by(name=name, user_id=user_id).limit(1)
|
||||
)
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_collections(self, session: Session = None) -> Sequence[Collection]:
|
||||
return (
|
||||
session.scalars(select(Collection).order_by(Collection.name.asc()))
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
@with_roms
|
||||
def get_collection_by_name(
|
||||
self, name: str, user_id: int, query: Query = None, session: Session = None
|
||||
) -> Collection | None:
|
||||
return session.scalar(query.filter_by(name=name, user_id=user_id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_virtual_collections(
|
||||
self, type: str, limit: int | None = None, session: Session = None
|
||||
) -> Sequence[VirtualCollection]:
|
||||
return (
|
||||
session.scalars(
|
||||
select(VirtualCollection)
|
||||
.filter(or_(VirtualCollection.type == type, literal(type == "all")))
|
||||
.limit(limit)
|
||||
.order_by(VirtualCollection.name.asc())
|
||||
)
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
@with_roms
|
||||
def get_collections(
|
||||
self, query: Query = None, session: Session = None
|
||||
) -> Sequence[Collection]:
|
||||
return session.scalars(query.order_by(Collection.name.asc())).unique().all()
|
||||
|
||||
@begin_session
|
||||
@with_roms
|
||||
def update_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict,
|
||||
rom_ids: list[int] | None = None,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> Collection:
|
||||
session.execute(
|
||||
@@ -92,7 +91,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
],
|
||||
)
|
||||
|
||||
return session.query(Collection).filter_by(id=id).one()
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def delete_collection(self, id: int, session: Session = None) -> None:
|
||||
@@ -101,3 +100,125 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
.where(Collection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
# Virtual collections
|
||||
@begin_session
|
||||
def get_virtual_collection(
|
||||
self, id: str, session: Session = None
|
||||
) -> VirtualCollection | None:
|
||||
name, type = VirtualCollection.from_id(id)
|
||||
return session.scalar(
|
||||
select(VirtualCollection).filter_by(name=name, type=type).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_virtual_collections(
|
||||
self, type: str, limit: int | None = None, session: Session = None
|
||||
) -> Sequence[VirtualCollection]:
|
||||
return (
|
||||
session.scalars(
|
||||
select(VirtualCollection)
|
||||
.filter(or_(VirtualCollection.type == type, literal(type == "all")))
|
||||
.limit(limit)
|
||||
.order_by(VirtualCollection.name.asc())
|
||||
)
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
|
||||
# Smart collections
|
||||
@begin_session
|
||||
def add_smart_collection(
|
||||
self, smart_collection: SmartCollection, session: Session = None
|
||||
) -> SmartCollection:
|
||||
smart_collection = session.merge(smart_collection)
|
||||
session.flush()
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=smart_collection.id).one()
|
||||
|
||||
@begin_session
|
||||
def get_smart_collection(
|
||||
self, id: int, session: Session = None
|
||||
) -> SmartCollection | None:
|
||||
return session.scalar(select(SmartCollection).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_smart_collection_by_name(
|
||||
self, name: str, user_id: int, session: Session = None
|
||||
) -> SmartCollection | None:
|
||||
return session.scalar(
|
||||
select(SmartCollection).filter_by(name=name, user_id=user_id).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_smart_collections(
|
||||
self, user_id: int | None = None, session: Session = None
|
||||
) -> Sequence[SmartCollection]:
|
||||
query = select(SmartCollection).order_by(SmartCollection.name.asc())
|
||||
|
||||
if user_id is not None:
|
||||
# Get user's smart collections and public ones
|
||||
query = query.filter(
|
||||
(SmartCollection.user_id == user_id) | SmartCollection.is_public
|
||||
)
|
||||
|
||||
return session.scalars(query).unique().all()
|
||||
|
||||
@begin_session
|
||||
def update_smart_collection(
|
||||
self,
|
||||
id: int,
|
||||
data: dict[str, Any],
|
||||
session: Session = None,
|
||||
) -> SmartCollection:
|
||||
session.execute(
|
||||
update(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
return session.query(SmartCollection).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def delete_smart_collection(self, id: int, session: Session = None) -> None:
|
||||
session.execute(
|
||||
delete(SmartCollection)
|
||||
.where(SmartCollection.id == id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
def get_smart_collection_roms(
|
||||
self, smart_collection: SmartCollection, user_id: int | None = None
|
||||
) -> Sequence["Rom"]:
|
||||
"""Get ROMs that match the smart collection's filter criteria."""
|
||||
from handler.database import db_rom_handler
|
||||
|
||||
# Extract filter criteria
|
||||
criteria = smart_collection.filter_criteria
|
||||
|
||||
# Use the existing filter_roms method with the stored criteria
|
||||
return db_rom_handler.get_roms_scalar(
|
||||
platform_id=criteria.get("platform_id"),
|
||||
collection_id=criteria.get("collection_id"),
|
||||
virtual_collection_id=criteria.get("virtual_collection_id"),
|
||||
search_term=criteria.get("search_term"),
|
||||
matched=criteria.get("matched"),
|
||||
favourite=criteria.get("favourite"),
|
||||
duplicate=criteria.get("duplicate"),
|
||||
playable=criteria.get("playable"),
|
||||
has_ra=criteria.get("has_ra"),
|
||||
missing=criteria.get("missing"),
|
||||
verified=criteria.get("verified"),
|
||||
selected_genre=criteria.get("selected_genre"),
|
||||
selected_franchise=criteria.get("selected_franchise"),
|
||||
selected_collection=criteria.get("selected_collection"),
|
||||
selected_company=criteria.get("selected_company"),
|
||||
selected_age_rating=criteria.get("selected_age_rating"),
|
||||
selected_status=criteria.get("selected_status"),
|
||||
selected_region=criteria.get("selected_region"),
|
||||
selected_language=criteria.get("selected_language"),
|
||||
user_id=user_id,
|
||||
order_by=criteria.get("order_by", "name"),
|
||||
order_dir=criteria.get("order_dir", "asc"),
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Sequence
|
||||
from collections.abc import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.firmware import Firmware
|
||||
@@ -29,11 +29,12 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
platform_id: int | None = None,
|
||||
session: Session = None,
|
||||
) -> Sequence[Firmware]:
|
||||
return session.scalars(
|
||||
select(Firmware)
|
||||
.filter_by(platform_id=platform_id)
|
||||
.order_by(Firmware.file_name.asc())
|
||||
).all()
|
||||
query = select(Firmware).order_by(Firmware.file_name.asc())
|
||||
|
||||
if platform_id:
|
||||
query = query.filter_by(platform_id=platform_id)
|
||||
|
||||
return session.scalars(query).all()
|
||||
|
||||
@begin_session
|
||||
def get_firmware_by_filename(
|
||||
@@ -64,10 +65,10 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def purge_firmware(
|
||||
def mark_missing_firmware(
|
||||
self, platform_id: int, fs_firmwares_to_keep: list[str], session: Session = None
|
||||
) -> Sequence[Firmware]:
|
||||
purged_firmware = (
|
||||
missing_firmware = (
|
||||
session.scalars(
|
||||
select(Firmware)
|
||||
.order_by(Firmware.file_name.asc())
|
||||
@@ -82,13 +83,14 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
.all()
|
||||
)
|
||||
session.execute(
|
||||
delete(Firmware)
|
||||
update(Firmware)
|
||||
.where(
|
||||
and_(
|
||||
Firmware.platform_id == platform_id,
|
||||
Firmware.file_name.not_in(fs_firmwares_to_keep),
|
||||
)
|
||||
)
|
||||
.values(**{"missing_from_fs": True})
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return purged_firmware
|
||||
return missing_firmware
|
||||
|
||||
@@ -1,43 +1,70 @@
|
||||
from typing import Sequence
|
||||
import functools
|
||||
from collections.abc import Sequence
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from sqlalchemy import delete, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import delete, or_, select, update
|
||||
from sqlalchemy.orm import Query, Session, selectinload
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def with_firmware(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
kwargs["query"] = select(Platform).options(
|
||||
selectinload(Platform.firmware),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class DBPlatformsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
@with_firmware
|
||||
def add_platform(
|
||||
self,
|
||||
platform: Platform,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> Platform:
|
||||
platform = session.merge(platform)
|
||||
session.flush()
|
||||
|
||||
return session.query(Platform).filter_by(id=platform.id).one()
|
||||
return session.scalar(query.filter_by(id=platform.id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_platform(self, id: int, *, session: Session = None) -> Platform | None:
|
||||
return session.scalar(select(Platform).filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
def get_platforms(self, *, session: Session = None) -> Sequence[Platform]:
|
||||
return (
|
||||
session.scalars(select(Platform).order_by(Platform.name.asc()))
|
||||
.unique()
|
||||
.all()
|
||||
def update_platform(self, id: int, data: dict, session: Session = None) -> Platform:
|
||||
session.execute(
|
||||
update(Platform)
|
||||
.where(Platform.id == id)
|
||||
.values(**data)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return session.query(Platform).filter_by(id=id).one()
|
||||
|
||||
@begin_session
|
||||
def get_platform_by_fs_slug(
|
||||
self, fs_slug: str, session: Session = None
|
||||
@with_firmware
|
||||
def get_platform(
|
||||
self, id: int, query: Query = None, session: Session = None
|
||||
) -> Platform | None:
|
||||
return session.scalar(select(Platform).filter_by(fs_slug=fs_slug).limit(1))
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_firmware
|
||||
def get_platforms(
|
||||
self, query: Query = None, session: Session = None
|
||||
) -> Sequence[Platform]:
|
||||
return session.scalars(query.order_by(Platform.name.asc())).unique().all()
|
||||
|
||||
@begin_session
|
||||
@with_firmware
|
||||
def get_platform_by_fs_slug(
|
||||
self, fs_slug: str, query: Query = None, session: Session = None
|
||||
) -> Platform | None:
|
||||
return session.scalar(query.filter_by(fs_slug=fs_slug).limit(1))
|
||||
|
||||
@begin_session
|
||||
def delete_platform(self, id: int, session: Session = None) -> None:
|
||||
@@ -55,10 +82,13 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def purge_platforms(
|
||||
self, fs_platforms_to_keep: list[str], session: Session = None
|
||||
def mark_missing_platforms(
|
||||
self,
|
||||
fs_platforms_to_keep: list[str],
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> Sequence[Platform]:
|
||||
purged_platforms = (
|
||||
missing_platforms = (
|
||||
session.scalars(
|
||||
select(Platform)
|
||||
.order_by(Platform.name.asc())
|
||||
@@ -73,8 +103,16 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
.all()
|
||||
)
|
||||
session.execute(
|
||||
delete(Platform)
|
||||
update(Platform)
|
||||
.where(or_(Platform.fs_slug.not_in(fs_platforms_to_keep), Platform.slug.is_(None))) # type: ignore[attr-defined]
|
||||
.values(**{"missing_from_fs": True})
|
||||
.execution_options(synchronize_session="fetch")
|
||||
)
|
||||
return purged_platforms
|
||||
|
||||
session.execute(
|
||||
update(Rom)
|
||||
.where(Rom.platform_id.in_([p.id for p in missing_platforms])) # type: ignore[attr-defined]
|
||||
.values(**{"missing_from_fs": True})
|
||||
.execution_options(synchronize_session="fetch")
|
||||
)
|
||||
return missing_platforms
|
||||
|
||||
@@ -1,31 +1,95 @@
|
||||
import functools
|
||||
from collections.abc import Iterable
|
||||
from typing import Sequence
|
||||
from collections.abc import Iterable, Sequence
|
||||
from typing import Any
|
||||
|
||||
from config import ROMM_DB_DRIVER
|
||||
from decorators.database import begin_session
|
||||
from models.collection import Collection, VirtualCollection
|
||||
from models.rom import Rom, RomFile, RomUser
|
||||
from sqlalchemy import and_, delete, func, or_, select, update
|
||||
from handler.metadata.base_hander import UniversalPlatformSlug as UPS
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile, RomMetadata, RomUser
|
||||
from sqlalchemy import (
|
||||
Integer,
|
||||
Row,
|
||||
String,
|
||||
Text,
|
||||
and_,
|
||||
cast,
|
||||
delete,
|
||||
false,
|
||||
func,
|
||||
literal,
|
||||
not_,
|
||||
or_,
|
||||
select,
|
||||
text,
|
||||
update,
|
||||
)
|
||||
from sqlalchemy.orm import Query, Session, selectinload
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
EJS_SUPPORTED_PLATFORMS = [
|
||||
UPS._3DO,
|
||||
UPS.AMIGA,
|
||||
UPS.AMIGA_CD,
|
||||
UPS.AMIGA_CD32,
|
||||
UPS.ARCADE,
|
||||
UPS.NEOGEOAES,
|
||||
UPS.NEOGEOMVS,
|
||||
UPS.ATARI2600,
|
||||
UPS.ATARI5200,
|
||||
UPS.ATARI7800,
|
||||
UPS.C_PLUS_4,
|
||||
UPS.C64,
|
||||
UPS.CPET,
|
||||
UPS.C64,
|
||||
UPS.C128,
|
||||
UPS.COLECOVISION,
|
||||
UPS.JAGUAR,
|
||||
UPS.LYNX,
|
||||
UPS.NEO_GEO_POCKET,
|
||||
UPS.NEO_GEO_POCKET_COLOR,
|
||||
UPS.NES,
|
||||
UPS.FAMICOM,
|
||||
UPS.FDS,
|
||||
UPS.N64,
|
||||
UPS.N64DD,
|
||||
UPS.NDS,
|
||||
UPS.NINTENDO_DSI,
|
||||
UPS.GB,
|
||||
UPS.GBA,
|
||||
UPS.PC_FX,
|
||||
UPS.PHILIPS_CD_I,
|
||||
UPS.PSX,
|
||||
UPS.PSP,
|
||||
UPS.SEGACD,
|
||||
UPS.GENESIS,
|
||||
UPS.SMS,
|
||||
UPS.GAMEGEAR,
|
||||
UPS.SATURN,
|
||||
UPS.SNES,
|
||||
UPS.SFAM,
|
||||
UPS.TG16,
|
||||
UPS.VIC_20,
|
||||
UPS.VIRTUALBOY,
|
||||
UPS.WONDERSWAN,
|
||||
UPS.WONDERSWAN_COLOR,
|
||||
]
|
||||
|
||||
STRIP_ARTICLES_REGEX = r"^(the|a|an)\s+"
|
||||
|
||||
|
||||
def with_details(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
session = kwargs.get("session")
|
||||
if session is None:
|
||||
raise TypeError(
|
||||
f"{func} is missing required kwarg 'session' with type 'Session'"
|
||||
)
|
||||
|
||||
kwargs["query"] = select(Rom).options(
|
||||
selectinload(Rom.saves),
|
||||
selectinload(Rom.states),
|
||||
selectinload(Rom.screenshots),
|
||||
selectinload(Rom.rom_users),
|
||||
selectinload(Rom.sibling_roms),
|
||||
selectinload(Rom.metadatum),
|
||||
selectinload(Rom.files),
|
||||
selectinload(Rom.collections),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
@@ -36,14 +100,15 @@ def with_details(func):
|
||||
def with_simple(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
session = kwargs.get("session")
|
||||
if session is None:
|
||||
raise TypeError(
|
||||
f"{func} is missing required kwarg 'session' with type 'Session'"
|
||||
)
|
||||
|
||||
kwargs["query"] = select(Rom).options(
|
||||
selectinload(Rom.rom_users), selectinload(Rom.sibling_roms)
|
||||
# Display properties for the current user (last_played)
|
||||
selectinload(Rom.rom_users),
|
||||
# Sort table by metadata (first_release_date)
|
||||
selectinload(Rom.metadatum),
|
||||
# Required for multi-file ROM actions and 3DS QR code
|
||||
selectinload(Rom.files),
|
||||
# Show sibling rom badges on cards
|
||||
selectinload(Rom.sibling_roms),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@@ -51,58 +116,6 @@ def with_simple(func):
|
||||
|
||||
|
||||
class DBRomsHandler(DBBaseHandler):
|
||||
def _filter(
|
||||
self,
|
||||
data,
|
||||
platform_id: int | None,
|
||||
collection_id: int | None,
|
||||
virtual_collection_id: str | None,
|
||||
search_term: str,
|
||||
session: Session,
|
||||
):
|
||||
if platform_id:
|
||||
data = data.filter(Rom.platform_id == platform_id)
|
||||
|
||||
if collection_id:
|
||||
collection = (
|
||||
session.query(Collection)
|
||||
.filter(Collection.id == collection_id)
|
||||
.one_or_none()
|
||||
)
|
||||
if collection:
|
||||
data = data.filter(Rom.id.in_(collection.rom_ids))
|
||||
|
||||
if virtual_collection_id:
|
||||
name, type = VirtualCollection.from_id(virtual_collection_id)
|
||||
v_collection = (
|
||||
session.query(VirtualCollection)
|
||||
.filter(VirtualCollection.name == name, VirtualCollection.type == type)
|
||||
.one_or_none()
|
||||
)
|
||||
if v_collection:
|
||||
data = data.filter(Rom.id.in_(v_collection.rom_ids))
|
||||
|
||||
if search_term:
|
||||
data = data.filter(
|
||||
or_(
|
||||
Rom.fs_name.ilike(f"%{search_term}%"),
|
||||
Rom.name.ilike(f"%{search_term}%"),
|
||||
)
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
def _order(self, data, order_by: str, order_dir: str):
|
||||
if order_by == "id":
|
||||
_column = Rom.id
|
||||
else:
|
||||
_column = func.lower(Rom.name)
|
||||
|
||||
if order_dir == "desc":
|
||||
return data.order_by(_column.desc())
|
||||
else:
|
||||
return data.order_by(_column.asc())
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def add_rom(self, rom: Rom, query: Query = None, session: Session = None) -> Rom:
|
||||
@@ -118,49 +131,593 @@ class DBRomsHandler(DBBaseHandler):
|
||||
) -> Rom | None:
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
def filter_by_platform_id(self, query: Query, platform_id: int):
|
||||
return query.filter(Rom.platform_id == platform_id)
|
||||
|
||||
def filter_by_collection_id(
|
||||
self, query: Query, session: Session, collection_id: int
|
||||
):
|
||||
from . import db_collection_handler
|
||||
|
||||
collection = db_collection_handler.get_collection(collection_id)
|
||||
|
||||
if collection:
|
||||
return query.filter(Rom.id.in_(collection.rom_ids))
|
||||
return query
|
||||
|
||||
def filter_by_virtual_collection_id(
|
||||
self, query: Query, session: Session, virtual_collection_id: str
|
||||
):
|
||||
from . import db_collection_handler
|
||||
|
||||
v_collection = db_collection_handler.get_virtual_collection(
|
||||
virtual_collection_id
|
||||
)
|
||||
|
||||
if v_collection:
|
||||
return query.filter(Rom.id.in_(v_collection.rom_ids))
|
||||
return query
|
||||
|
||||
def filter_by_smart_collection_id(
|
||||
self, query: Query, session: Session, smart_collection_id: int, user_id: int
|
||||
):
|
||||
from . import db_collection_handler
|
||||
|
||||
smart_collection = db_collection_handler.get_smart_collection(
|
||||
smart_collection_id
|
||||
)
|
||||
|
||||
if smart_collection:
|
||||
# Ensure the latest ROMs are loaded
|
||||
smart_collection = smart_collection.update_properties(user_id)
|
||||
return query.filter(Rom.id.in_(smart_collection.rom_ids))
|
||||
return query
|
||||
|
||||
def filter_by_search_term(self, query: Query, search_term: str):
|
||||
return query.filter(
|
||||
or_(
|
||||
Rom.fs_name.ilike(f"%{search_term}%"),
|
||||
Rom.name.ilike(f"%{search_term}%"),
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_matched(self, query: Query, value: bool) -> Query:
|
||||
"""Filter based on whether the rom is matched to a metadata provider."""
|
||||
predicate = or_(
|
||||
Rom.igdb_id.isnot(None),
|
||||
Rom.moby_id.isnot(None),
|
||||
Rom.ss_id.isnot(None),
|
||||
Rom.ra_id.isnot(None),
|
||||
Rom.launchbox_id.isnot(None),
|
||||
Rom.hasheous_id.isnot(None),
|
||||
)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def filter_by_favourite(
|
||||
self, query: Query, session: Session, value: bool, user_id: int | None
|
||||
) -> Query:
|
||||
"""Filter based on whether the rom is in the user's Favourites collection."""
|
||||
if not user_id:
|
||||
return query
|
||||
|
||||
from . import db_collection_handler
|
||||
|
||||
favourites_collection = db_collection_handler.get_collection_by_name(
|
||||
"favourites", user_id
|
||||
)
|
||||
|
||||
if favourites_collection:
|
||||
predicate = Rom.id.in_(favourites_collection.rom_ids)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
# If no Favourites collection exists, return the original query if non-favourites
|
||||
# were requested, or an empty query if favourites were requested.
|
||||
if not value:
|
||||
return query
|
||||
return query.filter(false())
|
||||
|
||||
def filter_by_duplicate(self, query: Query, value: bool) -> Query:
|
||||
"""Filter based on whether the rom has duplicates."""
|
||||
predicate = Rom.sibling_roms.any()
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def filter_by_playable(self, query: Query, value: bool) -> Query:
|
||||
"""Filter based on whether the rom is playable on supported platforms."""
|
||||
predicate = Platform.slug.in_(EJS_SUPPORTED_PLATFORMS)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.join(Platform).filter(predicate)
|
||||
|
||||
def filter_by_has_ra(self, query: Query, value: bool) -> Query:
|
||||
predicate = Rom.ra_id.isnot(None)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def filter_by_missing_from_fs(self, query: Query, value: bool) -> Query:
|
||||
predicate = Rom.missing_from_fs.isnot(False)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def filter_by_verified(self, query: Query):
|
||||
keys_to_check = [
|
||||
"tosec_match",
|
||||
"mame_arcade_match",
|
||||
"mame_mess_match",
|
||||
"nointro_match",
|
||||
"redump_match",
|
||||
"whdload_match",
|
||||
"ra_match",
|
||||
"fbneo_match",
|
||||
]
|
||||
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
conditions = " OR ".join(
|
||||
f"(hasheous_metadata->>'{key}')::boolean" for key in keys_to_check
|
||||
)
|
||||
return query.filter(text(conditions))
|
||||
else:
|
||||
return query.filter(
|
||||
or_(*(Rom.hasheous_metadata[key].as_boolean() for key in keys_to_check))
|
||||
)
|
||||
|
||||
def filter_by_genre(self, query: Query, selected_genre: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("genres @> (:genre)::jsonb").bindparams(
|
||||
genre=f'["{selected_genre}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(genres, JSON_ARRAY(:genre))").bindparams(
|
||||
genre=selected_genre
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_franchise(self, query: Query, selected_franchise: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("franchises @> (:franchise)::jsonb").bindparams(
|
||||
franchise=f'["{selected_franchise}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(franchises, JSON_ARRAY(:franchise))").bindparams(
|
||||
franchise=selected_franchise
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_collection(self, query: Query, selected_collection: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("collections @> (:collection)::jsonb").bindparams(
|
||||
collection=f'["{selected_collection}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(collections, JSON_ARRAY(:collection))").bindparams(
|
||||
collection=selected_collection
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_company(self, query: Query, selected_company: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("companies @> (:company)::jsonb").bindparams(
|
||||
company=f'["{selected_company}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(companies, JSON_ARRAY(:company))").bindparams(
|
||||
company=selected_company
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_age_rating(self, query: Query, selected_age_rating: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("age_ratings @> (:age_rating)::jsonb").bindparams(
|
||||
age_rating=f'["{selected_age_rating}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(age_ratings, JSON_ARRAY(:age_rating))").bindparams(
|
||||
age_rating=selected_age_rating
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_status(self, query: Query, selected_status: str):
|
||||
status_filter = RomUser.status == selected_status
|
||||
if selected_status == "now_playing":
|
||||
status_filter = RomUser.now_playing.is_(True)
|
||||
elif selected_status == "backlogged":
|
||||
status_filter = RomUser.backlogged.is_(True)
|
||||
elif selected_status == "hidden":
|
||||
status_filter = RomUser.hidden.is_(True)
|
||||
|
||||
if selected_status == "hidden":
|
||||
return query.filter(status_filter)
|
||||
|
||||
return query.filter(status_filter, RomUser.hidden.is_(False))
|
||||
|
||||
def filter_by_region(self, query: Query, selected_region: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("regions @> (:region)::jsonb").bindparams(
|
||||
region=f'["{selected_region}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(regions, JSON_ARRAY(:region))").bindparams(
|
||||
region=selected_region
|
||||
)
|
||||
)
|
||||
|
||||
def filter_by_language(self, query: Query, selected_language: str):
|
||||
if ROMM_DB_DRIVER == "postgresql":
|
||||
return query.filter(
|
||||
text("languages @> (:language)::jsonb").bindparams(
|
||||
language=f'["{selected_language}"]'
|
||||
)
|
||||
)
|
||||
else:
|
||||
return query.filter(
|
||||
text("JSON_OVERLAPS(languages, JSON_ARRAY(:language))").bindparams(
|
||||
language=selected_language
|
||||
)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
@with_simple
|
||||
def get_roms(
|
||||
def filter_roms(
|
||||
self,
|
||||
*,
|
||||
query: Query,
|
||||
platform_id: int | None = None,
|
||||
collection_id: int | None = None,
|
||||
virtual_collection_id: str | None = None,
|
||||
search_term: str = "",
|
||||
smart_collection_id: int | None = None,
|
||||
search_term: str | None = None,
|
||||
matched: bool | None = None,
|
||||
favourite: bool | None = None,
|
||||
duplicate: bool | None = None,
|
||||
playable: bool | None = None,
|
||||
has_ra: bool | None = None,
|
||||
missing: bool | None = None,
|
||||
verified: bool | None = None,
|
||||
group_by_meta_id: bool = False,
|
||||
selected_genre: str | None = None,
|
||||
selected_franchise: str | None = None,
|
||||
selected_collection: str | None = None,
|
||||
selected_company: str | None = None,
|
||||
selected_age_rating: str | None = None,
|
||||
selected_status: str | None = None,
|
||||
selected_region: str | None = None,
|
||||
selected_language: str | None = None,
|
||||
user_id: int | None = None,
|
||||
session: Session = None,
|
||||
) -> Query[Rom]:
|
||||
if platform_id:
|
||||
query = self.filter_by_platform_id(query, platform_id)
|
||||
|
||||
if collection_id:
|
||||
query = self.filter_by_collection_id(query, session, collection_id)
|
||||
|
||||
if virtual_collection_id:
|
||||
query = self.filter_by_virtual_collection_id(
|
||||
query, session, virtual_collection_id
|
||||
)
|
||||
|
||||
if smart_collection_id and user_id:
|
||||
query = self.filter_by_smart_collection_id(
|
||||
query, session, smart_collection_id, user_id
|
||||
)
|
||||
|
||||
if search_term:
|
||||
query = self.filter_by_search_term(query, search_term)
|
||||
|
||||
if matched is not None:
|
||||
query = self.filter_by_matched(query, value=matched)
|
||||
|
||||
if favourite is not None:
|
||||
query = self.filter_by_favourite(
|
||||
query, session=session, value=favourite, user_id=user_id
|
||||
)
|
||||
|
||||
if duplicate is not None:
|
||||
query = self.filter_by_duplicate(query, value=duplicate)
|
||||
|
||||
if playable is not None:
|
||||
query = self.filter_by_playable(query, value=playable)
|
||||
|
||||
if has_ra is not None:
|
||||
query = self.filter_by_has_ra(query, value=has_ra)
|
||||
|
||||
if missing is not None:
|
||||
query = self.filter_by_missing_from_fs(query, value=missing)
|
||||
|
||||
# TODO: Correctly support true/false values.
|
||||
if verified:
|
||||
query = self.filter_by_verified(query)
|
||||
|
||||
# BEWARE YE WHO ENTERS HERE 💀
|
||||
if group_by_meta_id:
|
||||
# Convert NULL is_main_sibling to 0 (false) so it sorts after true values
|
||||
is_main_sibling_order = (
|
||||
func.coalesce(cast(RomUser.is_main_sibling, Integer), 0).desc()
|
||||
if user_id
|
||||
else literal(1)
|
||||
)
|
||||
|
||||
# Create a subquery that identifies the primary ROM in each group
|
||||
# Priority order: is_main_sibling (desc), then by fs_name_no_ext (asc)
|
||||
base_subquery = query.subquery()
|
||||
group_subquery = (
|
||||
select(base_subquery.c.id)
|
||||
.select_from(base_subquery)
|
||||
.with_only_columns(
|
||||
base_subquery.c.id,
|
||||
base_subquery.c.fs_name_no_ext,
|
||||
base_subquery.c.platform_id,
|
||||
base_subquery.c.igdb_id,
|
||||
base_subquery.c.ss_id,
|
||||
base_subquery.c.moby_id,
|
||||
base_subquery.c.ra_id,
|
||||
base_subquery.c.hasheous_id,
|
||||
base_subquery.c.launchbox_id,
|
||||
base_subquery.c.tgdb_id,
|
||||
)
|
||||
.outerjoin(
|
||||
RomUser,
|
||||
and_(
|
||||
base_subquery.c.id == RomUser.rom_id, RomUser.user_id == user_id
|
||||
),
|
||||
)
|
||||
.add_columns(
|
||||
func.row_number()
|
||||
.over(
|
||||
partition_by=func.coalesce(
|
||||
func.concat(
|
||||
"igdb-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.igdb_id,
|
||||
),
|
||||
func.concat(
|
||||
"ss-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.ss_id,
|
||||
),
|
||||
func.concat(
|
||||
"moby-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.moby_id,
|
||||
),
|
||||
func.concat(
|
||||
"ra-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.ra_id,
|
||||
),
|
||||
func.concat(
|
||||
"hasheous-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.hasheous_id,
|
||||
),
|
||||
func.concat(
|
||||
"launchbox-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.launchbox_id,
|
||||
),
|
||||
func.concat(
|
||||
"tgdb-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.tgdb_id,
|
||||
),
|
||||
func.concat(
|
||||
"romm-",
|
||||
base_subquery.c.platform_id,
|
||||
"-",
|
||||
base_subquery.c.id,
|
||||
),
|
||||
),
|
||||
order_by=[
|
||||
is_main_sibling_order,
|
||||
base_subquery.c.fs_name_no_ext.asc(),
|
||||
],
|
||||
)
|
||||
.label("row_num"),
|
||||
)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
# Add a filter to the original query to only include the primary ROM from each group
|
||||
query = query.filter(
|
||||
Rom.id.in_(
|
||||
session.query(group_subquery.c.id).filter(
|
||||
group_subquery.c.row_num == 1
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
selected_genre
|
||||
or selected_franchise
|
||||
or selected_collection
|
||||
or selected_company
|
||||
or selected_age_rating
|
||||
):
|
||||
query = query.outerjoin(RomMetadata)
|
||||
|
||||
if selected_genre:
|
||||
query = self.filter_by_genre(query, selected_genre)
|
||||
|
||||
if selected_franchise:
|
||||
query = self.filter_by_franchise(query, selected_franchise)
|
||||
|
||||
if selected_collection:
|
||||
query = self.filter_by_collection(query, selected_collection)
|
||||
|
||||
if selected_company:
|
||||
query = self.filter_by_company(query, selected_company)
|
||||
|
||||
if selected_age_rating:
|
||||
query = self.filter_by_age_rating(query, selected_age_rating)
|
||||
|
||||
if selected_region:
|
||||
query = self.filter_by_region(query, selected_region)
|
||||
|
||||
if selected_language:
|
||||
query = self.filter_by_language(query, selected_language)
|
||||
|
||||
# The RomUser table is already joined if user_id is set
|
||||
if selected_status and user_id:
|
||||
query = self.filter_by_status(query, selected_status)
|
||||
elif user_id:
|
||||
query = query.filter(
|
||||
or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None))
|
||||
)
|
||||
|
||||
return query
|
||||
|
||||
@with_simple
|
||||
@begin_session
|
||||
def get_roms_query(
|
||||
self,
|
||||
*,
|
||||
order_by: str = "name",
|
||||
order_dir: str = "asc",
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
user_id: int | None = None,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> tuple[Query[Rom], Any]:
|
||||
if user_id:
|
||||
query = query.outerjoin(
|
||||
RomUser, and_(RomUser.rom_id == Rom.id, RomUser.user_id == user_id)
|
||||
)
|
||||
|
||||
if user_id and hasattr(RomUser, order_by) and not hasattr(Rom, order_by):
|
||||
order_attr = getattr(RomUser, order_by)
|
||||
query = query.filter(RomUser.user_id == user_id, order_attr.isnot(None))
|
||||
elif hasattr(RomMetadata, order_by) and not hasattr(Rom, order_by):
|
||||
order_attr = getattr(RomMetadata, order_by)
|
||||
query = query.outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id).filter(
|
||||
order_attr.isnot(None)
|
||||
)
|
||||
elif hasattr(Rom, order_by):
|
||||
order_attr = getattr(Rom, order_by)
|
||||
else:
|
||||
order_attr = Rom.name
|
||||
|
||||
order_attr_column = order_attr
|
||||
|
||||
# Ignore case when the order attribute is a number
|
||||
if isinstance(order_attr.type, (String, Text)):
|
||||
# Remove any leading articles
|
||||
order_attr = func.trim(
|
||||
func.lower(order_attr).regexp_replace(STRIP_ARTICLES_REGEX, "", "i")
|
||||
)
|
||||
|
||||
if order_dir.lower() == "desc":
|
||||
order_attr = order_attr.desc()
|
||||
else:
|
||||
order_attr = order_attr.asc()
|
||||
|
||||
return query.order_by(order_attr), order_attr_column
|
||||
|
||||
@begin_session
|
||||
def get_roms_scalar(
|
||||
self,
|
||||
*,
|
||||
session: Session = None,
|
||||
**kwargs,
|
||||
) -> Sequence[Rom]:
|
||||
filtered_query = self._filter(
|
||||
query,
|
||||
platform_id,
|
||||
collection_id,
|
||||
virtual_collection_id,
|
||||
search_term,
|
||||
session,
|
||||
query, _ = self.get_roms_query(
|
||||
order_by=kwargs.get("order_by", "name"),
|
||||
order_dir=kwargs.get("order_dir", "asc"),
|
||||
user_id=kwargs.get("user_id", None),
|
||||
)
|
||||
roms = self.filter_roms(
|
||||
query=query,
|
||||
platform_id=kwargs.get("platform_id", None),
|
||||
collection_id=kwargs.get("collection_id", None),
|
||||
virtual_collection_id=kwargs.get("virtual_collection_id", None),
|
||||
search_term=kwargs.get("search_term", None),
|
||||
matched=kwargs.get("matched", None),
|
||||
favourite=kwargs.get("favourite", None),
|
||||
duplicate=kwargs.get("duplicate", None),
|
||||
playable=kwargs.get("playable", None),
|
||||
has_ra=kwargs.get("has_ra", None),
|
||||
missing=kwargs.get("missing", None),
|
||||
verified=kwargs.get("verified", None),
|
||||
selected_genre=kwargs.get("selected_genre", None),
|
||||
selected_franchise=kwargs.get("selected_franchise", None),
|
||||
selected_collection=kwargs.get("selected_collection", None),
|
||||
selected_company=kwargs.get("selected_company", None),
|
||||
selected_age_rating=kwargs.get("selected_age_rating", None),
|
||||
selected_status=kwargs.get("selected_status", None),
|
||||
selected_region=kwargs.get("selected_region", None),
|
||||
selected_language=kwargs.get("selected_language", None),
|
||||
user_id=kwargs.get("user_id", None),
|
||||
)
|
||||
return session.scalars(roms).all()
|
||||
|
||||
@begin_session
|
||||
def with_char_index(
|
||||
self, query: Query, order_by_attr: Any, session: Session = None
|
||||
) -> list[Row[tuple[str, int]]]:
|
||||
if isinstance(order_by_attr.type, (String, Text)):
|
||||
# Remove any leading articles
|
||||
order_by_attr = func.trim(
|
||||
func.lower(order_by_attr).regexp_replace(STRIP_ARTICLES_REGEX, "", "i")
|
||||
)
|
||||
else:
|
||||
order_by_attr = func.trim(
|
||||
func.lower(Rom.name).regexp_replace(STRIP_ARTICLES_REGEX, "", "i")
|
||||
)
|
||||
|
||||
# Get the row number and first letter for each item
|
||||
subquery = (
|
||||
query.with_only_columns(Rom.id, Rom.name) # type: ignore
|
||||
.add_columns( # type: ignore
|
||||
func.substring(
|
||||
order_by_attr,
|
||||
1,
|
||||
1,
|
||||
).label("letter"),
|
||||
func.row_number().over(order_by=order_by_attr).label("position"),
|
||||
)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
# Get the minimum position for each letter
|
||||
return (
|
||||
session.query(
|
||||
subquery.c.letter, func.min(subquery.c.position - 1).label("position")
|
||||
)
|
||||
.group_by(subquery.c.letter)
|
||||
.order_by(subquery.c.letter)
|
||||
.all()
|
||||
)
|
||||
ordered_query = self._order(filtered_query, order_by, order_dir)
|
||||
offset_query = ordered_query.offset(offset)
|
||||
limited_query = offset_query.limit(limit)
|
||||
return session.scalars(limited_query).unique().all()
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_fs_name(
|
||||
self,
|
||||
platform_id: int,
|
||||
fs_name: str,
|
||||
query: Query = None,
|
||||
session: Session = None,
|
||||
) -> Rom | None:
|
||||
return session.scalar(
|
||||
query.filter_by(platform_id=platform_id, fs_name=fs_name).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_roms_by_fs_name(
|
||||
self,
|
||||
platform_id: int,
|
||||
@@ -169,7 +726,6 @@ class DBRomsHandler(DBBaseHandler):
|
||||
session: Session = None,
|
||||
) -> dict[str, Rom]:
|
||||
"""Retrieve a dictionary of roms by their filesystem names."""
|
||||
query = query or select(Rom)
|
||||
roms = (
|
||||
session.scalars(
|
||||
query.filter(Rom.fs_name.in_(fs_names)).filter_by(
|
||||
@@ -181,20 +737,6 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
return {rom.fs_name: rom for rom in roms}
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_fs_name_no_tags(
|
||||
self, fs_name_no_tags: str, query: Query = None, session: Session = None
|
||||
) -> Rom | None:
|
||||
return session.scalar(query.filter_by(fs_name_no_tags=fs_name_no_tags).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_rom_by_fs_name_no_ext(
|
||||
self, fs_name_no_ext: str, query: Query = None, session: Session = None
|
||||
) -> Rom | None:
|
||||
return session.scalar(query.filter_by(fs_name_no_ext=fs_name_no_ext).limit(1))
|
||||
|
||||
@begin_session
|
||||
def update_rom(self, id: int, data: dict, session: Session = None) -> Rom:
|
||||
session.execute(
|
||||
@@ -214,10 +756,10 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def purge_roms(
|
||||
def mark_missing_roms(
|
||||
self, platform_id: int, fs_roms_to_keep: list[str], session: Session = None
|
||||
) -> Sequence[Rom]:
|
||||
purged_roms = (
|
||||
missing_roms = (
|
||||
session.scalars(
|
||||
select(Rom)
|
||||
.order_by(Rom.fs_name.asc())
|
||||
@@ -232,15 +774,16 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.all()
|
||||
)
|
||||
session.execute(
|
||||
delete(Rom)
|
||||
update(Rom)
|
||||
.where(
|
||||
and_(
|
||||
Rom.platform_id == platform_id, Rom.fs_name.not_in(fs_roms_to_keep)
|
||||
)
|
||||
)
|
||||
.values(**{"missing_from_fs": True})
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
return purged_roms
|
||||
return missing_roms
|
||||
|
||||
@begin_session
|
||||
def add_rom_user(
|
||||
@@ -256,40 +799,6 @@ 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,
|
||||
virtual_collection_id: str | 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,
|
||||
virtual_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))
|
||||
|
||||