diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9b579bdb3..9eac00336 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: version: - description: 'romm version' + description: "romm version" required: true type: string @@ -18,23 +18,39 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v3 + - name: Set environment variables - run: echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV + run: | + CURRENT_RC_VERSION=$(wget -q -O - "https://hub.docker.com/v2/repositories/zurdi15/romm/tags?page_size=2" | grep -o '"name": *"[^"]*' | grep -o '[^"]*$' | grep "dev-${{ inputs.version }}-rc" | cut -d "-" -f 3 | cut -d "." -f 2) + [[ -z $CURRENT_RC_VERSION ]] && CURRENT_RC_VERSION=0 + NEXT_RC_VERSION="$(($CURRENT_RC_VERSION + 1))" + echo "VERSION_PREFIX=${{ github.ref != format('refs/heads/{0}', 'release') && 'dev-' || '' }}" >> $GITHUB_ENV + echo "VERSION_SUFFIX=${{ github.ref == format('refs/heads/{0}', 'master') && '-rc.$NEXT_RC_VERSION' || '' }}" >> $GITHUB_ENV + + - name: Set version + run: | + version=${{ env.VERSION_PREFIX }}${{ inputs.version }}${{ env.VERSION_SUFFIX }} + sed -i 's//'"${version}"'/' backend/__version__.py + - name: Set up QEMU uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 + - name: Login to Docker Hub uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} + - name: Login to GitHub Container Registry uses: docker/login-action@v2 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - name: Generate Docker metadata id: meta uses: docker/metadata-action@v4 @@ -45,7 +61,8 @@ jobs: flavor: | # latest on release branch, prefix dev on other branches latest=true - prefix=${{ github.ref != format('refs/heads/{0}', 'release') && 'dev-' || '' }},onlatest=true + prefix=${{ env.VERSION_PREFIX }},onlatest=true + suffix=${{ env.VERSION_SUFFIX }},onlatest=false tags: | type=raw,value=${{ inputs.version }} labels: | diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 564c6fcb7..0fd6520cf 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -37,23 +37,30 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v3 + - name: Install mariadb connectors run: | sudo apt-get update sudo apt-get install -y libmariadb3 libmariadb-dev + - name: Install poetry - run: pipx install poetry + run: | + pipx install git+https://github.com/radoering/poetry.git@non-package-mode + - name: Set up Python 3.10 uses: actions/setup-python@v4 with: python-version: '3.10' cache: 'poetry' + - name: Install dependencies run: | poetry install --sync + - name: Initiate database run: | mysql --host 127.0.0.1 --port ${{ job.services.mariadb.ports['3306'] }} -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON romm_test.* TO 'romm_test'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;" + - name: Run python tests env: DB_HOST: 127.0.0.1 @@ -61,6 +68,7 @@ jobs: run: | cd backend poetry run pytest -vv --maxfail=10 --junitxml=pytest-report.xml . + - name: Publish test results uses: EnricoMi/publish-unit-test-result-action/composite@v2 if: always() diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c34e897ce..462a5bb3b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,51 +1,40 @@ { - "version": "2.0.0", "tasks": [ { + "label": "Launch frontend", "type": "npm", - "script": "dev", "path": "frontend", - "problemMatcher": [], - "label": "Launch frontend [npm]" - }, - { - "type": "shell", - "command": "source ~/.cache/pypoetry/virtualenvs/romm-TjwgbYlf-py3.11/bin/activate; cd backend; python main.py", - "label": "Launch backend [python]", + "script": "dev", "problemMatcher": [] }, { + "label": "Launch backend", "type": "shell", - "command": "source ~/.cache/pypoetry/virtualenvs/romm-TjwgbYlf-py3.11/bin/activate; cd backend; pytest -v", - "label": "Execute tests [pytest]", + "command": "cd backend && poetry run python3 main.py", "problemMatcher": [] }, { + "label": "Launch worker", "type": "shell", - "command": "./docker/build_local_image.sh", - "label": "Build docker local image [docker]", - "problemMatcher": [], - "group": { - "kind": "build", - "isDefault": true - } + "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", - "label": "Setup development environment [docker] (1)", "problemMatcher": [] }, { + "label": "Setup testing environment", "type": "shell", - "command": "export $(cat .env | xargs); docker exec -i mariadb mariadb -u root -p$DB_ROOT_PASSWD < backend/romm_test/setup.sql", - "label": "Setup development environment migrations [docker] (2)", - "problemMatcher": [] - }, - { - "type": "shell", - "command": "cd romm_mock; docker compose up -d", - "label": "Setup testing environment [docker]", + "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": [] } ] diff --git a/DEVELOPER-SETUP.md b/DEVELOPER-SETUP.md index 63998a543..311d7a2c0 100644 --- a/DEVELOPER-SETUP.md +++ b/DEVELOPER-SETUP.md @@ -19,21 +19,34 @@ touch romm_mock/config.yml cp env.template .env ``` +### - Install system dependencies + +```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 +``` + ### - Install python dependencies You'll need poetry installed https://python-poetry.org/docs/#installing-with-the-official-installer -Then initialize the virtual environment and install the dependencies +**_WARNING:_** Until poetry 1.8.0 version is released, poetry needs to be installed with the new non-package-mode feature branch: + +```sh +pipx install git+https://github.com/radoering/poetry.git@non-package-mode +``` + +More info: https://github.com/python-poetry/poetry/pull/8650 + + +Then creat the virtual environment ```sh -poetry shell # Fix disable parallel installation stuck: $> poetry config experimental.new-installer false # Fix Loading macOS/linux stuck: $> export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring -# Fix mariadb install on linux: $> sudo apt install libmariadb3 libmariadb-dev -# Fix mariadb connector/c >= 3.3.1: https://mariadb.com/docs/skysql-previous-release/connect/programming-languages/c/install/#Installation_via_Package_Repository_(Linux) -poetry install +poetry install --sync ``` ### - Spin up mariadb in docker @@ -48,7 +61,7 @@ docker-compose up -d ```sh cd backend -python main.py +poetry run python3 main.py ``` @@ -56,7 +69,7 @@ python main.py ```sh cd backend -python worker.py +poetry run python3 worker.py ``` ## Setting up the frontend @@ -87,8 +100,7 @@ npm run dev ### - Create the test user and database with root user ```sh -docker exec -i mariadb mysql -u root -p < backend/romm_test/setup.sql # for amd images -docker exec -i mariadb mariadb -u root -p < backend/romm_test/setup.sql # for arm images +docker exec -i mariadb mariadb -u root -p < backend/romm_test/setup.sql ``` ### - Run tests @@ -98,5 +110,5 @@ docker exec -i mariadb mariadb -u root -p < backend/romm_test/set ```sh cd backend # path or test file can be passed as argument to test only a subset -pytest [path/file] +poetry run pytest [path/file] ``` diff --git a/backend/__version__.py b/backend/__version__.py new file mode 100644 index 000000000..cc4a13849 --- /dev/null +++ b/backend/__version__.py @@ -0,0 +1 @@ +__version__ = '' diff --git a/backend/config/config_loader.py b/backend/config/config_loader.py index 6db6fc032..bcc8e03b2 100644 --- a/backend/config/config_loader.py +++ b/backend/config/config_loader.py @@ -46,6 +46,9 @@ class Config: class ConfigLoader: # Tests require custom config path def __init__(self, config_path: str = ROMM_USER_CONFIG_PATH): + if os.path.isdir(config_path): + log.critical(f"Your config file {config_path} is a directory, not a file. Docker creates folders by default for binded files that doesn't exists in advance in the host system.") + raise FileNotFoundError() try: with open(config_path) as config_file: self._raw_config = yaml.load(config_file, Loader=SafeLoader) or {} diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 6024d5a9d..7f8d72489 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -1,6 +1,6 @@ from datetime import datetime import json -from typing import Optional +from typing import Optional, Annotated from typing_extensions import TypedDict from fastapi import ( APIRouter, @@ -10,6 +10,7 @@ from fastapi import ( File, UploadFile, ) +from fastapi import Query from fastapi_pagination.ext.sqlalchemy import paginate from fastapi_pagination.cursor import CursorPage, CursorParams from fastapi.responses import FileResponse @@ -147,7 +148,7 @@ def upload_roms( @protected_route(router.get, "/roms/{id}/download", ["roms.read"]) -def download_rom(request: Request, id: int, files: str): +def download_rom(request: Request, id: int, files: Annotated[list[str] | None, Query()] = None): """Downloads a rom or a zip file with multiple roms""" rom = dbh.get_rom(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" @@ -155,18 +156,19 @@ def download_rom(request: Request, id: int, files: str): if not rom.multi: return FileResponse(path=rom_path, filename=rom.file_name) - file_list = files.split(",") if files else rom.files - # Builds a generator of tuples for each member file def local_files(): def contents(file_name): - with open(f"{rom_path}/{file_name}", "rb") as f: - while chunk := f.read(65536): - yield chunk + try: + with open(f"{rom_path}/{file_name}", "rb") as f: + while chunk := f.read(65536): + yield chunk + except FileNotFoundError: + log.error(f"File {rom_path}/{file_name} not found!") return [ (file_name, datetime.now(), S_IFREG | 0o600, ZIP_64, contents(file_name)) - for file_name in file_list + for file_name in files ] zipped_chunks = stream_zip(local_files()) diff --git a/backend/endpoints/scan.py b/backend/endpoints/scan.py index c1eefe86e..3ee05ffdf 100644 --- a/backend/endpoints/scan.py +++ b/backend/endpoints/scan.py @@ -29,6 +29,7 @@ from config import ENABLE_EXPERIMENTAL_REDIS async def scan_platforms( platform_slugs: list[str], complete_rescan: bool = False, + rescan_unidentified: bool = False, selected_roms: list[str] = (), ): # Connect to external socketio server @@ -72,7 +73,7 @@ async def scan_platforms( for fs_rom in fs_roms: rom = dbh.get_rom_by_filename(scanned_platform.slug, fs_rom["file_name"]) - if rom and rom.id not in selected_roms and not complete_rescan: + if (rom and rom.id not in selected_roms and not complete_rescan) and not (rescan_unidentified and rom and not rom.igdb_id): continue scanned_rom = await scan_rom(scanned_platform, fs_rom) @@ -203,7 +204,7 @@ async def scan_platforms( dbh.purge_platforms(fs_platforms) dbh.purge_screenshots(fs_screenshots) - log.info(emoji.emojize(":check_mark: Scan completed ")) + log.info(emoji.emojize(":check_mark: Scan completed ")) await sm.emit("scan:done", {}) @@ -216,7 +217,8 @@ async def scan_handler(_sid: str, options: dict): store_default_resources() platform_slugs = options.get("platforms", []) - complete_rescan = options.get("rescan", False) + complete_rescan = options.get("completeRescan", False) + rescan_unidentified = options.get("rescanUnidentified", False) selected_roms = options.get("roms", []) # Run in worker if redis is available @@ -225,8 +227,9 @@ async def scan_handler(_sid: str, options: dict): scan_platforms, platform_slugs, complete_rescan, + rescan_unidentified, selected_roms, job_timeout=14400, # Timeout after 4 hours ) else: - await scan_platforms(platform_slugs, complete_rescan, selected_roms) + await scan_platforms(platform_slugs, complete_rescan, rescan_unidentified, selected_roms) diff --git a/backend/endpoints/tests/test_heartbeat.py b/backend/endpoints/tests/test_heartbeat.py index 500bcc517..77944604c 100644 --- a/backend/endpoints/tests/test_heartbeat.py +++ b/backend/endpoints/tests/test_heartbeat.py @@ -1,6 +1,7 @@ from fastapi.testclient import TestClient from main import app +from utils import get_version client = TestClient(app) @@ -9,6 +10,7 @@ def test_heartbeat(): response = client.get("/heartbeat") assert response.status_code == 200 assert response.json() == { + "VERSION" : get_version(), "ROMM_AUTH_ENABLED": True, "WATCHER": { "ENABLED": True, diff --git a/backend/handler/db_handler.py b/backend/handler/db_handler.py index bbe70b625..2679acbd3 100644 --- a/backend/handler/db_handler.py +++ b/backend/handler/db_handler.py @@ -69,7 +69,7 @@ class DBHandler: ) return session.execute( delete(Platform) - .where(or_(Platform.slug.not_in(platforms), Platform.slug.is_(None))) + .where(or_(Platform.fs_slug.not_in(platforms), Platform.slug.is_(None))) .execution_options(synchronize_session="evaluate") ) diff --git a/backend/handler/igdb_handler.py b/backend/handler/igdb_handler.py index 1114280cd..b03d988cd 100644 --- a/backend/handler/igdb_handler.py +++ b/backend/handler/igdb_handler.py @@ -24,7 +24,7 @@ EXPANDED_GAME_CATEGORY: Final = 10 N_SCREENSHOTS: Final = 5 PS2_IGDB_ID: Final = 8 SWITCH_IGDB_ID: Final = 130 -ARCADE_IGDB_ID: Final = 52 +ARCADE_IGDB_IDS: Final = [52, 79, 80] PS2_OPL_REGEX: Final = r"^([A-Z]{4}_\d{3}\.\d{2})\..*$" PS2_OPL_INDEX_FILE: Final = os.path.join( @@ -240,7 +240,7 @@ class IGDBHandler: search_term = index_entry["name"] # type: ignore # Support for MAME arcade filename format - if platform_idgb_id == ARCADE_IGDB_ID: + if platform_idgb_id in ARCADE_IGDB_IDS: mame_index = {"menu": {"game": []}} try: @@ -262,7 +262,8 @@ class IGDBHandler: if game["@name"] == search_term ] if index_entry: - search_term = index_entry[0].get("description", search_term) + # Run through get_search_term to remove tags + search_term = get_search_term(index_entry[0].get("description", search_term)) search_term = ( search_term.replace("\u2122", "") # Remove trademark symbol @@ -340,7 +341,7 @@ class IGDBHandler: igdb_id=rom["id"], slug=rom["slug"], name=rom["name"], - summary=rom["summary"], + summary=rom.get("summary", ""), url_cover=self._search_cover(rom["id"]).replace( "t_thumb", "t_cover_big" ), diff --git a/backend/main.py b/backend/main.py index 491fc4059..5d7eb7493 100644 --- a/backend/main.py +++ b/backend/main.py @@ -30,6 +30,7 @@ from utils.auth import ( CustomCSRFMiddleware, create_default_admin_user, ) +from utils import get_version app = FastAPI(title="RomM API", version="0.1.0") @@ -79,6 +80,7 @@ app.mount("/ws", socket_app) @app.get("/heartbeat") def heartbeat(): return { + "VERSION": get_version(), "ROMM_AUTH_ENABLED": ROMM_AUTH_ENABLED, "WATCHER": { "ENABLED": ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, diff --git a/backend/utils/__init__.py b/backend/utils/__init__.py index 491e3dcff..933870b8d 100644 --- a/backend/utils/__init__.py +++ b/backend/utils/__init__.py @@ -1,5 +1,6 @@ import re -import numpy as np +import subprocess as sp +from __version__ import __version__ LANGUAGES = [ ("Ar", "Arabic"), @@ -68,7 +69,7 @@ def parse_tags(file_name: str) -> tuple: langs = [] other_tags = [] tags = [tag[0] or tag[1] for tag in re.findall(TAG_REGEX, file_name)] - tags = np.array([tag.split(",") for tag in tags]).flatten() + tags = [tag for subtags in tags for tag in subtags.split(",")] tags = [tag.strip() for tag in tags] for tag in tags: @@ -119,3 +120,16 @@ def get_file_name_with_no_tags(file_name: str) -> str: def get_file_extension(file_name: str) -> str: return re.search(EXTENSION_REGEX, file_name).group(1) + + +def get_version() -> str | None: + """Returns current version or branch name.""" + if not __version__ == "": + return __version__ + else: + try: + output = str(sp.check_output(["git", "branch"], universal_newlines=True)) + except sp.CalledProcessError: + return None + branch = [a for a in output.split("\n") if a.find("*") >= 0][0] + return branch[branch.find("*") + 2 :] diff --git a/backend/utils/fs.py b/backend/utils/fs.py index 4180be502..0f7b9e807 100644 --- a/backend/utils/fs.py +++ b/backend/utils/fs.py @@ -29,7 +29,6 @@ DEFAULT_HEIGHT_COVER_L: Final = 352 # Height of big cover of IGDB DEFAULT_WIDTH_COVER_S: Final = 90 # Width of small cover of IGDB DEFAULT_HEIGHT_COVER_S: Final = 120 # Height of small cover of IGDB - # ========= Resources utils ========= class CoverSize(Enum): SMALL = "small" diff --git a/backend/utils/tests/test_fs.py b/backend/utils/tests/test_fs.py index efba1fa02..3a18827e3 100644 --- a/backend/utils/tests/test_fs.py +++ b/backend/utils/tests/test_fs.py @@ -24,11 +24,11 @@ from config import ( @pytest.mark.vcr def test_get_rom_cover(): - # Game: Paper Mario (USA).z64 + # Game: Metroid Prime (EUR).iso cover = get_rom_cover( overwrite=False, - fs_slug="n64", - rom_name="Paper Mario", + fs_slug="ngc", + rom_name="Metroid Prime", ) assert DEFAULT_PATH_COVER_S in cover["path_cover_s"] diff --git a/docker/Dockerfile b/docker/Dockerfile index 1cd490002..7d0ba83bf 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -31,7 +31,8 @@ RUN apk add --upgrade \ mariadb-connector-c-dev \ musl-dev \ python3-dev \ - py3-pip + py3-pip \ + git # Create python venv to not clash with OS python packages RUN python3 -m venv /backend/ @@ -42,14 +43,14 @@ COPY ./pyproject.toml ./poetry.lock / # Install poetry using pip RUN . /backend/bin/activate && \ pip install --no-cache --upgrade pip && \ - pip install --no-cache poetry && \ + pip install --no-cache git+https://github.com/radoering/poetry.git@non-package-mode && \ pip freeze | awk -F= '{print $1}' > /installed_pip_requirements.txt # Install project dependencies using poetry RUN . /backend/bin/activate && \ - poetry config --no-cache virtualenvs.create false && \ - poetry install --no-interaction --no-ansi --no-cache --only main && \ - poetry export --without-hashes --only main --without-urls | awk -F= '{print $1}' > /installed_poetry_requirements.txt + python3 -m poetry config --no-cache virtualenvs.create false && \ + python3 -m poetry install --no-interaction --no-ansi --no-cache --only main && \ + python3 -m poetry export --without-hashes --only main --without-urls | awk -F= '{print $1}' > /installed_poetry_requirements.txt # cleanup python dependencies that are not needed anymore RUN . /backend/bin/activate && \ @@ -69,7 +70,8 @@ RUN apk del \ mariadb-connector-c-dev \ musl-dev \ python3-dev \ - py3-pip + py3-pip \ + git # cleanup leftover files that are not needed at runtime RUN rm -r \ diff --git a/frontend/package.json b/frontend/package.json index 7d24b0768..24e61fc71 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,5 @@ { "name": "romm", - "version": "2.1.0", "private": true, "scripts": { "dev": "vite --host", diff --git a/frontend/src/App.vue b/frontend/src/App.vue index fc05eeca0..bb3e7a871 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -4,14 +4,17 @@ import cookie from "js-cookie"; import storeAuth from "@/stores/auth"; import Notification from "@/components/Notification.vue"; import { api } from "@/services/api"; +import storeHeartbeat from "@/stores/heartbeat"; // Props const auth = storeAuth(); +const heartbeat = storeHeartbeat(); onBeforeMount(async () => { - // Set CSRF token for all requests const { data } = await api.get("/heartbeat"); + heartbeat.set(data) auth.setEnabled(data.ROMM_AUTH_ENABLED ?? false); + // Set CSRF token for all requests api.defaults.headers.common["x-csrftoken"] = cookie.get("csrftoken"); }); diff --git a/frontend/src/components/Details/Title.vue b/frontend/src/components/Details/Title.vue index 330848575..c7f4bddc5 100644 --- a/frontend/src/components/Details/Title.vue +++ b/frontend/src/components/Details/Title.vue @@ -25,21 +25,21 @@ const { smAndUp } = useDisplay(); - + - {{ regionToEmoji(region) }} {{ regionToEmoji(region) }} - {{ languageToEmoji(language) }} {{ languageToEmoji(language) }} Rev {{ rom.revision }} diff --git a/frontend/src/components/Game/Card/Cover.vue b/frontend/src/components/Game/Card/Cover.vue index 8bcd5d1de..1ddcf1dc2 100644 --- a/frontend/src/components/Game/Card/Cover.vue +++ b/frontend/src/components/Game/Card/Cover.vue @@ -98,29 +98,25 @@ function onTouchEnd() { {{ rom.name || rom.file_name }} - + - - {{ regionToEmoji(region) }}  + + {{ regionToEmoji(region) }} - - {{ languageToEmoji(language) }}  + + {{ languageToEmoji(language) }} @@ -148,8 +144,7 @@ function onTouchEnd() { bottom: 0.2rem; right: 0.2rem; } - -.chips { +.flags { bottom: -0.25rem; left: 0; } diff --git a/frontend/src/components/Game/DataTable/Base.vue b/frontend/src/components/Game/DataTable/Base.vue index 3f947d734..5b20bace0 100644 --- a/frontend/src/components/Game/DataTable/Base.vue +++ b/frontend/src/components/Game/DataTable/Base.vue @@ -7,6 +7,7 @@ import storeRoms from "@/stores/roms"; import storeAuth from "@/stores/auth"; import { VDataTable } from "vuetify/labs/VDataTable"; import AdminMenu from "@/components/AdminMenu/Base.vue"; +import { regionToEmoji, languageToEmoji } from "@/utils/utils"; const HEADERS = [ { @@ -37,7 +38,13 @@ const HEADERS = [ title: "Reg", align: "start", sortable: true, - key: "region", + key: "regions", + }, + { + title: "Lang", + align: "start", + sortable: true, + key: "languages", }, { title: "Rev", @@ -101,6 +108,16 @@ function rowClick(_, row) { {{ item.selectable.file_size_units }} + +