Merge branch 'master' into retrodeck-bios-files

This commit is contained in:
Georges-Antoine Assi
2025-02-10 18:45:31 -05:00
888 changed files with 24779 additions and 13013 deletions

View File

@@ -2,7 +2,6 @@
name: Bug report
about: Report a bug, issue or problem
title: "[Bug] Bug title"
labels: bug
assignees: ""
---

View File

@@ -2,6 +2,5 @@
name: Custom issue template
about: Describe this issue template's purpose here.
title: "[Other] Custom issue title"
labels: other
assignees: ""
---

View File

@@ -2,7 +2,6 @@
name: Feature request
about: Suggest an idea for this project
title: "[Feature] Feature title"
labels: feature
assignees: ""
---

15
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,15 @@
**Description**
<sup>Explain the changes or enhancements you are proposing with this pull request.</sup>
**Related** Issues
<sup>List any related issues that are addressed or fixed by this pull request.</sup>
**Checklist**
<sup>Please check all that apply.</sup>
- [ ] I've tested the changes locally
- [ ] I've updated relevant comments
- [ ] I've assigned reviewers for this PR
- [ ] I've added unit tests that cover the changes
**Screenshots**

View File

@@ -1 +0,0 @@
blank_pull_request_template_enabled: false

View File

@@ -1,24 +0,0 @@
# Pull request template
## Description
Please describe the changes or enhancements you are proposing with this pull request.
## Related Issues
List any related issues that are addressed or fixed by this pull request.
## Checklist
Please check all that apply.
- [ ] I've tested the changes locally
- [ ] I've updated the wiki accordingly
- [ ] I've have updated relevant comments
- [ ] I've assigned reviewers for this PR
- [ ] I've added unit tests that cover the changes
- [ ] All existing tests are passing
## Additional Notes
Add any additional information or context about the pull request here.

16
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
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"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 50 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

BIN
.github/resources/logotipo.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" version="1.0" viewBox="0 0 375 375"><path fill="#a453ff" 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="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>

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 MiB

BIN
.github/resources/social_preview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

1
.github/resources/social_preview.svg vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -16,30 +16,50 @@ jobs:
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Generate Docker metadata
- name: Generate Docker metadata (slim)
id: meta-slim
uses: docker/metadata-action@v5
with:
images: |
name=rommapp/romm
name=ghcr.io/rommapp/romm
flavor: |
latest=auto
suffix=-slim,onlatest=true
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
labels: |
org.opencontainers.image.version={{version}}-slim
org.opencontainers.image.title="rommapp/romm"
org.opencontainers.image.description="RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators."
org.opencontainers.image.licenses="AGPLv3"
- name: Generate Docker metadata (full)
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5
with:
images: |
name=rommapp/romm
@@ -52,14 +72,27 @@ jobs:
org.opencontainers.image.version={{version}}
org.opencontainers.image.title="rommapp/romm"
org.opencontainers.image.description="RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators."
org.opencontainers.image.licenses="GPL-3.0"
org.opencontainers.image.licenses="AGPLv3"
- name: Set version
run: |
sed -i 's/<version>/${{ steps.meta.outputs.version }}/' backend/__version__.py
- name: Build image
uses: docker/build-push-action@v4
- name: Build slim image
id: build-slim
uses: docker/build-push-action@v6
with:
file: docker/Dockerfile
context: .
push: true
platforms: linux/arm64,linux/amd64
tags: ${{ steps.meta-slim.outputs.tags }}
labels: ${{ steps.meta-slim.outputs.labels }}
target: slim-image
- name: Build full image
id: build-full
uses: docker/build-push-action@v6
with:
file: docker/Dockerfile
context: .
@@ -67,3 +100,4 @@ jobs:
platforms: linux/arm64,linux/amd64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
target: full-image

View File

@@ -31,7 +31,7 @@ jobs:
options: --health-cmd="mysqladmin ping" --health-interval=5s --health-timeout=2s --health-retries=3
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install mariadb connectors
run: |
@@ -43,14 +43,14 @@ jobs:
pipx install poetry
- name: Set up Python 3.12
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: "poetry"
- name: Install dependencies
run: |
poetry install --sync
poetry sync --extras test
- name: Initiate database
run: |

View File

@@ -17,6 +17,6 @@ jobs:
contents: read # For repo checkout
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Trunk Check
uses: trunk-io/trunk-action@v1

View File

@@ -20,10 +20,10 @@ jobs:
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: "18"
@@ -34,3 +34,8 @@ jobs:
- name: Run typecheck
run: npm run typecheck
working-directory: frontend
- name: Lockfile lint
run: |
[ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value | has("resolved") | not)) | .key' < package-lock.json)" ]
working-directory: frontend

1
.gitignore vendored
View File

@@ -40,6 +40,7 @@ __pycache__
# database
mariadb
*.sqlite
# used to mock the library/config/mounts/etc while testing
frontend/assets/romm

View File

@@ -7,6 +7,7 @@ module.exports = {
removeViewBox: false, // https://github.com/svg/svgo/issues/1128
sortAttrs: true,
removeOffCanvasPaths: true,
cleanupIDs: false,
},
},
},

View File

@@ -2,41 +2,41 @@
# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml
version: 0.1
cli:
version: 1.22.3
version: 1.22.9
# Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins)
plugins:
sources:
- id: trunk
ref: v1.6.1
ref: v1.6.6
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.12.1
- node@18.20.5
- python@3.12.2
# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration)
lint:
enabled:
- markdownlint@0.41.0
- eslint@9.9.0
- actionlint@1.7.1
- bandit@1.7.9
- black@24.8.0
- checkov@3.2.228
- markdownlint@0.43.0
- eslint@9.18.0
- actionlint@1.7.7
- bandit@1.8.2
- black@24.10.0
- checkov@3.2.357
- git-diff-check
- isort@5.13.2
- mypy@1.11.1
- osv-scanner@1.8.3
- oxipng@9.1.2
- prettier@3.3.3
- ruff@0.6.0
- mypy@1.14.1
- osv-scanner@1.9.2
- oxipng@9.1.3
- prettier@3.4.2
- ruff@0.9.3
- shellcheck@0.10.0
- shfmt@3.6.0
- svgo@3.3.2
- taplo@0.9.3
- trivy@0.54.1
- trufflehog@3.81.9
- trivy@0.58.2
- trufflehog@3.88.2
- yamllint@1.35.1
ignore:
- linters: [ALL]
@@ -61,7 +61,6 @@ lint:
- yaml
- css
- postcss
- sass
- html
- markdown
- json

6
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"python.testing.cwd": "${workspaceFolder}/backend",
"python.testing.pytestArgs": ["."],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}

85
.vscode/tasks.json vendored
View File

@@ -1,41 +1,48 @@
{
"tasks": [
{
"label": "Launch frontend",
"type": "npm",
"path": "frontend",
"script": "dev",
"problemMatcher": []
},
{
"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",
"problemMatcher": []
},
{
"label": "Execute tests",
"type": "shell",
"command": "cd backend && poetry run pytest -vv -c ../pytest.ini",
"problemMatcher": []
},
{
"label": "Setup development environment",
"type": "shell",
"command": "docker compose up -d",
"problemMatcher": []
},
{
"label": "Setup testing environment",
"type": "shell",
"command": "export $(cat .env | grep DB_ROOT_PASSWD | xargs) && docker exec -i mariadb mariadb -u root -p$DB_ROOT_PASSWD < backend/romm_test/setup.sql",
"problemMatcher": []
}
]
"version": "2.0.0",
"tasks": [
{
"label": "Launch frontend",
"type": "npm",
"path": "frontend",
"script": "dev",
"problemMatcher": []
},
{
"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",
"problemMatcher": []
},
{
"label": "Execute tests",
"type": "shell",
"command": "cd backend && poetry run pytest -vv -c ../pytest.ini",
"problemMatcher": []
},
{
"label": "Setup development environment",
"type": "shell",
"command": "docker compose up -d",
"problemMatcher": []
},
{
"label": "Setup testing environment",
"type": "shell",
"command": "export $(cat .env | grep DB_ROOT_PASSWD | xargs) && docker exec -i mariadb mariadb -u root -p$DB_ROOT_PASSWD < backend/romm_test/setup.sql",
"problemMatcher": []
},
{
"label": "Launch full stack",
"dependsOn": ["Launch frontend", "Launch backend", "Launch worker"],
"problemMatcher": [],
"dependsOrder": "parallel"
}
]
}

View File

@@ -1,16 +0,0 @@
{
"languages": {
"Python": {
"tab_size": 4
},
"Vue.js": {
"tab_size": 2,
"formatter": {
"external": {
"command": "prettier",
"arguments": ["--stdin-filepath", "{buffer_path}"]
}
}
}
}
}

View File

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

View File

@@ -27,7 +27,7 @@ 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 pipx
sudo apt install libmariadb3 libmariadb-dev libpq-dev pipx
```
#### - Install python dependencies
@@ -45,13 +45,20 @@ Then create the virtual environment
```sh
# Fix disable parallel installation stuck: $> poetry config experimental.new-installer false
# Fix Loading macOS/linux stuck: $> export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring
poetry install --sync
poetry sync
```
If you are on Arch Linux or another Arch-based distro, you need to run the command as follows:
```sh
# https://bbs.archlinux.org/viewtopic.php?id=296542
CFLAGS="-Wno-error=incompatible-pointer-types" poetry sync
```
#### - Spin up mariadb in docker
```sh
docker-compose up -d
docker compose up -d
```
#### - Run the backend
@@ -118,12 +125,12 @@ trunk check
### - Create the test user and database with root user
```sh
docker exec -i mariadb mariadb -u root -p<root password> < backend/romm_test/setup.sql
docker exec -i romm-mariadb-dev mariadb -uroot -p<root password> < backend/romm_test/setup.sql
```
### - Run tests
*\_\_*Migrations will be run automatically when running the tests.\_\_\*
*\_*Migrations will be run automatically when running the tests.\_\_\_
```sh
cd backend

View File

