Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Action to mass rename all ROMs for a platform #253

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 58 additions & 21 deletions backend/endpoints/rom.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import emoji
from fastapi import APIRouter, Request, status, HTTPException

from logger.logger import log
from handler import dbh
from handler import dbh, igdbh
from utils import fs, get_file_name_with_no_tags
from utils.exceptions import RomNotFoundError, RomAlreadyExistsException
from models.rom import Rom
from models.platform import Platform

router = APIRouter()
Expand All @@ -14,51 +14,88 @@
def rom(id: int) -> dict:
"""Returns one rom data of the desired platform"""

return {'data': dbh.get_rom(id)}
return {"data": dbh.get_rom(id)}


@router.get("/platforms/{p_slug}/roms", status_code=200)
def roms(p_slug: str) -> dict:
"""Returns all roms of the desired platform"""
"""Returns all roms of the given platform"""

return {'data': dbh.get_roms(p_slug)}
return {"data": dbh.get_roms(p_slug)}


async def rename_all_roms(_sid: str, platform_slug: str, sm=None) -> dict:
"""Renames all ROMs of the given platform to IGDB format"""

platform = dbh.get_platform(platform_slug)
platform_roms = [r for r in dbh.get_roms(platform_slug) if r.r_igdb_id]
log.info(emoji.emojize(f":pencil: Renaming all {platform.name} ROMs"))

for rom in platform_roms:
try:
igdb_rom_data = igdbh.get_rom_by_id(rom.r_igdb_id)
fs.rename_rom(
platform.fs_slug, rom.file_name, igdb_rom_data[0].get("r_name", "")
)
log.info(f'Renamed {rom.file_name} to {igdb_rom_data[0].get("r_name", "")}')
except RomAlreadyExistsException as e:
log.info(str(e))
gantoine marked this conversation as resolved.
Show resolved Hide resolved

await sm.emit("mass_rename:done")


@router.patch("/platforms/{p_slug}/roms/{id}", status_code=200)
async def updateRom(req: Request, p_slug: str, id: int) -> dict:
"""Updates rom details"""

data: dict = await req.json()
updated_rom: dict = data['updatedRom']
db_rom: Rom = dbh.get_rom(id)
platform: Platform = dbh.get_platform(p_slug)
data = await req.json()
updated_rom: dict = data["updatedRom"]
db_rom = dbh.get_rom(id)
platform = dbh.get_platform(p_slug)

try:
fs.rename_rom(platform.fs_slug, db_rom.file_name, updated_rom['file_name'])
fs.rename_rom(platform.fs_slug, db_rom.file_name, updated_rom["file_name"])
except RomAlreadyExistsException as e:
error: str = f"{e}"
log.error(error)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error)
updated_rom['file_name_no_tags'] = get_file_name_with_no_tags(updated_rom['file_name'])
updated_rom.update(fs.get_cover(True, p_slug, updated_rom['file_name'], updated_rom['url_cover']))
updated_rom.update(fs.get_screenshots(p_slug, updated_rom['file_name'], updated_rom['url_screenshots']))
log.error(str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)

updated_rom["file_name_no_tags"] = get_file_name_with_no_tags(
updated_rom["file_name"]
)
updated_rom.update(
fs.get_cover(True, p_slug, updated_rom["file_name"], updated_rom["url_cover"])
)
updated_rom.update(
fs.get_screenshots(
p_slug, updated_rom["file_name"], updated_rom["url_screenshots"]
)
)
dbh.update_rom(id, updated_rom)
return {'data': dbh.get_rom(id), 'msg': f"{updated_rom['file_name']} updated successfully!"}

return {
"data": dbh.get_rom(id),
"msg": f"{updated_rom['file_name']} updated successfully!",
}


@router.delete("/platforms/{p_slug}/roms/{id}", status_code=200)
def delete_rom(p_slug: str, id: int, filesystem: bool=False) -> dict:
def delete_rom(p_slug: str, id: int, filesystem: bool = False) -> dict:
"""Detele rom from database [and filesystem]"""

rom: Rom = dbh.get_rom(id)
rom = dbh.get_rom(id)
log.info(f"Deleting {rom.file_name} from database")
dbh.delete_rom(id)

