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..400f7c508 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -11,20 +11,51 @@ 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=true + prefix=${{ github.ref != format('refs/heads/{0}', 'master') && 'dev-' || '' }},onlatest=true + tags: | + 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 }} diff --git a/README.md b/README.md index 3dde3aaaa..cc340eac9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@
- Gameyfin Logo + RomM Logo

RomM (Rom Manager)

@@ -130,7 +130,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 | ❌ | diff --git a/backend/requirements.txt b/backend/requirements.txt index 536cde608..7af61898b 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -3,5 +3,7 @@ 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 +Unidecode==1.3.6 +emoji==2.2.0 \ No newline at end of file diff --git a/backend/src/alembic.ini b/backend/src/alembic.ini new file mode 100644 index 000000000..051854d0b --- /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)s: [RomM][%(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..933a84264 --- /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. + + """ + + engine = create_engine(get_db_engine()) + + with engine.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_.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 new file mode 100644 index 000000000..bdf5255be --- /dev/null +++ b/backend/src/alembic/versions/1.6.3_.py @@ -0,0 +1,30 @@ +"""add multifile games + +Revision ID: 1.6.3 +Revises: 1.6.2 +Create Date: 2023-04-10 23:13:43.591414 + +""" +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)) + 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/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/config/config_loader.py b/backend/src/config/config_loader.py index 097a2870b..efc0be00d 100644 --- a/backend/src/config/config_loader.py +++ b/backend/src/config/config_loader.py @@ -27,5 +27,5 @@ def get_db_engine(): return f"sqlite:////{SQLITE_DB_BASE_PATH}/romm.db" else: - log.critical(f"Not supported {ROMM_DB_DRIVER} database") + log.critical(f"{ROMM_DB_DRIVER} database not supported") sys.exit(3) diff --git a/backend/src/handler/db_handler.py b/backend/src/handler/db_handler.py index 01f211936..c139c1f74 100644 --- a/backend/src/handler/db_handler.py +++ b/backend/src/handler/db_handler.py @@ -1,19 +1,21 @@ 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() + 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: @@ -22,55 +24,55 @@ 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: + 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/handler/igdb_handler.py b/backend/src/handler/igdb_handler.py index bb1283a71..5447633a7 100644 --- a/backend/src/handler/igdb_handler.py +++ b/backend/src/handler/igdb_handler.py @@ -39,9 +39,9 @@ class IGDBHandler(): igdb_id = res_details['id'] name = res_details['name'] except IndexError: - log.warning("platform not found in igdb") + log.warning(f"{slug} 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 @@ -101,33 +101,36 @@ class IGDBHandler(): except KeyError: pass except IndexError: - log.warning(f"{file_name} rom not found in igdb") + log.warning(f"{file_name} not found in IGDB") if r_igdb_id: try: res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers, data=f"fields url; where game={r_igdb_id};").json()[0] url_cover: str = f"https:{res_details['url']}" except IndexError: - log.warning(f"{name} cover not found in igdb") + log.warning(f"{name} cover not found in IGDB") if not name: name = file_name_no_tags return (r_igdb_id, file_name_no_tags, slug, name, summary, url_cover) @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])) + 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() + 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 @@ -158,14 +161,14 @@ class TwitchAuth(): try: self.token_valid_seconds = res['expires_in'] self.token = res['access_token'] - log.info("twitch token fetched!") + log.info("Twitch token fetched!") except KeyError: - log.error("could not get twitch auth token: check client_id and client_secret") + log.error("Could not get twitch auth token: check client_id and client_secret") sys.exit(2) def get_oauth_token(self) -> str: if not self._is_token_valid(): - log.warning("twitch token invalid: fetching a new one") + log.warning("Twitch token invalid: fetching a new one") self._update_twitch_token() return self.token \ No newline at end of file diff --git a/backend/src/logger/logger.py b/backend/src/logger/logger.py index 653638d9c..56fef3002 100644 --- a/backend/src/logger/logger.py +++ b/backend/src/logger/logger.py @@ -1,31 +1,32 @@ import logging +COLORS: dict = { + 'grey': '\033[92m', + 'pink': '\033[95m', + 'blue': '\033[94m', + 'cyan': '\033[96m', + 'orange': '\033[93m', + 'orange_i': '\033[3;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 = ":" - 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 86685396c..3d21f3c3c 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -1,8 +1,9 @@ -import os from fastapi import FastAPI, Request import uvicorn +import json +import emoji -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 @@ -13,21 +14,58 @@ app = FastAPI() fastapi.allow_cors(app) +@app.on_event("startup") +def startup() -> None: + """Startup application.""" + pass + + +@app.get("/scan") +def scan(platforms_to_scan: str, full_scan: bool=False) -> dict: + """Scan platforms and roms and write them in database.""" + + log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning ")) + 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 + log.info(f"Platforms detected: {', '.join(platforms)}") + for p_slug in platforms: + log.info(emoji.emojize(f":video_game: {p_slug} {COLORS['reset']}")) + platform: Platform = fastapi.scan_platform(p_slug) + if p_slug != str(platform): log.info(f"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: + log.info(f"Getting {COLORS['orange']}{rom['file_name']}{COLORS['reset']} details") + if rom['multi']: [log.info(f"\t - {COLORS['orange_i']}{file}{COLORS['reset']}") for file in rom['files']] + rom = fastapi.scan_rom(platform, rom) + dbh.add_rom(rom) + log.info(emoji.emojize(":wastebasket: Purging database")) + [dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) for p_slug in platforms] + dbh.purge_platforms(fs_platforms) + return {'msg': 'success'} + + +@app.get("/platforms") +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: +def rom(p_slug: str, file_name: str) -> dict: """Returns one rom data of the desired platform""" 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") +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") @@ -37,6 +75,7 @@ async def updateRom(req: Request, p_slug: str) -> dict: data: dict = await req.json() rom: dict = data['rom'] updatedRom: dict = data['updatedRom'] + log.info(f"Updating {COLORS['orange']}{updatedRom['file_name']}{COLORS['reset']} details") r_igdb_id, file_name_no_tags, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(updatedRom['file_name'], rom['p_igdb_id'], updatedRom['r_igdb_id']) path_cover_s, path_cover_l, has_cover = fs.get_cover_details(True, p_slug, updatedRom['file_name'], url_cover) updatedRom['file_name_no_tags'] = file_name_no_tags @@ -60,35 +99,15 @@ 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}") +def remove_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(f"Deleting {file_name} from database") + dbh.delete_rom(p_slug, file_name) + if filesystem: + log.info(f"Removing {file_name} from filesystem") + fs.remove_rom(p_slug, file_name) return {'msg': 'success'} @@ -97,8 +116,12 @@ 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(emoji.emojize(":magnifying_glass_tilted_right: IGDB Searching")) + log.info(emoji.emojize(f":video_game: {data['rom']['p_slug']}: {COLORS['orange']}{data['rom']['file_name']}{COLORS['reset']}")) + matched_roms = igdbh.get_matched_roms(data['rom']['file_name'], data['rom']['p_igdb_id'], data['rom']['p_slug']) + log.info("Results:") + [log.info(f"\t - {COLORS['blue']}{rom['name']}{COLORS['reset']}") for rom in matched_roms] + return {'data': matched_roms} if __name__ == '__main__': 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..e861f867b 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,6 @@ 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 self.name diff --git a/backend/src/models/rom.py b/backend/src/models/rom.py index 3be7cb30a..a22ac19ab 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="") @@ -31,3 +31,13 @@ class Rom(BaseModel): region = Column(String(20), default="") revision = Column(String(20), default="") tags = Column(JSON, default=[]) + + multi = Column(Boolean, default=False) + files = Column(JSON, default=[]) + + @property + def full_path(self) -> str: + return f"{self.file_path}/{self.file_name}" + + def __repr__(self) -> str: + return self.file_name diff --git a/backend/src/utils/fastapi.py b/backend/src/utils/fastapi.py index b359b18f1..a0eff8327 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 @@ -16,7 +16,6 @@ def allow_cors(app: FastAPI) -> None: allow_methods=["*"], allow_headers=["*"], ) - log.info("CORS enabled") def scan_platform(p_slug: str) -> Platform: @@ -27,19 +26,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['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']}") platform = Platform(**platform_attrs) - dbh.add_platform(platform) 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 @@ -53,4 +46,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 401c302b3..7447e10e1 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,36 +25,25 @@ 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 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 ========= -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 - +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: @@ -74,46 +59,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_roms_structure(p_slug) roms: list[dict] = [] - roms_path, roms_files = _check_folder_structure(p_slug) - roms_files = _exclude_files(roms_files) + 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]] - if only_amount: return len(roms_files) + if only_amount: return len(db_roms) - 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 - 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['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}") - if only_amount: return 0 return roms @@ -126,24 +128,29 @@ 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_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, _ = _check_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.") + rom_path = _get_roms_structure(p_slug) + if _rom_exists(p_slug, new_name): + log.info(f"Can't rename {old_name} to {new_name}. {new_name} already exists") + 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: +def remove_rom(p_slug: str, file_name: str) -> None: + rom_path = _get_roms_structure(p_slug) try: - rom_path, _ = _check_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}") + log.error(f"{rom_path}/{file_name} not found in filesystem") def _cover_exists(p_slug: str, file_name: str, size: str) -> bool: @@ -160,17 +167,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 @@ -190,7 +186,18 @@ def _store_cover(p_slug: str, file_name: str, url_cover: str, size: str) -> None shutil.copyfileobj(res.raw, f) log.info(f"{file_name} {sizes[size]} cover downloaded successfully!") else: - log.warning(f"{file_name} {sizes[size]} cover couldn't be downloaded") + log.error(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: @@ -208,4 +215,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/docker/Dockerfile b/docker/Dockerfile index 492e3ee57..ab5819fc4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,37 +1,43 @@ # 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 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 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"] diff --git a/docker/init_scripts/init_back b/docker/init_scripts/init_back index 8112c1e90..66dbbf56c 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 \ No newline at end of file diff --git a/frontend/.env b/frontend/.env index 5f9286bec..4cd46d6be 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.3 \ No newline at end of file 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/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 09840bc24..ff5bf24f4 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", @@ -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/Navigation.vue b/frontend/src/components/Navigation.vue index dcbe38d2a..55abd72e7 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,9 +34,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_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'}) @@ -104,7 +101,7 @@ getPlatforms() - + @@ -145,9 +142,13 @@ getPlatforms() - + - + + + + + diff --git a/frontend/src/components/RomDetails.vue b/frontend/src/components/RomDetails.vue index 1963ca784..3353d49a2 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') @@ -28,8 +29,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 @@ -100,7 +100,7 @@ async function deleteRom() { - + @@ -135,17 +135,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 }} @@ -220,7 +223,7 @@ async function deleteRom() { Cancel
- +
diff --git a/frontend/src/components/RomsGallery.vue b/frontend/src/components/RomsGallery.vue index 0a51dd15a..17e262700 100644 --- a/frontend/src/components/RomsGallery.vue +++ b/frontend/src/components/RomsGallery.vue @@ -94,15 +94,15 @@ onMounted(() => { if(localStorage.getItem('currentPlatform')){ getRoms(JSON.pars
+ + +
Feels cold here... mdi-emoticon-sad
+
- -
Feels cold here... mdi-emoticon-sad
-
-