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..109b51e3d
--- /dev/null
+++ b/backend/src/alembic/versions/1.6.3_rom_add_multi.py
@@ -0,0 +1,30 @@
+"""rom - add multi
+
+Revision ID: 1.6.3
+Revises: 1.6.2
+Create Date: 2023-04-10 16:21:34.680282
+
+"""
+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/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..a266392ea 100644
--- a/backend/src/main.py
+++ b/backend/src/main.py
@@ -1,4 +1,6 @@
-import os
+import sys
+import subprocess
+from subprocess import CalledProcessError
from fastapi import FastAPI, Request
import uvicorn
@@ -13,6 +15,42 @@ 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}")
+ sys.exit(4)
+
+
+@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 +58,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 +95,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..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="")
@@ -31,3 +31,22 @@ 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 (
+ 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}"
+ )
diff --git a/backend/src/utils/fs.py b/backend/src/utils/fs.py
index fdb690601..a6b0027bc 100644
--- a/backend/src/utils/fs.py
+++ b/backend/src/utils/fs.py
@@ -53,13 +53,8 @@ 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
+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"
def _exclude_files(roms_files) -> list[str]:
@@ -100,22 +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_path = _get_folder_structure(p_slug)
roms: list[dict] = []
- roms_path, roms_files = _check_folder_structure(p_slug)
- roms_files = _exclude_files(roms_files)
- 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
@@ -128,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}")
@@ -210,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-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..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..489ca4ca3 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 }} |
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")
}