if filesystem:
log.info(f"Deleting {rom.file_name} from filesystem")
try:
platform: Platform = dbh.get_platform(p_slug)
fs.remove_rom(platform.fs_slug, rom.file_name)
except RomNotFoundError as e:
error: str = f"{e}. Couldn't delete from filesystem."
error = f"{str(e)}. Couldn't delete from filesystem."
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
return {'msg': f'{rom.file_name} deleted successfully!'}

return {"msg": f"{rom.file_name} deleted successfully!"}
10 changes: 5 additions & 5 deletions backend/endpoints/scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from models.rom import Rom


async def scan(sid: str, platforms: str, complete_rescan: bool=True, sm=None):
async def scan(_sid: str, platforms: str, complete_rescan: bool = True, sm = None):
"""Scan platforms and roms and write them in database."""

log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning "))
Expand All @@ -18,7 +18,7 @@ async def scan(sid: str, platforms: str, complete_rescan: bool=True, sm=None):
try: # Scanning platforms
fs_platforms: list[str] = fs.get_platforms()
except PlatformsNotFoundException as e:
log.error(e); await sm.emit('done_ko', e.message); return
log.error(e); await sm.emit('scan:done_ko', e.message); return

platforms: list[str] = json.loads(platforms) if len(json.loads(platforms)) > 0 else fs_platforms
log.info(f"Platforms to be scanned: {', '.join(platforms)}")
Expand All @@ -28,7 +28,7 @@ async def scan(sid: str, platforms: str, complete_rescan: bool=True, sm=None):
scanned_platform: Platform = fastapi.scan_platform(platform)
except RomsNotFoundException as e:
log.error(e); continue
await sm.emit('scanning_platform', [scanned_platform.name, scanned_platform.slug]); await sm.emit('') # Workaround to emit in real-time
await sm.emit('scan:scanning_platform', [scanned_platform.name, scanned_platform.slug]); await sm.emit('') # Workaround to emit in real-time
if platform != str(scanned_platform): log.info(f"Identified as {COLORS['blue']}{scanned_platform}{COLORS['reset']}")
dbh.add_platform(scanned_platform)

Expand All @@ -37,12 +37,12 @@ async def scan(sid: str, platforms: str, complete_rescan: bool=True, sm=None):
for rom in fs_roms:
rom_id: int = dbh.rom_exists(scanned_platform.slug, rom['file_name'])
if rom_id and not complete_rescan: continue
await sm.emit('scanning_rom', rom['file_name']); await sm.emit('') # Workaround to emit in real-time
await sm.emit('scan:scanning_rom', rom['file_name']); await sm.emit('') # Workaround to emit in real-time
log.info(f"Scanning {COLORS['orange']}{rom['file_name']}{COLORS['reset']}")
if rom['multi']: [log.info(f"\t - {COLORS['orange_i']}{file}{COLORS['reset']}") for file in rom['files']]
scanned_rom: Rom = fastapi.scan_rom(scanned_platform, rom)
if rom_id: scanned_rom.id = rom_id
dbh.add_rom(scanned_rom)
dbh.purge_roms(scanned_platform.slug, [rom['file_name'] for rom in fs_roms])
dbh.purge_platforms(fs_platforms)
await sm.emit('done')
await sm.emit('scan:done')
15 changes: 12 additions & 3 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,17 @@
sm = SocketManager()
sm.mount_to("/ws", app)

async def scan_handler(*args): await scan.scan(*args, sm)
sm.on('scan', handler=scan_handler)

async def scan_handler(*args):
await scan.scan(*args, sm)


async def mass_rename_handler(*args):
await rom.rename_all_roms(*args, sm)


sm.on("scan", handler=scan_handler)
sm.on("mass_rename", handler=mass_rename_handler)


@app.on_event("startup")
Expand All @@ -31,6 +40,6 @@ def startup() -> None:
pass


if __name__ == '__main__':
if __name__ == "__main__":
uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True)
# uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=False, workers=2)
2 changes: 1 addition & 1 deletion backend/utils/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def _rom_exists(p_slug: str, file_name: str) -> bool:


def rename_rom(p_slug: str, old_name: str, new_name: str) -> None:
if new_name != old_name:
if new_name and new_name != old_name:
rom_path = get_roms_structure(p_slug)
if _rom_exists(p_slug, new_name):
raise RomAlreadyExistsException(new_name)
Expand Down
15 changes: 15 additions & 0 deletions frontend/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
10 changes: 10 additions & 0 deletions frontend/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"env": {
"node": true,
"browser": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-recommended"
]
}
Loading