Merge remote-tracking branch 'origin/master' into mobygames-new-api

This commit is contained in:
zurdi
2024-03-19 18:18:41 +01:00
20 changed files with 1199 additions and 866 deletions

14
.github/FUNDING.yml vendored
View File

@@ -1,13 +1 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: [https://www.buymeacoffee.com/zurdi15] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
buy_me_a_coffee: zurdi15

View File

@@ -1,6 +1,6 @@
---
name: Bug report
about: Create a report to help me improve
about: Report a bug, issue or problem
title: "[Bug] Bug title"
labels: bug
assignees: ''

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

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

View File

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

View File

@@ -0,0 +1,19 @@
### Description
<sup>Please describe 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
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
<sup>Add any additional information or context about the pull request here.</sup>
```

View File

@@ -47,10 +47,10 @@ jobs:
run: |
pipx install git+https://github.com/radoering/poetry.git@non-package-mode
- name: Set up Python 3.10
- name: Set up Python 3.11
uses: actions/setup-python@v4
with:
python-version: '3.10'
python-version: '3.11'
cache: 'poetry'
- name: Install dependencies

View File

@@ -1 +1 @@
3.10
3.11

130
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,130 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Sharing copyrighted ROM files, discussing how to pirate ROMs, posting links
to file downloads, or any other discussions about copyrighted ROMs
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
community@romm.fastmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

53
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,53 @@
## Contributing to RomM
Thank you for considering contributing to RomM! This document outlines some guidelines to help you get started with your contributions.
**If you're looking to implement a large feature or make significant changes to the project, it's best to open an issue first AND join the Discord to discuss your ideas with the maintainers.**
### Code of Conduct
Please note that this project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). By participating in this project, you are expected to uphold this code.
### Contributing to the Wiki
If you would like to contribute to the project's [documentation](https://github.com/zurdi15/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).
### How to Contribute Code
1. Fork the repository.
2. Clone your forked repository: `git clone https://github.com/your-username/romm.git`
3. Checkout the `master` branch: `git checkout master`
4. Create a new branch for your feature/fix: `git checkout -b feature-or-fix-name`
5. Make your changes and commit them with descriptive commit messages: `git commit -am 'Add feature XYZ'`
6. Push your changes to your fork: `git push origin feature-or-fix-name`
7. Open a pull request to the `master` branch of the original repository.
### Pull Request Guidelines
- Make sure your code follows the project's coding standards.
- Test your changes locally before opening a pull request.
- Update the documentation if necessary.
- Ensure all existing tests pass, and add new tests for new functionality.
- Use clear and descriptive titles and descriptions for your pull requests.
### Code Style
Follow the existing code style used throughout the project. If working with VSCode or a similar editor, consider installing these extensions:
- [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
- [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
- [Pylance](https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance)
- [Ruff](https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff)
- [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
### Issue Reporting
If you encounter any bugs or have suggestions for improvements, please [create an issue](https://github.com/zurdi15/romm/issues) on GitHub. Provide as much detail as possible, including steps to reproduce the issue if applicable.
### Licensing
By contributing to ROMM, you agree that your contributions will be licensed under the project's [LICENSE](LICENSE).
---
Thank you for contributing to ROMM! Your help is greatly appreciated.

View File

@@ -32,7 +32,7 @@ RomM (ROM Manager) allows you to scan, enrich, and browse your game collection w
- Scans your existing games library and enchances it with metadata from [IGDB][igdb]
- Supports a large number of **[platforms][platform-support]**
- Play games directly from the browser using [EmulatorJS][wiki-emulatorjs-url]
- Built-in [authentication][authentication] with multiple users and permissions
- Share your library with friend while [limiting access and permissions][authentication]
- Supports [MAME][mame-xml-update], [Nintendo Switch][switch-titledb-update] and PS2 naming schemes
- Detects and groups **multifile games** (e.g. PS1 games with multiple CDs)
- Can [parse tags][tag-support] in filenames (e.g. (E), (USA), (rev v1), etc.)

View File

@@ -26,8 +26,8 @@ DB_PASSWD: Final = os.environ.get("DB_PASSWD")
DB_NAME: Final = os.environ.get("DB_NAME", "romm")
# REDIS
REDIS_HOST: Final = "127.0.0.1"
REDIS_PORT: Final = 6379
REDIS_HOST: Final = os.environ.get("REDIS_HOST", "127.0.0.1")
REDIS_PORT: Final = os.environ.get("REDIS_PORT", 6379)
# IGDB
IGDB_CLIENT_ID: Final = os.environ.get(

View File

@@ -199,6 +199,7 @@ def get_rom_content(
yield chunk
except FileNotFoundError:
log.error(f"File {rom_path}/{f} not found!")
raise
m3u_file = [str.encode(f"{files_to_download[i]}\n") for i in range(len(files_to_download))]
return [

View File

@@ -1,5 +1,11 @@
from starlette.types import Receive, Scope, Send
import time
import typing
from collections import namedtuple
from starlette.datastructures import MutableHeaders, Secret
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from starlette_csrf.middleware import CSRFMiddleware
from jose import jwt, JWTError
class CustomCSRFMiddleware(CSRFMiddleware):
@@ -9,3 +15,122 @@ class CustomCSRFMiddleware(CSRFMiddleware):
return
await super().__call__(scope, receive, send)
SecretKey = namedtuple("SecretKey", ("encode", "decode"))
class SessionMiddleware:
def __init__(
self,
app: ASGIApp,
secret_key: typing.Union[str, Secret, SecretKey],
session_cookie: str = "session",
max_age: int = 14 * 24 * 60 * 60, # 14 days, in seconds
same_site: str = "lax",
https_only: bool = False,
jwt_alg: str = "HS256",
) -> None:
self.app = app
self.jwt_alg = jwt_alg
if not isinstance(secret_key, SecretKey):
self.jwt_secret = SecretKey(Secret(str(secret_key)), None)
else:
self.jwt_secret = secret_key
# check crypto setup so we bail out if needed
_jwt = jwt.encode({"1": 2}, key=str(self.jwt_secret.encode), algorithm=jwt_alg)
assert {"1": 2} == jwt.decode(
_jwt,
key=str(
self.jwt_secret.decode
if self.jwt_secret.decode
else self.jwt_secret.encode
),
algorithms=[jwt_alg],
), "wrong crypto setup"
self.session_cookie = session_cookie
self.max_age = max_age
self.security_flags = "httponly; samesite=" + same_site
if https_only: # Secure flag can be used with HTTPS only
self.security_flags += "; secure"
def _validate_jwt_payload(self, jwt_payload):
if not isinstance(jwt_payload, dict):
return {}
# The "exp" (expiration time) claim identifies the expiration time on
# or after which the JWT MUST NOT be accepted for processing.
if "exp" in jwt_payload and jwt_payload["exp"] < int(time.time()):
return {}
# The "nbf" (not before) claim identifies the time before which the JWT
# MUST NOT be accepted for processing.
if "nbf" in jwt_payload and jwt_payload["nbf"] > int(time.time()):
return {}
return jwt_payload
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"): # pragma: no cover
await self.app(scope, receive, send)
return
connection = HTTPConnection(scope)
initial_session_was_empty = True
if self.session_cookie in connection.cookies:
data = connection.cookies[self.session_cookie].encode("utf-8")
try:
jwt_payload = jwt.decode(
data,
key=str(
self.jwt_secret.decode
if self.jwt_secret.decode
else self.jwt_secret.encode
),
algorithms=[self.jwt_alg],
)
jwt_payload = self._validate_jwt_payload(jwt_payload)
scope["session"] = jwt_payload
initial_session_was_empty = False
except JWTError:
scope["session"] = {}
else:
scope["session"] = {}
async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
if scope["session"]:
if "exp" not in scope["session"]:
scope["session"]["exp"] = int(time.time()) + self.max_age
data = jwt.encode(
scope["session"],
key=str(self.jwt_secret.encode),
algorithm=self.jwt_alg,
)
headers = MutableHeaders(scope=message)
header_value = "%s=%s; path=/; Max-Age=%d; %s" % (
self.session_cookie,
data,
self.max_age,
self.security_flags,
)
headers.append("Set-Cookie", header_value)
elif not initial_session_was_empty:
# The session has been cleared.
headers = MutableHeaders(scope=message)
header_value = "%s=%s; %s" % (
self.session_cookie,
"null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;",
self.security_flags,
)
headers.append("Set-Cookie", header_value)
await send(message)
await self.app(scope, receive, send_wrapper)

View File

@@ -4,6 +4,7 @@ import sys
import alembic.config
import uvicorn
from config import DEV_HOST, DEV_PORT, ROMM_AUTH_SECRET_KEY, DISABLE_CSRF_PROTECTION
from contextlib import asynccontextmanager
from endpoints import (
auth,
config,
@@ -27,11 +28,21 @@ from fastapi_pagination import add_pagination
from handler import auth_handler, db_user_handler, github_handler, socket_handler
from handler.auth_handler import ALGORITHM
from handler.auth_handler.hybrid_auth import HybridAuthBackend
from handler.auth_handler.middleware import CustomCSRFMiddleware
from handler.auth_handler.middleware import CustomCSRFMiddleware, SessionMiddleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette_authlib.middleware import AuthlibMiddleware as SessionMiddleware
app = FastAPI(title="RomM API", version=github_handler.get_version())
@asynccontextmanager
async def lifespan(app: FastAPI):
if "pytest" not in sys.modules:
# Create default admin user if no admin user exists
if len(db_user_handler.get_admin_users()) == 0:
auth_handler.create_default_admin_user()
yield
app = FastAPI(title="RomM API", version=github_handler.get_version(), lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
@@ -83,18 +94,6 @@ add_pagination(app)
app.mount("/ws", socket_handler.socket_app)
@app.on_event("startup")
def startup() -> None:
"""Event to handle RomM startup logic."""
if "pytest" in sys.modules:
return
# Create default admin user if no admin user exists
if len(db_user_handler.get_admin_users()) == 0:
auth_handler.create_default_admin_user()
if __name__ == "__main__":
# Run migrations
alembic.config.main(argv=["upgrade", "head"])

View File

@@ -107,7 +107,10 @@ cd /backend || { error_log "/backend directory doesn't seem to exist"; }
# function definition done, lets start our main loop
while true; do
# Start redis server if we dont have a corresponding PID file
watchdog_process_pid bin redis-server
# and REDIS_HOST is not set (which would mean we're using an external redis)
if [[ -z "${REDIS_HOST}" ]]; then
watchdog_process_pid bin redis-server
fi
# Run needed database migrations on startup,
# but only if it was not successful since the last full docker container start

View File

@@ -44,7 +44,7 @@ function onFullScreenChange() {
</script>
<template>
<v-row v-if="rom" no-gutters>
<v-row v-if="rom" class="h-screen" no-gutters>
<v-col v-if="!gameRunning" cols="3" class="px-3">
<v-img
class="mx-auto mt-6 mb-5"
@@ -121,7 +121,7 @@ function onFullScreenChange() {
</v-btn>
</v-col>
<v-col class="my-4 bg-primary" rounded id="game-wrapper">
<v-col class="bg-primary" rounded id="game-wrapper">
<player :rom="rom" :state="stateRef" :save="saveRef" />
</v-col>
</v-row>
@@ -130,5 +130,7 @@ function onFullScreenChange() {
<style>
#game-wrapper {
aspect-ratio: 16 / 9;
max-width: 100%;
max-height: 100%;
}
</style>

View File

@@ -389,6 +389,12 @@ window.EJS_onGameStart = async () => {
<div id="game"></div>
</template>
<style scoped>
#game {
max-height: 100dvh;
}
</style>
<!-- Other config options: https://emulatorjs.org/docs/Options.html -->
<!-- window.EJS_biosUrl; -->

1596
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,51 +11,50 @@ authors = [
]
[tool.poetry.dependencies]
python = "^3.10"
python = "^3.11"
requests = "2.31.0"
fastapi = "0.103.1"
uvicorn = "0.22.0"
websockets = "11.0.3"
python-socketio = "5.8.0"
SQLAlchemy = {extras = ["mypy"], version = "^2.0.19"}
alembic = "1.10.4"
fastapi = "0.110.0"
uvicorn = "0.28.0"
websockets = "12.0"
python-socketio = "5.11.1"
SQLAlchemy = {extras = ["mypy"], version = "^2.0.28"}
alembic = "1.13.1"
PyYAML = "6.0.1"
Unidecode = "1.3.6"
emoji = "2.2.0"
python-dotenv = "1.0.0"
Unidecode = "1.3.8"
emoji = "2.10.1"
python-dotenv = "1.0.1"
ipdb = "0.13.13"
fastapi-pagination = "^0.12.4"
sqlakeyset = "^2.0.1684285512"
pydash = "^7.0.6"
mariadb = "1.1.7"
rq = "^1.15.1"
fastapi-pagination = "^0.12.19"
sqlakeyset = "^2.0.1708907391"
pydash = "^7.0.7"
mariadb = "1.1.10"
rq = "^1.16.1"
aioredis = "^2.0.1"
types-pyyaml = "^6.0.12.11"
types-requests = "^2.31.0.2"
mypy = "^1.4.1"
types-redis = "^4.6.0.3"
types-pyyaml = "^6.0.12.20240311"
types-requests = "^2.31.0.20240311"
mypy = "^1.9.0"
types-redis = "^4.6.0.20240311 "
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
itsdangerous = "^2.1.2"
stream-zip = "^0.0.67"
stream-zip = "^0.0.71"
rq-scheduler = "^0.13.1"
starlette-csrf = "^3.0.0"
httpx = "^0.24.1"
python-multipart = "^0.0.6"
types-python-jose = "^3.3.4.8"
types-passlib = "^1.7.7.13"
watchdog = "^3.0.0"
httpx = "^0.27.0"
python-multipart = "^0.0.9"
types-python-jose = "^3.3.4.20240106"
types-passlib = "^1.7.7.20240311"
watchdog = "^4.0.0"
xmltodict = "^0.13.0"
Pillow = "10.1.0"
numpy = "^1.26.2"
starlette-authlib = "^0.1.38"
Pillow = "10.2.0"
numpy = "^1.26.4"
[tool.poetry.group.test.dependencies]
pytest = "^7.4.0"
pytest-env = "^0.8.2"
pytest = "^8.1.1"
pytest-env = "^1.1.3"
pytest-vcr = "^1.0.2"
pytest-mock = "^3.11.1"
pytest-asyncio = "^0.21.1"
pytest-mock = "^3.12.0"
pytest-asyncio = "^0.23.5"
[tool.mypy]
plugins = "sqlalchemy.ext.mypy.plugin"