@@ -2,7 +2,9 @@
<!-- trunk-ignore(markdownlint/MD041) -->
<div align="center">
<img src=".github/resources/romm_complete.svg" height="220px" width="auto" alt="romm logo">
<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">
<h3 style="font-size: 25px;">
A beautiful, powerful, self-hosted rom manager.
@@ -22,22 +24,31 @@
# Table of Contents
- [Table of Contents](#table-of-contents)
- [Overview](#overview)
- [Features](#features)
- [Preview](#preview)
- [Installation](#installation)
- [Configuration](#configuration)
- [Folder Structure](#folder-structure)
- [Folder Structure](#folder-structure)
- [Configuration File](#configuration-file)
- [Scheduler](#scheduler)
- [Naming Convention](#naming-convention)
- [Platform Support](#platform-support)
- [Tag Support](#tag-support)
- [Community](#community)
- [Support](#support)
- [Our Friends](#our-friends)
# Overview
RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes, and custom tags, RomM is a must-have for anyone who plays on emulators.
RomM (ROM Manager) allows you to scan, enrich, browse and play your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes, and custom tags, RomM is a must-have for anyone who plays on emulators.
## Features
- Scans your existing games library and enhances it with metadata from [IGDB][igdb-api] and [MobyGames][mobygames-api]
- Supports a large number of **[platforms][platform-support]**
- Play games directly from the browser using [EmulatorJS][wiki-emulatorjs]
- Play games directly from the browser using [EmulatorJS][wiki-emulatorjs] and RuffleRS
- Share your library with friends while [limiting access and permissions][wiki-authentication]
- Supports MAME, Nintendo Switch, and Sony Playstation naming schemes
- Detects and groups **multifile games** (e.g. PS1 games with multiple CDs)
@@ -46,20 +57,13 @@ RomM (ROM Manager) allows you to scan, enrich, and browse your game collection w
## Preview
| 🖥 Desktop | 📱 Mobile |
| :---------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------: |
| <img src=".github/resources/screenshots/romm-desktop-slider.gif" alt="desktop preview" /> | <img style="width: 325px; aspect-ratio: auto;" src=".github/resources/screenshots/romm-mobile-slider.gif" alt="mobile 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" /> |
# Installation
Before running the [image][docker-tags], please ensure that Docker is installed and running on your system.
1. [Generate API keys][wiki-generate-api-keys] for IGDB and/or MobyGames to fetch metadata.
2. Verify that your library folder structure matches one of the options listed in the [folder structure][folder-structure] section.
3. Create a docker-compose.yml file by referring to the example [docker-compose.yml][docker-compose-example] file for guidance, and customize it for your setup with [the available environment variables][wiki-env-variables].
4. Launch the container(s) with `docker-compose up -d`.
> [!NOTE] > **If you are having issues with RomM, please review the [wiki page][wiki-troubleshooting] for troubleshooting steps and common issues.**
To start using RomM, check out the [Quick Start Guide][wiki-quick-start-guide] in the wiki. If you are having issues with RomM, please review the page for [troubleshooting steps][wiki-troubleshooting] and common issues, or join the [Discord][discord-invite] for support from the community.
# Configuration
@@ -170,8 +174,9 @@ Tags can be used to search for games in the search bar. For example, searching f
# Community
Here are a few projects maintained by members of our community. Since the RomM team does not regularly review them, **we recommend that you review them closely before you use them**.
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
@@ -181,9 +186,9 @@ Join us on Discord, where you can ask questions, submit ideas, get help, showcas
## Support
If you like this project, consider buying me a coffee!
Consider supporting the development of this project on Open Collective.
[![coffee-donate-img]][coffee-donate]
[![oc-donate-img]][oc-donate]
## Our Friends
@@ -192,7 +197,8 @@ Here are a few projects that we think you might like:
- [EmulatorJS](https://emulatorjs.org/): An embeddable, browser-based emulator
- [RetroDECK](https://retrodeck.net/): Retro gaming on SteamOS and Linux
- [ES-DE Frontend](https://es-de.org/): Emulator frontend for Linux, macOS and Windows
- [Gaseous](https://github.com/gaseous-project/gaseous-server): Another self-hosted ROM manager
- [Gaseous](https://github.com/gaseous-project/gaseous-server): Another ROM manager with web-based emulator
- [Retrom](https://github.com/JMBeresford/retrom): A centralized game library/collection management service
- [Steam ROM Manager](https://steamgriddb.github.io/steam-rom-manager/): An app for managing ROMs in Steam
<!-- Sections -->
@@ -215,9 +221,8 @@ Here are a few projects that we think you might like:
[wiki-platforms-icons]: https://github.com/rommapp/romm/wiki/Custom-Platform-Icons
[wiki-troubleshooting]: https://github.com/rommapp/romm/wiki/Troubleshooting
[wiki-emulatorjs]: https://github.com/rommapp/romm/wiki/EmulatorJS-Player
[wiki-env-variables]: https://github.com/rommapp/romm/wiki/Environment-Variables
[wiki-scheduled-tasks]: https://github.com/rommapp/romm/wiki/Scheduled-Tasks
[wiki-generate-api-keys]: https://github.com/rommapp/romm/wiki/Generate-API-Keys
[wiki-quick-start-guide]: https://github.com/rommapp/romm/wiki/Quick-Start-Guide
<!-- Badges -->
@@ -237,13 +242,13 @@ Here are a few projects that we think you might like:
[discord-invite-img]: https://invidget.switchblade.xyz/P5HtHnhUDH
[discord-invite]: https://discord.gg/P5HtHnhUDH
[coffee-donate-img]: https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png
[coffee-donate]: https://www.buymeacoff.ee/zurdi15
[oc-donate-img]: https://opencollective.com/romm/donate/button.png?color=blue
[oc-donate]: https://opencollective.com/romm
<!-- External links -->
[docker-tags]: https://hub.docker.com/r/rommapp/romm/tags
[igdb-api]: https://api-docs.igdb.com/#account-creation
[mobygames-api]: https://www.mobygames.com/info/api/
[big-bear-casaos]: https://github.com/bigbeartechworld/big-bear-casaos
[kubernetes-helm-chart]: https://artifacthub.io/packages/helm/crystalnet/romm
[romm-comm-discord-bot]: https://github.com/idio-sync/romm-comm

View File

View File

View File

@@ -0,0 +1,491 @@
from __future__ import annotations
import enum
from typing import Literal, NewType, TypedDict
# https://api-docs.igdb.com/#expander
type ExpandableField[T] = T | int
# TODO: Add missing structures until all are implemented.
UnimplementedEntity = NewType("UnimplementedEntity", dict)
AgeRatingContentDescription = UnimplementedEntity
Artwork = UnimplementedEntity
CollectionRelation = UnimplementedEntity
ExternalGame = UnimplementedEntity
GameEngine = UnimplementedEntity
GameMode = UnimplementedEntity
InvolvedCompany = UnimplementedEntity
Keyword = UnimplementedEntity
LanguageSupport = UnimplementedEntity
PlatformVersionReleaseDate = UnimplementedEntity
PlatformWebsite = UnimplementedEntity
PlayerPerspective = UnimplementedEntity
ReleaseDate = UnimplementedEntity
TagNumber = UnimplementedEntity
Theme = UnimplementedEntity
Website = UnimplementedEntity
class IGDBEntity(TypedDict):
"""Base class for all IGDB entities.
All IGDB entities include an ID field. They must inherit from this class, and set `total=False`
in the class definition, as they only include the `fields` requested in the API query.
"""
id: int
# https://api-docs.igdb.com/#age-rating-enums
class AgeRatingCategory(enum.IntEnum):
ESRB = 1
PEGI = 2
CERO = 3
USK = 4
GRAC = 5
CLASS_IND = 6
ACB = 7
# https://api-docs.igdb.com/#age-rating-enums
class AgeRatingRating(enum.IntEnum):
THREE = 1
SEVEN = 2
TWELVE = 3
SIXTEEN = 4
EIGHTEEN = 5
RP = 6
EC = 7
E = 8
E10 = 9
T = 10
M = 11
AO = 12
CERO_A = 13
CERO_B = 14
CERO_C = 15
CERO_D = 16
CERO_Z = 17
USK_0 = 18
USK_6 = 19
USK_12 = 20
USK_16 = 21
USK_18 = 22
GRAC_ALL = 23
GRAC_TWELVE = 24
GRAC_FIFTEEN = 25
GRAC_EIGHTEEN = 26
GRAC_TESTING = 27
CLASS_IND_L = 28
CLASS_IND_TEN = 29
CLASS_IND_TWELVE = 30
CLASS_IND_FOURTEEN = 31
CLASS_IND_SIXTEEN = 32
CLASS_IND_EIGHTEEN = 33
ACB_G = 34
ACB_PG = 35
ACB_M = 36
ACB_MA15 = 37
ACB_R18 = 38
ACB_RC = 39
# https://api-docs.igdb.com/#age-rating
class AgeRating(IGDBEntity, total=False):
category: AgeRatingCategory
checksum: str # uuid
content_descriptions: list[ExpandableField[AgeRatingContentDescription]]
rating: AgeRatingRating
rating_cover_url: str
synopsis: str
# https://api-docs.igdb.com/#alternative-name
class AlternativeName(IGDBEntity, total=False):
checksum: str # uuid
comment: str
game: ExpandableField[Game]
name: str
# https://api-docs.igdb.com/#collection
class Collection(IGDBEntity, total=False):
as_child_relations: list[ExpandableField[CollectionRelation]]
as_parent_relations: list[ExpandableField[CollectionRelation]]
checksum: str # uuid
created_at: int # timestamp
games: list[ExpandableField[Game]]
name: str
slug: str
type: ExpandableField[CollectionType]
updated_at: int # timestamp
url: str
# https://api-docs.igdb.com/#collection-type
class CollectionType(IGDBEntity, total=False):
checksum: str # uuid
created_at: int # timestamp
description: str
name: str
updated_at: int # timestamp
# https://api-docs.igdb.com/#company
class Company(IGDBEntity, total=False):
change_date: int # timestamp
change_date_category: CompanyChangeDateCategory
changed_company_id: ExpandableField[Company]
checksum: str # uuid
country: int
created_at: int # timestamp
description: str
developed: list[ExpandableField[Game]]
logo: ExpandableField[CompanyLogo]
name: str
parent: ExpandableField[Company]
published: list[ExpandableField[Game]]
slug: str
start_date: int # timestamp
start_date_category: CompanyStartDateCategory
updated_at: int # timestamp
url: str
websites: list[ExpandableField[CompanyWebsite]]
# https://api-docs.igdb.com/#company-enums
class CompanyChangeDateCategory(enum.IntEnum):
YYYYMMMMDD = 0
YYYYMMMM = 1
YYYY = 2
YYYYQ1 = 3
YYYYQ2 = 4
YYYYQ3 = 5
YYYYQ4 = 6
TBD = 7
# https://api-docs.igdb.com/#company-logo
class CompanyLogo(IGDBEntity, total=False):
alpha_channel: bool
animated: bool
checksum: str # uuid
height: int
image_id: str
url: str
width: int
# https://api-docs.igdb.com/#company-enums
class CompanyStartDateCategory(enum.IntEnum):
YYYYMMMMDD = 0
YYYYMMMM = 1
YYYY = 2
YYYYQ1 = 3
YYYYQ2 = 4
YYYYQ3 = 5
YYYYQ4 = 6
TBD = 7
# https://api-docs.igdb.com/#company-website
class CompanyWebsite(IGDBEntity, total=False):
category: CompanyWebsiteCategory
checksum: str # uuid
trusted: bool
url: str
# https://api-docs.igdb.com/#company-website-enums
class CompanyWebsiteCategory(enum.IntEnum):
OFFICIAL = 1
WIKIA = 2
WIKIPEDIA = 3
FACEBOOK = 4
TWITTER = 5
TWITCH = 6
INSTAGRAM = 8
YOUTUBE = 9
IPHONE = 10
IPAD = 11
ANDROID = 12
STEAM = 13
REDDIT = 14
ITCH = 15
EPICGAMES = 16
GOG = 17
DISCORD = 18
# https://api-docs.igdb.com/#cover
class Cover(IGDBEntity, total=False):
alpha_channel: bool
animated: bool
checksum: str # uuid
game: ExpandableField[Game]
game_localization: ExpandableField[GameLocalization]
height: int
image_id: str
url: str
width: int
# https://api-docs.igdb.com/#franchise
class Franchise(IGDBEntity, total=False):
checksum: str # uuid
created_at: int # timestamp
games: list[ExpandableField[Game]]
name: str
slug: str
updated_at: int # timestamp
url: str
# https://api-docs.igdb.com/#game-enums
class GameCategory(enum.IntEnum):
MAIN_GAME = 0
DLC_ADDON = 1
EXPANSION = 2
BUNDLE = 3
STANDALONE_EXPANSION = 4
MOD = 5
EPISODE = 6
SEASON = 7
REMAKE = 8
REMASTER = 9
EXPANDED_GAME = 10
PORT = 11
FORK = 12
PACK = 13
UPDATE = 14
# https://api-docs.igdb.com/#game-enums
class GameStatus(enum.IntEnum):
RELEASED = 0
ALPHA = 2
BETA = 3
EARLY_ACCESS = 4
OFFLINE = 5
CANCELLED = 6
RUMORED = 7
DELISTED = 8
# https://api-docs.igdb.com/#game
class Game(IGDBEntity, total=False):
age_ratings: list[ExpandableField[AgeRating]]
aggregated_rating: float
aggregated_rating_count: int
alternative_names: list[ExpandableField[AlternativeName]]
artworks: list[ExpandableField[Artwork]]
bundles: list[ExpandableField[Game]]
category: GameCategory
checksum: str # uuid
collections: list[ExpandableField[Collection]]
cover: ExpandableField[Cover]
created_at: int # timestamp
dlcs: list[ExpandableField[Game]]
expanded_games: list[ExpandableField[Game]]
expansions: list[ExpandableField[Game]]
external_games: list[ExpandableField[ExternalGame]]
first_release_date: int # timestamp
forks: list[ExpandableField[Game]]
franchise: ExpandableField[Franchise]
franchises: list[ExpandableField[Franchise]]
game_engines: list[ExpandableField[GameEngine]]
game_localizations: list[ExpandableField[GameLocalization]]
game_modes: list[ExpandableField[GameMode]]
genres: list[ExpandableField[Genre]]
hypes: int
involved_companies: list[ExpandableField[InvolvedCompany]]
keywords: list[ExpandableField[Keyword]]
language_supports: list[ExpandableField[LanguageSupport]]
multiplayer_modes: list[ExpandableField[MultiplayerMode]]
name: str
parent_game: ExpandableField[Game]
platforms: list[ExpandableField[Platform]]
player_perspectives: list[ExpandableField[PlayerPerspective]]
ports: list[ExpandableField[Game]]
rating: float
rating_count: int
release_dates: list[ExpandableField[ReleaseDate]]
remakes: list[ExpandableField[Game]]
remasters: list[ExpandableField[Game]]
screenshots: list[ExpandableField[Screenshot]]
similar_games: list[ExpandableField[Game]]
slug: str
standalone_expansions: list[ExpandableField[Game]]
status: GameStatus
storyline: str
summary: str
tags: list[TagNumber]
themes: list[ExpandableField[Theme]]
total_rating: float
total_rating_count: int
updated_at: int # timestamp
url: str
version_parent: ExpandableField[Game]
version_title: str
videos: list[ExpandableField[GameVideo]]
websites: list[ExpandableField[Website]]
# https://api-docs.igdb.com/#game-localization
class GameLocalization(IGDBEntity, total=False):
checksum: str # uuid
cover: ExpandableField[Cover]
created_at: int # timestamp
game: ExpandableField[Game]
name: str
region: ExpandableField[Region]
updated_at: int # timestamp
# https://api-docs.igdb.com/#game-time-to-beat
class GameTimeToBeat(IGDBEntity, total=False):
checksum: str # uuid
completely: int
count: int
created_at: int # timestamp
game_id: int
hastily: int
normally: int
updated_at: int # timestamp
# https://api-docs.igdb.com/#game-video
class GameVideo(IGDBEntity, total=False):
checksum: str # uuid
game: ExpandableField[Game]
name: str
video_id: str
# https://api-docs.igdb.com/#genre
class Genre(IGDBEntity, total=False):
checksum: str # uuid
created_at: int # timestamp
name: str
slug: str
updated_at: int # timestamp
url: str
# https://api-docs.igdb.com/#multiplayer-mode
class MultiplayerMode(IGDBEntity, total=False):
campaigncoop: bool
checksum: str # uuid
dropin: bool
game: ExpandableField[Game]
lancoop: bool
offlinecoop: bool
offlinecoopmax: int
offlinemax: int
onlinecoop: bool
onlinecoopmax: int
onlinemax: int
platform: ExpandableField[Platform]
splitscreen: bool
splitscreenonline: bool
# https://api-docs.igdb.com/#platform-enums
class PlatformCategory(enum.IntEnum):
CONSOLE = 1
ARCADE = 2
PLATFORM = 3
OPERATING_SYSTEM = 4
PORTABLE_CONSOLE = 5
COMPUTER = 6
# https://api-docs.igdb.com/#platform
class Platform(IGDBEntity, total=False):
abbreviation: str
alternative_name: str
category: PlatformCategory
checksum: str # uuid
created_at: int # timestamp
generation: int
name: str
platform_family: ExpandableField[PlatformFamily]
platform_logo: ExpandableField[PlatformLogo]
slug: str
summary: str
updated_at: int # timestamp
url: str
versions: list[ExpandableField[PlatformVersion]]
websites: list[ExpandableField[PlatformWebsite]]
# https://api-docs.igdb.com/#platform-family
class PlatformFamily(IGDBEntity, total=False):
checksum: str # uuid
name: str
slug: str
# https://api-docs.igdb.com/#platform-logo
class PlatformLogo(IGDBEntity, total=False):
alpha_channel: bool
animated: bool
checksum: str # uuid
height: int
image_id: str
url: str
width: int
# https://api-docs.igdb.com/#platform-version
class PlatformVersion(IGDBEntity, total=False):
checksum: str # uuid
companies: list[ExpandableField[PlatformVersionCompany]]
connectivity: str
cpu: str
graphics: str
main_manufacturer: ExpandableField[PlatformVersionCompany]
media: str
memory: str
name: str
os: str
output: str
platform_logo: ExpandableField[PlatformLogo]
platform_version_release_dates: list[ExpandableField[PlatformVersionReleaseDate]]
resolutions: str
slug: str
sound: str
storage: str
summary: str
url: str
# https://api-docs.igdb.com/#platform-version-company
class PlatformVersionCompany(IGDBEntity, total=False):
checksum: str # uuid
comment: str
company: ExpandableField[Company]
developer: bool
manufacturer: bool
# https://api-docs.igdb.com/#region
class Region(IGDBEntity, total=False):
category: Literal["locale", "continent"]
checksum: str # uuid
created_at: int # timestamp
identifier: str
name: str
updated_at: int # timestamp
# https://api-docs.igdb.com/#screenshot
class Screenshot(IGDBEntity, total=False):
alpha_channel: bool
animated: bool
checksum: str # uuid
game: ExpandableField[Game]
height: int
image_id: str
url: str
width: int

View File

@@ -0,0 +1,127 @@
import asyncio
import re
from pathlib import Path
from logger.logger import log
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,
}
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=}"
)
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,
)
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=}")
if proc.stdout is None:
raise RAHasherError("RAHasher did not return a hash.")
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=}"
)
return file_hash

View File

@@ -8,7 +8,7 @@ from models.assets import Save, Screenshot, State # noqa
from models.base import BaseModel
from models.firmware import Firmware # noqa
from models.platform import Platform # noqa
from models.rom import Rom # noqa
from models.rom import Rom, SiblingRom # noqa
from models.user import User # noqa
from sqlalchemy import create_engine
@@ -33,6 +33,14 @@ target_metadata = BaseModel.metadata
# ... etc.
# Ignore specific models when running migrations
def include_object(object, name, type_, reflected, compare_to):
if type_ == "table" and name in [SiblingRom.__tablename__]: # Virtual table
return False
return True
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
@@ -53,6 +61,7 @@ def run_migrations_offline() -> None:
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
include_object=include_object,
)
with context.begin_transaction():
@@ -75,6 +84,7 @@ def run_migrations_online() -> None:
target_metadata=target_metadata,
render_as_batch=True,
compare_type=True,
include_object=include_object,
)
with context.begin_transaction():

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,7 +8,7 @@ Create Date: 2024-02-13 17:57:25.936825
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from utils.database import CustomJSON, is_postgresql
# revision identifiers, used by Alembic.
revision = "0015_mobygames_data"
@@ -18,18 +18,20 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.add_column(sa.Column("moby_id", sa.Integer(), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(sa.Column("moby_id", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("moby_metadata", mysql.JSON(), nullable=True))
batch_op.add_column(sa.Column("moby_metadata", CustomJSON(), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("update roms set moby_metadata = '\\{\\}'")
# ### end Alembic commands ###
if is_postgresql(connection):
batch_op.execute("update roms set moby_metadata = jsonb_build_object()")
else:
batch_op.execute("update roms set moby_metadata = JSON_OBJECT()")
def downgrade() -> None:

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,99 @@
"""empty message
Revision ID: 0026_romuser_status_fields
Revises: 0025_roms_hashes
Create Date: 2024-08-29 15:52:56.031850
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from utils.database import is_postgresql
# revision identifiers, used by Alembic.
revision = "0026_romuser_status_fields"
down_revision = "0025_roms_hashes"
branch_labels = None
depends_on = None
def upgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_l",
existing_type=sa.VARCHAR(length=1000),
type_=sa.Text(),
existing_nullable=True,
)
batch_op.alter_column(
"path_cover_s",
existing_type=sa.VARCHAR(length=1000),
type_=sa.Text(),
existing_nullable=True,
)
if is_postgresql(connection):
rom_user_status_enum = ENUM(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
create_type=False,
)
rom_user_status_enum.create(connection, checkfirst=False)
else:
rom_user_status_enum = sa.Enum(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
)
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.add_column(
sa.Column("last_played", sa.DateTime(timezone=True), nullable=True)
)
batch_op.add_column(sa.Column("backlogged", sa.Boolean(), nullable=False))
batch_op.add_column(sa.Column("now_playing", sa.Boolean(), nullable=False))
batch_op.add_column(sa.Column("hidden", sa.Boolean(), nullable=False))
batch_op.add_column(sa.Column("rating", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("difficulty", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("completion", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("status", rom_user_status_enum, nullable=True))
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.drop_column("status")
batch_op.drop_column("completion")
batch_op.drop_column("difficulty")
batch_op.drop_column("rating")
batch_op.drop_column("hidden")
batch_op.drop_column("now_playing")
batch_op.drop_column("backlogged")
batch_op.drop_column("last_played")
if is_postgresql(connection):
ENUM(name="romuserstatus").drop(connection, checkfirst=False)
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_s",
existing_type=sa.Text(),
type_=sa.VARCHAR(length=1000),
existing_nullable=True,
)
batch_op.alter_column(
"path_cover_l",
existing_type=sa.Text(),
type_=sa.VARCHAR(length=1000),
existing_nullable=True,
)

View File

@@ -0,0 +1,56 @@
"""platforms_data
Revision ID: 0027_platforms_data
Revises: 0026_romuser_status_fields
Create Date: 2024-11-17 23:05:31.038917
"""
import sqlalchemy as sa
from alembic import op
from models.platform import DEFAULT_COVER_ASPECT_RATIO
# revision identifiers, used by Alembic.
revision = "0027_platforms_data"
down_revision = "0026_romuser_status_fields"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.add_column(sa.Column("category", sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column("generation", sa.Integer(), nullable=True))
batch_op.add_column(
sa.Column("family_name", sa.String(length=1000), nullable=True)
)
batch_op.add_column(
sa.Column("family_slug", sa.String(length=1000), nullable=True)
)
batch_op.add_column(sa.Column("url", sa.String(length=1000), nullable=True))
batch_op.add_column(
sa.Column("url_logo", sa.String(length=1000), nullable=True)
)
batch_op.add_column(
sa.Column(
"aspect_ratio",
sa.String(length=10),
nullable=False,
server_default=DEFAULT_COVER_ASPECT_RATIO,
)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.drop_column("url_logo")
batch_op.drop_column("url")
batch_op.drop_column("family_name")
batch_op.drop_column("family_slug")
batch_op.drop_column("generation")
batch_op.drop_column("category")
batch_op.drop_column("aspect_ratio")
# ### end Alembic commands ###

View File

@@ -0,0 +1,28 @@
"""empty message
Revision ID: 0028_user_email
Revises: 0027_platforms_data
Create Date: 2024-12-09 19:26:34.257411
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0028_user_email"
down_revision = "0027_platforms_data"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.add_column(sa.Column("email", sa.String(length=255), nullable=True))
batch_op.create_index(batch_op.f("ix_users_email"), ["email"], unique=True)
def downgrade() -> None:
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_users_email"))
batch_op.drop_column("email")

View File

@@ -0,0 +1,32 @@
"""platforms_custom_name
Revision ID: 0029_platforms_custom_name
Revises: 0028_user_email
Create Date: 2024-12-24 01:32:57.121432
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0029_platforms_custom_name"
down_revision = "0028_user_email"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.add_column(
sa.Column("custom_name", sa.String(length=400), nullable=True)
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.drop_column("custom_name")
# ### end Alembic commands ###

View File

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

View File

@@ -0,0 +1,350 @@
"""empty message
Revision ID: 0031_datetime_to_timestamp
Revises: 0030_user_email_null
Create Date: 2025-01-14 04:13:33.209508
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0031_datetime_to_timestamp"
down_revision = "0030_user_email_null"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("firmware", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.alter_column(
"last_played",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=True,
)
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
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(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("saves", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("screenshots", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("states", schema=None) as batch_op:
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.alter_column(
"last_login",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=True,
)
batch_op.alter_column(
"last_active",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=True,
)
batch_op.alter_column(
"created_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"updated_at",
existing_type=sa.DateTime(timezone=True),
type_=sa.TIMESTAMP(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"last_active",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=True,
)
batch_op.alter_column(
"last_login",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=True,
)
with op.batch_alter_table("states", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("screenshots", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("saves", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(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(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"last_played",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=True,
)
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("firmware", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"updated_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
batch_op.alter_column(
"created_at",
existing_type=sa.TIMESTAMP(timezone=True),
type_=sa.DateTime(timezone=True),
existing_nullable=False,
existing_server_default=sa.text("now()"),
)
# ### end Alembic commands ###

View File

@@ -0,0 +1,65 @@
"""empty message
Revision ID: 0032_longer_fs_fields
Revises: 0031_datetime_to_timestamp
Create Date: 2025-01-24 02:18:30.069263
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0032_longer_fs_fields"
down_revision = "0031_datetime_to_timestamp"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"slug",
existing_type=sa.String(length=50),
type_=sa.String(length=100),
existing_nullable=False,
)
batch_op.alter_column(
"fs_slug",
existing_type=sa.String(length=50),
type_=sa.String(length=100),
existing_nullable=False,
)
batch_op.alter_column(
"category",
existing_type=sa.String(length=50),
type_=sa.String(length=100),
existing_nullable=True,
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
"category",
existing_type=sa.String(length=100),
type_=sa.String(length=50),
existing_nullable=True,
)
batch_op.alter_column(
"fs_slug",
existing_type=sa.String(length=100),
type_=sa.String(length=50),
existing_nullable=False,
)
batch_op.alter_column(
"slug",
existing_type=sa.String(length=100),
type_=sa.String(length=50),
existing_nullable=False,
)
# ### end Alembic commands ###

View File

@@ -0,0 +1,273 @@
"""empty message
Revision ID: 0033_rom_file_and_hashes
Revises: 0032_longer_fs_fields
Create Date: 2024-12-19 23:16:11.053536
"""
import sqlalchemy as sa
from alembic import op
from config import IS_PYTEST_RUN, SCAN_TIMEOUT
from endpoints.sockets.scan import scan_platforms
from handler.redis_handler import high_prio_queue
from handler.scan_handler import ScanType
from sqlalchemy.dialects.postgresql import ENUM
from utils.database import CustomJSON, is_postgresql
# revision identifiers, used by Alembic.
revision = "0033_rom_file_and_hashes"
down_revision = "0032_longer_fs_fields"
branch_labels = None
depends_on = None
def upgrade() -> None:
connection = op.get_bind()
if is_postgresql(connection):
rom_file_category_enum = ENUM(
"DLC",
"HACK",
"MANUAL",
"PATCH",
"UPDATE",
"MOD",
"DEMO",
"TRANSLATION",
"PROTOTYPE",
name="romfilecategory",
create_type=False,
)
rom_file_category_enum.create(connection, checkfirst=False)
else:
rom_file_category_enum = sa.Enum(
"DLC",
"HACK",
"MANUAL",
"PATCH",
"UPDATE",
"MOD",
"DEMO",
"TRANSLATION",
"PROTOTYPE",
name="romfilecategory",
)
op.create_table(
"rom_files",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("rom_id", sa.Integer(), nullable=False),
sa.Column("file_name", sa.String(length=450), nullable=False),
sa.Column("file_path", sa.String(length=1000), nullable=False),
sa.Column("file_size_bytes", sa.BigInteger(), nullable=False),
sa.Column("last_modified", sa.Float(), nullable=True),
sa.Column("crc_hash", sa.String(length=100), nullable=True),
sa.Column("md5_hash", sa.String(length=100), nullable=True),
sa.Column("sha1_hash", sa.String(length=100), nullable=True),
sa.Column("category", rom_file_category_enum, nullable=True),
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(["rom_id"], ["roms.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
if is_postgresql(connection):
op.execute(
"""
INSERT INTO rom_files (
rom_id,
file_name,
file_path,
file_size_bytes,
last_modified,
crc_hash,
md5_hash,
sha1_hash
)
SELECT
r.id AS rom_id,
file_data->>'filename' AS file_name,
CASE WHEN not r.multi THEN r.file_path ELSE CONCAT(TRIM(TRAILING '/' FROM r.file_path), '/', r.file_name) END AS file_path,
(file_data->>'size')::bigint AS file_size_bytes,
(file_data->>'last_modified')::float AS last_modified,
CASE WHEN NOT r.multi THEN r.crc_hash ELSE NULL END AS crc_hash,
CASE WHEN NOT r.multi THEN r.md5_hash ELSE NULL END AS md5_hash,
CASE WHEN NOT r.multi THEN r.sha1_hash ELSE NULL END AS sha1_hash
FROM roms r
CROSS JOIN jsonb_array_elements(r.files) AS file_data;
"""
)
else:
op.execute(
"""
INSERT INTO rom_files (
rom_id,
file_name,
file_path,
file_size_bytes,
last_modified,
crc_hash,
md5_hash,
sha1_hash
)
SELECT
r.id AS rom_id,
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.filename')) AS file_name,
CASE WHEN r.multi = 0 THEN r.file_path ELSE CONCAT(TRIM(TRAILING '/' FROM r.file_path), '/', r.file_name) END AS file_path,
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.size')) AS file_size_bytes,
JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.last_modified')) AS last_modified,
CASE WHEN r.multi = 0 THEN r.crc_hash ELSE NULL END AS crc_hash,
CASE WHEN r.multi = 0 THEN r.md5_hash ELSE NULL END AS md5_hash,
CASE WHEN r.multi = 0 THEN r.sha1_hash ELSE NULL END AS sha1_hash
FROM roms r,
JSON_TABLE(r.files, '$[*]'
COLUMNS (
file_data JSON PATH '$'
)
) AS extracted_files;
"""
)
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.alter_column(
"file_name", new_column_name="fs_name", existing_type=sa.String(length=450)
)
batch_op.alter_column(
"file_name_no_tags",
new_column_name="fs_name_no_tags",
existing_type=sa.String(length=450),
)
batch_op.alter_column(
"file_name_no_ext",
new_column_name="fs_name_no_ext",
existing_type=sa.String(length=450),
)
batch_op.alter_column(
"file_extension",
new_column_name="fs_extension",
existing_type=sa.String(length=100),
)
batch_op.alter_column(
"file_path", new_column_name="fs_path", existing_type=sa.String(length=1000)
)
batch_op.drop_column("files")
batch_op.drop_column("multi")
batch_op.drop_column("file_size_bytes")
# Run a no-scan in the background on migrate
if not IS_PYTEST_RUN:
high_prio_queue.enqueue(
scan_platforms, [], ScanType.QUICK, [], [], job_timeout=SCAN_TIMEOUT
)
high_prio_queue.enqueue(
scan_platforms, [], ScanType.HASHES, [], [], job_timeout=SCAN_TIMEOUT
)
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(
sa.Column("multi", sa.Boolean(), nullable=False, server_default="0")
)
batch_op.alter_column("multi", server_default=None)
batch_op.add_column(sa.Column("files", CustomJSON(), nullable=True))
batch_op.add_column(
sa.Column(
"file_size_bytes", sa.BigInteger(), nullable=False, server_default="0"
)
)
batch_op.alter_column("file_size_bytes", server_default=None)
batch_op.alter_column(
"fs_path", new_column_name="file_path", existing_type=sa.String(length=1000)
)
batch_op.alter_column(
"fs_extension",
new_column_name="file_extension",
existing_type=sa.String(length=100),
)
batch_op.alter_column(
"fs_name_no_ext",
new_column_name="file_name_no_ext",
existing_type=sa.String(length=450),
)
batch_op.alter_column(
"fs_name_no_tags",
new_column_name="file_name_no_tags",
existing_type=sa.String(length=450),
)
batch_op.alter_column(
"fs_name", new_column_name="file_name", existing_type=sa.String(length=450)
)
if is_postgresql(connection):
op.execute(
"""
WITH aggregated_data AS (
SELECT
rom_id,
JSONB_AGG(
JSONB_BUILD_OBJECT(
'filename', file_name,
'size', file_size_bytes,
'last_modified', last_modified
)
) AS files,
COUNT(*) > 1 AS multi,
COALESCE(SUM(file_size_bytes), 0) AS total_size
FROM rom_files
GROUP BY rom_id
)
UPDATE roms
SET
files = aggregated_data.files,
multi = aggregated_data.multi,
file_size_bytes = aggregated_data.total_size
FROM aggregated_data
WHERE roms.id = aggregated_data.rom_id;
"""
)
else:
op.execute(
"""
UPDATE roms
JOIN (
SELECT
rom_id,
JSON_ARRAYAGG(
JSON_OBJECT(
'filename', file_name,
'size', file_size_bytes,
'last_modified', last_modified
)
) AS files,
COUNT(*) > 1 AS multi,
COALESCE(SUM(file_size_bytes), 0) AS total_size
FROM rom_files
GROUP BY rom_id
) AS aggregated_data
ON roms.id = aggregated_data.rom_id
SET
roms.files = aggregated_data.files,
roms.multi = aggregated_data.multi,
roms.file_size_bytes = aggregated_data.total_size;
"""
)
op.drop_table("rom_files")
if is_postgresql(connection):
ENUM(name="romfilecategory").drop(connection, checkfirst=False)

View File

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

View File

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

View File

@@ -8,6 +8,7 @@ Create Date: 2023-04-17 12:03:19.163501
import sqlalchemy as sa
from alembic import op
from utils.database import CustomJSON, is_postgresql
# revision identifiers, used by Alembic.
revision = "1.8.1"
@@ -17,17 +18,29 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
json_array_build_func = (
"jsonb_build_array()" if is_postgresql(connection) else "JSON_ARRAY()"
)
with op.batch_alter_table("roms") as batch_op:
batch_op.add_column(
sa.Column("url_screenshots", sa.JSON(), nullable=False, server_default="[]")
sa.Column(
"url_screenshots",
CustomJSON(),
nullable=False,
server_default=sa.text(f"({json_array_build_func})"),
)
)
batch_op.add_column(
sa.Column(
"path_screenshots", sa.JSON(), nullable=False, server_default="[]"
"path_screenshots",
CustomJSON(),
nullable=False,
server_default=sa.text(f"({json_array_build_func})"),
)
)
# ### end Alembic commands ###
def downgrade() -> None:

View File

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

View File

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

View File

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

View File

@@ -2,6 +2,7 @@ import os
import secrets
from typing import Final
import yarl
from dotenv import load_dotenv
load_dotenv()
@@ -12,8 +13,9 @@ def str_to_bool(value: str) -> bool:
# GUNICORN
DEV_PORT: Final = int(os.environ.get("VITE_BACKEND_DEV_PORT", "5000"))
DEV_HOST: Final = "127.0.0.1"
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"))
GUNICORN_WORKERS: Final = int(os.environ.get("GUNICORN_WORKERS", 2))
# PATHS
@@ -23,12 +25,13 @@ RESOURCES_BASE_PATH: Final = f"{ROMM_BASE_PATH}/resources"
ASSETS_BASE_PATH: Final = f"{ROMM_BASE_PATH}/assets"
FRONTEND_RESOURCES_PATH: Final = "/assets/romm/resources"
# MARIADB
# 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")
# REDIS
REDIS_HOST: Final = os.environ.get("REDIS_HOST", "127.0.0.1")
@@ -36,6 +39,15 @@ REDIS_PORT: Final = int(os.environ.get("REDIS_PORT", 6379))
REDIS_PASSWORD: Final = os.environ.get("REDIS_PASSWORD")
REDIS_USERNAME: Final = os.environ.get("REDIS_USERNAME", "")
REDIS_DB: Final = int(os.environ.get("REDIS_DB", 0))
REDIS_SSL: Final = str_to_bool(os.environ.get("REDIS_SSL", "false"))
REDIS_URL: Final = yarl.URL.build(
scheme="rediss" if REDIS_SSL else "redis",
user=REDIS_USERNAME or None,
password=REDIS_PASSWORD or None,
host=REDIS_HOST,
port=REDIS_PORT,
path=f"/{REDIS_DB}",
)
# IGDB
IGDB_CLIENT_ID: Final = os.environ.get(
@@ -51,9 +63,6 @@ STEAMGRIDDB_API_KEY: Final = os.environ.get("STEAMGRIDDB_API_KEY", "")
# MOBYGAMES
MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "")
# DB DRIVERS
ROMM_DB_DRIVER: Final = os.environ.get("ROMM_DB_DRIVER", "mariadb")
# AUTH
ROMM_AUTH_SECRET_KEY: Final = os.environ.get(
"ROMM_AUTH_SECRET_KEY", secrets.token_hex(32)
@@ -64,6 +73,16 @@ DISABLE_CSRF_PROTECTION = str_to_bool(
DISABLE_DOWNLOAD_ENDPOINT_AUTH = str_to_bool(
os.environ.get("DISABLE_DOWNLOAD_ENDPOINT_AUTH", "false")
)
DISABLE_USERPASS_LOGIN = str_to_bool(os.environ.get("DISABLE_USERPASS_LOGIN", "false"))
# OIDC
OIDC_ENABLED: Final = str_to_bool(os.environ.get("OIDC_ENABLED", "false"))
OIDC_PROVIDER: Final = os.environ.get("OIDC_PROVIDER", "")
OIDC_CLIENT_ID: Final = os.environ.get("OIDC_CLIENT_ID", "")
OIDC_CLIENT_SECRET: Final = os.environ.get("OIDC_CLIENT_SECRET", "")
OIDC_REDIRECT_URI: Final = os.environ.get("OIDC_REDIRECT_URI", "")
OIDC_SERVER_APPLICATION_URL: Final = os.environ.get("OIDC_SERVER_APPLICATION_URL", "")
OIDC_TLS_CACERTFILE: Final = os.environ.get("OIDC_TLS_CACERTFILE", None)
# SCANS
SCAN_TIMEOUT: Final = int(os.environ.get("SCAN_TIMEOUT", 60 * 60 * 4)) # 4 hours
@@ -94,5 +113,17 @@ SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON: Final = os.environ.get(
DISABLE_EMULATOR_JS = str_to_bool(os.environ.get("DISABLE_EMULATOR_JS", "false"))
DISABLE_RUFFLE_RS = str_to_bool(os.environ.get("DISABLE_RUFFLE_RS", "false"))
# FRONTEND
UPLOAD_TIMEOUT = int(os.environ.get("UPLOAD_TIMEOUT", 600))
KIOSK_MODE = str_to_bool(os.environ.get("KIOSK_MODE", "false"))
# LOGGING
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"))
# SENTRY
SENTRY_DSN: Final = os.environ.get("SENTRY_DSN", None)
# TESTING
IS_PYTEST_RUN: Final = bool(os.environ.get("PYTEST_VERSION", False))

View File

@@ -83,30 +83,36 @@ class ConfigManager:
str: database connection string
"""
if ROMM_DB_DRIVER == "mariadb":
if not DB_USER or not DB_PASSWD:
log.critical(
"Missing database credentials, check your environment variables!"
)
sys.exit(3)
return URL.create(
drivername="mariadb+mariadbconnector",
username=DB_USER,
password=DB_PASSWD,
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
)
# DEPRECATED
if ROMM_DB_DRIVER == "sqlite":
log.critical("Sqlite is not supported anymore, migrate to mariaDB")
sys.exit(6)
# DEPRECATED
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)
if ROMM_DB_DRIVER == "mariadb":
driver = "mariadb+mariadbconnector"
elif ROMM_DB_DRIVER == "mysql":
driver = "mysql+mysqlconnector"
elif ROMM_DB_DRIVER == "postgresql":
driver = "postgresql+psycopg"
else:
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)
if not DB_USER or not DB_PASSWD:
log.critical(
"Missing database credentials, check your environment variables!"
)
sys.exit(3)
return URL.create(
drivername=driver,
username=DB_USER,
password=DB_PASSWD,
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
)
def _parse_config(self):
"""Parses each entry in the config.yml"""
@@ -270,7 +276,7 @@ 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.warn(f"Binding for {fs_slug} already exists")
log.warning(f"Binding for {fs_slug} already exists")
return
platform_bindings[fs_slug] = slug
@@ -291,7 +297,7 @@ 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.warn(f"Version for {fs_slug} already exists")
log.warning(f"Version for {fs_slug} already exists")
return
platform_versions[fs_slug] = slug
@@ -309,21 +315,25 @@ class ConfigManager:
self.config.PLATFORMS_VERSIONS = platform_versions
self.update_config_file()
def add_exclusion(self, config_key: str, exclusion: str):
config_item = self.config.__getattribute__(config_key)
config_item.append(exclusion)
self.config.__setattr__(config_key, config_item)
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
config_item.append(exclusion_value)
self.config.__setattr__(exclusion_type, config_item)
self.update_config_file()
def remove_exclusion(self, config_key: str, exclusion: str):
config_item = self.config.__getattribute__(config_key)
def remove_exclusion(self, exclusion_type: str, exclusion_value: str):
config_item = self.config.__getattribute__(exclusion_type)
try:
config_item.remove(exclusion)
config_item.remove(exclusion_value)
except ValueError:
pass
self.config.__setattr__(config_key, config_item)
self.config.__setattr__(exclusion_type, config_item)
self.update_config_file()

View File

@@ -1,34 +1,75 @@
from typing import Any
from authlib.integrations.starlette_client import OAuth
from authlib.oidc.discovery import get_well_known_url
from config import (
OIDC_CLIENT_ID,
OIDC_CLIENT_SECRET,
OIDC_ENABLED,
OIDC_PROVIDER,
OIDC_REDIRECT_URI,
OIDC_SERVER_APPLICATION_URL,
OIDC_TLS_CACERTFILE,
)
from fastapi import Security
from fastapi.security.http import HTTPBasic
from fastapi.security.oauth2 import OAuth2PasswordBearer
from fastapi.types import DecoratedCallable
from handler.auth.base_handler import (
DEFAULT_SCOPES_MAP,
from handler.auth.constants import (
EDIT_SCOPES_MAP,
FULL_SCOPES_MAP,
READ_SCOPES_MAP,
WRITE_SCOPES_MAP,
Scope,
)
from starlette.authentication import requires
from starlette.config import Config
# Using the internal password flow
oauth2_password_bearer = OAuth2PasswordBearer(
tokenUrl="/token",
auto_error=False,
scopes={
**DEFAULT_SCOPES_MAP,
**READ_SCOPES_MAP,
**WRITE_SCOPES_MAP,
**EDIT_SCOPES_MAP,
**FULL_SCOPES_MAP,
},
)
# Using an OIDC authorization code flow
config = Config(
environ={
"OIDC_ENABLED": str(OIDC_ENABLED),
"OIDC_PROVIDER": OIDC_PROVIDER,
"OIDC_CLIENT_ID": OIDC_CLIENT_ID,
"OIDC_CLIENT_SECRET": OIDC_CLIENT_SECRET,
"OIDC_REDIRECT_URI": OIDC_REDIRECT_URI,
"OIDC_SERVER_APPLICATION_URL": OIDC_SERVER_APPLICATION_URL,
}
)
oauth = OAuth(config=config)
oauth.register(
name="openid",
client_id=config.get("OIDC_CLIENT_ID"),
client_secret=config.get("OIDC_CLIENT_SECRET"),
server_metadata_url=get_well_known_url(
config.get("OIDC_SERVER_APPLICATION_URL"), external=True
),
client_kwargs={
"scope": "openid profile email",
"verify": OIDC_TLS_CACERTFILE,
},
)
def protected_route(
method: Any,
path: str,
scopes: list[str] | None = None,
scopes: list[Scope] | None = None,
**kwargs,
):
def decorator(func: DecoratedCallable):
def decorator(func: DecoratedCallable) -> DecoratedCallable:
fn = requires(scopes or [])(func)
return method(
path,

View File

@@ -1,20 +1,86 @@
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from typing import Annotated, Final
from config import DISABLE_USERPASS_LOGIN, OIDC_ENABLED, OIDC_REDIRECT_URI
from decorators.auth import oauth
from endpoints.forms.identity import OAuth2RequestForm
from endpoints.responses import MessageResponse
from endpoints.responses.oauth import TokenResponse
from exceptions.auth_exceptions import AuthCredentialsException, DisabledException
from exceptions.auth_exceptions import (
AuthCredentialsException,
OIDCDisabledException,
OIDCNotConfiguredException,
UserDisabledException,
UserPassDisabledException,
)
from fastapi import Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from fastapi.security.http import HTTPBasic
from handler.auth import auth_handler, oauth_handler
from handler.auth import auth_handler, oauth_handler, oidc_handler
from handler.database import db_user_handler
from utils.router import APIRouter
ACCESS_TOKEN_EXPIRE_MINUTES: Final = 30
REFRESH_TOKEN_EXPIRE_DAYS: Final = 7
router = APIRouter()
router = APIRouter(
tags=["auth"],
)
# Session authentication endpoints
@router.post("/login")
def login(
request: Request,
credentials=Depends(HTTPBasic()), # noqa
) -> MessageResponse:
"""Session login endpoint
Args:
request (Request): Fastapi Request object
credentials: Defaults to Depends(HTTPBasic()).
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
if not user.enabled:
raise UserDisabledException
request.session.update({"iss": "romm:auth", "sub": user.username})
# Update last login and active times
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:
"""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")
@@ -48,6 +114,11 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
user, claims = await oauth_handler.get_current_active_user_from_bearer_token(
token
)
if not user or not claims:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
)
if claims.get("type") != "refresh":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token"
@@ -133,52 +204,73 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
}
@router.post("/login")
def login(
request: Request, credentials=Depends(HTTPBasic()) # noqa
) -> MessageResponse:
"""Session login endpoint
# OIDC login and callback endpoints
@router.get("/login/openid")
async def login_via_openid(request: Request):
"""OIDC login endpoint
Args:
request (Request): Fastapi Request object
credentials: Defaults to Depends(HTTPBasic()).
Raises:
CredentialsException: Invalid credentials
DisabledException: Auth is disabled
OIDCDisabledException: OAuth is disabled
OIDCNotConfiguredException: OAuth not configured
Returns:
MessageResponse: Standard message response
RedirectResponse: Redirect to OIDC provider
"""
user = auth_handler.authenticate_user(credentials.username, credentials.password)
if not user:
raise AuthCredentialsException
if not OIDC_ENABLED:
raise OIDCDisabledException
if not user.enabled:
raise DisabledException
if not oauth.openid:
raise OIDCNotConfiguredException
request.session.update({"iss": "romm:auth", "sub": user.username})
# Update last login and active times
db_user_handler.update_user(
user.id, {"last_login": datetime.now(), "last_active": datetime.now()}
)
return {"msg": "Successfully logged in"}
return await oauth.openid.authorize_redirect(request, OIDC_REDIRECT_URI)
@router.post("/logout")
def logout(request: Request) -> MessageResponse:
"""Session logout endpoint
@router.get("/oauth/openid")
async def auth_openid(request: Request):
"""OIDC callback endpoint
Args:
request (Request): Fastapi Request object
Raises:
OIDCDisabledException: OAuth is disabled
OIDCNotConfiguredException: OAuth not configured
AuthCredentialsException: Invalid credentials
UserDisabledException: Auth is disabled
Returns:
MessageResponse: Standard message response
RedirectResponse: Redirect to home page
"""
request.session.clear()
if not OIDC_ENABLED:
raise OIDCDisabledException
return {"msg": "Successfully logged out"}
if not oauth.openid:
raise OIDCNotConfiguredException
token = await oauth.openid.authorize_access_token(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
if not potential_user.enabled:
raise UserDisabledException
request.session.update({"iss": "romm:auth", "sub": potential_user.username})
# Update last login and active times
now = datetime.now(timezone.utc)
db_user_handler.update_user(
potential_user.id, {"last_login": now, "last_active": now}
)
return RedirectResponse(url="/")

View File

@@ -1,7 +1,8 @@
import json
from io import BytesIO
from shutil import rmtree
from anyio import open_file
from anyio import Path
from config import RESOURCES_BASE_PATH
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
@@ -12,18 +13,23 @@ from exceptions.endpoint_exceptions import (
CollectionPermissionError,
)
from fastapi import Request, UploadFile
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.logger import log
from models.collection import Collection
from PIL import Image
from sqlalchemy.inspection import inspect
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/collections",
tags=["collections"],
)
@protected_route(router.post, "/collections", ["collections.write"])
@protected_route(router.post, "/", [Scope.COLLECTIONS_WRITE])
async def add_collection(
request: Request,
artwork: UploadFile | None = None,
@@ -54,7 +60,7 @@ async def add_collection(
_added_collection = db_collection_handler.add_collection(Collection(**cleaned_data))
if artwork is not None:
if artwork is not None and artwork.filename is not None:
file_ext = artwork.filename.split(".")[-1]
(
path_cover_l,
@@ -62,15 +68,14 @@ async def add_collection(
artwork_path,
) = await fs_resource_handler.build_artwork_path(_added_collection, file_ext)
artwork_file = artwork.file.read()
file_location_s = f"{artwork_path}/small.{file_ext}"
async with await open_file(file_location_s, "wb+") as artwork_s:
await artwork_s.write(artwork_file)
fs_resource_handler.resize_cover_to_small(file_location_s)
file_location_l = f"{artwork_path}/big.{file_ext}"
async with await open_file(file_location_l, "wb+") as artwork_l:
await artwork_l.write(artwork_file)
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
)
else:
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
overwrite=True,
@@ -80,8 +85,9 @@ async def add_collection(
_added_collection.path_cover_s = path_cover_s
_added_collection.path_cover_l = path_cover_l
# Update the collection with the cover path and update database
return db_collection_handler.update_collection(
created_collection = db_collection_handler.update_collection(
_added_collection.id,
{
c: getattr(_added_collection, c)
@@ -89,8 +95,10 @@ async def add_collection(
},
)
return CollectionSchema.model_validate(created_collection)
@protected_route(router.get, "/collections", ["collections.read"])
@protected_route(router.get, "/", [Scope.COLLECTIONS_READ])
def get_collections(request: Request) -> list[CollectionSchema]:
"""Get collections endpoint
@@ -103,10 +111,10 @@ def get_collections(request: Request) -> list[CollectionSchema]:
"""
collections = db_collection_handler.get_collections()
return CollectionSchema.for_user(request.user.id, collections)
return CollectionSchema.for_user(request.user.id, [c for c in collections])
@protected_route(router.get, "/collections/{id}", ["collections.read"])
@protected_route(router.get, "/{id}", [Scope.COLLECTIONS_READ])
def get_collection(request: Request, id: int) -> CollectionSchema:
"""Get collections endpoint
@@ -123,10 +131,10 @@ def get_collection(request: Request, id: int) -> CollectionSchema:
if not collection:
raise CollectionNotFoundInDatabaseException(id)
return collection
return CollectionSchema.model_validate(collection)
@protected_route(router.put, "/collections/{id}", ["collections.write"])
@protected_route(router.put, "/{id}", [Scope.COLLECTIONS_WRITE])
async def update_collection(
request: Request,
id: int,
@@ -146,6 +154,8 @@ async def update_collection(
data = await request.form()
collection = db_collection_handler.get_collection(id)
if not collection:
raise CollectionNotFoundInDatabaseException(id)
if collection.user_id != request.user.id:
raise CollectionPermissionError(id)
@@ -154,7 +164,7 @@ async def update_collection(
raise CollectionNotFoundInDatabaseException(id)
try:
roms = json.loads(data["roms"])
roms = json.loads(data["roms"]) # type: ignore
except json.JSONDecodeError as e:
raise ValueError("Invalid list for roms field in update collection") from e
except KeyError:
@@ -172,7 +182,7 @@ async def update_collection(
cleaned_data.update(fs_resource_handler.remove_cover(collection))
cleaned_data.update({"url_cover": ""})
else:
if artwork is not None:
if artwork is not None and artwork.filename is not None:
file_ext = artwork.filename.split(".")[-1]
(
path_cover_l,
@@ -183,15 +193,15 @@ async def update_collection(
cleaned_data["path_cover_l"] = path_cover_l
cleaned_data["path_cover_s"] = path_cover_s
artwork_file = artwork.file.read()
file_location_s = f"{artwork_path}/small.{file_ext}"
async with await open_file(file_location_s, "wb+") as artwork_s:
await artwork_s.write(artwork_file)
fs_resource_handler.resize_cover_to_small(file_location_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
)
file_location_l = f"{artwork_path}/big.{file_ext}"
async with await open_file(file_location_l, "wb+") as artwork_l:
await artwork_l.write(artwork_file)
cleaned_data.update({"url_cover": ""})
else:
if data.get("url_cover", "") != collection.url_cover or not (
@@ -203,16 +213,18 @@ async def update_collection(
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
overwrite=True,
entity=collection,
url_cover=data.get("url_cover", ""),
url_cover=data.get("url_cover", ""), # type: ignore
)
cleaned_data.update(
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
)
return db_collection_handler.update_collection(id, cleaned_data)
updated_collection = db_collection_handler.update_collection(id, cleaned_data)
return CollectionSchema.model_validate(updated_collection)
@protected_route(router.delete, "/collections/{id}", ["collections.write"])
@protected_route(router.delete, "/{id}", [Scope.COLLECTIONS_WRITE])
async def delete_collections(request: Request, id: int) -> MessageResponse:
"""Delete collections endpoint

View File

@@ -7,13 +7,17 @@ from exceptions.config_exceptions import (
ConfigNotWritableException,
)
from fastapi import HTTPException, Request, status
from handler.auth.constants import Scope
from logger.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/config",
tags=["config"],
)
@router.get("/config")
@router.get("/")
def get_config() -> ConfigResponse:
"""Get config endpoint
@@ -32,9 +36,6 @@ def get_config() -> ConfigResponse:
EXCLUDED_MULTI_PARTS_FILES=cfg.EXCLUDED_MULTI_PARTS_FILES,
PLATFORMS_BINDING=cfg.PLATFORMS_BINDING,
PLATFORMS_VERSIONS=cfg.PLATFORMS_VERSIONS,
ROMS_FOLDER_NAME=cfg.ROMS_FOLDER_NAME,
FIRMWARE_FOLDER_NAME=cfg.FIRMWARE_FOLDER_NAME,
HIGH_PRIO_STRUCTURE_PATH=cfg.HIGH_PRIO_STRUCTURE_PATH,
)
except ConfigNotReadableException as exc:
log.critical(exc.message)
@@ -43,7 +44,7 @@ def get_config() -> ConfigResponse:
) from exc
@protected_route(router.post, "/config/system/platforms", ["platforms.write"])
@protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE])
async def add_platform_binding(request: Request) -> MessageResponse:
"""Add platform binding to the configuration"""
@@ -62,9 +63,7 @@ async def add_platform_binding(request: Request) -> MessageResponse:
return {"msg": f"{fs_slug} binded to: {slug} successfully!"}
@protected_route(
router.delete, "/config/system/platforms/{fs_slug}", ["platforms.write"]
)
@protected_route(router.delete, "/system/platforms/{fs_slug}", [Scope.PLATFORMS_WRITE])
async def delete_platform_binding(request: Request, fs_slug: str) -> MessageResponse:
"""Delete platform binding from the configuration"""
@@ -79,7 +78,7 @@ async def delete_platform_binding(request: Request, fs_slug: str) -> MessageResp
return {"msg": f"{fs_slug} bind removed successfully!"}
@protected_route(router.post, "/config/system/versions", ["platforms.write"])
@protected_route(router.post, "/system/versions", [Scope.PLATFORMS_WRITE])
async def add_platform_version(request: Request) -> MessageResponse:
"""Add platform version to the configuration"""
@@ -98,9 +97,7 @@ async def add_platform_version(request: Request) -> MessageResponse:
return {"msg": f"Added {fs_slug} as version of: {slug} successfully!"}
@protected_route(
router.delete, "/config/system/versions/{fs_slug}", ["platforms.write"]
)
@protected_route(router.delete, "/system/versions/{fs_slug}", [Scope.PLATFORMS_WRITE])
async def delete_platform_version(request: Request, fs_slug: str) -> MessageResponse:
"""Delete platform version from the configuration"""
@@ -115,25 +112,44 @@ async def delete_platform_version(request: Request, fs_slug: str) -> MessageResp
return {"msg": f"{fs_slug} version removed successfully!"}
# @protected_route(router.post, "/config/exclude", ["platforms.write"])
# async def add_exclusion(request: Request) -> MessageResponse:
# """Add platform binding to the configuration"""
@protected_route(router.post, "/exclude", [Scope.PLATFORMS_WRITE])
async def add_exclusion(request: Request) -> MessageResponse:
"""Add platform exclusion to the configuration"""
# data = await request.json()
# exclude = data['exclude']
# exclusion = data['exclusion']
# cm.add_exclusion(exclude, exclusion)
data = await request.json()
exclusion_value = data["exclusion_value"]
exclusion_type = data["exclusion_type"]
try:
cm.add_exclusion(exclusion_type, exclusion_value)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
# return {"msg": f"Exclusion {exclusion} added to {exclude} successfully!"}
return {
"msg": f"Exclusion {exclusion_value} added to {exclusion_type} successfully!"
}
# @protected_route(router.delete, "/config/exclude", ["platforms.write"])
# async def delete_exclusion(request: Request) -> MessageResponse:
# """Delete platform binding from the configuration"""
@protected_route(
router.delete,
"/exclude/{exclusion_type}/{exclusion_value}",
[Scope.PLATFORMS_WRITE],
)
async def delete_exclusion(
request: Request, exclusion_type: str, exclusion_value: str
) -> MessageResponse:
"""Delete platform binding from the configuration"""
# data = await request.json()
# exclude = data['exclude']
# exclusion = data['exclusion']
# cm.remove_exclusion(exclude, exclusion)
try:
cm.remove_exclusion(exclusion_type, exclusion_value)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
# return {"msg": f"Exclusion {exclusion} removed from {exclude} successfully!"}
return {
"msg": f"Exclusion {exclusion_value} removed from {exclusion_type} successfully!"
}

View File

@@ -1,3 +1,5 @@
from typing import Sequence
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
from decorators.auth import protected_route
from endpoints.responses.feeds import (
@@ -12,6 +14,7 @@ from endpoints.responses.feeds import (
WebrcadeFeedSchema,
)
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
@@ -19,13 +22,15 @@ from models.rom import Rom
from starlette.datastructures import URLPath
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
tags=["feeds"],
)
@protected_route(
router.get,
"/webrcade/feed",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["roms.read"],
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
)
def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
"""Get webrcade feed endpoint
@@ -56,7 +61,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
request.url_for(
"get_rom_content",
id=rom.id,
file_name=rom.file_name,
file_name=rom.fs_name,
)
),
),
@@ -129,15 +134,17 @@ async def tinfoil_index_feed(
error="Nintendo Switch platform not found",
)
roms: list[Rom] = db_rom_handler.get_roms(platform_id=switch.id)
roms = db_rom_handler.get_roms(platform_id=switch.id)
async def extract_titledb(roms: list[Rom]) -> dict[str, TinfoilFeedTitleDBSchema]:
async def extract_titledb(
roms: Sequence[Rom],
) -> dict[str, TinfoilFeedTitleDBSchema]:
titledb = {}
for rom in roms:
match = SWITCH_TITLEDB_REGEX.search(rom.file_name)
match = SWITCH_TITLEDB_REGEX.search(rom.fs_name)
if match:
_search_term, index_entry = (
await meta_igdb_handler._switch_titledb_format(match, rom.file_name)
await meta_igdb_handler._switch_titledb_format(match, rom.fs_name)
)
if index_entry:
titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema(
@@ -159,11 +166,9 @@ async def tinfoil_index_feed(
files=[
TinfoilFeedFileSchema(
url=str(
request.url_for(
"get_rom_content", id=rom.id, file_name=rom.file_name
)
request.url_for("get_rom_content", id=rom.id, file_name=rom.fs_name)
),
size=rom.file_size_bytes,
size=rom.fs_size_bytes,
)
for rom in roms
],

View File

@@ -4,16 +4,20 @@ from endpoints.responses import MessageResponse
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
from fastapi import File, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse
from handler.auth.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.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/firmware",
tags=["firmware"],
)
@protected_route(router.post, "/firmware", ["firmware.write"])
@protected_route(router.post, "/", [Scope.FIRMWARE_WRITE])
def add_firmware(
request: Request,
platform_id: int,
@@ -27,25 +31,28 @@ def add_firmware(
files (list[UploadFile], optional): List of files to upload
Raises:
HTTPException: No files were uploaded
HTTPException
Returns:
AddFirmwareResponse: Standard message response
"""
db_platform = db_platform_handler.get_platform(platform_id)
if not db_platform:
error = f"Platform with ID {platform_id} not found"
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
log.info(f"Uploading firmware to {db_platform.fs_slug}")
if files is None:
log.error("No files were uploaded")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="No files were uploaded",
)
uploaded_firmware = []
firmware_path = fs_firmware_handler.build_upload_file_path(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)
db_firmware = db_firmware_handler.get_firmware_by_filename(
@@ -68,15 +75,16 @@ def add_firmware(
db_firmware_handler.add_firmware(scanned_firmware)
uploaded_firmware.append(scanned_firmware)
db_platform = db_platform_handler.get_platform(platform_id)
return {
"uploaded": len(files),
"firmware": db_platform.firmware,
"firmware": [
FirmwareSchema.model_validate(f)
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
],
}
@protected_route(router.get, "/firmware", ["firmware.read"])
@protected_route(router.get, "/", [Scope.FIRMWARE_READ])
def get_platform_firmware(
request: Request,
platform_id: int | None = None,
@@ -89,13 +97,16 @@ def get_platform_firmware(
Returns:
list[FirmwareSchema]: Firmware stored in the database
"""
return db_firmware_handler.list_firmware(platform_id=platform_id)
return [
FirmwareSchema.model_validate(f)
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
]
@protected_route(
router.get,
"/firmware/{id}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["firmware.read"],
"/{id}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def get_firmware(request: Request, id: int) -> FirmwareSchema:
"""Get firmware endpoint
@@ -107,13 +118,19 @@ def get_firmware(request: Request, id: int) -> FirmwareSchema:
Returns:
FirmwareSchema: Firmware stored in the database
"""
return FirmwareSchema(**db_firmware_handler.get_firmware(id))
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)
return FirmwareSchema.model_validate(firmware)
@protected_route(
router.head,
"/firmware/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["firmware.read"],
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def head_firmware_content(request: Request, id: int, file_name: str):
"""Head firmware content endpoint
@@ -128,6 +145,11 @@ def head_firmware_content(request: Request, id: int, file_name: str):
"""
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)
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
return FileResponse(
@@ -139,7 +161,11 @@ def head_firmware_content(request: Request, id: int, file_name: str):
)
@protected_route(router.get, "/firmware/{id}/content/{file_name}", ["firmware.read"])
@protected_route(
router.get,
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def get_firmware_content(
request: Request,
id: int,
@@ -157,12 +183,17 @@ def get_firmware_content(
"""
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)
firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}"
return FileResponse(path=firmware_path, filename=firmware.file_name)
@protected_route(router.post, "/firmware/delete", ["firmware.write"])
@protected_route(router.post, "/delete", [Scope.FIRMWARE_WRITE])
async def delete_firmware(
request: Request,
) -> MessageResponse:

View File

@@ -7,12 +7,14 @@ class UserForm:
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

View File

@@ -1,12 +1,16 @@
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,
OIDC_ENABLED,
OIDC_PROVIDER,
RESCAN_ON_FILESYSTEM_CHANGE_DELAY,
SCHEDULED_RESCAN_CRON,
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
UPLOAD_TIMEOUT,
)
from endpoints.responses.heartbeat import HeartbeatResponse
from handler.database import db_user_handler
@@ -17,7 +21,9 @@ from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED
from utils import get_version
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
tags=["system"],
)
@router.get("/heartbeat")
@@ -29,15 +35,19 @@ def heartbeat() -> HeartbeatResponse:
"""
return {
"VERSION": get_version(),
"SHOW_SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0,
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED,
"SYSTEM": {
"VERSION": get_version(),
"SHOW_SETUP_WIZARD": len(db_user_handler.get_admin_users()) == 0,
},
"METADATA_SOURCES": {
"ANY_SOURCE_ENABLED": IGDB_API_ENABLED or MOBY_API_ENABLED,
"IGDB_API_ENABLED": IGDB_API_ENABLED,
"MOBY_API_ENABLED": MOBY_API_ENABLED,
"STEAMGRIDDB_ENABLED": STEAMGRIDDB_API_ENABLED,
},
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
"FILESYSTEM": {
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
},
"WATCHER": {
"ENABLED": ENABLE_RESCAN_ON_FILESYSTEM_CHANGE,
"TITLE": "Rescan on filesystem change",
@@ -61,4 +71,12 @@ def heartbeat() -> HeartbeatResponse:
"DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS,
"DISABLE_RUFFLE_RS": DISABLE_RUFFLE_RS,
},
"FRONTEND": {
"UPLOAD_TIMEOUT": UPLOAD_TIMEOUT,
"DISABLE_USERPASS_LOGIN": DISABLE_USERPASS_LOGIN,
},
"OIDC": {
"ENABLED": OIDC_ENABLED,
"PROVIDER": OIDC_PROVIDER,
},
}

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, timezone
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
@@ -6,18 +6,21 @@ from endpoints.responses.platform import PlatformSchema
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
from exceptions.fs_exceptions import PlatformAlreadyExistsException
from fastapi import Request
from handler.auth.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.scan_handler import scan_platform
from logger.logger import log
from models.platform import Platform
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/platforms",
tags=["platforms"],
)
@protected_route(router.post, "/platforms", ["platforms.write"])
@protected_route(router.post, "/", [Scope.PLATFORMS_WRITE])
async def add_platforms(request: Request) -> PlatformSchema:
"""Create platform endpoint
@@ -35,10 +38,12 @@ async def add_platforms(request: Request) -> PlatformSchema:
except PlatformAlreadyExistsException:
log.info(f"Detected platform: {fs_slug}")
scanned_platform = await scan_platform(fs_slug, [fs_slug])
return db_platform_handler.add_platform(scanned_platform)
return PlatformSchema.model_validate(
db_platform_handler.add_platform(scanned_platform)
)
@protected_route(router.get, "/platforms", ["platforms.read"])
@protected_route(router.get, "/", [Scope.PLATFORMS_READ])
def get_platforms(request: Request) -> list[PlatformSchema]:
"""Get platforms endpoint
@@ -50,10 +55,12 @@ def get_platforms(request: Request) -> list[PlatformSchema]:
list[PlatformSchema]: List of platforms
"""
return db_platform_handler.get_platforms()
return [
PlatformSchema.model_validate(p) for p in db_platform_handler.get_platforms()
]
@protected_route(router.get, "/platforms/supported", ["platforms.read"])
@protected_route(router.get, "/supported", [Scope.PLATFORMS_READ])
def get_supported_platforms(request: Request) -> list[PlatformSchema]:
"""Get list of supported platforms endpoint
@@ -65,10 +72,11 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
"""
supported_platforms = []
db_platforms: list[Platform] = db_platform_handler.get_platforms()
db_platforms = db_platform_handler.get_platforms()
db_platforms_map = {p.name: p.id for p in db_platforms}
for platform in IGDB_PLATFORM_LIST:
now = datetime.now(timezone.utc)
sup_plat = {
"id": -1,
"name": platform["name"],
@@ -77,8 +85,8 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
"logo_path": "",
"roms": [],
"rom_count": 0,
"created_at": datetime.now(),
"updated_at": datetime.now(),
"created_at": now,
"updated_at": now,
}
if platform["name"] in db_platforms_map:
@@ -89,7 +97,7 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]:
return supported_platforms
@protected_route(router.get, "/platforms/{id}", ["platforms.read"])
@protected_route(router.get, "/{id}", [Scope.PLATFORMS_READ])
def get_platform(request: Request, id: int) -> PlatformSchema:
"""Get platforms endpoint
@@ -106,24 +114,34 @@ def get_platform(request: Request, id: int) -> PlatformSchema:
if not platform:
raise PlatformNotFoundInDatabaseException(id)
return platform
return PlatformSchema.model_validate(platform)
@protected_route(router.put, "/platforms/{id}", ["platforms.write"])
async def update_platform(request: Request) -> MessageResponse:
@protected_route(router.put, "/{id}", [Scope.PLATFORMS_WRITE])
async def update_platform(request: Request, id: int) -> PlatformSchema:
"""Update platform endpoint
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)
return {"msg": "Enpoint not available yet"}
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)
platform_db = db_platform_handler.add_platform(platform_db)
return PlatformSchema.model_validate(platform_db)
@protected_route(router.delete, "/platforms/{id}", ["platforms.write"])
@protected_route(router.delete, "/{id}", [Scope.PLATFORMS_WRITE])
async def delete_platforms(request: Request, id: int) -> MessageResponse:
"""Delete platforms endpoint

View File

@@ -2,18 +2,22 @@ from config import ASSETS_BASE_PATH
from decorators.auth import protected_route
from fastapi import Request
from fastapi.responses import FileResponse
from handler.auth.constants import Scope
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/raw",
tags=["raw"],
)
@protected_route(router.head, "/raw/assets/{path:path}", ["assets.read"])
@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])
@protected_route(router.get, "/raw/assets/{path:path}", ["assets.read"])
@protected_route(router.get, "/assets/{path:path}", [Scope.ASSETS_READ])
def get_raw_asset(request: Request, path: str):
"""Download a single asset file

View File

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

View File

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

View File

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

View File

@@ -10,6 +10,3 @@ class ConfigResponse(TypedDict):
EXCLUDED_MULTI_PARTS_FILES: list[str]
PLATFORMS_BINDING: dict[str, str]
PLATFORMS_VERSIONS: dict[str, str]
ROMS_FOLDER_NAME: str
FIRMWARE_FOLDER_NAME: str
HIGH_PRIO_STRUCTURE_PATH: str

View File

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

View File

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

View File

@@ -1,12 +1,14 @@
from datetime import datetime
from models.user import Role
from pydantic import BaseModel
from .base import BaseModel
class UserSchema(BaseModel):
id: int
username: str
email: str | None
enabled: bool
role: Role
oauth_scopes: list[str]

View File

@@ -1,7 +1,9 @@
from datetime import datetime
from pydantic import BaseModel, Field
from models.platform import DEFAULT_COVER_ASPECT_RATIO
from pydantic import Field, computed_field
from .base import BaseModel
from .firmware import FirmwareSchema
@@ -9,16 +11,28 @@ class PlatformSchema(BaseModel):
id: int
slug: str
fs_slug: str
name: str
rom_count: int
name: str
custom_name: str | None = None
igdb_id: int | None = None
sgdb_id: int | None = None
moby_id: int | None = None
logo_path: str | 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
class Config:
from_attributes = True
@computed_field # type: ignore
@property
def display_name(self) -> str:
return self.custom_name or self.name

View File

@@ -1,7 +1,7 @@
from __future__ import annotations
import re
from datetime import datetime
from datetime import datetime, timezone
from typing import NotRequired, TypedDict, get_type_hints
from endpoints.responses.assets import SaveSchema, ScreenshotSchema, StateSchema
@@ -9,44 +9,78 @@ from endpoints.responses.collection import CollectionSchema
from fastapi import Request
from handler.metadata.igdb_handler import IGDBMetadata
from handler.metadata.moby_handler import MobyMetadata
from models.rom import Rom, RomFile
from pydantic import BaseModel, Field, computed_field
from models.rom import Rom, RomFileCategory, RomUserStatus
from pydantic import computed_field
from .base import BaseModel
SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s")
RomIGDBMetadata = TypedDict( # type: ignore[misc]
"RomIGDBMetadata",
{k: NotRequired[v] for k, v in get_type_hints(IGDBMetadata).items()},
dict((k, NotRequired[v]) for k, v in get_type_hints(IGDBMetadata).items()),
total=False,
)
RomMobyMetadata = TypedDict( # type: ignore[misc]
"RomMobyMetadata",
{k: NotRequired[v] for k, v in get_type_hints(MobyMetadata).items()},
dict((k, NotRequired[v]) for k, v in get_type_hints(MobyMetadata).items()),
total=False,
)
def rom_user_schema_factory() -> RomUserSchema:
now = datetime.now(timezone.utc)
return RomUserSchema(
id=-1,
user_id=-1,
rom_id=-1,
created_at=now,
updated_at=now,
last_played=None,
note_raw_markdown="",
note_is_public=False,
is_main_sibling=False,
backlogged=False,
now_playing=False,
hidden=False,
rating=0,
difficulty=0,
completion=0,
status=None,
user__username="",
)
class RomUserSchema(BaseModel):
id: int
user_id: int
rom_id: int
created_at: datetime
updated_at: datetime
last_played: datetime | None
note_raw_markdown: str
note_is_public: bool
is_main_sibling: bool
backlogged: bool
now_playing: bool
hidden: bool
rating: int
difficulty: int
completion: int
status: RomUserStatus | None
user__username: str
class Config:
from_attributes = True
@classmethod
def for_user(cls, user_id: int, db_rom: Rom) -> RomUserSchema | None:
def for_user(cls, user_id: int, db_rom: Rom) -> RomUserSchema:
for n in db_rom.rom_users:
if n.user_id == user_id:
return cls.model_validate(n)
return None
# Return a dummy RomUserSchema if the user + rom combination doesn't exist
return rom_user_schema_factory()
@classmethod
def notes_for_user(cls, user_id: int, db_rom: Rom) -> list[UserNotesSchema]:
@@ -62,6 +96,25 @@ class RomUserSchema(BaseModel):
]
class RomFileSchema(BaseModel):
id: int
rom_id: int
file_name: str
file_path: str
file_size_bytes: int
full_path: str
created_at: datetime
updated_at: datetime
last_modified: datetime
crc_hash: str | None
md5_hash: str | None
sha1_hash: str | None
category: RomFileCategory | None
class Config:
from_attributes = True
class RomSchema(BaseModel):
id: int
igdb_id: int | None
@@ -70,14 +123,17 @@ class RomSchema(BaseModel):
platform_id: int
platform_slug: str
platform_fs_slug: str
platform_name: str
platform_custom_name: str | None
platform_display_name: str
file_name: str
file_name_no_tags: str
file_name_no_ext: str
file_extension: str
file_path: str
file_size_bytes: int
fs_name: str
fs_name_no_tags: str
fs_name_no_ext: str
fs_extension: str
fs_path: str
fs_size_bytes: int
name: str | None
slug: str | None
@@ -85,12 +141,15 @@ class RomSchema(BaseModel):
# Metadata fields
first_release_date: int | None
youtube_video_id: str | None
average_rating: float | None
alternative_names: list[str]
genres: list[str]
franchises: list[str]
collections: list[str]
companies: list[str]
game_modes: list[str]
age_ratings: list[str]
igdb_metadata: RomIGDBMetadata | None
moby_metadata: RomMobyMetadata | None
@@ -104,11 +163,12 @@ class RomSchema(BaseModel):
languages: list[str]
tags: list[str]
multi: bool
files: list[RomFile]
crc_hash: str | None
md5_hash: str | None
sha1_hash: str | None
multi: bool
files: list[RomFileSchema]
full_path: str
created_at: datetime
updated_at: datetime
@@ -122,60 +182,65 @@ class RomSchema(BaseModel):
return (
SORT_COMPARE_REGEX.sub(
"",
self.name or self.file_name_no_tags,
self.name or self.fs_name_no_tags,
)
.strip()
.lower()
)
@classmethod
def from_orm_with_request(cls, db_rom: Rom, _request: Request) -> RomSchema:
return cls.model_validate(db_rom)
class SimpleRomSchema(RomSchema):
sibling_roms: list[RomSchema] = Field(default_factory=list)
rom_user: RomUserSchema | None = Field(default=None)
sibling_roms: list[RomSchema]
rom_user: RomUserSchema
@classmethod
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> SimpleRomSchema:
rom = cls.model_validate(db_rom)
user_id = request.user.id
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # type: ignore
return cls.model_validate(db_rom)
rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
return rom
@classmethod
def from_orm_with_factory(cls, db_rom: Rom) -> SimpleRomSchema:
db_rom.rom_user = rom_user_schema_factory() # type: ignore
return cls.model_validate(db_rom)
class DetailedRomSchema(RomSchema):
merged_screenshots: list[str]
sibling_roms: list[RomSchema] = Field(default_factory=list)
rom_user: RomUserSchema | None = Field(default=None)
user_saves: list[SaveSchema] = Field(default_factory=list)
user_states: list[StateSchema] = Field(default_factory=list)
user_screenshots: list[ScreenshotSchema] = Field(default_factory=list)
user_notes: list[UserNotesSchema] = Field(default_factory=list)
user_collections: list[CollectionSchema] = Field(default_factory=list)
sibling_roms: list[RomSchema]
rom_user: RomUserSchema
user_saves: list[SaveSchema]
user_states: list[StateSchema]
user_screenshots: list[ScreenshotSchema]
user_notes: list[UserNotesSchema]
user_collections: list[CollectionSchema]
@classmethod
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
rom = cls.model_validate(db_rom)
user_id = request.user.id
rom.rom_user = RomUserSchema.for_user(user_id, db_rom)
rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom)
rom.user_saves = [
db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) # 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
]
rom.user_states = [
db_rom.user_states = [ # type: ignore
StateSchema.model_validate(s) for s in db_rom.states if s.user_id == user_id
]
rom.user_screenshots = [
db_rom.user_screenshots = [ # type: ignore
ScreenshotSchema.model_validate(s)
for s in db_rom.screenshots
if s.user_id == user_id
]
rom.user_collections = CollectionSchema.for_user(
user_id, db_rom.get_collections()
db_rom.user_collections = CollectionSchema.for_user( # type: ignore
user_id, [c for c in db_rom.get_collections()]
)
return rom
return cls.model_validate(db_rom)
class UserNotesSchema(TypedDict):

View File

@@ -1,4 +1,4 @@
from pydantic import BaseModel
from .base import BaseModel
class SearchRomSchema(BaseModel):
@@ -9,6 +9,7 @@ class SearchRomSchema(BaseModel):
summary: str
igdb_url_cover: str = ""
moby_url_cover: str = ""
platform_id: int
class SearchCoverSchema(BaseModel):

View File

@@ -1,39 +1,54 @@
import binascii
from base64 import b64encode
from datetime import datetime, timezone
from io import BytesIO
from shutil import rmtree
from typing import Annotated
from typing import Any
from urllib.parse import quote
from anyio import Path, open_file
from anyio import Path
from config import (
DEV_MODE,
DISABLE_DOWNLOAD_ENDPOINT_AUTH,
LIBRARY_BASE_PATH,
RESOURCES_BASE_PATH,
)
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
from endpoints.responses.rom import DetailedRomSchema, RomUserSchema, SimpleRomSchema
from endpoints.responses.rom import (
DetailedRomSchema,
RomSchema,
RomUserSchema,
SimpleRomSchema,
)
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from exceptions.fs_exceptions import RomAlreadyExistsException
from fastapi import HTTPException, Query, Request, UploadFile, status
from fastapi import HTTPException, Request, UploadFile, status
from fastapi.responses import Response
from handler.database import db_platform_handler, db_rom_handler
from handler.auth.constants import Scope
from handler.database import db_collection_handler, db_platform_handler, db_rom_handler
from handler.filesystem import fs_resource_handler, fs_rom_handler
from handler.filesystem.base_handler import CoverSize
from handler.metadata import meta_igdb_handler, meta_moby_handler
from logger.logger import log
from models.rom import Rom, RomUser
from PIL import Image
from starlette.requests import ClientDisconnect
from starlette.responses import FileResponse
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import FileTarget, NullTarget
from utils.filesystem import sanitize_filename
from utils.hashing import crc32_to_hex
from utils.nginx import ZipContentLine, ZipResponse
from utils.nginx import FileRedirectResponse, ZipContentLine, ZipResponse
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/roms",
tags=["roms"],
)
@protected_route(router.post, "/roms", ["roms.write"])
@protected_route(router.post, "/", [Scope.ROMS_WRITE])
async def add_rom(request: Request):
"""Upload single rom endpoint
@@ -59,7 +74,7 @@ async def add_rom(request: Request):
) from None
platform_fs_slug = db_platform.fs_slug
roms_path = fs_rom_handler.build_upload_file_path(platform_fs_slug)
roms_path = fs_rom_handler.build_upload_fs_path(platform_fs_slug)
log.info(f"Uploading file to {platform_fs_slug}")
file_location = Path(f"{roms_path}/{filename}")
@@ -95,42 +110,71 @@ async def add_rom(request: Request):
return Response(status_code=status.HTTP_201_CREATED)
@protected_route(router.get, "/roms", ["roms.read"])
@protected_route(router.get, "/", [Scope.ROMS_READ])
def get_roms(
request: Request,
platform_id: int | None = None,
collection_id: int | None = None,
search_term: str = "",
limit: int | None = None,
offset: int | None = None,
order_by: str = "name",
order_dir: str = "asc",
) -> list[SimpleRomSchema]:
with_extra: bool = True,
) -> list[SimpleRomSchema | RomSchema]:
"""Get roms endpoint
Args:
request (Request): Fastapi Request object
id (int, optional): Rom internal id
platform_id (int, optional): Platform ID to filter ROMs
collection_id (int, optional): Collection ID to filter ROMs
search_term (str, optional): Search term to filter ROMs
limit (int, optional): Limit the number of ROMs returned
offset (int, optional): Offset for pagination
order_by (str, optional): Field to order ROMs by
order_dir (str, optional): Direction to order ROMs (asc or desc)
last_played (bool, optional): Flag to filter ROMs by last played
Returns:
list[SimpleRomSchema]: List of roms stored in the database
list[DetailedRomSchema]: List of ROMs stored in the database
"""
roms = db_rom_handler.get_roms(
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term.lower(),
order_by=order_by.lower(),
order_dir=order_dir.lower(),
limit=limit,
)
if hasattr(Rom, order_by):
roms = db_rom_handler.get_roms(
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term.lower(),
order_by=order_by.lower(),
order_dir=order_dir.lower(),
limit=limit,
offset=offset,
)
elif hasattr(RomUser, order_by):
roms = db_rom_handler.get_roms_user(
user_id=request.user.id,
platform_id=platform_id,
collection_id=collection_id,
search_term=search_term,
order_by=order_by,
order_dir=order_dir,
limit=limit,
offset=offset,
)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid order_by field",
)
return [SimpleRomSchema.from_orm_with_request(rom, request) for rom in roms]
SelectedSchema = SimpleRomSchema if with_extra else RomSchema
roms = [SelectedSchema.from_orm_with_request(rom, request) for rom in roms]
return [rom for rom in roms if rom]
@protected_route(
router.get,
"/roms/{id}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["roms.read"],
"/{id}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
)
def get_rom(request: Request, id: int) -> DetailedRomSchema:
"""Get rom endpoint
@@ -153,21 +197,21 @@ def get_rom(request: Request, id: int) -> DetailedRomSchema:
@protected_route(
router.head,
"/roms/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["roms.read"],
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
)
async def head_rom_content(
request: Request,
id: int,
file_name: str,
files: Annotated[list[str] | None, Query()] = None,
):
"""Head rom content endpoint
Args:
request (Request): Fastapi Request object
id (int): Rom internal id
file_name (str): Required due to a bug in emulatorjs
file_name (str): File name to download
file_ids (list[int]): List of file ids to download for multi-part roms
Returns:
FileResponse: Returns the response with headers
@@ -178,24 +222,55 @@ async def head_rom_content(
if not rom:
raise RomNotFoundInDatabaseException(id)
files_to_check = files or [r["filename"] for r in rom.files]
file_ids = request.query_params.get("file_ids") or ""
file_ids = [int(f) for f in file_ids.split(",") if f]
files = db_rom_handler.get_rom_files(rom.id)
files = [f for f in files if f.id in file_ids or not file_ids]
# Serve the file directly in development mode for emulatorjs
if DEV_MODE:
if not rom.multi:
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
return FileResponse(
path=rom_path,
filename=rom.fs_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.fs_name)}"',
"Content-Type": "application/octet-stream",
"Content-Length": str(rom.fs_size_bytes),
},
)
if len(files) == 1:
file = files[0]
rom_path = f"{LIBRARY_BASE_PATH}/{file.full_path}"
return FileResponse(
path=rom_path,
filename=file.file_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(file.file_name)}"',
"Content-Type": "application/octet-stream",
"Content-Length": str(file.file_size_bytes),
},
)
if not rom.multi:
return Response(
media_type="application/octet-stream",
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"',
"X-Accel-Redirect": f"/library/{rom.full_path}",
"Content-Type": "application/zip",
"Content-Disposition": f'attachment; filename="{quote(file_name)}.zip"',
},
)
if len(files_to_check) == 1:
return Response(
media_type="application/octet-stream",
headers={
"Content-Disposition": f'attachment; filename="{quote(files_to_check[0])}"',
"X-Accel-Redirect": f"/library/{rom.full_path}/{files_to_check[0]}",
},
# Otherwise proxy through nginx
if not rom.multi:
return FileRedirectResponse(
download_path=Path(f"/library/{rom.full_path}"),
filename=rom.fs_name,
)
if len(files) == 1:
return FileRedirectResponse(
download_path=Path(f"/library/{files[0].full_path}"),
)
return Response(
@@ -208,21 +283,20 @@ async def head_rom_content(
@protected_route(
router.get,
"/roms/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else ["roms.read"],
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
)
async def get_rom_content(
request: Request,
id: int,
file_name: str,
files: Annotated[list[str] | None, Query()] = None,
):
"""Download rom endpoint (one single file or multiple zipped files for multi-part roms)
Args:
request (Request): Fastapi Request object
id (int): Rom internal id
files (Annotated[list[str] | None, Query, optional): List of files to download for multi-part roms. Defaults to None.
file_name: Zip file output name
Returns:
FileResponse: Returns one file for single file roms
@@ -231,44 +305,86 @@ async def get_rom_content(
ZipResponse: Returns a response for nginx to serve a Zip file for multi-part roms
"""
current_username = request.user.username if request.user else "unknown"
rom = db_rom_handler.get_rom(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
files_to_download = sorted(files or [r["filename"] for r in rom.files])
file_ids = request.query_params.get("file_ids") or ""
file_ids = [int(f) for f in file_ids.split(",") if f]
files = db_rom_handler.get_rom_files(rom.id)
files = [f for f in files if f.id in file_ids or not file_ids]
if not rom.multi:
return Response(
media_type="application/octet-stream",
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"',
"X-Accel-Redirect": f"/library/{rom.full_path}",
},
log.info(f"User {current_username} is downloading {rom.fs_name}")
# Serve the file directly in development mode for emulatorjs
if DEV_MODE:
if not rom.multi:
rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}"
return FileResponse(
path=rom_path,
filename=rom.fs_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(rom.fs_name)}"',
"Content-Type": "application/octet-stream",
"Content-Length": str(rom.fs_size_bytes),
},
)
if len(files) == 1:
file = files[0]
rom_path = f"{LIBRARY_BASE_PATH}/{file.full_path}"
return FileResponse(
path=rom_path,
filename=file.file_name,
headers={
"Content-Disposition": f'attachment; filename="{quote(file.file_name)}"',
"Content-Type": "application/octet-stream",
"Content-Length": str(file.file_size_bytes),
},
)
content_lines = [
ZipContentLine(
crc32=f.crc_hash,
size_bytes=(await Path(LIBRARY_BASE_PATH, f.full_path).stat()).st_size,
encoded_location=quote(f"{LIBRARY_BASE_PATH}/{f.full_path}"),
filename=f.full_path.replace(rom.full_path, ""),
)
for f in files
]
return ZipResponse(
content_lines=content_lines,
filename=f"{quote(file_name)}.zip",
)
if len(files_to_download) == 1:
return Response(
media_type="application/octet-stream",
headers={
"Content-Disposition": f'attachment; filename="{quote(files_to_download[0])}"',
"X-Accel-Redirect": f"/library/{rom.full_path}/{files_to_download[0]}",
},
# Otherwise proxy through nginx
if not rom.multi:
return FileRedirectResponse(
download_path=Path(f"/library/{rom.full_path}"),
filename=rom.fs_name,
)
if len(files) == 1:
return FileRedirectResponse(
download_path=Path(f"/library/{files[0].full_path}"),
)
content_lines = [
ZipContentLine(
# TODO: Use calculated CRC-32 if available.
crc32=None,
size_bytes=(await Path(f"{rom_path}/{f}").stat()).st_size,
encoded_location=quote(f"/library-zip/{rom.full_path}/{f}"),
filename=f,
crc32=f.crc_hash,
size_bytes=(await Path(LIBRARY_BASE_PATH, f.full_path).stat()).st_size,
encoded_location=quote(f"/library-zip/{f.full_path}"),
filename=f.full_path.replace(rom.full_path, ""),
)
for f in files_to_download
for f in files
]
m3u_encoded_content = "\n".join([f for f in files_to_download]).encode()
m3u_encoded_content = "\n".join(
[f.full_path.replace(rom.full_path, "") for f in files]
).encode()
m3u_base64_content = b64encode(m3u_encoded_content).decode()
m3u_line = ZipContentLine(
crc32=crc32_to_hex(binascii.crc32(m3u_encoded_content)),
@@ -283,13 +399,14 @@ async def get_rom_content(
)
@protected_route(router.put, "/roms/{id}", ["roms.write"])
@protected_route(router.put, "/{id}", [Scope.ROMS_WRITE])
async def update_rom(
request: Request,
id: int,
rename_as_source: bool = False,
remove_cover: bool = False,
artwork: UploadFile | None = None,
unmatch_metadata: bool = False,
) -> DetailedRomSchema:
"""Update rom endpoint
@@ -298,6 +415,7 @@ async def update_rom(
id (Rom): Rom internal id
rename_as_source (bool, optional): Flag to rename rom file as matched IGDB game. Defaults to False.
artwork (UploadFile, optional): Custom artork to set as cover. Defaults to File(None).
unmatch_metadata: Remove the metadata matches for this game. Defaults to False.
Raises:
HTTPException: If a rom already have that name when enabling the rename_as_source flag
@@ -313,16 +431,41 @@ async def update_rom(
if not rom:
raise RomNotFoundInDatabaseException(id)
cleaned_data = {
"igdb_id": data.get("igdb_id", None),
"moby_id": data.get("moby_id", None),
if unmatch_metadata:
db_rom_handler.update_rom(
id,
{
"igdb_id": None,
"sgdb_id": None,
"moby_id": None,
"name": rom.fs_name,
"summary": "",
"url_screenshots": [],
"path_screenshots": [],
"path_cover_s": "",
"path_cover_l": "",
"url_cover": "",
"slug": "",
"igdb_metadata": {},
"moby_metadata": {},
"revision": "",
},
)
rom = db_rom_handler.get_rom(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
return DetailedRomSchema.from_orm_with_request(rom, request)
cleaned_data: dict[str, Any] = {
"igdb_id": data.get("igdb_id", rom.igdb_id),
"moby_id": data.get("moby_id", rom.moby_id),
}
if (
cleaned_data.get("moby_id", "")
and int(cleaned_data.get("moby_id", "")) != rom.moby_id
):
moby_rom = await meta_moby_handler.get_rom_by_id(cleaned_data["moby_id"])
moby_id = cleaned_data["moby_id"]
if moby_id and int(moby_id) != rom.moby_id:
moby_rom = await meta_moby_handler.get_rom_by_id(int(moby_id))
cleaned_data.update(moby_rom)
path_screenshots = await fs_resource_handler.get_rom_screenshots(
rom=rom,
@@ -330,11 +473,9 @@ async def update_rom(
)
cleaned_data.update({"path_screenshots": path_screenshots})
if (
cleaned_data.get("igdb_id", "")
and int(cleaned_data.get("igdb_id", "")) != rom.igdb_id
):
igdb_rom = await meta_igdb_handler.get_rom_by_id(cleaned_data["igdb_id"])
igdb_id = cleaned_data["igdb_id"]
if igdb_id and int(igdb_id) != rom.igdb_id:
igdb_rom = await meta_igdb_handler.get_rom_by_id(int(igdb_id))
cleaned_data.update(igdb_rom)
path_screenshots = await fs_resource_handler.get_rom_screenshots(
rom=rom,
@@ -349,26 +490,26 @@ async def update_rom(
}
)
new_file_name = data.get("file_name", rom.file_name)
new_fs_name = str(data.get("fs_name") or rom.fs_name)
try:
if rename_as_source:
new_file_name = rom.file_name.replace(
rom.file_name_no_tags or rom.file_name_no_ext,
data.get("name", rom.name),
new_fs_name = rom.fs_name.replace(
rom.fs_name_no_tags or rom.fs_name_no_ext,
str(data.get("name") or rom.name),
)
new_file_name = sanitize_filename(new_file_name)
fs_rom_handler.rename_file(
old_name=rom.file_name,
new_name=new_file_name,
file_path=rom.file_path,
new_fs_name = sanitize_filename(new_fs_name)
fs_rom_handler.rename_fs_rom(
old_name=rom.fs_name,
new_name=new_fs_name,
fs_path=rom.fs_path,
)
elif rom.file_name != new_file_name:
new_file_name = sanitize_filename(new_file_name)
fs_rom_handler.rename_file(
old_name=rom.file_name,
new_name=new_file_name,
file_path=rom.file_path,
elif rom.fs_name != new_fs_name:
new_fs_name = sanitize_filename(new_fs_name)
fs_rom_handler.rename_fs_rom(
old_name=rom.fs_name,
new_name=new_fs_name,
fs_path=rom.fs_path,
)
except RomAlreadyExistsException as exc:
log.error(exc)
@@ -378,12 +519,10 @@ async def update_rom(
cleaned_data.update(
{
"file_name": new_file_name,
"file_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(
new_file_name
),
"file_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
new_file_name
"fs_name": new_fs_name,
"fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(new_fs_name),
"fs_name_no_ext": fs_rom_handler.get_file_name_with_no_extension(
new_fs_name
),
}
)
@@ -392,7 +531,7 @@ async def update_rom(
cleaned_data.update(fs_resource_handler.remove_cover(rom))
cleaned_data.update({"url_cover": ""})
else:
if artwork:
if artwork is not None and artwork.filename is not None:
file_ext = artwork.filename.split(".")[-1]
(
path_cover_l,
@@ -404,15 +543,15 @@ async def update_rom(
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
)
artwork_file = artwork.file.read()
file_location_s = f"{artwork_path}/small.{file_ext}"
async with await open_file(file_location_s, "wb+") as artwork_s:
await artwork_s.write(artwork_file)
fs_resource_handler.resize_cover_to_small(file_location_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
)
file_location_l = f"{artwork_path}/big.{file_ext}"
async with await open_file(file_location_l, "wb+") as artwork_l:
await artwork_l.write(artwork_file)
cleaned_data.update({"url_cover": ""})
else:
if data.get("url_cover", "") != rom.url_cover or not (
@@ -422,18 +561,21 @@ async def update_rom(
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
overwrite=True,
entity=rom,
url_cover=data.get("url_cover", ""),
url_cover=str(data.get("url_cover") or ""),
)
cleaned_data.update(
{"path_cover_s": path_cover_s, "path_cover_l": path_cover_l}
)
db_rom_handler.update_rom(id, cleaned_data)
rom = db_rom_handler.get_rom(id)
if not rom:
raise RomNotFoundInDatabaseException(id)
return DetailedRomSchema.from_orm_with_request(db_rom_handler.get_rom(id), request)
return DetailedRomSchema.from_orm_with_request(rom, request)
@protected_route(router.post, "/roms/delete", ["roms.write"])
@protected_route(router.post, "/delete", [Scope.ROMS_WRITE])
async def delete_roms(
request: Request,
) -> MessageResponse:
@@ -460,22 +602,30 @@ async def delete_roms(
if not rom:
raise RomNotFoundInDatabaseException(id)
log.info(f"Deleting {rom.file_name} from database")
log.info(f"Deleting {rom.fs_name} from database")
db_rom_handler.delete_rom(id)
# Update collections to remove the deleted rom
collections = db_collection_handler.get_collections_by_rom_id(id)
for collection in collections:
collection.roms = {rom_id for rom_id in collection.roms if rom_id != id}
db_collection_handler.update_collection(
collection.id, {"roms": collection.roms}
)
try:
rmtree(f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}")
except FileNotFoundError:
log.error(f"Couldn't find resources to delete for {rom.name}")
if id in delete_from_fs:
log.info(f"Deleting {rom.file_name} from filesystem")
log.info(f"Deleting {rom.fs_name} from filesystem")
try:
fs_rom_handler.remove_file(
file_name=rom.file_name, file_path=rom.file_path
)
fs_rom_handler.remove_from_fs(fs_path=rom.fs_path, fs_name=rom.fs_name)
except FileNotFoundError as exc:
error = f"Rom file {rom.file_name} not found for platform {rom.platform_slug}"
error = (
f"Rom file {rom.fs_name} not found for platform {rom.platform_slug}"
)
log.error(error)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=error
@@ -484,9 +634,10 @@ async def delete_roms(
return {"msg": f"{len(roms_ids)} roms deleted successfully!"}
@protected_route(router.put, "/roms/{id}/props", ["roms.user.write"])
@protected_route(router.put, "/{id}/props", [Scope.ROMS_USER_WRITE])
async def update_rom_user(request: Request, id: int) -> RomUserSchema:
data = await request.json()
rom_user_data = data.get("data", {})
rom = db_rom_handler.get_rom(id)
@@ -497,12 +648,30 @@ async def update_rom_user(request: Request, id: int) -> RomUserSchema:
id, request.user.id
) or db_rom_handler.add_rom_user(id, request.user.id)
fields_to_update = [
"note_raw_markdown",
"note_is_public",
"is_main_sibling",
"backlogged",
"now_playing",
"hidden",
"rating",
"difficulty",
"completion",
"status",
]
cleaned_data = {
"note_raw_markdown": data.get(
"note_raw_markdown", db_rom_user.note_raw_markdown
),
"note_is_public": data.get("note_is_public", db_rom_user.note_is_public),
"is_main_sibling": data.get("is_main_sibling", db_rom_user.is_main_sibling),
field: rom_user_data[field]
for field in fields_to_update
if field in rom_user_data
}
return db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
if data.get("update_last_played", False):
cleaned_data.update({"last_played": datetime.now(timezone.utc)})
elif data.get("remove_last_played", False):
cleaned_data.update({"last_played": None})
rom_user = db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data)
return RomUserSchema.model_validate(rom_user)

View File

@@ -1,17 +1,24 @@
from datetime import datetime, timezone
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
from endpoints.responses.assets import SaveSchema, UploadedSavesResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, HTTPException, Request, UploadFile, status
from handler.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 logger.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/saves",
tags=["saves"],
)
@protected_route(router.post, "/saves", ["assets.write"])
@protected_route(router.post, "/", [Scope.ASSETS_WRITE])
def add_saves(
request: Request,
rom_id: int,
@@ -19,21 +26,21 @@ def add_saves(
emulator: str | None = None,
) -> UploadedSavesResponse:
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
current_user = request.user
log.info(f"Uploading saves to {rom.name}")
if saves is None:
log.error("No saves were uploaded")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="No saves were uploaded",
)
saves_path = fs_asset_handler.build_saves_file_path(
user=request.user, platform_fs_slug=rom.platform.fs_slug, 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
@@ -57,24 +64,40 @@ def add_saves(
scanned_save.emulator = emulator
db_save_handler.add_save(scanned_save)
# Set the last played time for the current user
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
if not rom_user:
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
db_rom_handler.update_rom_user(
rom_user.id, {"last_played": datetime.now(timezone.utc)}
)
# Refetch the rom to get updated saves
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
return {
"uploaded": len(saves),
"saves": [s for s in rom.saves if s.user_id == current_user.id],
"saves": [
SaveSchema.model_validate(s)
for s in rom.saves
if s.user_id == current_user.id
],
}
# @protected_route(router.get, "/saves", ["assets.read"])
# @protected_route(router.get, "/", [Scope.ASSETS_READ])
# def get_saves(request: Request) -> MessageResponse:
# pass
# @protected_route(router.get, "/saves/{id}", ["assets.read"])
# @protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
# def get_save(request: Request, id: int) -> MessageResponse:
# pass
@protected_route(router.put, "/saves/{id}", ["assets.write"])
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
async def update_save(request: Request, id: int) -> SaveSchema:
data = await request.form()
@@ -90,15 +113,25 @@ async def update_save(request: Request, id: int) -> SaveSchema:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
if "file" in data:
file: UploadFile = data["file"]
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})
# Set the last played time for the current user
current_user = request.user
rom_user = db_rom_handler.get_rom_user(db_save.rom_id, current_user.id)
if not rom_user:
rom_user = db_rom_handler.add_rom_user(db_save.rom_id, current_user.id)
db_rom_handler.update_rom_user(
rom_user.id, {"last_played": datetime.now(timezone.utc)}
)
# Refetch the save to get updated fields
db_save = db_save_handler.get_save(id)
return db_save
return SaveSchema.model_validate(db_save)
@protected_route(router.post, "/saves/delete", ["assets.write"])
@protected_route(router.post, "/delete", [Scope.ASSETS_WRITE])
async def delete_saves(request: Request) -> MessageResponse:
data: dict = await request.json()
save_ids: list = data["saves"]

View File

@@ -1,37 +1,42 @@
from decorators.auth import protected_route
from endpoints.responses.assets import UploadedScreenshotsResponse
from fastapi import File, HTTPException, Request, UploadFile, status
from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, Request, UploadFile
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.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/screenshots",
tags=["screenshots"],
)
@protected_route(router.post, "/screenshots", ["assets.write"])
@protected_route(router.post, "/", [Scope.ASSETS_WRITE])
def add_screenshots(
request: Request,
rom_id: int,
screenshots: list[UploadFile] = File(...), # noqa: B008
) -> UploadedScreenshotsResponse:
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
current_user = request.user
log.info(f"Uploading screenshots to {rom.name}")
if screenshots is None:
log.error("No screenshots were uploaded")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="No screenshots were uploaded",
)
screenshots_path = fs_asset_handler.build_screenshots_file_path(
user=request.user, platform_fs_slug=rom.platform_slug
)
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
@@ -55,8 +60,15 @@ def add_screenshots(
db_screenshot_handler.add_screenshot(scanned_screenshot)
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
return {
"uploaded": len(screenshots),
"screenshots": [s for s in rom.screenshots if s.user_id == current_user.id],
"screenshots": [
ScreenshotSchema.model_validate(s)
for s in rom.screenshots
if s.user_id == current_user.id
],
"merged_screenshots": rom.merged_screenshots,
}

View File

@@ -2,22 +2,26 @@ import emoji
from decorators.auth import protected_route
from endpoints.responses.search import SearchCoverSchema, SearchRomSchema
from fastapi import HTTPException, Request, status
from handler.auth.constants import Scope
from handler.database import db_rom_handler
from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_sgdb_handler
from handler.metadata.igdb_handler import IGDB_API_ENABLED
from handler.metadata.moby_handler import MOBY_API_ENABLED
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.scan_handler import _get_main_platform_igdb_id
from logger.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/search",
tags=["search"],
)
@protected_route(router.get, "/search/roms", ["roms.read"])
@protected_route(router.get, "/roms", [Scope.ROMS_READ])
async def search_rom(
request: Request,
rom_id: str,
rom_id: int,
search_term: str | None = None,
search_by: str = "name",
) -> list[SearchRomSchema]:
@@ -25,7 +29,7 @@ async def search_rom(
Args:
request (Request): FastAPI request
rom_id (str): Rom ID
rom_id (int): Rom ID
source (str): Source of the rom
search_term (str, optional): Search term. Defaults to None.
search_by (str, optional): Search by name or ID. Defaults to "name".
@@ -46,7 +50,7 @@ async def search_rom(
if not rom:
return []
search_term = search_term or rom.file_name_no_tags
search_term = search_term or rom.fs_name_no_tags
if not search_term:
return []
@@ -56,35 +60,39 @@ async def search_rom(
matched_roms: list = []
log.info(f"Searching by {search_by.lower()}: {search_term}")
log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.file_name}"))
log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.fs_name}"))
igdb_matched_roms: list[IGDBRom] = []
moby_matched_roms: list[MobyGamesRom] = []
if search_by.lower() == "id":
try:
igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_id(
int(search_term)
)
moby_matched_roms = await meta_moby_handler.get_matched_roms_by_id(
int(search_term)
)
igdb_rom = await meta_igdb_handler.get_matched_rom_by_id(int(search_term))
moby_rom = await meta_moby_handler.get_matched_rom_by_id(int(search_term))
except ValueError as exc:
log.error(f"Search error: invalid ID '{search_term}'")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Tried searching by ID, but '{search_term}' is not a valid ID",
) from exc
else:
igdb_matched_roms = [igdb_rom] if igdb_rom else []
moby_matched_roms = [moby_rom] if moby_rom else []
elif search_by.lower() == "name":
main_platform_igdb_id = await _get_main_platform_igdb_id(rom.platform)
igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_name(
search_term, (await _get_main_platform_igdb_id(rom.platform))
search_term, main_platform_igdb_id or rom.platform.igdb_id
)
moby_matched_roms = await meta_moby_handler.get_matched_roms_by_name(
search_term, rom.platform.moby_id
)
merged_dict = {
item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")}
item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")} # type: ignore
for item in igdb_matched_roms
}
for item in moby_matched_roms:
merged_dict[item["name"]] = {
merged_dict[item["name"]] = { # type: ignore
**item,
"moby_url_cover": item.pop("url_cover", ""),
**merged_dict.get(item.get("name", ""), {}),
@@ -98,6 +106,7 @@ async def search_rom(
"summary": "",
"igdb_url_cover": "",
"moby_url_cover": "",
"platform_id": rom.platform_id,
},
**item,
}
@@ -111,7 +120,7 @@ async def search_rom(
return matched_roms
@protected_route(router.get, "/search/cover", ["roms.read"])
@protected_route(router.get, "/cover", [Scope.ROMS_READ])
async def search_cover(
request: Request,
search_term: str = "",

View File

@@ -1,11 +1,13 @@
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 SCAN_TIMEOUT
from config import REDIS_URL, SCAN_TIMEOUT
from endpoints.responses.platform import PlatformSchema
from endpoints.responses.rom import SimpleRomSchema
from exceptions.fs_exceptions import (
@@ -22,20 +24,51 @@ from handler.filesystem import (
fs_rom_handler,
)
from handler.filesystem.roms_handler import FSRom
from handler.metadata.igdb_handler import IGDB_API_ENABLED
from handler.metadata.moby_handler import MOBY_API_ENABLED
from handler.redis_handler import high_prio_queue, redis_client, redis_url
from handler.redis_handler import high_prio_queue, low_prio_queue, redis_client
from handler.scan_handler import ScanType, scan_firmware, scan_platform, scan_rom
from handler.socket_handler import socket_handler
from logger.formatter import LIGHTYELLOW, RED
from logger.formatter import highlight as hl
from logger.logger import log
from models.platform import Platform
from models.rom import Rom
from models.rom import Rom, RomFile
from rq import Worker
from rq.job import Job
from sqlalchemy.inspection import inspect
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
@@ -64,12 +97,12 @@ class ScanStats:
)
def _get_socket_manager():
def _get_socket_manager() -> socketio.AsyncRedisManager:
"""Connect to external socketio server"""
return socketio.AsyncRedisManager(redis_url, write_only=True)
return socketio.AsyncRedisManager(str(REDIS_URL), write_only=True)
def _should_scan_rom(scan_type: ScanType, rom: Rom, roms_ids: list):
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:
@@ -79,7 +112,7 @@ def _should_scan_rom(scan_type: ScanType, rom: Rom, roms_ids: list):
"""
# This logic is tricky so only touch it if you know what you're doing"""
return (
return bool(
(scan_type in {ScanType.NEW_PLATFORMS, ScanType.QUICK} and not rom)
or (scan_type == ScanType.COMPLETE)
or (scan_type == ScanType.HASHES)
@@ -124,11 +157,6 @@ async def scan_platforms(
sm = _get_socket_manager()
if not IGDB_API_ENABLED and not MOBY_API_ENABLED:
log.error("Search error: No metadata providers enabled")
await sm.emit("scan:done_ko", "No metadata providers enabled")
return
try:
fs_platforms: list[str] = fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:
@@ -145,15 +173,20 @@ async def scan_platforms(
try:
platform_list = [
db_platform_handler.get_platform(s).fs_slug for s in platform_ids
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.warn(
"⚠️ No platforms found, verify that the folder structure is right and the volume is mounted correctly "
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 file system ")
log.info(f"Found {len(platform_list)} platforms in the file system")
for platform_slug in platform_list:
scan_stats += await _identify_platform(
@@ -165,9 +198,15 @@ async def scan_platforms(
socket_manager=sm,
)
# Same protection for platforms
# 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:
db_platform_handler.purge_platforms(fs_platforms)
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__)
@@ -231,7 +270,11 @@ async def _identify_platform(
fs_firmware = []
if len(fs_firmware) == 0:
log.warning(" ⚠️ No firmware found, skipping firmware scan for this platform")
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")
@@ -249,30 +292,52 @@ async def _identify_platform(
return scan_stats
if len(fs_roms) == 0:
log.warning(" ⚠️ No roms found, verify that the folder structure is correct")
else:
log.info(f" {len(fs_roms)} roms found")
for fs_rom in fs_roms:
scan_stats += await _identify_rom(
platform=platform,
fs_rom=fs_rom,
scan_type=scan_type,
roms_ids=roms_ids,
metadata_sources=metadata_sources,
socket_manager=socket_manager,
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:
db_rom_handler.purge_roms(platform.id, [rom["file_name"] for rom in fs_roms])
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:
db_firmware_handler.purge_firmware(platform.id, [fw for fw in fs_firmware])
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
@@ -302,9 +367,55 @@ async def _identify_firmware(
return scan_stats
def _set_rom_hashes(rom_id: int):
"""Set the hashes for the given rom
Args:
rom_id (int): Rom id
"""
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"],
},
)
async def _identify_rom(
platform: Platform,
fs_rom: FSRom,
rom: Rom | None,
scan_type: ScanType,
roms_ids: list[str],
metadata_sources: list[str],
@@ -316,14 +427,11 @@ async def _identify_rom(
if redis_client.get(STOP_SCAN_FLAG):
return scan_stats
rom = db_rom_handler.get_rom_by_filename(platform.id, fs_rom["file_name"])
if not _should_scan_rom(scan_type=scan_type, rom=rom, roms_ids=roms_ids):
# Just to update the filesystem data
rom.file_name = fs_rom["file_name"]
rom.multi = fs_rom["multi"]
rom.files = fs_rom["files"]
db_rom_handler.add_rom(rom)
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)
return scan_stats
@@ -341,6 +449,37 @@ async def _identify_rom(
_added_rom = db_rom_handler.add_rom(scanned_rom)
# Delete the existing rom files in the DB
db_rom_handler.purge_rom_files(_added_rom.id)
# Create each file entry for the rom
new_rom_files = [
RomFile(
rom_id=_added_rom.id,
file_name=file.file_name,
file_path=file.file_path,
file_size_bytes=file.file_size_bytes,
last_modified=file.last_modified,
category=file.category,
)
for file in fs_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:
# Uncomment this to run scan in the current process
# _set_rom_hashes(_added_rom.id)
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
@@ -373,7 +512,7 @@ async def _identify_rom(
{
"platform_name": platform.name,
"platform_slug": platform.slug,
**SimpleRomSchema.model_validate(_added_rom).model_dump(
**SimpleRomSchema.from_orm_with_factory(_added_rom).model_dump(
exclude={"created_at", "updated_at", "rom_user"}
),
},

View File

@@ -1,17 +1,24 @@
from datetime import datetime, timezone
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
from endpoints.responses.assets import StateSchema, UploadedStatesResponse
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from fastapi import File, HTTPException, Request, UploadFile, status
from handler.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 logger.logger import log
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/states",
tags=["states"],
)
@protected_route(router.post, "/states", ["assets.write"])
@protected_route(router.post, "/", [Scope.ASSETS_WRITE])
def add_states(
request: Request,
rom_id: int,
@@ -19,21 +26,21 @@ def add_states(
emulator: str | None = None,
) -> UploadedStatesResponse:
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
current_user = request.user
log.info(f"Uploading states to {rom.name}")
if states is None:
log.error("No states were uploaded")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="No states were uploaded",
)
states_path = fs_asset_handler.build_states_file_path(
user=request.user, platform_fs_slug=rom.platform.fs_slug, 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
@@ -57,24 +64,39 @@ def add_states(
scanned_state.emulator = emulator
db_state_handler.add_state(scanned_state)
# Set the last played time for the current user
rom_user = db_rom_handler.get_rom_user(rom.id, current_user.id)
if not rom_user:
rom_user = db_rom_handler.add_rom_user(rom.id, current_user.id)
db_rom_handler.update_rom_user(
rom_user.id, {"last_played": datetime.now(timezone.utc)}
)
rom = db_rom_handler.get_rom(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
return {
"uploaded": len(states),
"states": [s for s in rom.states if s.user_id == current_user.id],
"states": [
StateSchema.model_validate(s)
for s in rom.states
if s.user_id == current_user.id
],
}
# @protected_route(router.get, "/states", ["assets.read"])
# @protected_route(router.get, "/", [Scope.ASSETS_READ])
# def get_states(request: Request) -> MessageResponse:
# pass
# @protected_route(router.get, "/states/{id}", ["assets.read"])
# @protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
# def get_state(request: Request, id: int) -> MessageResponse:
# pass
@protected_route(router.put, "/states/{id}", ["assets.write"])
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
async def update_state(request: Request, id: int) -> StateSchema:
data = await request.form()
@@ -90,15 +112,24 @@ async def update_state(request: Request, id: int) -> StateSchema:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
if "file" in data:
file: UploadFile = data["file"]
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})
# Set the last played time for the current user
current_user = request.user
rom_user = db_rom_handler.get_rom_user(db_state.rom_id, current_user.id)
if not rom_user:
rom_user = db_rom_handler.add_rom_user(db_state.rom_id, current_user.id)
db_rom_handler.update_rom_user(
rom_user.id, {"last_played": datetime.now(timezone.utc)}
)
db_state = db_state_handler.get_state(id)
return db_state
return StateSchema.model_validate(db_state)
@protected_route(router.post, "/states/delete", ["assets.write"])
@protected_route(router.post, "/delete", [Scope.ASSETS_WRITE])
async def delete_states(request: Request) -> MessageResponse:
data: dict = await request.json()
state_ids: list = data["states"]

View File

@@ -2,10 +2,13 @@ from endpoints.responses.stats import StatsReturn
from handler.database import db_stats_handler
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/stats",
tags=["stats"],
)
@router.get("/stats")
@router.get("/")
def stats() -> StatsReturn:
"""Endpoint to return the current RomM stats

View File

@@ -1,13 +1,17 @@
from decorators.auth import protected_route
from endpoints.responses import MessageResponse
from fastapi import Request
from handler.auth.constants import Scope
from tasks.update_switch_titledb import update_switch_titledb_task
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/tasks",
tags=["tasks"],
)
@protected_route(router.post, "/tasks/run", ["tasks.run"])
@protected_route(router.post, "/run", [Scope.TASKS_RUN])
async def run_tasks(request: Request) -> MessageResponse:
"""Run all tasks endpoint
@@ -21,7 +25,7 @@ async def run_tasks(request: Request) -> MessageResponse:
return {"msg": "All tasks ran successfully!"}
@protected_route(router.post, "/tasks/{task}/run", ["tasks.run"])
@protected_route(router.post, "/{task}/run", [Scope.TASKS_RUN])
async def run_task(request: Request, task: str) -> MessageResponse:
"""Run all tasks endpoint

View File

@@ -21,5 +21,3 @@ def test_config(client):
assert config.get("EXCLUDED_MULTI_PARTS_EXT") == []
assert config.get("EXCLUDED_MULTI_PARTS_FILES") == []
assert config.get("PLATFORMS_BINDING") == {}
assert config.get("ROMS_FOLDER_NAME") == "roms"
assert config.get("FIRMWARE_FOLDER_NAME") == "bios"

View File

@@ -15,7 +15,7 @@ def test_heartbeat(client):
assert response.status_code == 200
heartbeat = response.json()
assert heartbeat.get("VERSION") == get_version()
assert heartbeat.get("SYSTEM").get("VERSION") == get_version()
assert heartbeat.get("WATCHER").get("ENABLED")
assert heartbeat.get("WATCHER").get("TITLE") == "Rescan on filesystem change"
assert heartbeat.get("SCHEDULER").get("RESCAN").get("ENABLED")
@@ -27,3 +27,4 @@ def test_heartbeat(client):
heartbeat.get("SCHEDULER").get("SWITCH_TITLEDB").get("TITLE")
== "Scheduled Switch TitleDB update"
)
assert heartbeat.get("FRONTEND").get("UPLOAD_TIMEOUT") == 20

View File

@@ -1,7 +1,13 @@
import base64
from datetime import timedelta
from http import HTTPStatus
from unittest import mock
import pytest
from endpoints.auth import ACCESS_TOKEN_EXPIRE_MINUTES
from fastapi.testclient import TestClient
from handler.auth import oauth_handler
from handler.database.users_handler import DBUsersHandler
from handler.redis_handler import sync_cache
from main import app
from models.user import Role
@@ -61,21 +67,87 @@ def test_get_user(client, access_token, editor_user):
assert user["username"] == "test_editor"
def test_create_user(client, access_token):
@pytest.mark.parametrize("new_user_role", [Role.VIEWER, Role.EDITOR, Role.ADMIN])
def test_add_user_from_admin_user(client, access_token, new_user_role):
response = client.post(
"/api/users",
params={
"username": "new_user",
"password": "new_user_password",
"role": "viewer",
"email": "new_user@example.com",
"role": new_user_role.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == 201
assert response.status_code == HTTPStatus.CREATED
user = response.json()
assert user["username"] == "new_user"
assert user["role"] == "viewer"
assert user["role"] == new_user_role.value
@pytest.mark.parametrize(
"fixture_requesting_user, existing_admin_users, expected_status_code",
[
("editor_user", False, HTTPStatus.CREATED),
("editor_user", True, HTTPStatus.FORBIDDEN),
("viewer_user", False, HTTPStatus.CREATED),
("viewer_user", True, HTTPStatus.FORBIDDEN),
],
)
def test_add_user_from_unauthorized_user(
request,
client,
admin_user,
fixture_requesting_user,
existing_admin_users,
expected_status_code,
):
requesting_user = request.getfixturevalue(fixture_requesting_user)
data = {
"sub": requesting_user.username,
"iss": "romm:oauth",
"scopes": " ".join(requesting_user.oauth_scopes),
"type": "access",
}
access_token = oauth_handler.create_oauth_token(
data=data, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
with mock.patch.object(
DBUsersHandler,
"get_admin_users",
return_value=[admin_user] if existing_admin_users else [],
):
response = client.post(
"/api/users",
params={
"username": "new_user",
"password": "new_user_password",
"email": "new_user@example.com",
"role": Role.VIEWER.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == expected_status_code
def test_add_user_with_existing_username(client, access_token, admin_user):
response = client.post(
"/api/users",
params={
"username": admin_user.username,
"password": "new_user_password",
"email": "new_user@example.com",
"role": Role.VIEWER.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == HTTPStatus.BAD_REQUEST
response = response.json()
assert response["detail"] == f"Username {admin_user.username} already exists"
def test_update_user(client, access_token, editor_user):

View File

@@ -2,7 +2,7 @@ import pytest
from endpoints.auth import ACCESS_TOKEN_EXPIRE_MINUTES
from fastapi.exceptions import HTTPException
from fastapi.testclient import TestClient
from handler.auth.base_handler import WRITE_SCOPES
from handler.auth.constants import EDIT_SCOPES
from main import app
@@ -96,7 +96,7 @@ def test_auth_via_upass_with_excess_scopes(client, viewer_user):
"grant_type": "password",
"username": "test_viewer",
"password": "test_viewer_password",
"scopes": WRITE_SCOPES,
"scopes": EDIT_SCOPES,
},
)
except HTTPException as e:

View File

@@ -37,9 +37,9 @@ def test_get_all_roms(client, access_token, rom, platform):
assert body[0]["id"] == rom.id
@patch.object(FSRomsHandler, "rename_file")
@patch.object(FSRomsHandler, "rename_fs_rom")
@patch.object(IGDBBaseHandler, "get_rom_by_id", return_value=IGDBRom(igdb_id=None))
def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token, rom):
def test_update_rom(rename_fs_rom_mock, get_rom_by_id_mock, client, access_token, rom):
response = client.put(
f"/api/roms/{rom.id}",
headers={"Authorization": f"Bearer {access_token}"},
@@ -48,7 +48,7 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token,
"igdb_id": "236663",
"name": "Metroid Prime Remastered",
"slug": "metroid-prime-remastered",
"file_name": "Metroid Prime Remastered.zip",
"fs_name": "Metroid Prime Remastered.zip",
"summary": "summary test",
"url_cover": "https://images.igdb.com/igdb/image/upload/t_cover_big/co2l7z.jpg",
"genres": '[{"id": 5, "name": "Shooter"}, {"id": 8, "name": "Platform"}, {"id": 31, "name": "Adventure"}]',
@@ -58,19 +58,21 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token,
"dlcs": "[]",
"companies": '[{"id": 203227, "company": {"id": 70, "name": "Nintendo"}}, {"id": 203307, "company": {"id": 766, "name": "Retro Studios"}}]',
"first_release_date": 1675814400,
"youtube_video_id": "dQw4w9WgXcQ",
"remasters": "[]",
"remakes": "[]",
"expanded_games": "[]",
"ports": "[]",
"similar_games": "[]",
"age_ratings": "[1, 2]",
},
)
assert response.status_code == 200
body = response.json()
assert body["file_name"] == "Metroid Prime Remastered.zip"
assert body["fs_name"] == "Metroid Prime Remastered.zip"
assert rename_file_mock.called
assert rename_fs_rom_mock.called
assert get_rom_by_id_mock.called

View File

@@ -1,47 +1,60 @@
from pathlib import Path
from typing import Annotated
from typing import Annotated, Any
from anyio import open_file
from config import ASSETS_BASE_PATH, IS_PYTEST_RUN
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 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 logger.logger import log
from models.user import Role, User
from utils.router import APIRouter
router = APIRouter()
router = APIRouter(
prefix="/users",
tags=["users"],
)
@protected_route(
router.post,
"/users",
(
[]
if not IS_PYTEST_RUN and len(db_user_handler.get_admin_users()) == 0
else ["users.write"]
),
"/",
[],
status_code=status.HTTP_201_CREATED,
)
def add_user(request: Request, username: str, password: str, role: str) -> UserSchema:
def add_user(
request: Request, username: str, password: str, email: str, role: str
) -> UserSchema:
"""Create user endpoint
Args:
request (Request): Fastapi Requests object
username (str): User username
password (str): User password
email (str): User email
role (str): RomM Role object represented as string
Returns:
UserSchema: Created user info
UserSchema: Newly created user
"""
if username in [user.username for user in db_user_handler.get_users()]:
# If there are admin users already, enforce the USERS_WRITE scope.
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 db_user_handler.get_user_by_username(username):
msg = f"Username {username} already exists"
log.error(msg)
raise HTTPException(
@@ -49,16 +62,25 @@ def add_user(request: Request, username: str, password: str, role: str) -> UserS
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,
username=username.lower(),
hashed_password=auth_handler.get_password_hash(password),
email=email.lower() or None,
role=Role[role.upper()],
)
return db_user_handler.add_user(user)
return UserSchema.model_validate(db_user_handler.add_user(user))
@protected_route(router.get, "/users", ["users.read"])
@protected_route(router.get, "/", [Scope.USERS_READ])
def get_users(request: Request) -> list[UserSchema]:
"""Get all users endpoint
@@ -69,10 +91,10 @@ def get_users(request: Request) -> list[UserSchema]:
list[UserSchema]: All users stored in the RomM's database
"""
return db_user_handler.get_users()
return [UserSchema.model_validate(u) for u in db_user_handler.get_users()]
@protected_route(router.get, "/users/me", ["me.read"])
@protected_route(router.get, "/me", [Scope.ME_READ])
def get_current_user(request: Request) -> UserSchema | None:
"""Get current user endpoint
@@ -86,7 +108,7 @@ def get_current_user(request: Request) -> UserSchema | None:
return request.user
@protected_route(router.get, "/users/{id}", ["users.read"])
@protected_route(router.get, "/{id}", [Scope.USERS_READ])
def get_user(request: Request, id: int) -> UserSchema:
"""Get user endpoint
@@ -101,10 +123,10 @@ def get_user(request: Request, id: int) -> UserSchema:
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
return UserSchema.model_validate(user)
@protected_route(router.put, "/users/{id}", ["me.write"])
@protected_route(router.put, "/{id}", [Scope.ME_WRITE])
async def update_user(
request: Request, id: int, form_data: Annotated[UserForm, Depends()]
) -> UserSchema:
@@ -133,11 +155,10 @@ async def update_user(
if db_user.id != request.user.id and request.user.role != Role.ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
cleaned_data = {}
cleaned_data: dict[str, Any] = {}
if form_data.username and form_data.username != db_user.username:
existing_user = db_user_handler.get_user_by_username(form_data.username.lower())
if existing_user:
if db_user_handler.get_user_by_username(form_data.username):
msg = f"Username {form_data.username} already exists"
log.error(msg)
raise HTTPException(
@@ -152,6 +173,17 @@ async def update_user(
form_data.password
)
if form_data.email is not None and form_data.email != db_user.email:
if form_data.email and db_user_handler.get_user_by_email(form_data.email):
msg = f"User with email {form_data.email} already exists"
log.error(msg)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=msg,
)
cleaned_data["email"] = form_data.email.lower() or None
# You can't change your own role
if form_data.role and request.user.id != id:
cleaned_data["role"] = Role[form_data.role.upper()] # type: ignore[assignment]
@@ -182,10 +214,16 @@ async def update_user(
if request.user.id == id and creds_updated:
request.session.clear()
return db_user_handler.get_user(id)
db_user = db_user_handler.get_user(id)
if not db_user:
msg = f"Username with id {id} not found"
log.error(msg)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg)
return UserSchema.model_validate(db_user)
@protected_route(router.delete, "/users/{id}", ["users.write"])
@protected_route(router.delete, "/{id}", [Scope.USERS_WRITE])
def delete_user(request: Request, id: int) -> MessageResponse:
"""Delete user endpoint

View File

@@ -1,5 +1,10 @@
from fastapi import HTTPException, status
UserPassDisabledException = HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Username/password authentication disabled",
)
AuthCredentialsException = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
@@ -10,7 +15,7 @@ AuthenticationSchemeException = HTTPException(
detail="Invalid authentication scheme",
)
DisabledException = HTTPException(
UserDisabledException = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Disabled user",
)
@@ -20,3 +25,13 @@ OAuthCredentialsException = HTTPException(
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
OIDCDisabledException = HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="OAuth disabled",
)
OIDCNotConfiguredException = HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="OAuth not configured",
)

View File

@@ -1,4 +1,5 @@
from .base_handler import AuthHandler, OAuthHandler
from .base_handler import AuthHandler, OAuthHandler, OpenIDHandler
auth_handler = AuthHandler()
oauth_handler = OAuthHandler()
oidc_handler = OpenIDHandler()

View File

@@ -1,48 +1,19 @@
from datetime import datetime, timedelta
from typing import Final
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from config import ROMM_AUTH_SECRET_KEY
from exceptions.auth_exceptions import OAuthCredentialsException
from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY
from decorators.auth import oauth
from exceptions.auth_exceptions import OAuthCredentialsException, UserDisabledException
from fastapi import HTTPException, status
from handler.auth.constants import ALGORITHM, DEFAULT_OAUTH_TOKEN_EXPIRY
from joserfc import jwt
from joserfc.errors import BadSignatureError
from joserfc.jwk import OctKey
from logger.logger import log
from passlib.context import CryptContext
from starlette.requests import HTTPConnection
ALGORITHM: Final = "HS256"
DEFAULT_OAUTH_TOKEN_EXPIRY: Final = 15
DEFAULT_SCOPES_MAP: Final = {
"me.read": "View your profile",
"me.write": "Modify your profile",
"roms.read": "View ROMs",
"platforms.read": "View platforms",
"assets.read": "View assets",
"assets.write": "Modify assets",
"firmware.read": "View firmware",
"roms.user.read": "View user-rom properties",
"roms.user.write": "Modify user-rom properties",
"collections.read": "View collections",
"collections.write": "Modify collections",
}
WRITE_SCOPES_MAP: Final = {
"roms.write": "Modify ROMs",
"platforms.write": "Modify platforms",
"firmware.write": "Modify firmware",
}
FULL_SCOPES_MAP: Final = {
"users.read": "View users",
"users.write": "Modify users",
"tasks.run": "Run tasks",
}
DEFAULT_SCOPES: Final = list(DEFAULT_SCOPES_MAP.keys())
WRITE_SCOPES: Final = DEFAULT_SCOPES + list(WRITE_SCOPES_MAP.keys())
FULL_SCOPES: Final = WRITE_SCOPES + list(FULL_SCOPES_MAP.keys())
class AuthHandler:
def __init__(self) -> None:
@@ -79,21 +50,14 @@ class AuthHandler:
# Key exists therefore user is probably authenticated
user = db_user_handler.get_user_by_username(username)
if user is None:
if user is None or not user.enabled:
conn.session.clear()
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="User not found",
)
if not user.enabled:
conn.session.clear()
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Inactive user {user.username}",
log.error(
"User '%s' %s",
username,
"not found" if user is None else "not enabled",
)
return None
return user
@@ -102,14 +66,11 @@ class OAuthHandler:
def __init__(self) -> None:
pass
def create_oauth_token(self, data: dict, expires_delta: timedelta | None = None):
def create_oauth_token(
self, data: dict, expires_delta: timedelta = DEFAULT_OAUTH_TOKEN_EXPIRY
) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=DEFAULT_OAUTH_TOKEN_EXPIRY)
expire = datetime.now(timezone.utc) + expires_delta
to_encode.update({"exp": expire})
return jwt.encode(
@@ -126,7 +87,7 @@ class OAuthHandler:
issuer = payload.claims.get("iss")
if not issuer or issuer != "romm:oauth":
return None
return None, None
username = payload.claims.get("sub")
if username is None:
@@ -137,8 +98,68 @@ class OAuthHandler:
raise OAuthCredentialsException
if not user.enabled:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user"
)
raise UserDisabledException
return user, payload.claims
class OpenIDHandler:
async def get_current_active_user_from_openid_token(self, token: Any):
from handler.database import db_user_handler
from models.user import Role, User
if not OIDC_ENABLED:
return None, None
userinfo = token.get("userinfo")
if userinfo is None:
log.error("Userinfo is missing from token.")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Userinfo is missing from token.",
)
email = userinfo.get("email")
if email is None:
log.error("Email is missing from token.")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email is missing from token.",
)
metadata = await oauth.openid.load_server_metadata()
claims_supported = metadata.get("claims_supported")
is_email_verified = userinfo.get("email_verified", None)
# Fail if email is explicitly unverified, or `email_verified` is a supported claim and
# email is not explicitly verified.
if is_email_verified is False or (
claims_supported
and "email_verified" in claims_supported
and is_email_verified is not True
):
log.error("Email is not verified.")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email is not verified.",
)
preferred_username = userinfo.get("preferred_username")
user = db_user_handler.get_user_by_email(email)
if user is None:
log.info("User with email '%s' not found, creating new user", email)
user = User(
username=preferred_username,
hashed_password=str(uuid.uuid4()),
email=email,
enabled=True,
role=Role.VIEWER,
)
db_user_handler.add_user(user)
if not user.enabled:
raise UserDisabledException
log.info("User successfully authenticated: %s", email)
return user, userinfo

View File

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

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