### Install and run from source Source: https://github.com/ankimetho/mcscrapiscrape/blob/master/README.md Clone the repository, install dependencies, and launch the application from source. Requires Python 3.8 or later. ```bash git clone https://github.com/ankimetho/mcScrapiscrape.git cd mcScrapiscrape pip install -r requirements.txt python mcscrapiscrape.py ``` -------------------------------- ### Usage example for load_system_mapping Source: https://github.com/ankimetho/mcscrapiscrape Example of using load_system_mapping to iterate over the mapping entries sorted by display_name, printing each system's ID, display name, and ES-DE folder. ```python from mcscrapiscrape import load_system_mapping mapping = load_system_mapping() # {"4": {"display_name": "Super Nintendo", "esde_folder": "snes"}, ...} for eid, info in sorted(mapping.items(), key=lambda x: x[1]["display_name"]): print(eid, info["display_name"], info["esde_folder"]) ``` -------------------------------- ### Usage example for resource_path Source: https://github.com/ankimetho/mcscrapiscrape Example of using resource_path to load system_mapping.json. Checks existence and reads the file with UTF-8 encoding. ```python from mcscrapiscrape import resource_path import os, json path = resource_path("system_mapping.json") if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: mapping = json.load(f) ``` -------------------------------- ### CLI example: python scraper.py with all arguments Source: https://github.com/ankimetho/mcscrapiscrape Example invocation of the CLI scraper with required and optional arguments. Requires --rom-dir, --scrape-dir, --system, --user, --password, --devid, and --devpassword. Optional --gamelist-dir enables gamelist.xml generation; --systemeid is strongly recommended to avoid HTTP 400 errors. ```bash python scraper.py \ --rom-dir "/roms/snes" \ --scrape-dir "/ES-DE/downloaded_media" \ --system "snes" \ --user "alice" --password "secret" \ --devid "dev123" --devpassword "devsecret" \ --softname "mcScrapiscrape" \ --gamelist-dir "/ES-DE/gamelists" \ --systemeid "4" \ --threads 8 ``` -------------------------------- ### CLI usage example for scraper.py Source: https://github.com/ankimetho/mcscrapiscrape Example command line invocation of scraper.py with all required and optional arguments. Shows typical usage for scraping SNES ROMs with systemeid 4 and gamelist generation. ```bash python scraper.py \ --rom-dir "/path/to/roms/snes" \ --scrape-dir "/path/to/downloaded_media" \ --system "snes" \ --user "username" \ --password "password" \ --devid "dev_id" \ --devpassword "dev_password" \ --systemeid "4" \ --threads 6 \ --gamelist-dir "/path/to/gamelists" ``` -------------------------------- ### DirPickerModal.__init__ Source: https://github.com/ankimetho/mcscrapiscrape Constructor for the DirPickerModal class. Initializes the modal with a start path and target input ID. ```APIDOC ## DirPickerModal.__init__ ### Description Constructor for the DirPickerModal class. Initializes the modal with a start path and target input ID. ### Method Constructor ### Parameters - `start_path` (str) - Optional - Initial directory for the tree; silently replaced by `os.path.expanduser("~")` if it is not an existing directory. Default: `"/"`. - `target_input_id` (str) - Optional - Widget id of the TUI `Input` that should receive the picked path; returned in the dismissal payload. Default: `""`. ### Response No return value. ``` -------------------------------- ### Entry point: TuiScraperApp instantiation and run Source: https://github.com/ankimetho/mcscrapiscrape Starts the Textual TUI by instantiating TuiScraperApp and running the event loop. On mount, it checks for config.json in the current working directory; if missing, pushes ConfigWizard modal, otherwise loads config and runs startup audit tasks. ```python if __name__ == "__main__": app = TuiScraperApp() app.run() ``` -------------------------------- ### Usage example with ConfigWizard and TuiScraperApp Source: https://github.com/ankimetho/mcscrapiscrape Shows how to push the ConfigWizard screen and handle the result. The callback copies wizard input values into the main UI and persists them if True, or logs a skip message if False. ```python from mcscrapiscrape import ConfigWizard from mcscrapiscrape import TuiScraperApp app = TuiScraperApp() app.push_screen(ConfigWizard(), callback=app.handle_wizard_result) # handle_wizard_result(True) → copies #wiz-user → #user, #wiz-rom-dir → #rom-dir, etc., saves config.json, runs startup tasks # handle_wizard_result(False) → logs "[!] Wizard skipped. Please configure manually." ``` -------------------------------- ### DirPickerModal usage example Source: https://github.com/ankimetho/mcscrapiscrape Shows how to instantiate DirPickerModal and handle its dismissal result. The modal is pushed by the parent app; the callback receives a tuple (target_input_id, path) or None. ```python from mcscrapiscrape import DirPickerModal # Pushed by the parent app; dismissal result is a (target_input_id, path) tuple modal = DirPickerModal(start_path="/home/user/ROMs", target_input_id="rom-dir") # In the app: # app.push_screen(modal, callback=handle_dir_picker) # def handle_dir_picker(result): # if result is not None: # target_id, path = result # e.g. ("rom-dir", "/home/user/ROMs/snes") # app.query_one(f"#{target_id}", Input).value = path ``` -------------------------------- ### Direct invocation of run_scrape_worker Source: https://github.com/ankimetho/mcscrapiscrape Shows how to call run_scrape_worker directly, though it is normally launched automatically from start_scraping(). All parameters are positional; the example passes them as keyword arguments. The method is a Textual @work method. ```python from mcscrapiscrape import TuiScraperApp app = TuiScraperApp() # run_scrape_worker is a Textual @work method; it is launched # automatically from start_scraping(). Direct call pattern: app.run_scrape_worker( base_rom_dir="/roms", scrape_dir="/media", systems=[{"name": "snes", "eid": "4"}], user="u", password="p", devid="d", devpassword="dp", selected_media_types=["box-2D", "ss"], gamelist_dir=None, threads=6, fix_mode=True, ) ``` -------------------------------- ### Build request parameters for jeuInfos.php Source: https://github.com/ankimetho/mcscrapiscrape Constructs the query parameters for the GET /api2/jeuInfos.php endpoint. The systemeid parameter is only added if truthy. None-valued params are dropped before URL-encoding. ```python params = { "devid": devid, "devpassword": devpassword, "softname": softname, "ssid": ssid, "sspassword": sspassword, "romnom": rom_name, "output": "json" } if systemeid: params["systemeid"] = systemeid ``` -------------------------------- ### build_api_url usage example Source: https://github.com/ankimetho/mcscrapiscrape Shows how to call build_api_url with a dict containing a None value. The None entry (systemeid) is dropped from the resulting URL. ```python from scraper import build_api_url url = build_api_url("jeuInfos.php", {"devid": "1234", "systemeid": None, "romnom": "SuperMario.zip", "output": "json"}) print(url) # https://www.screenscraper.fr/api2/jeuInfos.php?devid=1234&romnom=SuperMario.zip&output=json # (note: systemeid was dropped because it was None) ``` -------------------------------- ### on_button_pressed handler Source: https://github.com/ankimetho/mcscrapiscrape Handles button presses in the wizard. SAVE & START dismisses with True, SKIP dismisses with False. ```python def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == "wiz-save-btn": # Pass data back or just dismiss with a signal self.dismiss(True) else: self.dismiss(False) ``` -------------------------------- ### main() function definition with argparse setup Source: https://github.com/ankimetho/mcscrapiscrape Defines the CLI entry point for scraper.py. Parses required and optional arguments for scraping from screenscraper.fr to ES-DE format. Invoked by `python scraper.py`. ```python def main(): parser = argparse.ArgumentParser(description="Scrape from screenscraper.fr to ES-DE format.") parser.add_argument("--rom-dir", required=True, help="Path to directory containing ROMs.") parser.add_argument("--scrape-dir", required=True, help="Path to ES-DE downloaded_media directory.") parser.add_argument("--system", required=True, help="System name (e.g., snes).") parser.add_argument("--user", required=True, help="Screenscraper Username.") parser.add_argument("--password", required=True, help="Screenscraper Password.") parser.add_argument("--devid", required=True, help="Screenscraper Developer ID.") parser.add_argument("--devpassword", required=True, help="Screenscraper Developer Password.") parser.add_argument("--softname", default="mcScrapiscrape", help="Your software name registered with Screenscraper.") parser.add_argument("--gamelist-dir", default=None, help="Path to ES-DE gamelists directory to generate gamelist.xml.") parser.add_argument("--systemeid", default=None, help="Screenscraper system ID (e.g. 4 for SNES). Strongly recommended to avoid HTTP 400 errors.") parser.add_argument("--threads", type=int, default=6, help="Number of concurrent threads (default: 6).") ``` -------------------------------- ### DirPickerModal class definition Source: https://github.com/ankimetho/mcscrapiscrape Defines a modal directory picker using Textual's DirectoryTree. The constructor accepts a start path and a target input ID; if the start path is not a directory, it falls back to the user's home directory. The modal dismisses with a tuple (target_input_id, selected_path) on SELECT, or None on CANCEL. ```python class DirPickerModal(ModalScreen): """A modal directory picker using DirectoryTree.""" def __init__(self, start_path: str = "/", target_input_id: str = ""): super().__init__() self.start_path = start_path if os.path.isdir(start_path) else os.path.expanduser("~") self.target_input_id = target_input_id self.selected_path = self.start_path ``` -------------------------------- ### Data flow from main to fetch_game_info and download_media Source: https://github.com/ankimetho/mcscrapiscrape Shows the call chain from scraper.main() or TuiScraperApp.run_scrape_worker through fetch_game_info to the GET request and subsequent media downloads. ```text scraper.main() / TuiScraperApp.run_scrape_worker └─ fetch_game_info(rom_name, devid, devpassword, softname, ssid, sspassword, systemeid) └─ GET https://www.screenscraper.fr/api2/jeuInfos.php? (JSON) └─ response.jeu → gamelist.xml nodes └─ for each medias[].url → download_media(url, out_path) (binary) ``` -------------------------------- ### GET /api2/jeuInfos.php Source: https://github.com/ankimetho/mcscrapiscrape Retrieves game information from ScreenScraper.fr based on a ROM file name. This is the only API endpoint called by the mcScrapiscrape client, and it returns JSON game data including metadata and media URLs. ```APIDOC ## [GET] /api2/jeuInfos.php ### Description Retrieves game information from ScreenScraper.fr based on a ROM file name. This is the only API endpoint called by the mcScrapiscrape client, and it returns JSON game data including metadata and media URLs. ### Method GET ### Endpoint https://www.screenscraper.fr/api2/jeuInfos.php ### Parameters #### Query Parameters - **devid** (str) - Required - ScreenScraper developer ID - **devpassword** (str) - Required - ScreenScraper developer password - **softname** (str) - Required - Registered software name; the CLI defaults to "mcScrapiscrape" - **ssid** (str) - Required - ScreenScraper account username - **sspassword** (str) - Required - ScreenScraper account password - **romnom** (str) - Required - ROM file name to look up (e.g. "SuperMario.zip") - **output** (str) - Required - Response format; always "json" in this codebase - **systemeid** (str) - Optional - ScreenScraper numeric system ID (e.g. "4" for SNES). Sent only when truthy; the CLI help notes it is "Strongly recommended to avoid HTTP 400 errors" ### Response #### Success Response (200) - **response.jeu** (object) - The game record. Absence means "not found" - **jeu.noms[0].text** (str) - Game title - **jeu.synopsis[0].text** (str) - Long description - **jeu.dates[0].text** (str) - Release date (YYYY-MM-DD or YYYY) - **jeu.developpeur.text** (str) - Developer - **jeu.editeur.text** (str) - Publisher - **jeu.genres[0].noms[0].text** (str) - Genre - **jeu.joueurs.text** (str) - Player count - **jeu.note.text** (str) - Numeric rating (0–100, divided by 20 for ES-DE) - **jeu.medias[]** (array) - Media asset list - **medias[].type** (str) - Media type key (compared against MEDIA_MAPPING) - **medias[].url** (str) - Absolute asset URL requiring auth params (see below) #### Error Responses - **400** - Bad Request — missing systemeid or invalid auth - **403** - Forbidden — invalid developer credentials (server body included in message) - **404** - Game not found on ScreenScraper - **430** - Quota exceeded or invalid credentials/softname - **other** - Generic HTTP : ``` -------------------------------- ### run_startup_tasks() method Source: https://github.com/ankimetho/mcscrapiscrape Runs automated detect and check tasks: auto_detect_systems and run_check_media_worker. ```python def run_startup_tasks(self) -> None: """Runs the automated detect and check tasks.""" self.auto_detect_systems() self.run_check_media_worker() ``` -------------------------------- ### check_initial_config() method Source: https://github.com/ankimetho/mcscrapiscrape Handles first-run wizard or automatic loading and auditing. If config.json is absent, pushes ConfigWizard with callback; otherwise loads config and runs startup tasks. ```python def check_initial_config(self) -> None: """Handles first-run wizard or automatic loading and auditing.""" if not os.path.exists("config.json"): # Show Wizard and handle result via callback self.push_screen(ConfigWizard(), callback=self.handle_wizard_result) else: self.load_config_file() self.run_startup_tasks() ``` -------------------------------- ### Build system selection options Source: https://github.com/ankimetho/mcscrapiscrape Constructs Selection objects for the systems list. Each option uses a label with display name and ES-DE folder, and a pipe-joined value combining ID and folder. The value is later split with val.split('|', 1) in start_scraping, auto_detect_systems, and run_check_media_worker. ```python label = f"{display_name} [{esde_folder}]" val = f"{eid}|{esde_folder}" # e.g. Selection("Super Nintendo [snes]", "4|snes", False) → unselected by default # Selection("Sega Mega Drive / Genesis [megadrive]", "1|megadrive", False) system_selections.append(Selection(label, val, False)) ``` -------------------------------- ### Run scraper.py from command line Source: https://github.com/ankimetho/mcscrapiscrape/blob/master/README.md Invoke the scraper module directly for scripted or automated use. Replace the placeholder paths and credentials with your own. Run `python scraper.py --help` for a full list of available arguments. ```bash python scraper.py \ --rom-dir "/path/to/roms/snes" \ --scrape-dir "/path/to/downloaded_media" \ --system "snes" \ --user "username" \ --password "password" \ --devid "dev_id" \ --devpassword "dev_password" \ --systemeid "4" \ --threads 6 ``` -------------------------------- ### Build media selection options Source: https://github.com/ankimetho/mcscrapiscrape Constructs Selection objects for the media list. Maps MEDIA_MAPPING keys to display names and defaults to selecting 'box-2D', 'ss', and 'screenmarquee'. Ordering follows the dict's insertion order. ```python media_names = { "box-2D": "Box 2D", "box-3D": "Box 3D", "screenmarquee": "Marquee", "mixrbv2": "Mix Image", "ss": "Screenshot", "video": "Video", "wheel": "Wheel", "fanart": "Fan-Art", "manual": "Manual", } media_selections = [ Selection(media_names.get(m, m), m, m in ["box-2D", "ss", "screenmarquee"]) for m in MEDIA_MAPPING.keys() ] ``` -------------------------------- ### on_mount() method definition Source: https://github.com/ankimetho/mcscrapiscrape Textual mount hook that caches log_view and progress_bar, creates xml_lock, sets title/sub-title, and schedules first-run logic. ```python def on_mount(self): ``` -------------------------------- ### Return-value handling with MEDIA_MAPPING Source: https://github.com/ankimetho/mcscrapiscrape Demonstrates checking for an existing file before downloading, treating an existing file as success. Uses MEDIA_MAPPING to derive folder and extension. Prints a failure message if download fails, mentioning auth params and 429/430 quota limits. ```python import os from scraper import MEDIA_MAPPING, download_media folder, ext = MEDIA_MAPPING["box-2D"] # caller: only download when the asset is missing out_path = os.path.join("downloaded_media", "snes", folder, f"SuperMario.{ext}") if os.path.exists(out_path): ok = True # treat existing file as success (callers in this repo do this) else: ok = download_media(media_url, out_path) if not ok: print(f"Failed to fetch {media_url} — verify auth params and that 429/430 quota limits are respected") ``` -------------------------------- ### load_config_file method Source: https://github.com/ankimetho/mcscrapiscrape Reads config.json (no-op if absent). For each key, queries the widget; SelectionList deselects all and reselects stored values, others assign widget.value. Logs success or error. Source: mcscrapiscrape.py:650. ```python def load_config_file(self): ``` -------------------------------- ### DirPickerModal constructor signature Source: https://github.com/ankimetho/mcscrapiscrape Constructor signature for DirPickerModal. The start_path defaults to '/' and is replaced with the user's home directory if it is not an existing directory. The target_input_id is the widget ID of the TUI Input that receives the picked path. ```python def __init__(self, start_path: str = "/", target_input_id: str = ""): ``` -------------------------------- ### Basic usage of download_media Source: https://github.com/ankimetho/mcscrapiscrape Shows how to call download_media with a ScreenScraper media URL that includes authentication query parameters. The caller must append ssid, sspassword, devid, devpassword, and softname parameters. ```python from scraper import download_media auth = "?ssid=user&sspassword=pass&devid=dev&devpassword=dpass&softname=mcScrapiscrape" ok = download_media(f"https://www.screenscraper.fr/media/box2D_1.png{auth}", "downloaded_media/megadrive/covers/Sonic.png") if ok: print("Media saved") ``` -------------------------------- ### load_system_mapping() Source: https://github.com/ankimetho/mcscrapiscrape Loads the definitive ScreenScraper ID to ES-DE folder mapping from system_mapping.json. Returns an empty dictionary on any failure and never raises an exception. ```APIDOC ## load_system_mapping() ### Description Loads the definitive ScreenScraper ID to ES-DE folder mapping from system_mapping.json. Returns an empty dictionary on any failure and never raises an exception. ### Returns - `dict` - Parsed contents of system_mapping.json, keyed by ScreenScraper system ID, each value is `{"display_name": str, "esde_folder": str}` ### Request Example ```python from mcscrapiscrape import load_system_mapping mapping = load_system_mapping() # {"4": {"display_name": "Super Nintendo", "esde_folder": "snes"}, ...} for eid, info in sorted(mapping.items(), key=lambda x: x[1]["display_name"]): print(eid, info["display_name"], info["esde_folder"]) ``` ``` -------------------------------- ### compose() method definition Source: https://github.com/ankimetho/mcscrapiscrape Textual compose hook that yields the Header, three-column layout, and Footer. Returns ComposeResult. ```python def compose(self) -> ComposeResult: ``` -------------------------------- ### Append credential query parameters to media URL (TUI variant) Source: https://github.com/ankimetho/mcscrapiscrape Adds ssid, sspassword, devid, devpassword, and softname to a media asset URL before download. Only appends if 'ssid=' is not already present and a user is provided. Uses '&' or '?' separator depending on existing query string. ```python if "ssid=" not in orig_url and user: sep = "&" if "?" in orig_url else "?" orig_url += f"{sep}ssid={user}&sspassword={password}" if devid: orig_url += f"&devid={devid}&devpassword={devpassword}&softname=mcScrapiscrape" ``` -------------------------------- ### DirPickerModal Textual event handlers Source: https://github.com/ankimetho/mcscrapiscrape Handles directory selection, input submission, and button presses. On SELECT, dismisses with the target input ID and selected path; on PARENT, navigates to the parent directory; on CANCEL or other buttons, dismisses with None. ```python def on_directory_tree_directory_selected(self, event: DirectoryTree.DirectorySelected) -> None: self.selected_path = str(event.path) self.query_one("#dirpicker-path-input", Input).value = self.selected_path def on_input_submitted(self, event: Input.Submitted) -> None: if event.input.id == "dirpicker-path-input": typed = event.value.strip() if os.path.isdir(typed): self._reload_tree(typed) def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == "dirpicker-select": self.dismiss((self.target_input_id, self.selected_path)) elif event.button.id == "dirpicker-parent": parent = os.path.dirname(self.selected_path) if parent and parent != self.selected_path: self._reload_tree(parent) else: self.dismiss(None) ``` -------------------------------- ### save_config_file method Source: https://github.com/ankimetho/mcscrapiscrape Serializes UI state into config.json in CWD with indent=4. Logs success or error message. Source: mcscrapiscrape.py:630. ```python def save_config_file(self): ``` ```python config_data = { "rom-dir": ..., "scrape-dir": ..., "user": ..., "password": ..., "devid": ..., "devpassword": ..., "gamelist-dir": ..., "threads": ..., "systems-list": ..., "media-list": ..., } ``` -------------------------------- ### Check download_media return value Source: https://github.com/ankimetho/mcscrapiscrape Catch binary download failures by checking the boolean return from download_media. Any exception during urlopen or open().write() returns False and prints '[!] Failed to download media : '. Note that callers treat an existing destination file as success and skip the download entirely; download_media itself does not do this. ```python from scraper import download_media if not download_media(media_url, out_path): print(f"media for {base_name} was not persisted; will be retried on next run") ``` -------------------------------- ### DirPickerModal _reload_tree method Source: https://github.com/ankimetho/mcscrapiscrape Re-roots the DirectoryTree at a new path. It is a no-op if the path is not a directory; otherwise it updates the selected path and the path input, and reloads the tree. ```python def _reload_tree(self, new_path: str) -> None: """Replace the DirectoryTree with one rooted at new_path.""" if not os.path.isdir(new_path): return self.selected_path = new_path self.query_one("#dirpicker-path-input", Input).value = new_path tree = self.query_one("#dirpicker-tree", DirectoryTree) tree.path = new_path tree.reload() ``` -------------------------------- ### fetch_game_info basic usage Source: https://github.com/ankimetho/mcscrapiscrape Calls fetch_game_info with a systemeid and inspects the response for a 'jeu' entry to print the game name. On failure prints the error dict. ```python from scraper import fetch_game_info info = fetch_game_info( rom_name="SonicTheHedgehog.zip", devid="my_dev_id", devpassword="my_dev_pass", softname="mcScrapiscrape", ssid="my_user", sspassword="my_pass", systemeid="1", # Sega Mega Drive / Genesis ) if info and "jeu" in info.get("response", {}): jeu = info["response"]["jeu"] name = jeu.get("noms", [{}])[0].get("text") print(f"Found: {name}") else: print("Not found or error:", info.get("error")) ``` -------------------------------- ### DirPickerModal._reload_tree Source: https://github.com/ankimetho/mcscrapiscrape Re-roots the directory tree at a new path. Updates the selected path and the path input. ```APIDOC ## DirPickerModal._reload_tree ### Description Re-roots the directory tree at a new path. Updates the selected path and the path input. ### Method _reload_tree ### Parameters - `new_path` (str) - Required - The new directory path to root the tree at. ### Response No return value. ``` -------------------------------- ### DirPickerModal.on_input_submitted Source: https://github.com/ankimetho/mcscrapiscrape Event handler for when the path input is submitted. If the typed path is a directory, reloads the tree. ```APIDOC ## DirPickerModal.on_input_submitted ### Description Event handler for when the path input is submitted. If the typed path is a directory, reloads the tree. ### Method Event handler ### Parameters - `event` (Input.Submitted) - Required - The event object containing the submitted input value. ### Response No return value. ``` -------------------------------- ### DirPickerModal.compose Source: https://github.com/ankimetho/mcscrapiscrape Composes the UI for the modal directory picker. Renders the centered card with navigation, directory tree, and buttons. ```APIDOC ## DirPickerModal.compose ### Description Composes the UI for the modal directory picker. Renders the centered card with navigation, directory tree, and buttons. ### Method compose ### Parameters None ### Response Returns a ComposeResult. ``` -------------------------------- ### download_media(media_url, out_path) Source: https://github.com/ankimetho/mcscrapiscrape Downloads a media asset from a given URL to a local file path. Returns True on success, False on any exception. ```APIDOC ## `download_media(media_url, out_path)` ### Description Downloads a media asset from the given URL to the specified local file path. Returns `True` if the file was written successfully, `False` on any exception. ### Parameters - `media_url` (str) - Required - Absolute URL of the media asset returned by ScreenScraper. The caller is responsible for appending `ssid`/`sspassword`/`devid`/`devpassword` auth query params. - `out_path` (str) - Required - Destination file path. The parent directory must exist or the write fails and `False` is returned. ### Returns `bool` - `True` when the body was written to `out_path`; `False` on any exception (network failure, HTTP error status, filesystem error). ### Side Effects Prints `[!] Failed to download media : ` on failure. ### Request Example ```python from scraper import download_media auth = "?ssid=user&sspassword=pass&devid=dev&devpassword=dpass&softname=mcScrapiscrape" ok = download_media(f"https://www.screenscraper.fr/media/box2D_1.png{auth}", "downloaded_media/megadrive/covers/Sonic.png") if ok: print("Media saved") ``` ### Return-value handling Example ```python import os from scraper import MEDIA_MAPPING, download_media folder, ext = MEDIA_MAPPING["box-2D"] # caller: only download when the asset is missing out_path = os.path.join("downloaded_media", "snes", folder, f"SuperMario.{ext}") if os.path.exists(out_path): ok = True # treat existing file as success (callers in this repo do this) else: ok = download_media(media_url, out_path) if not ok: print(f"Failed to fetch {media_url} — verify auth params and that 429/430 quota limits are respected") ``` ``` -------------------------------- ### DirPickerModal.on_directory_tree_directory_selected Source: https://github.com/ankimetho/mcscrapiscrape Event handler for when a directory is selected in the tree. Updates the selected path and the path input. ```APIDOC ## DirPickerModal.on_directory_tree_directory_selected ### Description Event handler for when a directory is selected in the tree. Updates the selected path and the path input. ### Method Event handler ### Parameters - `event` (DirectoryTree.DirectorySelected) - Required - The event object containing the selected directory path. ### Response No return value. ``` -------------------------------- ### DirPickerModal.on_button_pressed Source: https://github.com/ankimetho/mcscrapiscrape Event handler for button presses. Handles SELECT, PARENT, and CANCEL actions. ```APIDOC ## DirPickerModal.on_button_pressed ### Description Event handler for button presses. Handles SELECT, PARENT, and CANCEL actions. ### Method Event handler ### Parameters - `event` (Button.Pressed) - Required - The event object containing the pressed button. ### Response No return value. ``` -------------------------------- ### fetch_game_info function definition Source: https://github.com/ankimetho/mcscrapiscrape Builds the params dict for a ScreenScraper request. The systemeid parameter is only included when truthy; omitting it can cause an HTTP 400. ```python def fetch_game_info(rom_name, devid, devpassword, softname, ssid, sspassword, systemeid=None): params = { "devid": devid, "devpassword": devpassword, "softname": softname, "ssid": ssid, "sspassword": sspassword, "romnom": rom_name, "output": "json" } if systemeid: params["systemeid"] = systemeid ``` -------------------------------- ### resource_path(relative_path) Source: https://github.com/ankimetho/mcscrapiscrape Resolves the absolute path to a bundled resource, working both in development and when packaged with PyInstaller. It uses sys._MEIPASS when available, otherwise the current working directory. ```APIDOC ## resource_path(relative_path) ### Description Resolves the absolute path to a bundled resource, working both in development and when packaged with PyInstaller. It uses sys._MEIPASS when available, otherwise the current working directory. ### Parameters - `relative_path` (str) - Required - Path relative to the application root ### Returns - `str` - Absolute path to the resource ### Request Example ```python from mcscrapiscrape import resource_path import os, json path = resource_path("system_mapping.json") if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: mapping = json.load(f) ``` ``` -------------------------------- ### ConfigWizard class definition Source: https://github.com/ankimetho/mcscrapiscrape Defines the ConfigWizard modal screen for initial configuration. Composes the wizard card with credential inputs, folder path inputs, and action buttons. ```python class ConfigWizard(ModalScreen): """A centered modal for initial configuration.""" def compose(self) -> ComposeResult: with Center(): with Vertical(id="wizard-card"): yield Label(" 🚀 mcScrapiscrape INITIAL SETUP ", id="wizard-title") yield Label( "It looks like you're starting fresh. Please provide your core settings to begin.", id="wizard-desc", ) ... with Horizontal(id="wizard-actions"): yield Button("SAVE & START", variant="success", id="wiz-save-btn") yield Button("SKIP", variant="default", id="wiz-skip-btn") ``` -------------------------------- ### handle_dir_picker callback Source: https://github.com/ankimetho/mcscrapiscrape Dismissal callback for DirPickerModal. If result is not None, it is a tuple (target_input_id, selected_path) and sets the corresponding Input value. Source: mcscrapiscrape.py:575. ```python def handle_dir_picker(self, result) -> None: ``` -------------------------------- ### Media directory structure Source: https://github.com/ankimetho/mcscrapiscrape/blob/master/README.md Standard ES-DE media directory layout used by mcScrapiscrape. ROM directories are expected to be organized by system shortname (e.g., `snes`, `megadrive`, `psx`). ```text downloaded_media/ └── / ├── 3dboxes/ ├── covers/ ├── marquees/ ├── miximages/ ├── screenshots/ └── videos/ ``` -------------------------------- ### Module architecture dependency graph Source: https://github.com/ankimetho/mcscrapiscrape Shows the module dependency graph for mcscrapiscrape.py, listing internal modules, data files, and imported libraries. Note that screenscraper_system_ids.json is bundled but not referenced by any code. ```text mcscrapiscrape.py (TUI) ├── scraper.fetch_game_info (per-ROM metadata lookup) ├── scraper.download_media (per-asset download) ├── scraper.MEDIA_MAPPING (media type → folder/extension table) ├── system_mapping.json (ScreenScraper ID → ES-DE folder; bundled at resource_path) ├── config.json (persisted UI state; read/written in CWD) ├── textual (App, ComposeResult, Horizontal, VerticalScroll, Vertical, Center, │ ModalScreen, Header, Footer, Input, Button, Log, ProgressBar, │ Label, Static, Select, SelectionList, DataTable, DirectoryTree, │ Selection, work, get_current_worker) └── stdlib (os, xml.etree.ElementTree, xml.dom.minidom, concurrent.futures, threading, json, sys) ``` -------------------------------- ### load_system_mapping function definition Source: https://github.com/ankimetho/mcscrapiscrape Loads the ScreenScraper ID to ES-DE folder mapping from system_mapping.json. Returns an empty dict on any failure and never raises exceptions. ```python def load_system_mapping(): """Load the definitive ScreenScraper ID → ES-DE folder mapping.""" mapping = {} try: path = resource_path("system_mapping.json") if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: mapping = json.load(f) except Exception: pass return mapping ``` -------------------------------- ### download_media function definition Source: https://github.com/ankimetho/mcscrapiscrape Downloads a media file from a URL to a local path. Returns True on success, False on any exception. Prints an error message on failure. The caller must ensure the parent directory exists. ```python def download_media(media_url, out_path): try: req = urllib.request.Request(media_url, headers={'User-Agent': 'Mozilla/5.0'}) with urllib.request.urlopen(req) as response: with open(out_path, "wb") as f: f.write(response.read()) return True except Exception as e: print(f" [!] Failed to download media {media_url}: {e}") return False ``` -------------------------------- ### Inspect fetch_game_info result for error key Source: https://github.com/ankimetho/mcscrapiscrape Because library-level calls never raise exceptions, check the returned dictionary for an 'error' key. HTTP 430 and 4xx are retryable, while HTTP 404 and generic network failures are permanent or retry later. ```python info = fetch_game_info(...) if "error" in info: # retryable: HTTP 430 (throttle), HTTP 4xx (credential/param problems) # permanent in practice: HTTP 404 (game unknown), generic network failures retry later ... ``` -------------------------------- ### TuiScraperApp class definition with compose method Source: https://github.com/ankimetho/mcscrapiscrape Defines the Textual application class for the TUI. The CSS is omitted in the source (shown as a placeholder). The compose method yields the main UI components including header, config panel, progress bar, log view, audit table, and selection panel. ```python class TuiScraperApp(App): CSS = """ ... """ # 240 lines of Textual CSS (mcscrapiscrape.py:240–479) BINDINGS = [("q", "quit", "Quit")] def compose(self) -> ComposeResult: yield Header(show_clock=True) with Horizontal(): yield ConfigPanel() with Vertical(id="log-container"): with Vertical(id="progress-area"): yield Label("Overall Scrape Progress") yield ProgressBar(id="progress", show_eta=True) yield Label("⚙ Live Thread Activity") with VerticalScroll(id="thread-container"): pass yield Label("📋 Console Log") yield Log(id="log_view", highlight=True) yield Label("📊 Audit Summary", id="table-label", classes="hidden") yield DataTable(id="audit_table") yield SelectionPanel() yield Footer() ``` -------------------------------- ### resource_path function definition Source: https://github.com/ankimetho/mcscrapiscrape Resolves absolute paths for bundled resources, working in both development and PyInstaller bundles. Uses sys._MEIPASS when available, otherwise the current working directory. ```python def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) ``` -------------------------------- ### fetch_game_info(rom_name, devid, devpassword, softname, ssid, sspassword, systemeid=None) Source: https://github.com/ankimetho/mcscrapiscrape Fetches game information from the ScreenScraper API for a given ROM file. It constructs the required parameters and returns the parsed JSON response, or an error dictionary on failure. This function never raises exceptions; all HTTP errors and generic exceptions are caught and converted into an error dict. ```APIDOC ## fetch_game_info(rom_name, devid, devpassword, softname, ssid, sspassword, systemeid=None) ### Description Fetches game information from the ScreenScraper API for a given ROM file. It constructs the required parameters and returns the parsed JSON response, or an error dictionary on failure. This function never raises exceptions; all HTTP errors and generic exceptions are caught and converted into an error dict. ### Parameters - `rom_name` (str) - Required - ROM file name (e.g. `"SuperMario.zip"`) sent as `romnom` - `devid` (str) - Required - ScreenScraper developer ID (`devid`) - `devpassword` (str) - Required - ScreenScraper developer password (`devpassword`) - `softname` (str) - Required - Registered software name (the TUI passes `"mcScrapiscrape"`) - `ssid` (str) - Required - ScreenScraper account username (`ssid`) - `sspassword` (str) - Required - ScreenScraper account password (`sspassword`) - `systemeid` (str) - Optional - ScreenScraper numeric system ID (e.g. `"4"` for SNES). Only sent when truthy. Omission can cause HTTP 400. ### Returns - `dict` - the parsed JSON response on success (the ScreenScraper `jeuInfos.php` payload); on failure returns `{"error": }`. Never raises. ### Request Example ```python from scraper import fetch_game_info info = fetch_game_info( rom_name="SonicTheHedgehog.zip", devid="my_dev_id", devpassword="my_dev_pass", softname="mcScrapiscrape", ssid="my_user", sspassword="my_pass", systemeid="1", # Sega Mega Drive / Genesis ) if info and "jeu" in info.get("response", {}): jeu = info["response"]["jeu"] name = jeu.get("noms", [{}])[0].get("text") print(f"Found: {name}") else: print("Not found or error:", info.get("error")) ``` ### Error-handling usage ```python from scraper import fetch_game_info info = fetch_game_info("GameThatDoesNotExist.zip", devid, devpassword, "mcScrapiscrape", user, password) if "error" in info: # info["error"] is one of the documented messages, e.g. # "HTTP 430: Quota exceeded or invalid credentials/softname" print(f"Scrape failed: {info['error']}") else: response = info.get("response", {}) if "jeu" not in response: print(f"{info} contained no 'jeu' entry — game not found or throttled") ``` ``` -------------------------------- ### build_api_url(endpoint, params) Source: https://github.com/ankimetho/mcscrapiscrape Builds a fully qualified ScreenScraper API URL by URL-encoding the provided query parameters and appending them to the base API URL. Parameters with a value of None are omitted from the query string. ```APIDOC ## build_api_url(endpoint, params) ### Description Builds a fully qualified ScreenScraper API URL by URL-encoding the provided query parameters and appending them to the base API URL. Parameters with a value of None are omitted from the query string. ### Parameters - `endpoint` (str) - Required - API endpoint file name, e.g. `"jeuInfos.php"` - `params` (dict) - Required - Query parameters; entries whose value is `None` are dropped ### Returns - `str` - a fully built URL of the form `https://www.screenscraper.fr/api2/?` ### Request Example ```python from scraper import build_api_url url = build_api_url("jeuInfos.php", {"devid": "1234", "systemeid": None, "romnom": "SuperMario.zip", "output": "json"}) print(url) # https://www.screenscraper.fr/api2/jeuInfos.php?devid=1234&romnom=SuperMario.zip&output=json # (note: systemeid was dropped because it was None) ``` ``` -------------------------------- ### DirPickerModal compose method signature Source: https://github.com/ankimetho/mcscrapiscrape Signature for the compose method that renders the modal's UI components. It builds a centered card with navigation, a directory tree, and SELECT/CANCEL buttons. ```python def compose(self) -> ComposeResult: ``` -------------------------------- ### on_button_pressed event handler Source: https://github.com/ankimetho/mcscrapiscrape Async Textual button-event dispatcher that routes actions by event.button.id. Source: mcscrapiscrape.py:546. ```python async def on_button_pressed(self, event: Button.Pressed) -> None: ``` -------------------------------- ### fetch_game_info error-handling usage Source: https://github.com/ankimetho/mcscrapiscrape Checks for an 'error' key in the returned dict and prints the documented error message. Also handles a response without a 'jeu' entry, indicating game not found or throttled. ```python from scraper import fetch_game_info info = fetch_game_info("GameThatDoesNotExist.zip", devid, devpassword, "mcScrapiscrape", user, password) if "error" in info: # info["error"] is one of the documented messages, e.g. # "HTTP 430: Quota exceeded or invalid credentials/softname" print(f"Scrape failed: {info['error']}") else: response = info.get("response", {}) if "jeu" not in response: print(f"{info} contained no 'jeu' entry — game not found or throttled") ``` -------------------------------- ### SelectionPanel compose method Source: https://github.com/ankimetho/mcscrapiscrape Defines the right sidebar widget with utility actions and selection lists. It composes a vertical column with id 'selection-sidebar' containing utility buttons and selection lists for systems and media types. ```python class SelectionPanel(VerticalScroll): def compose(self) -> ComposeResult: with Vertical(id="selection-sidebar"): ... ``` -------------------------------- ### Catch fetch_game_info error dict Source: https://github.com/ankimetho/mcscrapiscrape fetch_game_info never raises exceptions; it returns a dict with an 'error' key on failure. Check the dict and handle specific HTTP 430 quota errors by sleeping before retrying. ```python from scraper import fetch_game_info info = fetch_game_info(rom_name, devid, devpassword, "mcScrapiscrape", user, password, systemeid="4") if isinstance(info, dict) and "error" in info: print(f"lookup failed: {info['error']}") # e.g. "HTTP 430: Quota exceeded or invalid credentials/softname" if info["error"].startswith("HTTP 430"): time.sleep(60) # respect API usage limits before retrying ``` -------------------------------- ### ConfigPanel compose method Source: https://github.com/ankimetho/mcscrapiscrape Defines the left sidebar widget for scrape controls and settings. It composes a vertical column with id 'config-sidebar' containing buttons, inputs, and browse buttons. The widget is a passive container read via TuiScraperApp.get_input_value. ```python class ConfigPanel(VerticalScroll): def compose(self) -> ComposeResult: with Vertical(id="config-sidebar"): ... ``` -------------------------------- ### Import scraping engine functions Source: https://github.com/ankimetho/mcscrapiscrape Imports the scraping engine functions used by the TUI. This is the only import from the scraper module. ```python from scraper import fetch_game_info, download_media, MEDIA_MAPPING ```