From 7bc3d7da62a554b0966af5c1593be92ce30f3df1 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 14:02:40 +0200 Subject: [PATCH 01/35] readme logo renamed --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 738fead40..5eb0e2031 100644 --- a/readme.md +++ b/readme.md @@ -1,5 +1,5 @@
- Gameyfin Logo + RomM Logo

RomM (Rom Manager)

From 4b3b118e16b62773b25b7ba60b7ec3efe2964537 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 15:40:40 +0200 Subject: [PATCH 02/35] fix search igdb for not supported platforms --- backend/src/handler/igdb_handler.py | 33 ++++++++++-------- backend/src/main.py | 4 +-- .../platforms/{commodore.ico => c64.ico} | Bin frontend/src/components/RomDetails.vue | 3 +- readme.md | 2 +- 5 files changed, 23 insertions(+), 19 deletions(-) rename frontend/assets/platforms/{commodore.ico => c64.ico} (100%) diff --git a/backend/src/handler/igdb_handler.py b/backend/src/handler/igdb_handler.py index bb1283a71..2dc787db7 100644 --- a/backend/src/handler/igdb_handler.py +++ b/backend/src/handler/igdb_handler.py @@ -114,20 +114,25 @@ class IGDBHandler(): @check_twitch_token - def get_matched_roms(self, file_name: str, p_igdb_id: int) -> list: - search_term: str = unidecode.unidecode(re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0])) - matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers, - data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json() - log.info(f"Matched roms for {file_name}: {matched_roms}") - for rom in matched_roms: - try: - res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers, - data=f"fields url; where game={rom['id']};").json()[0] - rom['url_cover'] = f"https:{res_details['url']}".replace('t_thumb', f't_cover_big') - except IndexError: - rom['url_cover'] = DEFAULT_URL_COVER_L - rom['r_igdb_id'] = rom.pop('id') - rom['r_slug'] = rom.pop('slug') + def get_matched_roms(self, file_name: str, p_igdb_id: int, p_slug: str) -> list: + matched_roms: list[dict] = [] + if p_igdb_id != '': + search_term: str = unidecode.unidecode(re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0])) + log.debug(search_term) + matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers, + data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json() + log.info(f"Matched roms for {file_name}: {matched_roms}") + for rom in matched_roms: + try: + res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers, + data=f"fields url; where game={rom['id']};").json()[0] + rom['url_cover'] = f"https:{res_details['url']}".replace('t_thumb', f't_cover_big') + except IndexError: + rom['url_cover'] = DEFAULT_URL_COVER_L + rom['r_igdb_id'] = rom.pop('id') + rom['r_slug'] = rom.pop('slug') + else: + log.warning(f"{p_slug} is not supported!") return matched_roms diff --git a/backend/src/main.py b/backend/src/main.py index 86685396c..1780aa2bc 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -97,8 +97,8 @@ async def search_rom_igdb(req: Request) -> dict: """Get all the roms matched from igdb.""" data: dict = await req.json() - log.info(f"getting {data['file_name']} roms from {data['p_igdb_id']} igdb ...") - return {'data': igdbh.get_matched_roms(data['file_name'], data['p_igdb_id'])} + log.info(f"getting {data['rom']['file_name']} roms from {data['rom']['p_slug']} igdb ...") + return {'data': igdbh.get_matched_roms(data['rom']['file_name'], data['rom']['p_igdb_id'], data['rom']['p_slug'])} if __name__ == '__main__': diff --git a/frontend/assets/platforms/commodore.ico b/frontend/assets/platforms/c64.ico similarity index 100% rename from frontend/assets/platforms/commodore.ico rename to frontend/assets/platforms/c64.ico diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index 1963ca784..c27119bba 100644 --- a/frontend/src/components/RomDetails.vue +++ b/frontend/src/components/RomDetails.vue @@ -28,8 +28,7 @@ async function searchRomIGDB() { dialogSearchRom.value = true console.log("searching for rom... "+rom.value.file_name) await axios.put('/api/search/roms/igdb', { - file_name: rom.value.file_name, - p_igdb_id: rom.value.p_igdb_id + rom: rom.value }).then((response) => { console.log(response.data.data) matchedRoms.value = response.data.data diff --git a/readme.md b/readme.md index 5eb0e2031..fc6c998ae 100644 --- a/readme.md +++ b/readme.md @@ -124,7 +124,7 @@ This will change over the time, adding games metadata for more platforms. Make s | arcade | Arcade | ✅ | | atari | atari | ❌ | | coleco | coleco | ❌ | -| commodore | commodore | ❌ | +| c64 | Commodore C64/128/MAX | ✅ | | cpc | cpc | ❌ | | cps1 | cps1 | ❌ | | cps2 | cps2 | ❌ | From 4cd299291955f2f9321ef23ebd62d8cf599a22d8 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 16:29:30 +0200 Subject: [PATCH 03/35] version upgraded to 1.6.2 --- frontend/.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/.env b/frontend/.env index 5f9286bec..65daa322c 100644 --- a/frontend/.env +++ b/frontend/.env @@ -1 +1 @@ -VITE_ROMM_VERSION='1.6.1' \ No newline at end of file +VITE_ROMM_VERSION='1.6.2' \ No newline at end of file From 8375ae3f227d9b952b918b2e59492c082bc17e68 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 16:35:37 +0200 Subject: [PATCH 04/35] debug logs cleaned --- backend/src/handler/igdb_handler.py | 1 - 1 file changed, 1 deletion(-) diff --git a/backend/src/handler/igdb_handler.py b/backend/src/handler/igdb_handler.py index 2dc787db7..fcf3891f9 100644 --- a/backend/src/handler/igdb_handler.py +++ b/backend/src/handler/igdb_handler.py @@ -118,7 +118,6 @@ class IGDBHandler(): matched_roms: list[dict] = [] if p_igdb_id != '': search_term: str = unidecode.unidecode(re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0])) - log.debug(search_term) matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers, data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json() log.info(f"Matched roms for {file_name}: {matched_roms}") From b12e88390f8cc22a495201bc8efb67a0a536294f Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 17:03:10 +0200 Subject: [PATCH 05/35] refactor versioning ci/cd --- .github/actions/build.sh | 18 +++++++++++------- .github/workflows/image.yml | 14 +++++--------- frontend/.env | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/actions/build.sh b/.github/actions/build.sh index ea469a440..461973316 100755 --- a/.github/actions/build.sh +++ b/.github/actions/build.sh @@ -1,9 +1,13 @@ +VERSION=$(cat ./frontend/.env | grep VITE_ROMM_VERSION | cut -d "=" -f2) + if [[ $GIT_BRANCH != 'master' ]]; then - docker buildx build --push\ - --tag zurdi15/romm:dev-latest --tag zurdi15/romm:dev-${VERSION}\ - --platform linux/arm64 . --file ./docker/Dockerfile -else - docker buildx build --push\ - --tag zurdi15/romm:latest --tag zurdi15/romm:${VERSION}\ - --platform linux/arm64,linux/amd64 . --file ./docker/Dockerfile + VERSION=dev-$VERSION + echo $VERSION + # docker buildx build --push\ + # --tag zurdi15/romm:dev-latest --tag zurdi15/romm:dev-${VERSION}\ + # --platform linux/arm64 . --file ./docker/Dockerfile +# else +# docker buildx build --push\ +# --tag zurdi15/romm:latest --tag zurdi15/romm:${VERSION}\ +# --platform linux/arm64,linux/amd64 . --file ./docker/Dockerfile fi \ No newline at end of file diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 4d0aa73de..1997b14fa 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -1,12 +1,6 @@ name: build romm image -on: - workflow_dispatch: - inputs: - version: - description: 'romm version' - required: true - type: string +on: [workflow_dispatch] jobs: build: @@ -14,17 +8,19 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v2 + - name: Set environment variables run: echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV + - name: Install buildx id: buildx uses: crazy-max/ghaction-docker-buildx@v1 with: version: latest + - name: Login to docker hub run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin + - name: Build the image shell: bash run: ./.github/actions/build.sh - env: - VERSION: ${{ inputs.version }} \ No newline at end of file diff --git a/frontend/.env b/frontend/.env index 65daa322c..4cd46d6be 100644 --- a/frontend/.env +++ b/frontend/.env @@ -1 +1 @@ -VITE_ROMM_VERSION='1.6.2' \ No newline at end of file +VITE_ROMM_VERSION=1.6.3 \ No newline at end of file From 83188970cd87694d7bbdf436f7ce67ef82e1dbd2 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 4 Apr 2023 17:03:10 +0200 Subject: [PATCH 06/35] refactor versioning ci/cd --- .github/actions/build.sh | 3 +++ .github/workflows/image.yml | 14 +++++--------- frontend/.env | 2 +- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/.github/actions/build.sh b/.github/actions/build.sh index ea469a440..a22317fed 100755 --- a/.github/actions/build.sh +++ b/.github/actions/build.sh @@ -1,4 +1,7 @@ +VERSION=$(cat ./frontend/.env | grep VITE_ROMM_VERSION | cut -d "=" -f2) + if [[ $GIT_BRANCH != 'master' ]]; then + VERSION=dev-$VERSION docker buildx build --push\ --tag zurdi15/romm:dev-latest --tag zurdi15/romm:dev-${VERSION}\ --platform linux/arm64 . --file ./docker/Dockerfile diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 4d0aa73de..1997b14fa 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -1,12 +1,6 @@ name: build romm image -on: - workflow_dispatch: - inputs: - version: - description: 'romm version' - required: true - type: string +on: [workflow_dispatch] jobs: build: @@ -14,17 +8,19 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v2 + - name: Set environment variables run: echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV + - name: Install buildx id: buildx uses: crazy-max/ghaction-docker-buildx@v1 with: version: latest + - name: Login to docker hub run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin + - name: Build the image shell: bash run: ./.github/actions/build.sh - env: - VERSION: ${{ inputs.version }} \ No newline at end of file diff --git a/frontend/.env b/frontend/.env index 65daa322c..4cd46d6be 100644 --- a/frontend/.env +++ b/frontend/.env @@ -1 +1 @@ -VITE_ROMM_VERSION='1.6.2' \ No newline at end of file +VITE_ROMM_VERSION=1.6.3 \ No newline at end of file From 071ade3ae4e6210ba201df9e633bff030f651ea6 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Wed, 5 Apr 2023 21:26:43 +0200 Subject: [PATCH 07/35] error log added to platform scan --- backend/src/utils/fs.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index 401c302b3..fdb690601 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -47,7 +47,9 @@ def get_platforms() -> list[str]: log.info(f"filesystem platforms found: {platforms}") return platforms except IndexError: - raise HTTPException(status_code=404, detail="Platforms not found.") + error: str = "Platforms not found." + log.critical(error) + raise HTTPException(status_code=404, detail=error) # ========= Roms utils ========= From ae7d00d13b3fd4c5b47e7c7504175f952466b6b0 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 12:55:17 +0200 Subject: [PATCH 08/35] alembic migrations system added --- backend/requirements.txt | 1 + backend/src/alembic.ini | 110 ++++++++++++++++++ backend/src/alembic/README | 1 + backend/src/alembic/env.py | 80 +++++++++++++ backend/src/alembic/script.py.mako | 24 ++++ .../alembic/versions/1.6.2_first_commit.py | 59 ++++++++++ .../alembic/versions/1.6.3_rom_add_multi.py | 28 +++++ backend/src/handler/db_handler.py | 61 +++++----- backend/src/logger/logger.py | 18 +-- backend/src/main.py | 83 +++++++------ backend/src/models/base.py | 7 -- backend/src/models/platform.py | 10 +- backend/src/models/rom.py | 17 +++ backend/src/utils/fs.py | 13 +-- 14 files changed, 424 insertions(+), 88 deletions(-) create mode 100644 backend/src/alembic.ini create mode 100644 backend/src/alembic/README create mode 100644 backend/src/alembic/env.py create mode 100644 backend/src/alembic/script.py.mako create mode 100644 backend/src/alembic/versions/1.6.2_first_commit.py create mode 100644 backend/src/alembic/versions/1.6.3_rom_add_multi.py diff --git a/backend/requirements.txt b/backend/requirements.txt index 536cde608..6851fc9c1 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -3,5 +3,6 @@ fastapi==0.92.0 uvicorn==0.20.0 mariadb==1.1.6 SQLAlchemy==2.0.7 +alembic==1.10.3 PyYAML==6.0 Unidecode==1.3.6 \ No newline at end of file diff --git a/backend/src/alembic.ini b/backend/src/alembic.ini new file mode 100644 index 000000000..ec986023e --- /dev/null +++ b/backend/src/alembic.ini @@ -0,0 +1,110 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = '' + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/backend/src/alembic/README b/backend/src/alembic/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/backend/src/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/backend/src/alembic/env.py b/backend/src/alembic/env.py new file mode 100644 index 000000000..79b416d95 --- /dev/null +++ b/backend/src/alembic/env.py @@ -0,0 +1,80 @@ +import sys +from pathlib import Path + +from logging.config import fileConfig + +from sqlalchemy import create_engine +from config.config_loader import get_db_engine + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +sys.path.append(f"{Path(__file__).parent.parent.resolve()}") +from models.base import BaseModel +from models.platform import Platform +from models.rom import Rom +target_metadata = BaseModel.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + + context.configure( + url=get_db_engine(), + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = create_engine(get_db_engine()) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/src/alembic/script.py.mako b/backend/src/alembic/script.py.mako new file mode 100644 index 000000000..55df2863d --- /dev/null +++ b/backend/src/alembic/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/backend/src/alembic/versions/1.6.2_first_commit.py b/backend/src/alembic/versions/1.6.2_first_commit.py new file mode 100644 index 000000000..296aea739 --- /dev/null +++ b/backend/src/alembic/versions/1.6.2_first_commit.py @@ -0,0 +1,59 @@ +"""first commit + +Revision ID: 1.6.2 +Revises: +Create Date: 2023-04-10 11:50:44.824818 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1.6.2' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('platforms', + sa.Column('igdb_id', sa.String(length=10), nullable=True), + sa.Column('sgdb_id', sa.String(length=10), nullable=True), + sa.Column('slug', sa.String(length=50), nullable=False), + sa.Column('name', sa.String(length=400), nullable=True), + sa.Column('logo_path', sa.String(length=1000), nullable=True), + sa.Column('n_roms', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('slug') + ) + op.create_table('roms', + sa.Column('r_igdb_id', sa.String(length=10), nullable=True), + sa.Column('p_igdb_id', sa.String(length=10), nullable=True), + sa.Column('r_sgdb_id', sa.String(length=10), nullable=True), + sa.Column('p_sgdb_id', sa.String(length=10), nullable=True), + sa.Column('p_slug', sa.String(length=50), nullable=False), + sa.Column('file_name', sa.String(length=450), nullable=False), + sa.Column('file_name_no_tags', sa.String(length=450), nullable=True), + sa.Column('file_extension', sa.String(length=10), nullable=True), + sa.Column('file_path', sa.String(length=1000), nullable=True), + sa.Column('file_size', sa.Float(), nullable=True), + sa.Column('name', sa.String(length=350), nullable=True), + sa.Column('r_slug', sa.String(length=100), nullable=True), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('path_cover_s', sa.Text(), nullable=True), + sa.Column('path_cover_l', sa.Text(), nullable=True), + 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.PrimaryKeyConstraint('p_slug', 'file_name') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('roms') + op.drop_table('platforms') + # ### end Alembic commands ### diff --git a/backend/src/alembic/versions/1.6.3_rom_add_multi.py b/backend/src/alembic/versions/1.6.3_rom_add_multi.py new file mode 100644 index 000000000..eed4bff90 --- /dev/null +++ b/backend/src/alembic/versions/1.6.3_rom_add_multi.py @@ -0,0 +1,28 @@ +"""rom - add multi + +Revision ID: 1.6.3 +Revises: 1.6.2 +Create Date: 2023-04-10 11:54:23.748175 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1.6.3' +down_revision = '1.6.2' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('roms', sa.Column('multi', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('roms', 'multi') + # ### end Alembic commands ### diff --git a/backend/src/handler/db_handler.py b/backend/src/handler/db_handler.py index 01f211936..75ec9c2ad 100644 --- a/backend/src/handler/db_handler.py +++ b/backend/src/handler/db_handler.py @@ -1,19 +1,22 @@ import functools from fastapi import HTTPException +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker from sqlalchemy import select from sqlalchemy.exc import ProgrammingError -from models.base import Session, BaseModel, engine +from config.config_loader import get_db_engine from models.platform import Platform from models.rom import Rom from logger.logger import log -class DBHandler: +class DBHandler: + def __init__(self) -> None: - BaseModel.metadata.create_all(engine) - self.session = Session() + engine = create_engine(get_db_engine(), pool_pre_ping=True) + self.session = sessionmaker(bind=engine, expire_on_commit=False) def retry(func) -> tuple: @@ -22,55 +25,57 @@ class DBHandler: return func(*args) return wrapper - + + # ========= Platforms ========= def add_platform(self, Platform: Platform) -> None: try: - with Session.begin() as session: - session.merge(Platform) + with self.session.begin() as s: + s.merge(Platform) except ProgrammingError as e: raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}") def get_platforms(self) -> list[Platform]: try: - with Session.begin() as session: - return session.scalars(select(Platform).order_by(Platform.slug.asc())).all() + with self.session.begin() as s: + return s.scalars(select(Platform).order_by(Platform.slug.asc())).all() except ProgrammingError as e: raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}") + + def purge_platforms(self, platforms: list[str]) -> None: + log.info("Purging platforms") + with self.session.begin() as s: + s.query(Platform) \ + .filter(Platform.slug.not_in(platforms)) \ + .delete(synchronize_session='evaluate') + # ========= Roms ========= def add_rom(self, rom: Rom) -> None: - with Session.begin() as session: - session.merge(rom) + with self.session.begin() as s: + s.merge(rom) def get_roms(self, p_slug: str) -> list[Rom]: - with Session.begin() as session: - return session.scalars(select(Rom).filter_by(p_slug=p_slug).order_by(Rom.file_name.asc())).all() + with self.session.begin() as s: + return s.scalars(select(Rom).filter_by(p_slug=p_slug).order_by(Rom.file_name.asc())).all() def get_rom(self, p_slug: str, file_name: str) -> Rom: - with Session.begin() as session: - return session.scalars(select(Rom).filter_by(p_slug=p_slug, file_name=file_name)).first() + with self.session.begin() as s: + return s.scalars(select(Rom).filter_by(p_slug=p_slug, file_name=file_name)).first() def update_rom(self, p_slug: str, file_name: str, data: dict) -> None: - with Session.begin() as session: - session.query(Rom) \ + with self.session.begin() as s: + s.query(Rom) \ .filter(Rom.p_slug==p_slug, Rom.file_name==file_name) \ .update(data, synchronize_session='evaluate') def delete_rom(self, p_slug: str, file_name: str) -> None: - with Session.begin() as session: - session.query(Rom) \ + with self.session.begin() as s: + s.query(Rom) \ .filter(Rom.p_slug==p_slug, Rom.file_name==file_name) \ .delete(synchronize_session='evaluate') - def purge_platforms(self, platforms: list[str]) -> None: - log.info("Purging platforms") - with Session.begin() as session: - session.query(Platform) \ - .filter(Platform.slug.not_in(platforms)) \ - .delete(synchronize_session='evaluate') - def purge_roms(self, p_slug: str, roms: list[dict]) -> None: log.info(f"Purging {p_slug} roms") - with Session.begin() as session: - session.query(Rom) \ + with self.session.begin() as s: + s.query(Rom) \ .filter(Rom.p_slug==p_slug, Rom.file_name.not_in([rom['file_name'] for rom in roms])) \ .delete(synchronize_session='evaluate') diff --git a/backend/src/logger/logger.py b/backend/src/logger/logger.py index 653638d9c..b6857d9a1 100644 --- a/backend/src/logger/logger.py +++ b/backend/src/logger/logger.py @@ -15,17 +15,17 @@ class CustomFormatter(logging.Formatter): level: str = "%(levelname)s" dots: str = ":" - identifier: str = "\t [ROMM] " - identifier_warning: str = " [ROMM] " - identifier_critical: str = " [ROMM] " + identifier: str = "\t [RomM]" + identifier_warning: str = " [RomM]" + identifier_critical: str = " [RomM]" msg: str = "%(message)s" - date: str = " %(asctime)s" + date: str = "[%(asctime)s] " FORMATS: dict = { - logging.DEBUG: COLORS['pink'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['reset'] + msg + COLORS['cyan'] + date + COLORS['reset'], - logging.INFO: COLORS['grey'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['reset'] + msg + COLORS['cyan'] + date + COLORS['reset'], - logging.WARNING: COLORS['orange'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier_warning + COLORS['reset'] + msg + COLORS['cyan'] + date + COLORS['reset'], - logging.ERROR: COLORS['red'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['reset'] + msg + COLORS['cyan'] + date + COLORS['reset'], - logging.CRITICAL: COLORS['bold_red'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier_critical + COLORS['reset'] + msg + COLORS['cyan'] + date + COLORS['reset'] + logging.DEBUG: COLORS['pink'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['cyan'] + date + COLORS['reset'] + msg, + logging.INFO: COLORS['grey'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['cyan'] + date + COLORS['reset'] + msg, + logging.WARNING: COLORS['orange'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier_warning + COLORS['cyan'] + date + COLORS['reset'] + msg, + logging.ERROR: COLORS['red'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier + COLORS['cyan'] + date + COLORS['reset'] + msg, + logging.CRITICAL: COLORS['bold_red'] + level + COLORS['reset'] + dots + COLORS['blue'] + identifier_critical + COLORS['cyan'] + date + COLORS['reset'] + msg } def format(self, record): diff --git a/backend/src/main.py b/backend/src/main.py index 1780aa2bc..f5aefa4b6 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -1,4 +1,5 @@ -import os +import subprocess +from subprocess import CalledProcessError from fastapi import FastAPI, Request import uvicorn @@ -13,6 +14,41 @@ app = FastAPI() fastapi.allow_cors(app) +@app.on_event("startup") +async def startup() -> None: + """Startup application.""" + log.info("Applying migrations...") + try: + subprocess.run(['alembic', 'upgrade', 'head'], check=True) + except CalledProcessError as e: + log.critical(f"Could not apply migrations: {e}") + + +@app.put("/scan") +async def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: + """Scan platforms and roms and write them in database.""" + + log.info("complete scaning...") + fs.store_default_resources(overwrite) + data: dict = await req.json() + platforms: list[str] = data['platforms'] if data['platforms'] else fs.get_platforms() + for p_slug in platforms: + platform: Platform = fastapi.scan_platform(p_slug) + roms: list[dict] = fs.get_roms(p_slug, full_scan) + for rom in roms: + fastapi.scan_rom(platform, rom) + dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) + dbh.purge_platforms(fs.get_platforms()) + return {'msg': 'success'} + + +@app.get("/platforms") +async def platforms() -> dict: + """Returns platforms data""" + + return {'data': dbh.get_platforms()} + + @app.get("/platforms/{p_slug}/roms/{file_name}") async def rom(p_slug: str, file_name: str) -> dict: """Returns one rom data of the desired platform""" @@ -20,14 +56,11 @@ async def rom(p_slug: str, file_name: str) -> dict: return {'data': dbh.get_rom(p_slug, file_name)} -@app.delete("/platforms/{p_slug}/roms/{file_name}") -async def delete_rom(p_slug: str, file_name: str, filesystem: bool=False) -> dict: - """Detele rom from filesystem and database""" +@app.get("/platforms/{p_slug}/roms") +async def roms(p_slug: str) -> dict: + """Returns all roms of the desired platform""" - log.info("deleting rom...") - if filesystem: fs.delete_rom(p_slug, file_name) - dbh.delete_rom(p_slug, file_name) - return {'msg': 'success'} + return {'data': dbh.get_roms(p_slug)} @app.patch("/platforms/{p_slug}/roms") @@ -60,35 +93,13 @@ async def updateRom(req: Request, p_slug: str) -> dict: return {'data': updatedRom} -@app.get("/platforms/{p_slug}/roms") -async def roms(p_slug: str) -> dict: - """Returns all roms of the desired platform""" +@app.delete("/platforms/{p_slug}/roms/{file_name}") +async def delete_rom(p_slug: str, file_name: str, filesystem: bool=False) -> dict: + """Detele rom from filesystem and database""" - return {'data': dbh.get_roms(p_slug)} - - -@app.get("/platforms") -async def platforms() -> dict: - """Returns platforms data""" - - return {'data': dbh.get_platforms()} - - -@app.put("/scan") -async def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: - """Scan platforms and roms and write them in database.""" - - log.info("complete scaning...") - fs.store_default_resources(overwrite) - data: dict = await req.json() - platforms: list[str] = data['platforms'] if data['platforms'] else fs.get_platforms() - for p_slug in platforms: - platform: Platform = fastapi.scan_platform(p_slug) - roms: list[dict] = fs.get_roms(p_slug, full_scan) - for rom in roms: - fastapi.scan_rom(platform, rom) - dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) - dbh.purge_platforms(fs.get_platforms()) + log.info("deleting rom...") + if filesystem: fs.delete_rom(p_slug, file_name) + dbh.delete_rom(p_slug, file_name) return {'msg': 'success'} diff --git a/backend/src/models/base.py b/backend/src/models/base.py index 098b4e914..f3eb68ee1 100644 --- a/backend/src/models/base.py +++ b/backend/src/models/base.py @@ -1,10 +1,3 @@ -from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -from config.config_loader import get_db_engine BaseModel = declarative_base() - -engine = create_engine(get_db_engine(), pool_pre_ping=True) -Session = sessionmaker(bind=engine, expire_on_commit=False) diff --git a/backend/src/models/platform.py b/backend/src/models/platform.py index 753af2e4c..1e2e3e45a 100644 --- a/backend/src/models/platform.py +++ b/backend/src/models/platform.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, String, Integer, Text +from sqlalchemy import Column, String, Integer from config import DEFAULT_PATH_COVER_S from models.base import BaseModel @@ -15,3 +15,11 @@ class Platform(BaseModel): logo_path = Column(String(length=1000), default=DEFAULT_PATH_COVER_S) n_roms = Column(Integer, default=0) + + def __repr__(self) -> str: + return ( + f"igdb_id: {self.igdb_id}," + f"slug: {self.slug}," + f"name: {self.name}," + f"n_roms: {self.n_roms}," + ) diff --git a/backend/src/models/rom.py b/backend/src/models/rom.py index 3be7cb30a..68e749dfb 100644 --- a/backend/src/models/rom.py +++ b/backend/src/models/rom.py @@ -31,3 +31,20 @@ class Rom(BaseModel): region = Column(String(20), default="") revision = Column(String(20), default="") tags = Column(JSON, default=[]) + + multi = Column(Boolean, default=False) + + @property + def full_path(self) -> str: + return f"{self.file_path}/{self.file_name}" + + def __repr__(self) -> str: + return ( + f"r_igdb_id: {self.r_igdb_id}," + f"p_igdb_id: {self.p_igdb_id}," + f"r_slug: {self.r_slug}," + f"p_slug: {self.p_slug}," + f"file_name: {self.file_name}," + f"file_path: {self.file_path}," + f"multi: {self.multi}," + ) diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index fdb690601..be3f919a1 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -54,12 +54,7 @@ def get_platforms() -> list[str]: # ========= Roms utils ========= def _check_folder_structure(p_slug) -> tuple: - roms_path: str = f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms" - try: - roms_files = list(os.walk(roms_path))[0][2] - except IndexError: - roms_files = [] - return roms_path, roms_files + return f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms" def _exclude_files(roms_files) -> list[str]: @@ -101,7 +96,11 @@ def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[di Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH. Just the amount of them if only_amount=True """ roms: list[dict] = [] - roms_path, roms_files = _check_folder_structure(p_slug) + roms_path = _check_folder_structure(p_slug) + roms_files: list = list(os.walk(roms_path))[0][2] + list(os.walk(roms_path))[0][1] + roms_multi: list = [] + for rom_folder in list(os.walk(roms_path))[0][1]: + roms_multi.append(list(os.walk(f"{roms_path}/{rom_folder}"))[0][2]) roms_files = _exclude_files(roms_files) if only_amount: return len(roms_files) From 50eef356a6f49fbe56b2e1f780133abe1a8111da Mon Sep 17 00:00:00 2001 From: duhow Date: Mon, 10 Apr 2023 16:23:11 +0200 Subject: [PATCH 09/35] Initial rework of Dockerfile --- docker/Dockerfile | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 492e3ee57..286616113 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,37 +1,39 @@ # build frontend FROM node:lts-alpine as front-build-stage WORKDIR /front -COPY ./frontend/package*.json ./ +COPY ./frontend/package*.json . RUN npm install -COPY ./frontend ./ +COPY ./frontend . RUN npm run build # setup frontend FROM ubuntu/nginx:1.18-22.04_edge as production-stage -COPY --from=front-build-stage /front/dist /var/www/html -COPY ./frontend/assets/platforms /var/www/html/assets/platforms -RUN mkdir -p /var/www/html/assets/romm -RUN ln -s /romm/library /var/www/html/assets/romm/library -RUN ln -s /romm/resources /var/www/html/assets/romm/resources +ARG WEBSERVER_FOLDER=/var/www/html +COPY --from=front-build-stage /front/dist ${WEBSERVER_FOLDER} +COPY ./frontend/assets/platforms ${WEBSERVER_FOLDER}/assets/platforms +RUN mkdir -p ${WEBSERVER_FOLDER}/assets/romm && \ + ln -s /romm/library ${WEBSERVER_FOLDER}/assets/romm/library && \ + ln -s /romm/resources ${WEBSERVER_FOLDER}/assets/romm/resources # setup backend -RUN apt update -RUN apt install -y software-properties-common gcc -RUN add-apt-repository -y ppa:deadsnakes/ppa -RUN apt update -y && apt install libmariadb3 libmariadb-dev -y -RUN apt install -y python3.10 python3-pip +RUN apt update && \ + apt install -y --no-install-recommends software-properties-common gnupg gcc && \ + add-apt-repository -y ppa:deadsnakes/ppa && \ + apt update -y && apt install --no-install-recommends libmariadb3 libmariadb-dev -y && \ + apt install -y --no-install-recommends python3.10 python3.10-dev python3-pip && \ + apt autoremove && \ + rm -rf /var/lib/apt/lists/* /var/cache/apt/* WORKDIR /back COPY ./backend/requirements.txt ./requirements.txt -RUN pip install --upgrade pip -RUN pip install --no-cache-dir --upgrade -r ./requirements.txt -COPY ./backend/src ./ +RUN pip install --no-cache --upgrade pip && \ + pip install --no-cache --upgrade -r requirements.txt +COPY ./backend/src . # setup init script and config files -COPY ./docker/init_scripts/init_back /init_back -COPY ./docker/init_scripts/init_front /init_front -COPY ./docker/init_scripts/init /init +COPY ./docker/init_scripts/* / COPY ./docker/nginx/default.conf /etc/nginx/nginx.conf EXPOSE 80 +WORKDIR /romm CMD ["/init"] From 17b6d837d50638a79b83d9a62f43e0ebd1e51737 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 16:31:17 +0200 Subject: [PATCH 10/35] multifile selector added to front --- .../alembic/versions/1.6.3_rom_add_multi.py | 4 ++- backend/src/main.py | 2 ++ backend/src/models/rom.py | 4 ++- backend/src/utils/fs.py | 26 +++++++++++-------- frontend/package.json | 2 +- frontend/src/components/Navigation.vue | 2 +- frontend/src/components/RomDetails.vue | 17 +++++++----- 7 files changed, 35 insertions(+), 22 deletions(-) diff --git a/backend/src/alembic/versions/1.6.3_rom_add_multi.py b/backend/src/alembic/versions/1.6.3_rom_add_multi.py index eed4bff90..109b51e3d 100644 --- a/backend/src/alembic/versions/1.6.3_rom_add_multi.py +++ b/backend/src/alembic/versions/1.6.3_rom_add_multi.py @@ -2,7 +2,7 @@ Revision ID: 1.6.3 Revises: 1.6.2 -Create Date: 2023-04-10 11:54:23.748175 +Create Date: 2023-04-10 16:21:34.680282 """ from alembic import op @@ -19,10 +19,12 @@ depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('roms', sa.Column('multi', sa.Boolean(), nullable=True)) + op.add_column('roms', sa.Column('files', sa.JSON(), nullable=True)) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('roms', 'files') op.drop_column('roms', 'multi') # ### end Alembic commands ### diff --git a/backend/src/main.py b/backend/src/main.py index f5aefa4b6..a266392ea 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -1,3 +1,4 @@ +import sys import subprocess from subprocess import CalledProcessError from fastapi import FastAPI, Request @@ -22,6 +23,7 @@ async def startup() -> None: subprocess.run(['alembic', 'upgrade', 'head'], check=True) except CalledProcessError as e: log.critical(f"Could not apply migrations: {e}") + sys.exit(4) @app.put("/scan") diff --git a/backend/src/models/rom.py b/backend/src/models/rom.py index 68e749dfb..8ceca733c 100644 --- a/backend/src/models/rom.py +++ b/backend/src/models/rom.py @@ -17,7 +17,7 @@ class Rom(BaseModel): file_name_no_tags = Column(String(length=450), default="") file_extension = Column(String(length=10), default="") file_path = Column(String(length=1000), default="") - file_size = Column(Float, default="") + file_size = Column(Float, default=0.0) name = Column(String(length=350), default="") r_slug = Column(String(length=100), default="") @@ -33,6 +33,7 @@ class Rom(BaseModel): tags = Column(JSON, default=[]) multi = Column(Boolean, default=False) + files = Column(JSON, default=[]) @property def full_path(self) -> str: @@ -47,4 +48,5 @@ class Rom(BaseModel): f"file_name: {self.file_name}," f"file_path: {self.file_path}," f"multi: {self.multi}," + f"files: {self.files}" ) diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index be3f919a1..47f0eb910 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -95,26 +95,31 @@ def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[di only_amount: flag to return only amount of roms instead of all info Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH. Just the amount of them if only_amount=True """ - roms: list[dict] = [] roms_path = _check_folder_structure(p_slug) - roms_files: list = list(os.walk(roms_path))[0][2] + list(os.walk(roms_path))[0][1] - roms_multi: list = [] - for rom_folder in list(os.walk(roms_path))[0][1]: - roms_multi.append(list(os.walk(f"{roms_path}/{rom_folder}"))[0][2]) - roms_files = _exclude_files(roms_files) + roms: list[dict] = [] - if only_amount: return len(roms_files) + roms_files: list = _exclude_files(list(os.walk(roms_path))[0][2]) + roms_files_multi: list = list(os.walk(roms_path))[0][1] + + if only_amount: return len(roms_files) + len(roms_files_multi) + + not_new_roms: list[str] = [rom.file_name for rom in dbh.get_roms(p_slug)] - excluded_roms: list[str] = [rom.file_name for rom in dbh.get_roms(p_slug)] for rom in roms_files: - if rom in excluded_roms and not full_scan: continue + if rom in not_new_roms and not full_scan: continue file_size: str = str(round(os.stat(f"{roms_path}/{rom}").st_size / (1024 * 1024), 2)) file_extension: str = rom.split('.')[-1] if '.' in rom else "" reg, rev, other_tags = parse_tags(rom) roms.append({'file_name': rom, 'file_path': roms_path, 'file_size': file_size, 'file_extension': file_extension, 'region': reg, 'revision': rev, 'tags': other_tags}) + + for rom_multi in roms_files_multi: + if rom_multi in not_new_roms and not full_scan: continue + reg, rev, other_tags = parse_tags(rom_multi) + roms.append({'file_name': rom_multi, 'file_path': roms_path, 'multi': True, 'files': list(os.walk(f"{roms_path}/{rom_multi}"))[0][2], + 'region': reg, 'revision': rev, 'tags': other_tags, 'multi': True}) + log.info(f"Roms found for {p_slug}: {roms}") - if only_amount: return 0 return roms @@ -209,4 +214,3 @@ def get_cover_details(overwrite: bool, p_slug: str, file_name: str, url_cover: s path_cover_l = _get_cover_path(p_slug, file_name, 'l') has_cover = 1 return path_cover_s, path_cover_l, has_cover - diff --git a/frontend/package.json b/frontend/package.json index 09840bc24..1e0d93ecf 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "romm", - "version": "1.6.1", + "version": "1.6.3", "private": true, "scripts": { "dev": "vite --host", diff --git a/frontend/src/components/Navigation.vue b/frontend/src/components/Navigation.vue index dcbe38d2a..7bc6fbb03 100644 --- a/frontend/src/components/Navigation.vue +++ b/frontend/src/components/Navigation.vue @@ -104,7 +104,7 @@ getPlatforms() - + diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index c27119bba..1f977cc01 100644 --- a/frontend/src/components/RomDetails.vue +++ b/frontend/src/components/RomDetails.vue @@ -134,17 +134,20 @@ async function deleteRom() { - IGDB id{{ rom.r_igdb_id }} Name{{ rom.name }} - File{{ rom.file_name }} - Path{{ rom.file_path }} + File{{ rom.file_name }} + Files + + + Platform{{ rom.p_slug }} + Size{{ rom.file_size }} MB + + IGDB id{{ rom.r_igdb_id }} Region{{ rom.region }} Revision{{ rom.revision }} Tags{{ tag }} - Size{{ rom.file_size }} MB - Slug{{ rom.r_slug }} - Platform{{ rom.p_slug }} - Cover{{ rom.path_cover_l }} + + Summary{{ rom.summary }} From 9cdca7c7aaf88c689023efd2a0ea1414774baf1c Mon Sep 17 00:00:00 2001 From: duhow Date: Mon, 10 Apr 2023 16:40:55 +0200 Subject: [PATCH 11/35] Remove software-properties-common dependency --- docker/Dockerfile | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 286616113..ab5819fc4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -17,10 +17,14 @@ RUN mkdir -p ${WEBSERVER_FOLDER}/assets/romm && \ # setup backend RUN apt update && \ - apt install -y --no-install-recommends software-properties-common gnupg gcc && \ - add-apt-repository -y ppa:deadsnakes/ppa && \ - apt update -y && apt install --no-install-recommends libmariadb3 libmariadb-dev -y && \ - apt install -y --no-install-recommends python3.10 python3.10-dev python3-pip && \ + apt install -y --no-install-recommends ca-certificates curl gnupg && \ + # add deadsnakes ppa for Python versions + echo "deb https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy main" > /etc/apt/sources.list.d/deadsnakes-ubuntu-ppa-jammy.list && \ + apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F23C5A6CF475977595C89F51BA6932366A755776 && \ + apt update && \ + apt install -y --no-install-recommends \ + libmariadb3 libmariadb-dev gcc \ + python3.10 python3.10-dev python3-pip && \ apt autoremove && \ rm -rf /var/lib/apt/lists/* /var/cache/apt/* WORKDIR /back From 80b56bcdd790134ebe7a59079fe5e4d6df524dda Mon Sep 17 00:00:00 2001 From: duhow Date: Mon, 10 Apr 2023 17:01:49 +0200 Subject: [PATCH 12/35] Rework GitHub Actions Workflow --- .github/actions/build.sh | 9 ------ .github/workflows/image.yml | 56 +++++++++++++++++++++++++++++-------- 2 files changed, 44 insertions(+), 21 deletions(-) delete mode 100755 .github/actions/build.sh diff --git a/.github/actions/build.sh b/.github/actions/build.sh deleted file mode 100755 index ea469a440..000000000 --- a/.github/actions/build.sh +++ /dev/null @@ -1,9 +0,0 @@ -if [[ $GIT_BRANCH != 'master' ]]; then - docker buildx build --push\ - --tag zurdi15/romm:dev-latest --tag zurdi15/romm:dev-${VERSION}\ - --platform linux/arm64 . --file ./docker/Dockerfile -else - docker buildx build --push\ - --tag zurdi15/romm:latest --tag zurdi15/romm:${VERSION}\ - --platform linux/arm64,linux/amd64 . --file ./docker/Dockerfile -fi \ No newline at end of file diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 4d0aa73de..ae63c35df 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -11,20 +11,52 @@ on: jobs: build: runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + packages: write steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Set environment variables run: echo "GIT_BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV - - name: Install buildx - id: buildx - uses: crazy-max/ghaction-docker-buildx@v1 + - 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: - version: latest - - name: Login to docker hub - run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin - - name: Build the image - shell: bash - run: ./.github/actions/build.sh - env: - VERSION: ${{ inputs.version }} \ No newline at end of file + 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 + with: + images: | + name=zurdi15/romm + name=ghcr.io/zurdi15/romm + flavor: | + # latest on master branch, prefix dev on other branches + latest=${{ github.ref == format('refs/heads/{0}', 'master') }} + prefix=${{ github.ref != format('refs/heads/{0}', 'master') && 'dev-' || '' }} + tags: | + type=raw,value=latest + type=raw,value=${{ inputs.version }} + labels: | + org.opencontainers.image.version=${{ inputs.version }} + - name: Build image + uses: docker/build-push-action@v4 + with: + file: docker/Dockerfile + context: . + push: true + platforms: linux/arm64,linux/amd64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} From f9b8be2c3d34a945f9d7766fed9a65d34bfb3ffe Mon Sep 17 00:00:00 2001 From: duhow Date: Mon, 10 Apr 2023 17:27:04 +0200 Subject: [PATCH 13/35] Add latest always with prefix --- .github/workflows/image.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index ae63c35df..400f7c508 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -44,10 +44,9 @@ jobs: name=ghcr.io/zurdi15/romm flavor: | # latest on master branch, prefix dev on other branches - latest=${{ github.ref == format('refs/heads/{0}', 'master') }} - prefix=${{ github.ref != format('refs/heads/{0}', 'master') && 'dev-' || '' }} + latest=true + prefix=${{ github.ref != format('refs/heads/{0}', 'master') && 'dev-' || '' }},onlatest=true tags: | - type=raw,value=latest type=raw,value=${{ inputs.version }} labels: | org.opencontainers.image.version=${{ inputs.version }} From 6bbd4abd52e7777c75c2859a5f4cbcc677a86fd9 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 18:29:20 +0200 Subject: [PATCH 14/35] download function refactored --- backend/src/utils/fs.py | 10 +-- frontend/package-lock.json | 87 ++++++++++++++++++++++++-- frontend/package.json | 1 + frontend/src/components/RomDetails.vue | 2 +- frontend/src/utils/utils.js | 40 ++++++++---- 5 files changed, 116 insertions(+), 24 deletions(-) diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index 47f0eb910..a6b0027bc 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -53,7 +53,7 @@ def get_platforms() -> list[str]: # ========= Roms utils ========= -def _check_folder_structure(p_slug) -> tuple: +def _get_folder_structure(p_slug) -> tuple: return f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms" @@ -95,7 +95,7 @@ def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[di only_amount: flag to return only amount of roms instead of all info Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH. Just the amount of them if only_amount=True """ - roms_path = _check_folder_structure(p_slug) + roms_path = _get_folder_structure(p_slug) roms: list[dict] = [] roms_files: list = _exclude_files(list(os.walk(roms_path))[0][2]) @@ -132,21 +132,21 @@ def _rom_exists(p_slug: str, file_name: str) -> bool: Returns True if rom exists in filesystem else False """ - rom_path, _ = _check_folder_structure(p_slug) + rom_path = _get_folder_structure(p_slug) exists: bool = True if os.path.exists(f"{rom_path}/{file_name}") else False return exists def rename_rom(p_slug: str, old_name: str, new_name: str) -> None: if new_name != old_name: - rom_path, _ = _check_folder_structure(p_slug) + rom_path = _get_folder_structure(p_slug) if _rom_exists(p_slug, new_name): raise HTTPException(status_code=500, detail=f"Can't rename: {new_name} already exists.") os.rename(f"{rom_path}/{old_name}", f"{rom_path}/{new_name}") def delete_rom(p_slug: str, file_name: str) -> None: try: - rom_path, _ = _check_folder_structure(p_slug) + rom_path = _get_folder_structure(p_slug) os.remove(f"{rom_path}/{file_name}") except FileNotFoundError: log.warning(f"Rom not found in filesystem: {rom_path}/{file_name}") diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 58572f303..40497026e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,17 +1,18 @@ { "name": "romm", - "version": "1.6.1", + "version": "1.6.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "romm", - "version": "1.2.2", + "version": "1.6.3", "dependencies": { "@mdi/font": "7.0.96", "axios": "^1.3.4", "core-js": "^3.8.3", "file-saver": "^2.0.5", + "jszip": "^3.10.1", "mitt": "^3.0.0", "roboto-fontface": "*", "vue": "^3.2.13", @@ -568,6 +569,11 @@ "url": "https://opencollective.com/core-js" } }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -1430,6 +1436,11 @@ "node": ">= 4" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==" + }, "node_modules/immutable": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.2.4.tgz", @@ -1474,8 +1485,7 @@ "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/is-binary-path": { "version": "2.1.0", @@ -1540,6 +1550,11 @@ "node": ">=8" } }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -1580,6 +1595,17 @@ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "dev": true }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -1593,6 +1619,14 @@ "node": ">= 0.8.0" } }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dependencies": { + "immediate": "~3.0.5" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -1809,6 +1843,11 @@ "node": ">=6" } }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -1980,6 +2019,11 @@ "node": ">= 0.8.0" } }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", @@ -2014,6 +2058,20 @@ } ] }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -2132,6 +2190,11 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, "node_modules/sass": { "version": "1.58.3", "resolved": "https://registry.npmjs.org/sass/-/sass-1.58.3.tgz", @@ -2164,6 +2227,11 @@ "node": ">=10" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -2207,6 +2275,14 @@ "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", "deprecated": "Please use @jridgewell/sourcemap-codec instead" }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -2319,8 +2395,7 @@ "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, "node_modules/vite": { "version": "3.2.5", diff --git a/frontend/package.json b/frontend/package.json index 1e0d93ecf..ff5bf24f4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -13,6 +13,7 @@ "axios": "^1.3.4", "core-js": "^3.8.3", "file-saver": "^2.0.5", + "jszip": "^3.10.1", "mitt": "^3.0.0", "roboto-fontface": "*", "vue": "^3.2.13", diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index 1f977cc01..489ca4ca3 100644 --- a/frontend/src/components/RomDetails.vue +++ b/frontend/src/components/RomDetails.vue @@ -137,7 +137,7 @@ async function deleteRom() { Name{{ rom.name }} File{{ rom.file_name }} Files - + Platform{{ rom.p_slug }} Size{{ rom.file_size }} MB diff --git a/frontend/src/utils/utils.js b/frontend/src/utils/utils.js index 7a87db786..2c2c534da 100644 --- a/frontend/src/utils/utils.js +++ b/frontend/src/utils/utils.js @@ -1,22 +1,38 @@ import axios from 'axios' +import JSZip from "jszip" import { saveAs } from 'file-saver' -export function downloadRom(rom, emitter) { +export async function downloadRom(rom, emitter) { console.log("Downloading "+rom.file_name) emitter.emit('snackbarScan', {'msg': "Gathering "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'}) - emitter.emit('downloadingRom', true) - axios.get('/assets'+rom.file_path+'/'+rom.file_name, { responseType: 'blob' }).then(response => { - emitter.emit('downloadingRom', false, rom.file_name) - emitter.emit('snackbarScan', {'msg': "Downloading "+rom.file_name, 'icon': 'mdi-download', 'color': 'green'}) - saveAs(new Blob([response.data], { type: 'application/file' }), rom.file_name) - }).catch((error) => { - emitter.emit('downloadingRom', false) - console.log(error) - emitter.emit('snackbarScan', {'msg': "Couldn't download "+rom.file_name+". Something went wrong...", 'icon': 'mdi-close-circle', 'color': 'red'}) - }) + if(rom.multi){ + var zipFilename = rom.file_name+".zip" + const zip = new JSZip() + var count = 0; + rom.files.forEach(async function (file_part) { + var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name+"/"+file_part + console.log(file_full_path) + var file = await fetch(file_full_path) + var fileBlob = await file.blob() + var f = zip.folder(rom.file_name); + f.file(file_part, fileBlob, { binary: true }); + count ++ + if (count == rom.files.length) { + zip.generateAsync({ type: 'blob' }).then(function (content) { + saveAs(content, zipFilename); + }); + } + }) + } + else{ + var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name + var file = await fetch(file_full_path) + var fileBlob = await file.blob() + saveAs(fileBlob, rom.file_name) + } } -export function downloadSave(rom, emitter) { +export async function downloadSave(rom, emitter) { console.log("Downloading "+rom.file_name+" save file") } From eea482e362076b4e9be46c9cb147f249327df97c Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 18:37:31 +0200 Subject: [PATCH 15/35] version added to gh workflow --- .github/workflows/image.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 35b1e678b..400f7c508 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -1,6 +1,12 @@ name: build romm image -on: [workflow_dispatch] +on: + workflow_dispatch: + inputs: + version: + description: 'romm version' + required: true + type: string jobs: build: From 9f8d29141d14d55933a70604055596797070073d Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 19:05:40 +0200 Subject: [PATCH 16/35] startup and scan are not async anymore --- backend/src/alembic.ini | 2 +- backend/src/main.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/alembic.ini b/backend/src/alembic.ini index ec986023e..051854d0b 100644 --- a/backend/src/alembic.ini +++ b/backend/src/alembic.ini @@ -106,5 +106,5 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(levelname)-5.5s [%(name)s] %(message)s +format = %(levelname)s: [RomM][%(name)s] %(message)s datefmt = %H:%M:%S diff --git a/backend/src/main.py b/backend/src/main.py index a266392ea..740866b07 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -16,7 +16,7 @@ fastapi.allow_cors(app) @app.on_event("startup") -async def startup() -> None: +def startup() -> None: """Startup application.""" log.info("Applying migrations...") try: @@ -27,7 +27,7 @@ async def startup() -> None: @app.put("/scan") -async def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: +def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: """Scan platforms and roms and write them in database.""" log.info("complete scaning...") From 324260e6c954f5f4810e9524715397ce04eba3c4 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 19:15:30 +0200 Subject: [PATCH 17/35] fix async scan --- backend/src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/main.py b/backend/src/main.py index 740866b07..2ce2104e8 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -27,7 +27,7 @@ def startup() -> None: @app.put("/scan") -def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: +async def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: """Scan platforms and roms and write them in database.""" log.info("complete scaning...") From 8a34acddc8fd5b46ab4e424c59823fe082bf721a Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 20:14:01 +0200 Subject: [PATCH 18/35] migrations moved outside uvicorn startup --- .../alembic/versions/1.6.2_first_commit.py | 59 ------------------- .../alembic/versions/1.6.3_rom_add_multi.py | 4 +- backend/src/main.py | 15 ++--- frontend/src/utils/utils.js | 3 +- 4 files changed, 11 insertions(+), 70 deletions(-) delete mode 100644 backend/src/alembic/versions/1.6.2_first_commit.py diff --git a/backend/src/alembic/versions/1.6.2_first_commit.py b/backend/src/alembic/versions/1.6.2_first_commit.py deleted file mode 100644 index 296aea739..000000000 --- a/backend/src/alembic/versions/1.6.2_first_commit.py +++ /dev/null @@ -1,59 +0,0 @@ -"""first commit - -Revision ID: 1.6.2 -Revises: -Create Date: 2023-04-10 11:50:44.824818 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '1.6.2' -down_revision = None -branch_labels = None -depends_on = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('platforms', - sa.Column('igdb_id', sa.String(length=10), nullable=True), - sa.Column('sgdb_id', sa.String(length=10), nullable=True), - sa.Column('slug', sa.String(length=50), nullable=False), - sa.Column('name', sa.String(length=400), nullable=True), - sa.Column('logo_path', sa.String(length=1000), nullable=True), - sa.Column('n_roms', sa.Integer(), nullable=True), - sa.PrimaryKeyConstraint('slug') - ) - op.create_table('roms', - sa.Column('r_igdb_id', sa.String(length=10), nullable=True), - sa.Column('p_igdb_id', sa.String(length=10), nullable=True), - sa.Column('r_sgdb_id', sa.String(length=10), nullable=True), - sa.Column('p_sgdb_id', sa.String(length=10), nullable=True), - sa.Column('p_slug', sa.String(length=50), nullable=False), - sa.Column('file_name', sa.String(length=450), nullable=False), - sa.Column('file_name_no_tags', sa.String(length=450), nullable=True), - sa.Column('file_extension', sa.String(length=10), nullable=True), - sa.Column('file_path', sa.String(length=1000), nullable=True), - sa.Column('file_size', sa.Float(), nullable=True), - sa.Column('name', sa.String(length=350), nullable=True), - sa.Column('r_slug', sa.String(length=100), nullable=True), - sa.Column('summary', sa.Text(), nullable=True), - sa.Column('path_cover_s', sa.Text(), nullable=True), - sa.Column('path_cover_l', sa.Text(), nullable=True), - 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.PrimaryKeyConstraint('p_slug', 'file_name') - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('roms') - op.drop_table('platforms') - # ### end Alembic commands ### diff --git a/backend/src/alembic/versions/1.6.3_rom_add_multi.py b/backend/src/alembic/versions/1.6.3_rom_add_multi.py index 109b51e3d..e1415e81d 100644 --- a/backend/src/alembic/versions/1.6.3_rom_add_multi.py +++ b/backend/src/alembic/versions/1.6.3_rom_add_multi.py @@ -1,7 +1,7 @@ """rom - add multi Revision ID: 1.6.3 -Revises: 1.6.2 +Revises: Create Date: 2023-04-10 16:21:34.680282 """ @@ -11,7 +11,7 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1.6.3' -down_revision = '1.6.2' +down_revision = None branch_labels = None depends_on = None diff --git a/backend/src/main.py b/backend/src/main.py index 2ce2104e8..724860b57 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -18,12 +18,7 @@ fastapi.allow_cors(app) @app.on_event("startup") def startup() -> None: """Startup application.""" - log.info("Applying migrations...") - try: - subprocess.run(['alembic', 'upgrade', 'head'], check=True) - except CalledProcessError as e: - log.critical(f"Could not apply migrations: {e}") - sys.exit(4) + pass @app.put("/scan") @@ -115,4 +110,10 @@ async def search_rom_igdb(req: Request) -> dict: if __name__ == '__main__': - uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True) + log.info("Applying migrations...") + try: + subprocess.run(['alembic', 'upgrade', 'head'], check=True) + except CalledProcessError as e: + log.critical(f"Could not apply migrations: {e}") + sys.exit(4) + uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=False, workers=4) diff --git a/frontend/src/utils/utils.js b/frontend/src/utils/utils.js index 2c2c534da..14a566db3 100644 --- a/frontend/src/utils/utils.js +++ b/frontend/src/utils/utils.js @@ -1,11 +1,10 @@ -import axios from 'axios' import JSZip from "jszip" import { saveAs } from 'file-saver' export async function downloadRom(rom, emitter) { console.log("Downloading "+rom.file_name) - emitter.emit('snackbarScan', {'msg': "Gathering "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'}) + emitter.emit('snackbarScan', {'msg': "Downloading "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'}) if(rom.multi){ var zipFilename = rom.file_name+".zip" const zip = new JSZip() From 7c87c85d18397e19cef8460e75180c193324775e Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 20:32:15 +0200 Subject: [PATCH 19/35] added alembic upgrade head to backend init script --- docker/init_scripts/init_back | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/init_scripts/init_back b/docker/init_scripts/init_back index 8112c1e90..c0d3f1b9e 100755 --- a/docker/init_scripts/init_back +++ b/docker/init_scripts/init_back @@ -1,4 +1,4 @@ #!/bin/bash cd /back -uvicorn main:app --proxy-headers --host 0.0.0.0 --port 5000 --workers 3 \ No newline at end of file +alembic upgrade head && uvicorn main:app --proxy-headers --host 0.0.0.0 --port 5000 --workers 3 \ No newline at end of file From ccba083533b49ef9f026e31dc4cc77b8028983c8 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 20:56:02 +0200 Subject: [PATCH 20/35] scan is not async anymore --- backend/src/main.py | 8 ++++---- frontend/src/components/Navigation.vue | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/backend/src/main.py b/backend/src/main.py index 724860b57..9a8234488 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -3,6 +3,7 @@ import subprocess from subprocess import CalledProcessError from fastapi import FastAPI, Request import uvicorn +import json from logger.logger import log from handler import igdbh, dbh @@ -21,14 +22,13 @@ def startup() -> None: pass -@app.put("/scan") -async def scan(req: Request, full_scan: bool=False, overwrite: bool=False) -> dict: +@app.get("/scan") +def scan(platforms: str, full_scan: bool=False, overwrite: bool=False) -> dict: """Scan platforms and roms and write them in database.""" log.info("complete scaning...") fs.store_default_resources(overwrite) - data: dict = await req.json() - platforms: list[str] = data['platforms'] if data['platforms'] else fs.get_platforms() + platforms: list[str] = json.loads(platforms) if len(json.loads(platforms)) > 0 else fs.get_platforms() for p_slug in platforms: platform: Platform = fastapi.scan_platform(p_slug) roms: list[dict] = fs.get_roms(p_slug, full_scan) diff --git a/frontend/src/components/Navigation.vue b/frontend/src/components/Navigation.vue index 7bc6fbb03..01d1829b4 100644 --- a/frontend/src/components/Navigation.vue +++ b/frontend/src/components/Navigation.vue @@ -35,9 +35,7 @@ async function scan() { toRaw(platformsToScan)._rawValue.forEach(p => {platforms.push(toRaw(p.slug))}) console.log(platforms) - await axios.put('/api/scan?overwrite='+scanOverwrite.value+'&full_scan='+fullScan.value,{ - platforms: platforms - }).then((response) => { + await axios.get('/api/scan?platforms='+JSON.stringify(platforms)+'&overwrite='+scanOverwrite.value+'&full_scan='+fullScan.value).then((response) => { console.log("scan completed") console.log(response.data) emitter.emit('snackbarScan', {'msg': 'Scan completed successfully!', 'icon': 'mdi-check-bold', 'color': 'green'}) From 375663a5425b32278693cb74ccae0ceebd9d910c Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Mon, 10 Apr 2023 20:56:43 +0200 Subject: [PATCH 21/35] 1.6.3 migration renamed --- .../src/alembic/versions/{1.6.3_rom_add_multi.py => 1.6.3.py} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename backend/src/alembic/versions/{1.6.3_rom_add_multi.py => 1.6.3.py} (97%) diff --git a/backend/src/alembic/versions/1.6.3_rom_add_multi.py b/backend/src/alembic/versions/1.6.3.py similarity index 97% rename from backend/src/alembic/versions/1.6.3_rom_add_multi.py rename to backend/src/alembic/versions/1.6.3.py index e1415e81d..af0952af9 100644 --- a/backend/src/alembic/versions/1.6.3_rom_add_multi.py +++ b/backend/src/alembic/versions/1.6.3.py @@ -1,5 +1,4 @@ -"""rom - add multi - +""" Revision ID: 1.6.3 Revises: Create Date: 2023-04-10 16:21:34.680282 From ecd18d373517cd1e5b6994009ec49ad89076e72e Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 00:11:13 +0200 Subject: [PATCH 22/35] initial migration fixed --- backend/src/alembic/env.py | 4 +- backend/src/alembic/versions/1.6.2_.py | 62 +++++++++++++++++++ .../alembic/versions/{1.6.3.py => 1.6.3_.py} | 9 +-- backend/src/handler/db_handler.py | 4 +- backend/src/main.py | 10 +-- 5 files changed, 73 insertions(+), 16 deletions(-) create mode 100644 backend/src/alembic/versions/1.6.2_.py rename backend/src/alembic/versions/{1.6.3.py => 1.6.3_.py} (86%) diff --git a/backend/src/alembic/env.py b/backend/src/alembic/env.py index 79b416d95..933a84264 100644 --- a/backend/src/alembic/env.py +++ b/backend/src/alembic/env.py @@ -63,9 +63,9 @@ def run_migrations_online() -> None: """ - connectable = create_engine(get_db_engine()) + engine = create_engine(get_db_engine()) - with connectable.connect() as connection: + with engine.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata ) diff --git a/backend/src/alembic/versions/1.6.2_.py b/backend/src/alembic/versions/1.6.2_.py new file mode 100644 index 000000000..399921a33 --- /dev/null +++ b/backend/src/alembic/versions/1.6.2_.py @@ -0,0 +1,62 @@ +"""init + +Revision ID: 1.6.2 +Revises: +Create Date: 2023-04-10 23:02:37.472055 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.exc import OperationalError + + +# revision identifiers, used by Alembic. +revision = '1.6.2' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + try: + op.create_table('platforms', + sa.Column('igdb_id', sa.String(length=10), nullable=True), + sa.Column('sgdb_id', sa.String(length=10), nullable=True), + sa.Column('slug', sa.String(length=50), nullable=False), + sa.Column('name', sa.String(length=400), nullable=True), + sa.Column('logo_path', sa.String(length=1000), nullable=True), + sa.Column('n_roms', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('slug') + ) + op.create_table('roms', + sa.Column('r_igdb_id', sa.String(length=10), nullable=True), + sa.Column('p_igdb_id', sa.String(length=10), nullable=True), + sa.Column('r_sgdb_id', sa.String(length=10), nullable=True), + sa.Column('p_sgdb_id', sa.String(length=10), nullable=True), + sa.Column('p_slug', sa.String(length=50), nullable=False), + sa.Column('file_name', sa.String(length=450), nullable=False), + sa.Column('file_name_no_tags', sa.String(length=450), nullable=True), + sa.Column('file_extension', sa.String(length=10), nullable=True), + sa.Column('file_path', sa.String(length=1000), nullable=True), + sa.Column('file_size', sa.Float(), nullable=True), + sa.Column('name', sa.String(length=350), nullable=True), + sa.Column('r_slug', sa.String(length=100), nullable=True), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('path_cover_s', sa.Text(), nullable=True), + sa.Column('path_cover_l', sa.Text(), nullable=True), + 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.PrimaryKeyConstraint('p_slug', 'file_name') + ) + except OperationalError: + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### diff --git a/backend/src/alembic/versions/1.6.3.py b/backend/src/alembic/versions/1.6.3_.py similarity index 86% rename from backend/src/alembic/versions/1.6.3.py rename to backend/src/alembic/versions/1.6.3_.py index af0952af9..bdf5255be 100644 --- a/backend/src/alembic/versions/1.6.3.py +++ b/backend/src/alembic/versions/1.6.3_.py @@ -1,7 +1,8 @@ -""" +"""add multifile games + Revision ID: 1.6.3 -Revises: -Create Date: 2023-04-10 16:21:34.680282 +Revises: 1.6.2 +Create Date: 2023-04-10 23:13:43.591414 """ from alembic import op @@ -10,7 +11,7 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1.6.3' -down_revision = None +down_revision = '1.6.2' branch_labels = None depends_on = None diff --git a/backend/src/handler/db_handler.py b/backend/src/handler/db_handler.py index 75ec9c2ad..eb3d8ff6b 100644 --- a/backend/src/handler/db_handler.py +++ b/backend/src/handler/db_handler.py @@ -15,8 +15,8 @@ from logger.logger import log class DBHandler: def __init__(self) -> None: - engine = create_engine(get_db_engine(), pool_pre_ping=True) - self.session = sessionmaker(bind=engine, expire_on_commit=False) + self.engine = create_engine(get_db_engine(), pool_pre_ping=True) + self.session = sessionmaker(bind=self.engine, expire_on_commit=False) def retry(func) -> tuple: diff --git a/backend/src/main.py b/backend/src/main.py index 9a8234488..797126dec 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -19,7 +19,7 @@ fastapi.allow_cors(app) @app.on_event("startup") def startup() -> None: """Startup application.""" - pass + pass @app.get("/scan") @@ -110,10 +110,4 @@ async def search_rom_igdb(req: Request) -> dict: if __name__ == '__main__': - log.info("Applying migrations...") - try: - subprocess.run(['alembic', 'upgrade', 'head'], check=True) - except CalledProcessError as e: - log.critical(f"Could not apply migrations: {e}") - sys.exit(4) - uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=False, workers=4) + uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True) From d6db515e369b373596b80734e8eb088e675e8032 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 01:45:54 +0200 Subject: [PATCH 23/35] exclude files from config to multiple files game --- backend/src/utils/fs.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index a6b0027bc..ebdf29989 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -116,7 +116,11 @@ def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[di for rom_multi in roms_files_multi: if rom_multi in not_new_roms and not full_scan: continue reg, rev, other_tags = parse_tags(rom_multi) - roms.append({'file_name': rom_multi, 'file_path': roms_path, 'multi': True, 'files': list(os.walk(f"{roms_path}/{rom_multi}"))[0][2], + parts: list = _exclude_files(list(os.walk(f"{roms_path}/{rom_multi}"))[0][2]) + file_size: float = 0.0 + for part in parts: + file_size += round(os.stat(f"{roms_path}/{rom_multi}/{part}").st_size / (1024 * 1024), 2) + roms.append({'file_name': rom_multi, 'file_path': roms_path, 'multi': True, 'files': parts, 'file_size': str(file_size), 'region': reg, 'revision': rev, 'tags': other_tags, 'multi': True}) log.info(f"Roms found for {p_slug}: {roms}") From cbec4154b97005a2985152aed380c3c3373d65b3 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 01:58:21 +0200 Subject: [PATCH 24/35] chips added to selectors --- frontend/src/components/Navigation.vue | 2 +- frontend/src/components/RomDetails.vue | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/Navigation.vue b/frontend/src/components/Navigation.vue index 01d1829b4..a85b50a5d 100644 --- a/frontend/src/components/Navigation.vue +++ b/frontend/src/components/Navigation.vue @@ -102,7 +102,7 @@ getPlatforms() - + diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index 489ca4ca3..b27a524fd 100644 --- a/frontend/src/components/RomDetails.vue +++ b/frontend/src/components/RomDetails.vue @@ -137,7 +137,7 @@ async function deleteRom() { Name{{ rom.name }} File{{ rom.file_name }} Files - + Platform{{ rom.p_slug }} Size{{ rom.file_size }} MB From 24b316109a83ac1b98cf1cba0a951bf218d3ee71 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 02:13:05 +0200 Subject: [PATCH 25/35] download selected files for multifile games added --- frontend/src/components/RomDetails.vue | 5 +++-- frontend/src/utils/utils.js | 14 +++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index b27a524fd..773dfa127 100644 --- a/frontend/src/components/RomDetails.vue +++ b/frontend/src/components/RomDetails.vue @@ -17,6 +17,7 @@ const dialogEditRom = ref(false) const dialogDeleteRom = ref(false) const deleteFromFs = ref(false) const router = useRouter() +const filesToDownload = ref([]) // Event listeners bus const emitter = inject('emitter') @@ -99,7 +100,7 @@ async function deleteRom() { - + @@ -137,7 +138,7 @@ async function deleteRom() { Name{{ rom.name }} File{{ rom.file_name }} Files - + Platform{{ rom.p_slug }} Size{{ rom.file_size }} MB diff --git a/frontend/src/utils/utils.js b/frontend/src/utils/utils.js index 14a566db3..81a2a0c51 100644 --- a/frontend/src/utils/utils.js +++ b/frontend/src/utils/utils.js @@ -1,23 +1,27 @@ import JSZip from "jszip" +import { toRaw } from "vue" import { saveAs } from 'file-saver' -export async function downloadRom(rom, emitter) { +export async function downloadRom(rom, emitter, filesToDownload=[]) { console.log("Downloading "+rom.file_name) emitter.emit('snackbarScan', {'msg': "Downloading "+rom.file_name+"...", 'icon': 'mdi-download', 'color': 'green'}) if(rom.multi){ + var files = [] + toRaw(filesToDownload).forEach(f => {files.push(toRaw(f))}) var zipFilename = rom.file_name+".zip" const zip = new JSZip() - var count = 0; - rom.files.forEach(async function (file_part) { + var count = 0 + if (files.length == 0){ files = rom.files } + files.forEach(async function (file_part) { var file_full_path = "/assets"+rom.file_path+"/"+rom.file_name+"/"+file_part - console.log(file_full_path) + console.log("downloading part: "+file_full_path) var file = await fetch(file_full_path) var fileBlob = await file.blob() var f = zip.folder(rom.file_name); f.file(file_part, fileBlob, { binary: true }); count ++ - if (count == rom.files.length) { + if (count == files.length) { zip.generateAsync({ type: 'blob' }).then(function (content) { saveAs(content, zipFilename); }); From 01321bb484ae72c76303d642b0b7090670169bb8 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 14:05:45 +0200 Subject: [PATCH 26/35] fix and refactor some code to unify single and multi games --- backend/src/config/__init__.py | 2 +- backend/src/handler/igdb_handler.py | 2 +- backend/src/main.py | 12 ++- backend/src/utils/fastapi.py | 5 +- backend/src/utils/fs.py | 140 ++++++++++++------------- frontend/src/components/Navigation.vue | 3 +- 6 files changed, 80 insertions(+), 84 deletions(-) diff --git a/backend/src/config/__init__.py b/backend/src/config/__init__.py index 951423ce0..1a84b4164 100644 --- a/backend/src/config/__init__.py +++ b/backend/src/config/__init__.py @@ -10,8 +10,8 @@ DEV_HOST: str = "0.0.0.0" LIBRARY_BASE_PATH: str = "/romm/library" ROMM_USER_CONFIG_PATH: str = "/romm/config.yml" SQLITE_DB_BASE_PATH: str = "/romm/database" -HIGH_PRIO_STRUCTURE_PATH: str = f"{LIBRARY_BASE_PATH}/roms" RESOURCES_BASE_PATH: str = "/romm/resources" +HIGH_PRIO_STRUCTURE_PATH: str = f"{LIBRARY_BASE_PATH}/roms" # DEFAULT RESOURCES DEFAULT_URL_COVER_L: str = "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png" diff --git a/backend/src/handler/igdb_handler.py b/backend/src/handler/igdb_handler.py index fcf3891f9..66f0572a1 100644 --- a/backend/src/handler/igdb_handler.py +++ b/backend/src/handler/igdb_handler.py @@ -41,7 +41,7 @@ class IGDBHandler(): except IndexError: log.warning("platform not found in igdb") if not name: name = slug - return {'igdb_id': igdb_id, 'name': name} + return {'igdb_id': igdb_id, 'name': name, 'slug': slug, 'logo_path': ''} @check_twitch_token diff --git a/backend/src/main.py b/backend/src/main.py index 797126dec..f56d17c47 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -23,19 +23,21 @@ def startup() -> None: @app.get("/scan") -def scan(platforms: str, full_scan: bool=False, overwrite: bool=False) -> dict: +def scan(platforms_to_scan: str, full_scan: bool=False) -> dict: """Scan platforms and roms and write them in database.""" - log.info("complete scaning...") - fs.store_default_resources(overwrite) - platforms: list[str] = json.loads(platforms) if len(json.loads(platforms)) > 0 else fs.get_platforms() + log.info("scaning...") + fs.store_default_resources() + fs_platforms: list[str] = fs.get_platforms() + platforms: list[str] = json.loads(platforms_to_scan) if len(json.loads(platforms_to_scan)) > 0 else fs_platforms for p_slug in platforms: platform: Platform = fastapi.scan_platform(p_slug) + dbh.add_platform(platform) roms: list[dict] = fs.get_roms(p_slug, full_scan) for rom in roms: fastapi.scan_rom(platform, rom) dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) - dbh.purge_platforms(fs.get_platforms()) + dbh.purge_platforms(fs_platforms) return {'msg': 'success'} diff --git a/backend/src/utils/fastapi.py b/backend/src/utils/fastapi.py index b359b18f1..8245e155b 100644 --- a/backend/src/utils/fastapi.py +++ b/backend/src/utils/fastapi.py @@ -29,12 +29,9 @@ def scan_platform(p_slug: str) -> Platform: """ log.info(f"Getting {p_slug} details") platform_attrs: dict = igdbh.get_platform_details(p_slug) - platform_attrs['slug'] = p_slug - platform_attrs['logo_path'] = '' platform_attrs['n_roms'] = fs.get_roms(p_slug, True, only_amount=True) - log.info(f"Platform n_roms: {platform_attrs['n_roms']}") + log.info(f"Roms found for {platform_attrs['name']}: {platform_attrs['n_roms']}") platform = Platform(**platform_attrs) - dbh.add_platform(platform) return platform diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index ebdf29989..7074ca4de 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -12,16 +12,12 @@ from logger.logger import log # ========= Defaults utils ========= -def store_default_resources(overwrite: bool) -> None: - """Store default no_cover resources in the filesystem - - Args: - overwrite: flag to overwrite or not default resources - """ - if overwrite or not _cover_exists('default', 'cover', 'l'): - _store_cover('default', 'cover', DEFAULT_URL_COVER_L, 'l') - if overwrite or not _cover_exists('default', 'cover', 's'): - _store_cover('default', 'cover', DEFAULT_URL_COVER_S, 's') +def store_default_resources() -> None: + """Store default cover resources in the filesystem""" + defaul_covers: dict = [{'url': DEFAULT_URL_COVER_L, 'size': 'l'}, {'url': DEFAULT_URL_COVER_S, 'size': 's'}] + for cover in defaul_covers: + if not _cover_exists('default', 'cover', cover['size']): + _store_cover('default', 'cover', cover['url'], cover['size']) # ========= Platforms utils ========= @@ -29,20 +25,13 @@ def get_platforms() -> list[str]: """Gets all filesystem platforms Returns list with all the filesystem platforms found in the LIBRARY_BASE_PATH. - Automatically discards the reserved directories such resources or database directory. + Automatically exclude folders defined in user config. """ try: - if os.path.exists(f"{LIBRARY_BASE_PATH}/roms"): - platforms: list[str] = list(os.walk(f"{LIBRARY_BASE_PATH}/roms"))[0][1] - else: - platforms: list[str] = list(os.walk(LIBRARY_BASE_PATH))[0][1] + platforms: list[str] = list(os.walk(HIGH_PRIO_STRUCTURE_PATH))[0][1] if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else list(os.walk(LIBRARY_BASE_PATH))[0][1] try: - excluded_folders: list = user_config['exclude']['folders'] - try: - [platforms.remove(excluded) for excluded in excluded_folders if excluded in platforms] - except TypeError: - pass - except KeyError: + [platforms.remove(excluded) for excluded in user_config['exclude']['folders'] if excluded in platforms] + except (KeyError, TypeError): pass log.info(f"filesystem platforms found: {platforms}") return platforms @@ -53,9 +42,9 @@ def get_platforms() -> list[str]: # ========= Roms utils ========= -def _get_folder_structure(p_slug) -> tuple: +def _get_roms_structure(p_slug) -> tuple: return f"{HIGH_PRIO_STRUCTURE_PATH}/{p_slug}" if os.path.exists(HIGH_PRIO_STRUCTURE_PATH) else f"{LIBRARY_BASE_PATH}/{p_slug}/roms" - + def _exclude_files(roms_files) -> list[str]: try: @@ -71,57 +60,63 @@ def _exclude_files(roms_files) -> list[str]: def parse_tags(file_name: str) -> tuple: - reg='' - rev='' - other_tags=[] - tags = re.findall('\(([^)]+)', file_name) - for t in tags: - if t.split('-')[0].lower() == 'reg': - try: reg=t.split('-', 1)[1] + reg: str = '' + rev: str = '' + other_tags: list = [] + tags: list = re.findall('\(([^)]+)', file_name) + for tag in tags: + if tag.split('-')[0].lower() == 'reg': + try: reg = tag.split('-', 1)[1] except IndexError: pass - elif t.split('-')[0].lower() == 'rev': - try: rev=t.split('-', 1)[1] + elif tag.split('-')[0].lower() == 'rev': + try: rev = tag.split('-', 1)[1] except IndexError: pass else: - other_tags.append(t) + other_tags.append(tag) return reg, rev, other_tags +def _get_file_extension(file: str) -> str: + return file.split('.')[-1] if '.' in file else '' + + +def _get_rom_files(multi: bool, rom: str, roms_path: str) -> list[str]: + return [] if not multi else _exclude_files(list(os.walk(f"{roms_path}/{rom}"))[0][2]) + + +def _get_file_size(multi: bool, rom: str, files: list, roms_path:str) -> str: + files: list = [f"{roms_path}/{rom}"] if not multi else [f"{roms_path}/{rom}/{file}" for file in files] + total_size: float = 0.0 + for file in files: + total_size += round(os.stat(file).st_size / (1024 * 1024), 2) + return str(total_size) + + def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[dict]: """Gets all filesystem roms for a platform Args: p_slug: short name of the platform + full_scan: flag to get all roms in fs or only new ones only_amount: flag to return only amount of roms instead of all info Returns: list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH. Just the amount of them if only_amount=True """ - roms_path = _get_folder_structure(p_slug) + roms_path = _get_roms_structure(p_slug) roms: list[dict] = [] + db_roms: list[str] = [rom.file_name for rom in dbh.get_roms(p_slug)] + fs_roms: list[dict] = [{'multi': False, 'file': rom} for rom in _exclude_files(list(os.walk(roms_path))[0][2])] + \ + [{'multi': True, 'file': rom} for rom in list(os.walk(roms_path))[0][1]] - roms_files: list = _exclude_files(list(os.walk(roms_path))[0][2]) - roms_files_multi: list = list(os.walk(roms_path))[0][1] + if only_amount: return len(db_roms) - if only_amount: return len(roms_files) + len(roms_files_multi) - - not_new_roms: list[str] = [rom.file_name for rom in dbh.get_roms(p_slug)] - - for rom in roms_files: - if rom in not_new_roms and not full_scan: continue - file_size: str = str(round(os.stat(f"{roms_path}/{rom}").st_size / (1024 * 1024), 2)) - file_extension: str = rom.split('.')[-1] if '.' in rom else "" - reg, rev, other_tags = parse_tags(rom) - roms.append({'file_name': rom, 'file_path': roms_path, 'file_size': file_size, 'file_extension': file_extension, + for rom in fs_roms: + if rom in db_roms and not full_scan: continue + reg, rev, other_tags = parse_tags(rom['file']) + file_extension: str = _get_file_extension(rom['file']) + files: list = _get_rom_files(rom['multi'], rom['file'], roms_path) + file_size: str = _get_file_size(rom['multi'], rom['file'], files, roms_path) + roms.append({'file_name': rom['file'], 'file_path': roms_path, 'multi': rom['multi'], 'files': files, 'file_size': file_size, 'file_extension': file_extension, 'region': reg, 'revision': rev, 'tags': other_tags}) - - for rom_multi in roms_files_multi: - if rom_multi in not_new_roms and not full_scan: continue - reg, rev, other_tags = parse_tags(rom_multi) - parts: list = _exclude_files(list(os.walk(f"{roms_path}/{rom_multi}"))[0][2]) - file_size: float = 0.0 - for part in parts: - file_size += round(os.stat(f"{roms_path}/{rom_multi}/{part}").st_size / (1024 * 1024), 2) - roms.append({'file_name': rom_multi, 'file_path': roms_path, 'multi': True, 'files': parts, 'file_size': str(file_size), - 'region': reg, 'revision': rev, 'tags': other_tags, 'multi': True}) log.info(f"Roms found for {p_slug}: {roms}") return roms @@ -136,22 +131,25 @@ def _rom_exists(p_slug: str, file_name: str) -> bool: Returns True if rom exists in filesystem else False """ - rom_path = _get_folder_structure(p_slug) + rom_path = _get_roms_structure(p_slug) exists: bool = True if os.path.exists(f"{rom_path}/{file_name}") else False return exists def rename_rom(p_slug: str, old_name: str, new_name: str) -> None: if new_name != old_name: - rom_path = _get_folder_structure(p_slug) + rom_path = _get_roms_structure(p_slug) if _rom_exists(p_slug, new_name): raise HTTPException(status_code=500, detail=f"Can't rename: {new_name} already exists.") os.rename(f"{rom_path}/{old_name}", f"{rom_path}/{new_name}") def delete_rom(p_slug: str, file_name: str) -> None: + rom_path = _get_roms_structure(p_slug) try: - rom_path = _get_folder_structure(p_slug) - os.remove(f"{rom_path}/{file_name}") + try: + os.remove(f"{rom_path}/{file_name}") + except IsADirectoryError: + shutil.rmtree(f"{rom_path}/{file_name}") except FileNotFoundError: log.warning(f"Rom not found in filesystem: {rom_path}/{file_name}") @@ -170,17 +168,6 @@ def _cover_exists(p_slug: str, file_name: str, size: str) -> bool: return True if os.path.exists(logo_path) else False -def _get_cover_path(p_slug: str, file_name: str, size: str) -> str: - """Returns rom cover filesystem path adapted to frontend folder structure - - Args: - p_slug: short name of the platform - file_name: name of rom file - size: size of the cover -> big as 'l' | small as 's' - """ - return f"{RESOURCES_BASE_PATH}/{p_slug}/{file_name}_{size}.png" - - def _store_cover(p_slug: str, file_name: str, url_cover: str, size: str) -> None: """Store roms resources in filesystem @@ -203,6 +190,17 @@ def _store_cover(p_slug: str, file_name: str, url_cover: str, size: str) -> None log.warning(f"{file_name} {sizes[size]} cover couldn't be downloaded") +def _get_cover_path(p_slug: str, file_name: str, size: str) -> str: + """Returns rom cover filesystem path adapted to frontend folder structure + + Args: + p_slug: short name of the platform + file_name: name of rom file + size: size of the cover -> big as 'l' | small as 's' + """ + return f"{RESOURCES_BASE_PATH}/{p_slug}/{file_name}_{size}.png" + + def get_cover_details(overwrite: bool, p_slug: str, file_name: str, url_cover: str) -> tuple: path_cover_s: str = DEFAULT_PATH_COVER_S path_cover_l: str = DEFAULT_PATH_COVER_L diff --git a/frontend/src/components/Navigation.vue b/frontend/src/components/Navigation.vue index a85b50a5d..0b555bd2f 100644 --- a/frontend/src/components/Navigation.vue +++ b/frontend/src/components/Navigation.vue @@ -9,7 +9,6 @@ const platforms = ref([]) const currentPlatform = ref(JSON.parse(localStorage.getItem('currentPlatform')) || "") const platformsToScan = ref([]) const scanning = ref(false) -const scanOverwrite = ref(false) const fullScan = ref(false) const gettingRomsFlag = ref(false) const filter = ref('') @@ -35,7 +34,7 @@ async function scan() { toRaw(platformsToScan)._rawValue.forEach(p => {platforms.push(toRaw(p.slug))}) console.log(platforms) - await axios.get('/api/scan?platforms='+JSON.stringify(platforms)+'&overwrite='+scanOverwrite.value+'&full_scan='+fullScan.value).then((response) => { + await axios.get('/api/scan?platforms_to_scan='+JSON.stringify(platforms)+'&full_scan='+fullScan.value).then((response) => { console.log("scan completed") console.log(response.data) emitter.emit('snackbarScan', {'msg': 'Scan completed successfully!', 'icon': 'mdi-check-bold', 'color': 'green'}) From 07f72f10517a3d9721a9f5fea936e370a1ea8596 Mon Sep 17 00:00:00 2001 From: zurdi zurdo Date: Tue, 11 Apr 2023 16:25:41 +0200 Subject: [PATCH 27/35] clearer logs --- backend/src/handler/db_handler.py | 3 --- backend/src/logger/logger.py | 20 ++++++++++---------- backend/src/main.py | 15 ++++++++++++--- backend/src/models/platform.py | 7 +------ backend/src/models/rom.py | 11 +---------- backend/src/utils/fastapi.py | 7 ++----- backend/src/utils/fs.py | 5 +---- frontend/src/components/Navigation.vue | 8 ++++++-- frontend/src/components/RomsGallery.vue | 15 ++++++--------- 9 files changed, 39 insertions(+), 52 deletions(-) diff --git a/backend/src/handler/db_handler.py b/backend/src/handler/db_handler.py index eb3d8ff6b..c139c1f74 100644 --- a/backend/src/handler/db_handler.py +++ b/backend/src/handler/db_handler.py @@ -9,7 +9,6 @@ from sqlalchemy.exc import ProgrammingError from config.config_loader import get_db_engine from models.platform import Platform from models.rom import Rom -from logger.logger import log class DBHandler: @@ -42,7 +41,6 @@ class DBHandler: raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}") def purge_platforms(self, platforms: list[str]) -> None: - log.info("Purging platforms") with self.session.begin() as s: s.query(Platform) \ .filter(Platform.slug.not_in(platforms)) \ @@ -74,7 +72,6 @@ class DBHandler: .delete(synchronize_session='evaluate') def purge_roms(self, p_slug: str, roms: list[dict]) -> None: - log.info(f"Purging {p_slug} roms") with self.session.begin() as s: s.query(Rom) \ .filter(Rom.p_slug==p_slug, Rom.file_name.not_in([rom['file_name'] for rom in roms])) \ diff --git a/backend/src/logger/logger.py b/backend/src/logger/logger.py index b6857d9a1..c9360061c 100644 --- a/backend/src/logger/logger.py +++ b/backend/src/logger/logger.py @@ -1,17 +1,17 @@ import logging +COLORS: dict = { + 'grey': '\033[92m', + 'pink': '\033[95m', + 'blue': '\033[94m', + 'cyan': '\033[96m', + 'orange': '\033[93m', + 'red': '\033[91m', + 'bold_red': '\033[1;91m', + 'reset': '\033[0m', +} class CustomFormatter(logging.Formatter): - COLORS: dict = { - 'grey': '\033[92m', - 'pink': '\033[95m', - 'blue': '\033[94m', - 'cyan': '\033[96m', - 'orange': '\033[93m', - 'red': '\033[91m', - 'bold_red': '\033[1;91m', - 'reset': '\033[0m', - } level: str = "%(levelname)s" dots: str = ":" diff --git a/backend/src/main.py b/backend/src/main.py index f56d17c47..9f7076d3e 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -5,7 +5,7 @@ from fastapi import FastAPI, Request import uvicorn import json -from logger.logger import log +from logger.logger import log, COLORS from handler import igdbh, dbh from config import DEV_PORT, DEV_HOST from models.platform import Platform @@ -26,17 +26,26 @@ def startup() -> None: def scan(platforms_to_scan: str, full_scan: bool=False) -> dict: """Scan platforms and roms and write them in database.""" - log.info("scaning...") + log.info("Scaning...") fs.store_default_resources() fs_platforms: list[str] = fs.get_platforms() + log.info(f"Platforms found: {', '.join(fs_platforms)}") platforms: list[str] = json.loads(platforms_to_scan) if len(json.loads(platforms_to_scan)) > 0 else fs_platforms for p_slug in platforms: + log.info(f"{COLORS['pink']}== {p_slug} =={COLORS['reset']}") platform: Platform = fastapi.scan_platform(p_slug) + log.info(f"{p_slug} identified as {COLORS['blue']}{platform}{COLORS['reset']}") dbh.add_platform(platform) + log.info(f"Searching new roms...") roms: list[dict] = fs.get_roms(p_slug, full_scan) for rom in roms: - fastapi.scan_rom(platform, rom) + log.info(f"Getting {COLORS['orange']}{rom['file_name']}{COLORS['reset']} details") + if rom['multi']: [log.info(f"\t - {COLORS['orange']}{file}{COLORS['reset']}") for file in rom['files']] + rom = fastapi.scan_rom(platform, rom) + dbh.add_rom(rom) + log.info(f"Purging {platform} roms") dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) + log.info("Purging platforms") dbh.purge_platforms(fs_platforms) return {'msg': 'success'} diff --git a/backend/src/models/platform.py b/backend/src/models/platform.py index 1e2e3e45a..e861f867b 100644 --- a/backend/src/models/platform.py +++ b/backend/src/models/platform.py @@ -17,9 +17,4 @@ class Platform(BaseModel): n_roms = Column(Integer, default=0) def __repr__(self) -> str: - return ( - f"igdb_id: {self.igdb_id}," - f"slug: {self.slug}," - f"name: {self.name}," - f"n_roms: {self.n_roms}," - ) + return self.name diff --git a/backend/src/models/rom.py b/backend/src/models/rom.py index 8ceca733c..a22ac19ab 100644 --- a/backend/src/models/rom.py +++ b/backend/src/models/rom.py @@ -40,13 +40,4 @@ class Rom(BaseModel): return f"{self.file_path}/{self.file_name}" def __repr__(self) -> str: - return ( - f"r_igdb_id: {self.r_igdb_id}," - f"p_igdb_id: {self.p_igdb_id}," - f"r_slug: {self.r_slug}," - f"p_slug: {self.p_slug}," - f"file_name: {self.file_name}," - f"file_path: {self.file_path}," - f"multi: {self.multi}," - f"files: {self.files}" - ) + return self.file_name diff --git a/backend/src/utils/fastapi.py b/backend/src/utils/fastapi.py index 8245e155b..002f3fb1a 100644 --- a/backend/src/utils/fastapi.py +++ b/backend/src/utils/fastapi.py @@ -1,7 +1,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from handler import igdbh, dbh +from handler import igdbh from utils import fs from models.platform import Platform from models.rom import Rom @@ -27,16 +27,13 @@ def scan_platform(p_slug: str) -> Platform: Returns Platform object """ - log.info(f"Getting {p_slug} details") platform_attrs: dict = igdbh.get_platform_details(p_slug) platform_attrs['n_roms'] = fs.get_roms(p_slug, True, only_amount=True) - log.info(f"Roms found for {platform_attrs['name']}: {platform_attrs['n_roms']}") platform = Platform(**platform_attrs) return platform def scan_rom(platform: Platform, rom: dict, r_igbd_id_search: str = '', overwrite: bool = False) -> None: - log.info(f"Getting {rom['file_name']} details") r_igdb_id, file_name_no_tags, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(rom['file_name'], platform.igdb_id, r_igbd_id_search) path_cover_s, path_cover_l, has_cover = fs.get_cover_details(overwrite, platform.slug, rom['file_name'], url_cover) rom['file_name_no_tags'] = file_name_no_tags @@ -50,4 +47,4 @@ def scan_rom(platform: Platform, rom: dict, r_igbd_id_search: str = '', overwrit rom['path_cover_l'] = path_cover_l rom['has_cover'] = has_cover rom = Rom(**rom) - dbh.add_rom(rom) + return rom diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py index 7074ca4de..7e7edf8d9 100644 --- a/backend/src/utils/fs.py +++ b/backend/src/utils/fs.py @@ -33,7 +33,6 @@ def get_platforms() -> list[str]: [platforms.remove(excluded) for excluded in user_config['exclude']['folders'] if excluded in platforms] except (KeyError, TypeError): pass - log.info(f"filesystem platforms found: {platforms}") return platforms except IndexError: error: str = "Platforms not found." @@ -110,15 +109,13 @@ def get_roms(p_slug: str, full_scan: bool, only_amount: bool = False) -> list[di if only_amount: return len(db_roms) for rom in fs_roms: - if rom in db_roms and not full_scan: continue + if rom['file'] in db_roms and not full_scan: continue reg, rev, other_tags = parse_tags(rom['file']) file_extension: str = _get_file_extension(rom['file']) files: list = _get_rom_files(rom['multi'], rom['file'], roms_path) file_size: str = _get_file_size(rom['multi'], rom['file'], files, roms_path) roms.append({'file_name': rom['file'], 'file_path': roms_path, 'multi': rom['multi'], 'files': files, 'file_size': file_size, 'file_extension': file_extension, 'region': reg, 'revision': rev, 'tags': other_tags}) - - log.info(f"Roms found for {p_slug}: {roms}") return roms diff --git a/frontend/src/components/Navigation.vue b/frontend/src/components/Navigation.vue index 0b555bd2f..55abd72e7 100644 --- a/frontend/src/components/Navigation.vue +++ b/frontend/src/components/Navigation.vue @@ -142,9 +142,13 @@ getPlatforms() - + - + + + + + diff --git a/frontend/src/components/RomsGallery.vue b/frontend/src/components/RomsGallery.vue index 0a51dd15a..4a1e9d4df 100644 --- a/frontend/src/components/RomsGallery.vue +++ b/frontend/src/components/RomsGallery.vue @@ -93,16 +93,13 @@ onMounted(() => { if(localStorage.getItem('currentPlatform')){ getRoms(JSON.pars + + + + +
Feels cold here... mdi-emoticon-sad
+
- - - - - - -
Feels cold here... mdi-emoticon-sad
-
-