├── pyoplm ├── opl │ ├── __init__.py │ ├── pyoplm_manager.py │ ├── games_manager.py │ └── args.py ├── __main__.py ├── __init__.py ├── common.py ├── bintools.py ├── ul.py ├── game.py ├── bchunk.py ├── cue2pops_basic_conversion.py ├── binmerge.py └── storage.py ├── MANIFEST.in ├── requirements.txt ├── setup.cfg ├── readme_pics ├── step1.png ├── step2.png └── step3.png ├── .gitignore ├── Makefile ├── MANIFEST ├── example.pyopl.ini ├── pyproject.toml ├── setup.py ├── README.md ├── .vscode └── launch.json └── LICENSE /pyoplm/opl/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | 2 | recursive-include pyoplm/lib/linux64 * -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pillow==9.4.0 2 | beautifulsoup4==4.12.2 3 | lxml -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | # Inside of setup.cfg 2 | [metadata] 3 | description_file = README.md 4 | -------------------------------------------------------------------------------- /pyoplm/__main__.py: -------------------------------------------------------------------------------- 1 | from pyoplm.opl.args import main_parser as main 2 | 3 | main() 4 | -------------------------------------------------------------------------------- /pyoplm/__init__.py: -------------------------------------------------------------------------------- 1 | name = "pyoplm" 2 | 3 | from pyoplm.opl.args import main_parser as main -------------------------------------------------------------------------------- /readme_pics/step1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edisnord/PyOPLM/HEAD/readme_pics/step1.png -------------------------------------------------------------------------------- /readme_pics/step2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edisnord/PyOPLM/HEAD/readme_pics/step2.png -------------------------------------------------------------------------------- /readme_pics/step3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edisnord/PyOPLM/HEAD/readme_pics/step3.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | *.swp 4 | db 5 | dist 6 | build 7 | pyoplm.egg-info 8 | .vscode/launch.json 9 | .vscode/settings.json 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | default: build 2 | 3 | build: 4 | uv build 5 | 6 | install: 7 | uv pip install --force dist/*.whl 8 | 9 | clean: 10 | rm -rf dist build pyoplm.egg-info/ 11 | 12 | release: 13 | uv publish 14 | -------------------------------------------------------------------------------- /MANIFEST: -------------------------------------------------------------------------------- 1 | # file GENERATED by distutils, do NOT edit 2 | setup.cfg 3 | setup.py 4 | pyoplm/__init__.py 5 | pyoplm/api.py 6 | pyoplm/artwork.py 7 | pyoplm/common.py 8 | pyoplm/game.py 9 | pyoplm/popl.py 10 | pyoplm/ul.py 11 | -------------------------------------------------------------------------------- /example.pyopl.ini: -------------------------------------------------------------------------------- 1 | [STORAGE] 2 | # This is the location of your storage 3 | # Supports local directory paths or URLs for online storages 4 | # Don't forget to add http[s]:// before a web URL 5 | location = http://my.docker.lan 6 | 7 | # Optional, leave in if you want to index all the art files for quick access 8 | # Makes online storages work faster 9 | [STORAGE.INDEXING] 10 | # URL to the internet archive "(View Contents)" results for the zip backup 11 | # Placeholder is the archive to the august 2023 backup 12 | zip_contents_location=https://ia802706.us.archive.org/view_archive.php?archive=/4/items/OPLM_ART_2023_07/OPLM_ART_2023_07.zip -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "pyoplm" 7 | version = "0.71" 8 | description = "Tool To Manage Open-PS2-Loader USB-Drives & Games" 9 | authors = [ 10 | {name = "Nold", email = "nold@gnu.one"}, 11 | {name = "edisnord", email = "edisnord@gmail.com"} 12 | ] 13 | readme = "README.md" 14 | license = "GPL-3.0-or-later" 15 | requires-python = ">=3.10" 16 | dependencies = [ 17 | "pillow>=11.0", 18 | "beautifulsoup4==4.12.2", 19 | "lxml" 20 | ] 21 | classifiers = [ 22 | "Programming Language :: Python :: 3", 23 | "Operating System :: OS Independent" 24 | ] 25 | 26 | [project.urls] 27 | Homepage = "https://github.com/edisnord/pyoplm" 28 | 29 | [project.scripts] 30 | pyoplm = "pyoplm:main" 31 | 32 | # [tool.hatch.build.targets.sdist] 33 | # include = [ 34 | # "pyoplm/lib/linux64/bchunk/*", 35 | # "pyoplm/lib/linux64/binmerge/*", 36 | # "pyoplm/lib/linux64/cue2pops/*", 37 | # "pyoplm/**" 38 | # ] 39 | 40 | # [tool.hatch.build.targets.wheel] 41 | # include = [ 42 | # "pyoplm/lib/linux64/bchunk/*", 43 | # "pyoplm/lib/linux64/binmerge/*", 44 | # "pyoplm/lib/linux64/cue2pops/*", 45 | # "pyoplm/**" 46 | # ] 47 | 48 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="pyoplm", 8 | version="0.62", 9 | author="Nold, edisnord", 10 | author_email="nold@gnu.one, edisnord@gmail.com", 11 | description="Tool To Manage Open-PS2-Loader USB-Drives & Games", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/edisnord/pyoplm", 15 | packages=setuptools.find_packages(), 16 | include_package_data=True, 17 | install_requires=[ 18 | "pillow==9.4.0", 19 | "beautifulsoup4==4.12.2", 20 | "lxml" 21 | ], 22 | package_data={"": ["pyoplm/lib/linux64/bchunk/*"], 23 | "": ["pyoplm/lib/linux64/binmerge/*"], 24 | "": ["pyoplm/lib/linux64/cue2pops/*"]}, 25 | entry_points={ 26 | 'console_scripts': [ 27 | 'pyoplm= pyoplm:main', 28 | ] 29 | }, 30 | classifiers=[ 31 | "Programming Language :: Python :: 3", 32 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 33 | "Operating System :: POSIX :: Linux", 34 | "Environment :: Console" 35 | ], 36 | ) 37 | -------------------------------------------------------------------------------- /pyoplm/opl/pyoplm_manager.py: -------------------------------------------------------------------------------- 1 | from configparser import ConfigParser 2 | from pathlib import Path 3 | import sys 4 | from typing import List 5 | from pyoplm.common import path_to_ul_cfg 6 | from pyoplm.opl.games_manager import GamesManager 7 | 8 | from pyoplm.storage import Storage 9 | from pyoplm.ul import ULConfig 10 | 11 | 12 | class PyOPLManager: 13 | args = None 14 | opl_dir: Path 15 | storage: Storage 16 | games_manager: GamesManager 17 | 18 | def __init__(self, opl_dir: Path): 19 | self.opl_dir = opl_dir 20 | self.games_manager = GamesManager(opl_dir) 21 | self.initialize_storage() 22 | 23 | def initialize_storage(self): 24 | config = ConfigParser() 25 | config.read(str(self.opl_dir.joinpath("pyoplm.ini"))) 26 | self.storage = Storage(config.get("STORAGE", "location", fallback=None), self.opl_dir, config.get( 27 | "STORAGE.INDEXING", "zip_contents_location", fallback=None)) 28 | 29 | def delete(self, region_codes: List[str]): 30 | for code in region_codes: 31 | self.games_manager.delete(code) 32 | 33 | def rename(self, new_title: str | None = None, storage=False, opl_id: str | None = None): 34 | if storage: 35 | if not self.storage.is_enabled(): 36 | print("Proper storage link not supplied in opl_dir/pyoplm.ini,\ 37 | not renaming.", file=sys.stderr) 38 | sys.exit(0) 39 | 40 | if not opl_id and storage: 41 | print("Bulk renaming games from storage...") 42 | for game in self.games_manager.games_dict.values(): 43 | game.rename(self.storage.get_game_title(game.opl_id)) 44 | 45 | elif opl_id and storage: 46 | new_title = self.storage.get_game_title(opl_id) 47 | 48 | try: 49 | self.games_manager.games_dict[opl_id].rename(new_title) 50 | except: 51 | print( 52 | f"Game with region code {opl_id} is not installed.", file=sys.stderr) 53 | sys.exit(1) 54 | 55 | print("Fixing all games just in case...") 56 | self.fix() 57 | 58 | # Add game(s) to args.opl_dir 59 | # - split game if > 4GB / forced 60 | # - otherwise just copy with OPL-like filename 61 | # - If storage features are enabled, try to get title from storage and download artwork 62 | 63 | def add(self, src_files: List[Path], psx=False, iso=False, ul=False, force=False, storage=False): 64 | for game_path in src_files: 65 | game = self.games_manager.add(game_path, psx, iso, ul, force) 66 | 67 | if self.storage.is_enabled() and storage: 68 | self.storage.get_artwork_for_game(game.opl_id, True) 69 | self.rename(storage=True, opl_id=game.opl_id) 70 | 71 | print("Fixing all game titles...") 72 | self.fix() 73 | 74 | # Fix ISO names for faster OPL access 75 | # Delete UL games with missing parts 76 | # Recover UL games which are not in ul.cfg 77 | # Find corrupted entries in ul.cfg first and delete them 78 | def fix(self): 79 | if (ulcfg_file := path_to_ul_cfg(self.opl_dir)).exists(): 80 | ULConfig.find_and_delete_corrupted_entries( 81 | ulcfg_file) 82 | 83 | ulcfg = ULConfig(ulcfg_file) 84 | ulcfg.find_and_recover_games() 85 | 86 | print("Fixing ISO and POPS game file names for OPL read speed and deleting broken UL games") 87 | for game in self.games_manager.games_dict.values(): 88 | if not game.id: 89 | print(f"Error while parsing file: {game.filepath}") 90 | continue 91 | game.fix_if_not_ok() 92 | 93 | # Download all artwork for all games if storage is enabled 94 | 95 | def artwork(self, region_codes: List[str], overwrite): 96 | if self.storage.is_enabled(): 97 | for region_code in region_codes or self.games_manager.games_dict.keys(): 98 | try: 99 | game = self.games_manager.games_dict[region_code] 100 | except KeyError: 101 | print(f"Game with region code {region_code} does not exist, skipping...") 102 | continue 103 | print( 104 | f"Downloading artwork for [{game.opl_id}] {game.title}") 105 | self.storage.get_artwork_for_game( 106 | game.opl_id, bool(overwrite)) 107 | else: 108 | print( 109 | "Storage link not supplied in opl_dir/pyoplm.ini, not downloading artwork.", file=sys.stderr) 110 | sys.exit(0) 111 | 112 | # List all Games on OPL-Drive 113 | def list(self): 114 | self.games_manager.list() 115 | 116 | # Create OPL Folders and empty ul.cfg 117 | def init(self): 118 | print("Inititalizing OPL-Drive...") 119 | for dir in ["APPS", "LNG", "ART", "CD", "CFG", "CHT", "DVD", "THM", "VMC", "POPS"]: 120 | if not (dir := self.opl_dir.joinpath(dir)).is_dir(): 121 | dir.mkdir(0o777) 122 | self.opl_dir.joinpath("ul.cfg").touch(0o777) 123 | print("Done!") 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyOPLM - Python Open PS2 Loader Manager 2 | PyOPLM is a simple, Linux (and Windows using Docker, check [this](https://github.com/edisnord/PyOPLM-smb-docker-setup) repo for a Docker compose setup with a helper PowerShell script), WIP python app to manage games installed in a directory used by [Open PS2 Loader](https://github.com/Jay-Jay-OPL/OPL-Daily-Builds). Supports SMB and USB folders at the moment, hard drive games support is WIP. 3 | 4 | *IMPORTANT*: Only supporting Python version 3.10 and greater at the moment 5 | 6 | ## Features 7 | - Add, remove and rename games in your OPL Directory 8 | - Support for ISO games, UL and POPS games (POPS and PS2 CD bin/cue game install support is only on x86_64 linux) 9 | - Read, write and fix ul.cfg 10 | - List all games on n OPL directory 11 | - init OPL Directory with all needed folders 12 | - Fix game names for all games on drive 13 | - Update game titles and download game art from an online static file storage or local directory 14 | - Comes packaged with Python translations of [bchunk](https://github.com/extramaster/bchunk), [binmerge](https://github.com/putnam/binmerge) and [cue2pops](https://github.com/israpps/cue2pops), making this package officially *cross-platform* (yay!) 15 | 16 | ## Installation 17 | ```bash 18 | pip install pyoplm 19 | ``` 20 | 21 | The latest version is 0.71 (Do not download anything older, this app is under heavy development) 22 | 23 | ## TODO 24 | - CFG file editor, download game data from an open api like RAWG.io 25 | 26 | 27 | ## Artwork and title database 28 | 29 | Due to this being an open source project, a bit of "self hosting" is required to get these features that require storage to work 30 | 31 | In order to have support for artwork downloading and game title fetching, you need to either download one of danielb's [OPLM monthly art database backups](https://oplmanager.com/site/?backups) (i tested this program on [OPLM_ART_2023_07.zip](https://archive.org/download/OPLM_ART_2023_07/OPLM_ART_2023_07.zip)) on your system or host the contents of a ZIP backup in a static file storage server (like Google cloud storage buckets, i like using Google cloud because of te free trails but you can place the files anywhere), and give this program the location where the backup is unzipped, and then you can download artwork and update titles for any installed game on your drive. 32 | 33 | In order to be able to use storage features, you need to create a file named `pyoplm.ini` in your OPL directory, and insert your storage URL in there just like in the file `example.pyoplm.ini` in the root of this repo. 34 | 35 | ### Indexing the zip backups 36 | 37 | This program supports indexing for the zip files, which is a much faster way of downloading art and titles from online storages (for local storages too, but it doesn't make too much of a difference in speed). This is necessary because the types of art a game has on an online storage can only be found out through guessing without the data being indexed, which leads to the non-indexed usage of the storage features being much slower. 38 | 39 | Perform these steps to enable indexing: 40 | 41 | 1. Go to the page of the Archive.org danielb backup you want to use (i'm using the August 2023 backup) and select the `show all` button in the download options. ![step1](readme_pics/step1.png) 42 | 2. Click the `(view content)` button next to the zip file in the list that appears ![step2](readme_pics/step2.png) 43 | 3. Copy the link of the page where you will be redirected to after clicking ![step3](readme_pics/step3.png) 44 | 4. Paste this link to the `zip_contents_location` key of the `[STORAGE.INDEXING]` section of the `pyoplm.ini` file in your OPL drive 45 | ```ini 46 | [STORAGE.INDEXING] 47 | # URL to the internet archive "(View Contents)" results for the zip backup 48 | # Placeholder is the archive to the august 2023 backup 49 | zip_contents_location=https://ia802706.us.archive.org/view_archive.php?archive=/4/items/OPLM_ART_2023_07/OPLM_ART_2023_07.zip 50 | ``` 51 | 5. After running pyoplm, the indexing process will be performed and the results will be stored in the `indexed_storage.db` file in your OPL game directory. This process takes a bit of time but only needs to be performed once 52 | 6. Enjoy 2x+ faster online storage artwork and title download times :) 53 | 54 | ## Usage 55 | 56 | The argument opl_dir is mostly required to be supplid by the commands of this app, but can be avoided by putting your 57 | OPL Directory in an environment variable named PYOPLM_OPL_DIR 58 | 59 | ``` 60 | usage: pyoplm [-h] {list,rename,delete,fix,init,add,storage,bintools} ... 61 | 62 | positional arguments: 63 | {list,rename,delete,fix,init,add,storage,bintools} 64 | Choose your path... 65 | list List Games on OPL-Drive 66 | rename Change the title of the game corresponding to opl_id 67 | to new_title in the given opl_dir 68 | delete Delete game from Drive 69 | fix rename/fix media filenames 70 | init Initialize OPL folder structure 71 | add Add ISO/CUE PS2 and PSX game to opl_dir 72 | storage Art and title storage-related functionality 73 | bintools Tools for processing cue/bin games 74 | 75 | options: 76 | -h, --help show this help message and exit 77 | ``` 78 | 79 | Thank you danielb for the OPL Manager art database backups, great stuff 80 | -------------------------------------------------------------------------------- /pyoplm/common.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ### 3 | # Shared functions 4 | from enum import Enum 5 | import os 6 | from pathlib import Path 7 | 8 | import ctypes 9 | import sys 10 | from typing import List 11 | import unicodedata 12 | import re 13 | 14 | REGION_CODE_REGEX_BYTES = re.compile(rb'[HhMmPpGgNnCcSsJjTtBbDdAaKk][a-zA-Z]{3}.?\d{3}\.?\d{2}') 15 | REGION_CODE_REGEX_STR = re.compile(r'[HhMmPpGgNnCcSsJjTtBbDdAaKk][a-zA-Z]{3}.?\d{3}\.?\d{2}') 16 | 17 | def read_in_chunks(file_object, chunk_size=1024): 18 | """Lazy function (generator) to read a file piece by piece. 19 | Default chunk size: 1k.""" 20 | while True: 21 | data = file_object.read(chunk_size) 22 | if not data: 23 | break 24 | yield data 25 | 26 | 27 | def path_to_ul_cfg(opl_dir: Path) -> Path: 28 | return opl_dir.joinpath('ul.cfg') 29 | 30 | 31 | def get_iso_id(filepath: Path) -> str: 32 | with open(filepath, 'rb') as f: 33 | for chunk in read_in_chunks(f): 34 | id_matches: List[bytes] = REGION_CODE_REGEX_BYTES.findall(chunk) 35 | if id_matches: 36 | return id_matches[0].decode("ascii", "ignore") 37 | raise ValueError(f"Cannot find Game ID for ISO/VCD file '{filepath}'") 38 | 39 | 40 | def ul_files_from_iso(src_iso: Path, dest_path: Path, force=False) -> int: 41 | CHUNK_SIZE = 1073741824 42 | 43 | file_part = 0 44 | with src_iso.open('rb') as f: 45 | chunk = f.read(CHUNK_SIZE) 46 | title = re.sub(r'.[iI][sS][oO]', '', src_iso.name) 47 | 48 | while chunk: 49 | crc32 = hex(usba_crc32(title.encode('ascii')))[2:].upper() 50 | game_id = get_iso_id(src_iso) 51 | part = hex(file_part)[2:4].zfill(2).upper() 52 | 53 | filename = f"ul.{crc32}.{game_id}.{part}" 54 | filepath = dest_path.joinpath(filename) 55 | 56 | if filepath.is_file() and not force: 57 | print( 58 | f"Warn: File '{filename}' already exists! Use -f to force overwrite.") 59 | return 0 60 | 61 | print(f"Writing File '{filepath}'...") 62 | with filepath.open('wb') as outfile: 63 | outfile.write(chunk) 64 | file_part += 1 65 | chunk = f.read(CHUNK_SIZE) 66 | os.chmod(filepath, 0o777) 67 | return file_part 68 | 69 | 70 | 71 | 72 | def slugify(value, allow_unicode=False): 73 | """ 74 | Normalizes string, **DOESN'T** converts to lowercase, removes non-alpha characters, 75 | 76 | Stolen from: https://docs.djangoproject.com/en/2.1/ref/utils/#django.utils.text.slugify 77 | """ 78 | value = str(value) 79 | if allow_unicode: 80 | value = unicodedata.normalize('NFKC', value) 81 | else: 82 | value = unicodedata.normalize('NFKD', value).encode( 83 | 'ascii', 'ignore').decode("ascii", "ignore") 84 | value = re.sub(r'[^\w\s-]', '', value).strip() 85 | return value 86 | 87 | 88 | 89 | class ULCorruptionType(Enum): 90 | REGION_CODE = 1 91 | MEDIA_TYPE = 2 92 | NO_CORRUPTION = 3 93 | 94 | def check_ul_entry_for_corruption_and_crash(data: bytes): 95 | if not check_ul_entry_for_corruption(data): 96 | print( 97 | f"The entry \'{data[0:32].decode('ascii', 'ignore')}\' in ul.cfg is corrupted, run 'fix' on the directory to try automatically fixing the issue'") 98 | sys.exit(1) 99 | 100 | def check_ul_entry_for_corruption(data: bytes) -> ULCorruptionType: 101 | if not REGION_CODE_REGEX_BYTES.findall(bytes(data[32:46])): 102 | return ULCorruptionType.REGION_CODE 103 | if not (bytes([data[48]]) == b"\x12" or bytes([data[48]]) == b"\x14"): 104 | return ULCorruptionType.MEDIA_TYPE 105 | return ULCorruptionType.NO_CORRUPTION 106 | 107 | ''' 108 | 109 | 110 | //Original CRC32-Function from OPL-Sourcecode: 111 | 112 | unsigned int USBA_crc32(char *string) 113 | { 114 | int crc, table, count, byte; 115 | 116 | for (table = 0; table < 256; table++) { 117 | crc = table << 24; 118 | 119 | for (count = 8; count > 0; count--) { 120 | if (crc < 0) 121 | crc = crc << 1; 122 | else 123 | crc = (crc << 1) ^ 0x04C11DB7; 124 | } 125 | crctab[255 - table] = crc; 126 | } 127 | 128 | do { 129 | byte = string[count++]; 130 | crc = crctab[byte ^ ((crc >> 24) & 0xFF)] ^ ((crc << 8) & 0xFFFFFF00); 131 | } while (string[count - 1] != 0); 132 | 133 | return crc; 134 | } 135 | ''' 136 | 137 | 138 | # ^ That function in shitty python 139 | # Generate crc32 from game title for ul.cfg 140 | 141 | def usba_crc32(name: bytes): 142 | name = name.strip(b'\x00') 143 | crctab = [0] * 1024 144 | crc = ctypes.c_int32() 145 | for table in range(0, 256): 146 | crc = (table << 24) 147 | 148 | for i in range(8, 0, -1): 149 | crc = ctypes.c_int32(crc).value 150 | if ((crc)) < 0: 151 | crc = (crc << 1) 152 | else: 153 | crc = (crc << 1) ^ 0x04C11DB7 154 | crctab[255 - table] = ctypes.c_uint32(crc).value 155 | 156 | c = 0 157 | name += b'\x00' 158 | while c < len(name): 159 | crc = ctypes.c_uint32(crctab[name[c] ^ ((crc >> 24) & 0xFF)] 160 | ^ ((crc << 8) & 0xFFFFFF00)).value 161 | c += 1 162 | return ctypes.c_uint32(crc).value 163 | -------------------------------------------------------------------------------- /pyoplm/opl/games_manager.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from pathlib import Path 3 | import re 4 | from shutil import copyfile 5 | import sys 6 | 7 | from collections.abc import Iterator 8 | 9 | from pyoplm.bintools import install_ps2_cue, psx_add 10 | 11 | from ..ul import ULConfig 12 | from ..common import get_iso_id, path_to_ul_cfg 13 | from ..game import Game, ISOGame, ULGame, POPSGame 14 | from itertools import chain 15 | 16 | 17 | class GamesManager(): 18 | games_dict: dict[str, Game] 19 | iso_games: Iterator[ISOGame] 20 | ul_games: Iterator[ULGame] 21 | pops_games: Iterator[POPSGame] 22 | opl_dir: Path 23 | 24 | def __init__(self, opl_dir: Path): 25 | self.opl_dir = opl_dir 26 | self.games_dict = {} 27 | self.__initialize_games() 28 | 29 | def __get_pops_game_files(self) -> Iterator[Path]: 30 | path = self.opl_dir.joinpath("POPS") 31 | return path.glob("*.[vV][cC][dD]") 32 | 33 | def __get_iso_game_files(self) -> Iterator[Path]: 34 | extension_pattern = "*.[iI][sS][oO]" 35 | path1 = self.opl_dir.joinpath("DVD") 36 | path2 = self.opl_dir.joinpath("CD") 37 | return chain(path1.glob(extension_pattern), path2.glob(extension_pattern)) 38 | 39 | def __initialize_games(self): 40 | game_to_files_func = [ 41 | (POPSGame, self.__get_pops_game_files, "pops_games"), 42 | (ISOGame, self.__get_iso_game_files, "iso_games"), 43 | ] 44 | for (game_type, get_files, dest_list) in game_to_files_func: 45 | files = get_files() 46 | games = { 47 | game.opl_id: game 48 | for game in (game_type(file) for file in files) 49 | } 50 | self.games_dict.update(games) 51 | 52 | setattr(self, dest_list, iter(games.values())) 53 | self.__initialize_ul_games() 54 | 55 | def __initialize_ul_games(self) -> None: 56 | if not (ulcfg_file := path_to_ul_cfg(self.opl_dir)).exists(): 57 | self.ul_games = [] 58 | return 59 | 60 | games = { 61 | game_cfg.game.opl_id: game_cfg.game 62 | for game_cfg in ULConfig(ulcfg_file).ulgames.values() 63 | } 64 | self.games_dict.update(games) 65 | self.ul_games = iter(games.values()) 66 | 67 | def list(self) -> None: 68 | games_and_kinds: Dict[str, Iterator[Game]] = { 69 | "ISO": self.iso_games, 70 | "UL": self.ul_games, 71 | "POPS": self.pops_games 72 | } 73 | 74 | found_one = False 75 | for (kind, game_list) in games_and_kinds.items(): 76 | while game := next(iter(game_list), None): 77 | if not found_one: 78 | print(f"|-> {kind} Games:") 79 | found_one = True 80 | print(f" {game}") 81 | found_one = False 82 | 83 | def delete(self, game_id) -> None: 84 | try: 85 | print(f"Deleting game {game_id}...") 86 | self.games_dict[game_id].delete_game(self.opl_dir) 87 | print("Deleted!") 88 | except KeyError: 89 | print( 90 | f"Game with the given region code {game_id} not found", file=sys.stderr) 91 | sys.exit(1) 92 | 93 | # Installs game to OPL directory, returns the Game subclass object representing the added game 94 | def add(self, game_path: Path, psx=False, iso=False, ul=False, force=False) -> Game: 95 | if psx: 96 | print("Installing POPS game...") 97 | if game := psx_add(game_path, self.opl_dir): 98 | return game 99 | else: 100 | print("Error installing game", file=sys.stderr) 101 | 102 | if re.match(r"^.[cC][uU][eE]$", game_path.suffix): 103 | print( 104 | f"Attempting to convert game {game_path} to ISO and install...") 105 | if game := install_ps2_cue(game_path, self.opl_dir): 106 | return game 107 | else: 108 | print("Error installing game", file=sys.stderr) 109 | 110 | iso_id = get_iso_id(game_path) 111 | # Game size in MB 112 | game_size = game_path.stat().st_size / (1024 ** 2) 113 | 114 | if (game_size > 4000 and not iso) or ul: 115 | print("Converting to UL format because game is larger than 4GB") 116 | ul_cfg = ULConfig(path_to_ul_cfg(self.opl_dir)) 117 | if game := ul_cfg.add_game_from_iso(game_path, force).game: 118 | return game 119 | else: 120 | print("Error installing game", file=sys.stderr) 121 | else: 122 | if (iso_id in self.games_dict) and not force: 123 | print( 124 | f"Game with ID \'{iso_id}\' is already installed, skipping...") 125 | print("Use the -f flag to force the installation of this game") 126 | else: 127 | title = game_path.stem 128 | 129 | if len(title) > 32: 130 | print( 131 | f"Game title \'{title}\' is longer than 32 characters, skipping...") 132 | sys.exit(1) 133 | new_game_path: Path = self.opl_dir.joinpath( 134 | "DVD" if game_size > 700 else "CD", 135 | f"{iso_id}.{title}.iso") 136 | 137 | print( 138 | f"Copying game to \'{new_game_path}\', please wait...") 139 | copyfile(game_path, new_game_path) 140 | new_game_path.chmod(0o777) 141 | print("Done!") 142 | 143 | return ISOGame(new_game_path) 144 | sys.exit(0) 145 | -------------------------------------------------------------------------------- /pyoplm/bintools.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | import re 4 | from shutil import move 5 | import subprocess 6 | from collections import namedtuple 7 | from pathlib import Path 8 | import sys 9 | 10 | from pyoplm.game import ISOGame, POPSGame 11 | from pyoplm.bchunk import Args as BChunkArgsCls, main as bchunk_main 12 | from pyoplm.cue2pops_basic_conversion import convert as cue2pops_convert 13 | from pyoplm.binmerge import binmerge as binmerge_run 14 | 15 | BinMergeArgs = namedtuple( 16 | "BinMergeArgs", ["outdir", "license", "split", "cuefile", "basename"]) 17 | Cue2PopsArgs = namedtuple( 18 | "Cue2PopsArgs", ["input_file", "output_file"]) 19 | BChunkArgs = namedtuple("BChunkArgs", ["p", "src_bin", "src_cue", "basename"]) 20 | 21 | def cue2pops(args: Cue2PopsArgs): 22 | cue_path = args.input_file 23 | if not os.path.isfile(cue_path): 24 | print(f"Error: No input file {cue_path}", file=sys.stderr) 25 | return 2 26 | 27 | out_vcd = args.output_file 28 | if out_vcd is None: 29 | root, _ = os.path.splitext(cue_path) 30 | out_vcd = root + ".VCD" 31 | 32 | try: 33 | cue2pops_convert(cue_path, out_vcd, False) 34 | except Exception as e: 35 | print(str(e), file=sys.stderr) 36 | return 1 37 | return 0 38 | 39 | 40 | def bchunk(args: BChunkArgs): 41 | complete = bchunk_main(BChunkArgsCls(binfile=args.src_bin, cuefile=args.src_cue, psxtruncate=args.p, basefile=args.basename)) 42 | return complete 43 | 44 | 45 | def binmerge(args: BinMergeArgs): 46 | complete = binmerge_run(cuefile=args.cuefile, basename=args.basename, license=args.license, verbose=False, split=args.split, outdir=args.outdir) 47 | return complete 48 | 49 | 50 | def install_ps2_cue(cuefile_path: Path, opl_dir: Path) -> ISOGame | None: 51 | if not cuefile_path.exists(): 52 | print(f"File {cuefile_path.as_posix()} does not exist, skipping...") 53 | return 54 | if len(cuefile_path.stem) > 32: 55 | print( 56 | f"The cue file's name will be kept as a game title, please make the filename {cuefile_path.stem} less than 32 characters long", file=sys.stderr) 57 | return 58 | with cuefile_path.open("r") as cue: 59 | if len(binfile := re.findall(r"\"(.*.bin)\"", cue.read())) > 1: 60 | print( 61 | f"The game {cuefile_path.as_posix()} has more than one track, which is not supported for single-iso conversion by bchunk", file=sys.stderr) 62 | return 63 | elif not binfile: 64 | print( 65 | f"Cue file is invalid {cuefile_path.as_posix()} or there are no bin files, skipping...", file=sys.stderr) 66 | return 67 | 68 | os.chdir(cuefile_path.parent) 69 | bchunk_binfile = cuefile_path.parent.joinpath(binfile[0]) 70 | bchunk_exit_code = bchunk(BChunkArgs( 71 | p=None, 72 | src_bin=bchunk_binfile, 73 | src_cue=cuefile_path, 74 | basename=cuefile_path.stem 75 | )) 76 | if bchunk_exit_code != 0: 77 | print(f"Failed to install game {cuefile_path.stem}") 78 | print( 79 | f"Cue2pops finished with exit code: {bchunk_exit_code} for game {cuefile_path}, skipping...", file=sys.stderr) 80 | 81 | finished_conv_path = cuefile_path.with_name( 82 | cuefile_path.stem + "01.iso") 83 | final_path = opl_dir.joinpath("CD", cuefile_path.stem + ".iso") 84 | 85 | move( 86 | finished_conv_path, 87 | final_path 88 | ) 89 | 90 | final_path.chmod(0o777) 91 | 92 | print(f"Successfully installed game {cuefile_path.stem}") 93 | 94 | return ISOGame(final_path) 95 | 96 | 97 | def psx_add(cuefile_path: Path, opl_dir: Path) -> POPSGame | None: 98 | TMP_FILES_NAME = "pyoplm_tmp" 99 | print("Installing PSX game " + cuefile_path.as_posix()) 100 | if len(cuefile_path.stem) > 32: 101 | print( 102 | f"The cue file's name will be kept as a game title, please make the filename {cuefile_path.stem} less than 32 characters long", file=sys.stderr) 103 | return 104 | if not (cuefile_path.exists()): 105 | print( 106 | f"POPS game with path {cuefile_path.as_posix()} doesn't exist, skipping...", file=sys.stderr) 107 | return 108 | 109 | with cuefile_path.open("r") as cue: 110 | filecount = cue.read().count("FILE") 111 | needs_binmerge = filecount > 1 112 | if filecount == 0: 113 | print( 114 | f"Cue file is invalid {cuefile_path.as_posix()} or there are no bin files, skipping...", file=sys.stderr) 115 | return 116 | 117 | if needs_binmerge: 118 | bm_args: BinMergeArgs = BinMergeArgs(cuefile=cuefile_path, 119 | basename=TMP_FILES_NAME, 120 | license=None, 121 | split=None, 122 | outdir="/tmp") 123 | binmerge_exit_code = binmerge(bm_args) 124 | if binmerge_exit_code != 0: 125 | print( 126 | f"Binmerge finished with exit code: {binmerge_exit_code} for game {cuefile_path}, skipping...", file=sys.stderr) 127 | return 128 | 129 | cue2pops_input = cuefile_path if not needs_binmerge else Path( 130 | f"/tmp/{TMP_FILES_NAME}.cue") 131 | cue2pops_output = opl_dir.joinpath( 132 | "POPS", cuefile_path.stem + ".VCD") 133 | cue2pops_args: Cue2PopsArgs = Cue2PopsArgs( 134 | input_file=cue2pops_input, 135 | output_file=cue2pops_output 136 | ) 137 | cue2pops_exit_code = cue2pops(cue2pops_args) 138 | if cue2pops_exit_code != 1: 139 | print( 140 | f"Cue2pops finished with exit code: {cue2pops_exit_code} for game {cuefile_path}, skipping...", file=sys.stderr) 141 | if needs_binmerge: 142 | cue2pops_input.unlink() 143 | cue2pops_input.with_suffix(".bin").unlink() 144 | return 145 | 146 | print( 147 | f"Successfully installed POPS {cuefile_path.stem} game to opl_dir, ") 148 | if needs_binmerge: 149 | cue2pops_input.unlink() 150 | cue2pops_input.with_suffix(".bin").unlink() 151 | 152 | cue2pops_output.chmod(0o777) 153 | 154 | return POPSGame(cue2pops_output) 155 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Run cue2pops on file", 9 | "type": "python", 10 | "request": "launch", 11 | "module": "pyoplm", 12 | "justMyCode": true, 13 | "args": ["bintools", "cue2pops", "~/Downloads/Dynasty Warriors 2 (Europe)/backup.Dynasty Warriors 2 (Europe).cue"] 14 | }, 15 | { 16 | "name": "Run binmerge on file", 17 | "type": "python", 18 | "request": "launch", 19 | "module": "pyoplm", 20 | "justMyCode": true, 21 | "args": ["bintools", "binmerge", "-o", "/tmp" ,"/home/edish/Downloads/Mickey's Wild Adventure (Europe)/Mickey's Wild Adventure (Europe)/Mickey's Wild Adventure (Europe).cue", "Mickey"] 22 | }, 23 | { 24 | "name": "List Games", 25 | "type": "python", 26 | "request": "launch", 27 | "module": "pyoplm", 28 | "justMyCode": true, 29 | "args": [ 30 | "list", 31 | "~/Documents/PS2SMB/" 32 | ] 33 | }, 34 | { 35 | "name": "Delete PES 2013", 36 | "type": "python", 37 | "request": "launch", 38 | "module": "pyoplm", 39 | "justMyCode": true, 40 | "args": [ 41 | "delete", 42 | "~/Documents/PS2SMB/", 43 | "SLES_556.66" 44 | ] 45 | }, 46 | { 47 | "name": "Install PES 2013 as ISO", 48 | "type": "python", 49 | "request": "launch", 50 | "module": "pyoplm", 51 | "justMyCode": true, 52 | "args": [ 53 | "add", 54 | "~/Documents/PS2SMB/", 55 | "~/PES 2013 Pro Evolution Soccer.iso" 56 | ] 57 | }, 58 | { 59 | "name": "Install Shinobi as ISO, update from storage", 60 | "type": "python", 61 | "request": "launch", 62 | "module": "pyoplm", 63 | "justMyCode": true, 64 | "args": [ 65 | "add", 66 | "-s", 67 | "-f", 68 | "~/Documents/PS2SMB/", 69 | "~/SHINOBI.iso" 70 | ] 71 | }, 72 | { 73 | "name": "Install Shinobi as UL, update from storage", 74 | "type": "python", 75 | "request": "launch", 76 | "module": "pyoplm", 77 | "justMyCode": true, 78 | "args": [ 79 | "add", 80 | "-s", 81 | "-f", 82 | "-ul", 83 | "~/Documents/PS2SMB/", 84 | "~/SHINOBI.iso" 85 | ] 86 | }, 87 | { 88 | "name": "Install PES 2013 as UL", 89 | "type": "python", 90 | "request": "launch", 91 | "module": "pyoplm", 92 | "justMyCode": true, 93 | "args": [ 94 | "add", 95 | "--ul", 96 | "~/Documents/PS2SMB/", 97 | "~/PES 2013 Pro Evolution Soccer.iso" 98 | ] 99 | }, 100 | { 101 | "name": "Fix games", 102 | "type": "python", 103 | "request": "launch", 104 | "module": "pyoplm", 105 | "justMyCode": true, 106 | "args": [ 107 | "fix", 108 | "~/Documents/PS2SMB" 109 | ] 110 | }, 111 | { 112 | "name": "Install Crash Bandicoot in USB", 113 | "type": "python", 114 | "request": "launch", 115 | "module": "pyoplm", 116 | "args": [ 117 | "add", 118 | "--ul", 119 | "~/Documents/PS2SMB", 120 | "~/Documents/PS2SMB/CD/SLUS_202.38.Crash Bandicoot TWOC.iso" 121 | ] 122 | }, 123 | { 124 | "name": "Init directory structure on USB", 125 | "type": "python", 126 | "request": "launch", 127 | "module": "pyoplm", 128 | "args": [ 129 | "init", 130 | "~/Documents/PS2SMB" 131 | ] 132 | }, 133 | { 134 | "name": "Download all artwork", 135 | "type": "python", 136 | "request": "launch", 137 | "module": "pyoplm", 138 | "args": [ 139 | "storage", 140 | "artwork", 141 | "-o", 142 | "/home/edish/Documents/PS2SMB" 143 | ] 144 | }, 145 | { 146 | "name": "Download artwork for JAK II", 147 | "type": "python", 148 | "request": "launch", 149 | "module": "pyoplm", 150 | "args": [ 151 | "storage", 152 | "artwork", 153 | "-o", 154 | "/home/edish/Documents/PS2SMB", 155 | "SCUS_972.65" 156 | ] 157 | }, 158 | { 159 | "name": "Bulk rename games to their original name", 160 | "type": "python", 161 | "request": "launch", 162 | "module": "pyoplm", 163 | "args": [ 164 | "storage", 165 | "rename", 166 | "~/Documents/PS2SMB", 167 | "SCES_514.28", 168 | "SCUS_972.65", 169 | "SLES_556.66", 170 | "SLUS_209.46", 171 | "SLUS_212.28", 172 | "SLUS_215.03", 173 | "SLUS_216.21" 174 | ] 175 | }, 176 | { 177 | "name": "Rename JAK II to its original name", 178 | "type": "python", 179 | "request": "launch", 180 | "module": "pyoplm", 181 | "args": [ 182 | "storage", 183 | "rename", 184 | "~/Documents/PS2SMB", 185 | "SCUS_972.65" 186 | ] 187 | }, 188 | { 189 | "name": "Rename God Hand to its original name", 190 | "type": "python", 191 | "request": "launch", 192 | "module": "pyoplm", 193 | "args": [ 194 | "rename", 195 | "~/Documents/PS2SMB", 196 | "SLUS_215.03", 197 | "God Hand" 198 | ] 199 | } 200 | ] 201 | } -------------------------------------------------------------------------------- /pyoplm/ul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # from game import ULGameImage 3 | import math 4 | import re 5 | from enum import Enum 6 | from pathlib import Path 7 | from pyoplm.common import usba_crc32, get_iso_id, ul_files_from_iso\ 8 | , check_ul_entry_for_corruption_and_crash \ 9 | , check_ul_entry_for_corruption, ULCorruptionType 10 | 11 | 12 | 13 | class ULMediaType(Enum): 14 | CD = b'\x12' 15 | DVD = b'\x14' 16 | 17 | # single game in ul.cfg / on filesystem 18 | # ul.cfg is binary 19 | # 64byte per game 20 | 21 | 22 | class ULConfigGame(): 23 | filedir: Path 24 | global REGION_CODE_REGEX 25 | 26 | # Fields in ul.cfg per game (always 64byte) 27 | # 32byte - Title/Name of Game 28 | name: bytes 29 | 30 | # 14byte - region_code is "ul." + OPL_ID (aka ID/Serial of game) 31 | region_code: bytes 32 | 33 | # 1byte - According to USBUtil, "DESC" 34 | unknown: bytes 35 | # 1byte - Number of file chunks / parts 36 | parts: bytes 37 | 38 | # 1byte - media type?! so DVD/CD?... 39 | media: ULMediaType 40 | 41 | # 15byte - According to USBUtil, simply named "Information" 42 | remains: bytes 43 | 44 | # This CRC32-Hash is used for the ul-filenames 45 | # By hashing the "name"-bytes OPL finds the files, 46 | # that belong to a specific game 47 | 48 | # For Game object 49 | 50 | def __init__(self, filedir: Path, data: bytes): 51 | from pyoplm.game import ULGame 52 | self.filedir = filedir 53 | self.name = bytes(data[:32]) 54 | self.crc32: str = hex(usba_crc32(self.name)).capitalize() 55 | self.region_code = bytes(data[32:46]) 56 | self.unknown = bytes([data[46]]) 57 | self.parts = bytes([data[47]]) 58 | self.media = ULMediaType(bytes([data[48]])) 59 | self.remains = bytes(data[49:64]) 60 | 61 | self.opl_id: bytes = self.region_code[3:] 62 | self.game: ULGame = ULGame(ulcfg=self) 63 | 64 | def refresh_crc32(self): 65 | self.crc32 = hex(usba_crc32(self.name)).capitalize() 66 | 67 | # Get binary config data, with padding to 64byte 68 | def get_binary_data(self): 69 | assert self.name 70 | assert self.region_code 71 | assert self.parts 72 | assert self.media 73 | 74 | data = self.name[:32] + \ 75 | self.region_code + self.unknown + self.parts + self.media.value + self.remains 76 | 77 | return data.ljust(64, b'\x00') 78 | 79 | 80 | # ul.cfg handling class 81 | class ULConfig(): 82 | ulgames: dict[bytes, ULConfigGame] = {} 83 | filepath: Path 84 | 85 | # Generate ULconfig using ULGameConfig objects 86 | # Or Read ULConfig from filepath 87 | def __init__(self, filepath: Path): 88 | self.filepath = filepath 89 | if filepath.exists(): 90 | self.read() 91 | else: 92 | filepath.touch(777) 93 | 94 | # Insert game to ULConfig from an ISO file, return ULConfigGame object representing it 95 | def add_game_from_iso(self, src_iso: Path, force: bool, title: bytes|None=None): 96 | if not title: 97 | title = re.sub(r'.[iI][sS][oO]', '', 98 | src_iso.name).encode('ascii') 99 | game_size = src_iso.stat().st_size / 1024 ** 2 100 | 101 | if len(title) > 32: 102 | raise ValueError( 103 | f"Title length for game \'{title}\' is longer than 32 characters") 104 | 105 | title = title.ljust(32, b'\x00') 106 | region_code = ( 107 | b'ul.' + get_iso_id(src_iso).encode('ascii')).ljust(14, b'\x00') 108 | unknown = b'\x00' 109 | parts = chr(math.ceil(game_size * 1024 ** 110 | 2 / 1073741824)).encode('ascii') 111 | media = b'\x12' if src_iso.stat().st_size / 1024 ** 2 <= 700 else b'\x14' 112 | remaining = b'\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 113 | 114 | install_dir = self.filepath.parent 115 | data = title + region_code + unknown + parts + media + remaining 116 | 117 | _ = ul_files_from_iso(src_iso, install_dir, force) 118 | config = ULConfigGame(install_dir, data) 119 | if config.game.check_status(): 120 | self.add_ulgame(region_code, config) 121 | self.write() 122 | return config 123 | else: 124 | raise IOError( 125 | f"Files could not be created for game \'{title.decode('ascii', 'ignore')}\'") 126 | 127 | # Add / Update Game using ul_ID & ULGameConfi/g object 128 | 129 | def add_ulgame(self, ul_id: bytes, ulgame: ULConfigGame): 130 | self.ulgames.update({ul_id: ulgame}) 131 | 132 | # Print debug data 133 | def print_data(self): 134 | print("Filepath: " + str(self.filepath)) 135 | print("ULGames:") 136 | for game in self.ulgames: 137 | print(f" [{str(game)}] {str(self.ulgames[game].name)} ") 138 | 139 | # Read ul.cfg file 140 | def read(self): 141 | with open(self.filepath, 'rb') as data: 142 | game_cfg = data.read(64) 143 | while game_cfg: 144 | check_ul_entry_for_corruption_and_crash(game_cfg) 145 | 146 | game = ULConfigGame( 147 | data=game_cfg, filedir=self.filepath.parent) 148 | self.ulgames.update({game.region_code: game}) 149 | game_cfg = data.read(64) 150 | 151 | # Write back games to ul.cfg 152 | def write(self): 153 | with open(self.filepath, 'wb+') as cfg: 154 | for game in self.ulgames.values(): 155 | _ = cfg.write(game.get_binary_data()) 156 | 157 | self.filepath.chmod(0o777) 158 | 159 | def find_and_recover_games(self): 160 | installed_region_codes = set( 161 | map(lambda part: ".".join(["ul"] + str(part.name).split('.')[2:4]).encode('ascii'), self.filepath.parent.glob("ul.*.*.*") 162 | ) 163 | ) 164 | ul_region_codes: set[bytes] = set(self.ulgames.keys()) 165 | if installed_region_codes == ul_region_codes: 166 | print('Installed UL games correspond ul.cfg games, nothing to recover') 167 | else: 168 | to_recover = installed_region_codes.difference(ul_region_codes) 169 | print( 170 | "These games are installed but they are not part of UL.cfg, recovering...") 171 | for game in to_recover: 172 | part_nr = len(list(self.filepath.parent.glob( 173 | "*"+game.decode("ascii", "ignore").split('.')[1]+"*"))) 174 | 175 | first_part_size = next( 176 | self.filepath.parent.glob( 177 | "*"+".".join(game.decode("ascii", "ignore").split('.')[1:3])+".00") 178 | ).stat().st_size * (1024 ^ 2) 179 | 180 | self.recover_game(game, part_nr, first_part_size) 181 | print(f"Recovered \'{game.decode('ascii', 'ignore')}\'!") 182 | 183 | def recover_game(self, region_code: bytes, parts_nr: int, first_part_size: float, title=b"PLACEHOLDER"): 184 | region_code = region_code.ljust(14, b'\x00') 185 | title = title.ljust(32, b'\x00') 186 | unknown = b'\x00' 187 | parts = chr(parts_nr).encode("ascii") 188 | media = b'\x12' if first_part_size < 700 else b'\x14' 189 | remaining = b'\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 190 | 191 | data = title + region_code + unknown + parts + media + remaining 192 | 193 | crc32 = hex(usba_crc32(title))[2:].upper() 194 | to_rename = self.filepath.parent.glob( 195 | "*"+str(region_code).split(".")[1]+"*") 196 | for file in to_rename: 197 | file_parts = file.name.split(".") 198 | new_filename = ".".join( 199 | [file_parts[0], crc32, file_parts[2], file_parts[3], file_parts[4]]) 200 | _ = file.rename(self.filepath.parent.joinpath(new_filename)) 201 | 202 | self.add_ulgame(region_code, ULConfigGame(self.filepath.parent, data)) 203 | 204 | self.write() 205 | 206 | def rename_game(self, game_id: str, new_title: str): 207 | game_id_b = b"ul." + game_id.encode("ascii") 208 | game_to_rename = self.ulgames[game_id_b] 209 | game_to_rename.name = new_title.encode("ascii").ljust(32, b'\x00') 210 | 211 | crc32 = hex(usba_crc32(new_title.encode("ascii")))[2:].upper() 212 | for file in game_to_rename.game.get_filenames(): 213 | file_parts = file.name.split(".") 214 | new_filename = ".".join([file_parts[0], crc32, file_parts[2], file_parts[3], file_parts[4]]) 215 | _ = file.rename(self.filepath.parent.joinpath(new_filename)) 216 | 217 | game_to_rename.refresh_crc32() 218 | 219 | self.write() 220 | 221 | @staticmethod 222 | def find_and_delete_corrupted_entries(filepath: Path): 223 | final_file: bytes = b"" 224 | 225 | with filepath.open("rb") as data: 226 | game_cfg = data.read(64) 227 | while game_cfg: 228 | if len(game_cfg) < 64: 229 | game_cfg = data.read(64) 230 | continue 231 | corruption_type = check_ul_entry_for_corruption(game_cfg) 232 | if corruption_type == ULCorruptionType.REGION_CODE or corruption_type == ULCorruptionType.MEDIA_TYPE: 233 | print(f"The game with the title \'{game_cfg[0:32].decode('ascii', 'ignore')}\' is corrupted, recovering UL entry and renaming to 'PLACEHOLDER'") 234 | pass 235 | elif corruption_type == ULCorruptionType.NO_CORRUPTION: 236 | final_file += game_cfg 237 | 238 | game_cfg = data.read(64) 239 | 240 | _ = filepath.write_bytes(final_file) 241 | 242 | -------------------------------------------------------------------------------- /pyoplm/opl/args.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import sys 4 | 5 | from pyoplm.opl.pyoplm_manager import PyOPLManager 6 | from pyoplm.bintools import bchunk, BChunkArgs, cue2pops, Cue2PopsArgs, binmerge, BinMergeArgs 7 | 8 | from pathlib import Path 9 | from functools import reduce 10 | from enum import Enum 11 | 12 | 13 | class SubparserKind(Enum): 14 | BINTOOLS = 0 15 | OPLM = 1 16 | 17 | 18 | class OPLMCommand: 19 | LIST = 0 20 | ADD = 1 21 | ST_ARTWORK = 2 22 | ST_RENAME = 3 23 | RENAME = 4 24 | FIX = 5 25 | INIT = 6 26 | DELETE = 7 27 | 28 | 29 | class BinToolsCommand: 30 | BCHUNK = 0 31 | CUE2POPS = 1 32 | BINMERGE = 2 33 | 34 | 35 | def handle_oplm_commands(opl_dir: Path, cmd: OPLMCommand, **kwargs): 36 | opl = PyOPLManager(opl_dir) 37 | if cmd == OPLMCommand.LIST: 38 | opl.list() 39 | elif cmd == OPLMCommand.ADD: 40 | opl.add(**kwargs) 41 | elif cmd == OPLMCommand.RENAME: 42 | opl.rename(**kwargs) 43 | elif cmd == OPLMCommand.FIX: 44 | opl.fix() 45 | elif cmd == OPLMCommand.INIT: 46 | opl.init() 47 | elif cmd == OPLMCommand.DELETE: 48 | opl.delete(**kwargs) 49 | elif cmd == OPLMCommand.ST_RENAME: 50 | opl.rename(**kwargs, storage=True) 51 | elif cmd == OPLMCommand.ST_ARTWORK: 52 | opl.artwork(**kwargs) 53 | 54 | 55 | def handle_bintools_commands(cmd: BinToolsCommand, **kwargs): 56 | if cmd == BinToolsCommand.BCHUNK: 57 | sys.exit( 58 | bchunk( 59 | BChunkArgs( 60 | src_bin=kwargs["src_bin"], 61 | src_cue=kwargs["src_cue"], 62 | basename=kwargs["basename"], 63 | p=kwargs["p"]))) 64 | elif cmd == BinToolsCommand.CUE2POPS: 65 | sys.exit( 66 | cue2pops( 67 | Cue2PopsArgs( 68 | input_file=kwargs["input_file"], 69 | output_file=kwargs["output_file"]))) 70 | elif cmd == BinToolsCommand.BINMERGE: 71 | sys.exit( 72 | binmerge( 73 | BinMergeArgs( 74 | outdir=kwargs["outdir"], 75 | license=kwargs["license"], 76 | split=kwargs["split"], 77 | cuefile=kwargs["cuefile"], 78 | basename=kwargs["basename"]))) 79 | 80 | 81 | def add_parser(subparsers): 82 | parser = subparsers.add_parser( 83 | "add", help="Add ISO/CUE PS2 and PSX game to opl_dir") 84 | parser.add_argument( 85 | "--force", "-f", help="Force overwriting of existing files", action='store_true', default=False) 86 | parser.add_argument( 87 | "--psx", "-p", help="Install PSX games", action="store_true") 88 | parser.add_argument( 89 | "--ul", "-u", help="Force UL-Game converting", action="store_true") 90 | parser.add_argument( 91 | "--iso", "-i", help="Don't do UL conversion", action="store_true") 92 | parser.add_argument( 93 | "--storage", "-s", help="Get title and artwork from storage if it's enabled", action="store_true") 94 | parser.add_argument( 95 | "opl_dir", help="Path to your OPL directory", 96 | type=Path, nargs="?") 97 | parser.add_argument("src_files", nargs="+", 98 | help="Game files to install", 99 | type=Path) 100 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.ADD) 101 | return subparsers 102 | 103 | 104 | def list_parser(subparsers): 105 | parser = subparsers.add_parser("list", help="List Games on OPL-Drive") 106 | parser.add_argument( 107 | "opl_dir", help="Path to your OPL directory", 108 | type=Path, nargs="?") 109 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.LIST) 110 | return subparsers 111 | 112 | 113 | def fix_parser(subparsers): 114 | parser = subparsers.add_parser( 115 | "fix", help="rename/fix media filenames") 116 | parser.add_argument( 117 | "opl_dir", help="Path to your OPL directory", 118 | type=Path, nargs="?") 119 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.FIX) 120 | return subparsers 121 | 122 | 123 | def rename_parser(subparsers): 124 | parser = subparsers.add_parser( 125 | "rename", help="Change the title of the game corresponding to opl_id to new_title in the given opl_dir" 126 | ) 127 | parser.add_argument( 128 | "opl_dir", help="Path to your OPL directory", 129 | type=Path, nargs="?") 130 | parser.add_argument("opl_id", 131 | help="OPL-ID of Media/ISO File to delete") 132 | parser.add_argument("new_title", 133 | help="New title for the game") 134 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.RENAME) 135 | return subparsers 136 | 137 | 138 | def init_parser(subparsers): 139 | parser = subparsers.add_parser( 140 | "init", help="Initialize OPL folder structure") 141 | parser.add_argument( 142 | "opl_dir", help="Path to your OPL USB or SMB Directory\nExample: /media/usb", 143 | type=Path, nargs="?") 144 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.INIT) 145 | return subparsers 146 | 147 | 148 | def delete_parser(subparsers): 149 | parser = subparsers.add_parser("delete", help="Delete game from Drive") 150 | parser.add_argument( 151 | "opl_dir", help="Path to your OPL directory", 152 | type=Path, nargs="?") 153 | parser.add_argument("region_codes", nargs="+", 154 | help="Region codes/OPL IDs of games to delete") 155 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.DELETE) 156 | return subparsers 157 | 158 | 159 | def storage_parser(subparsers): 160 | def artwork_parser(subparsers): 161 | parser = subparsers.add_parser( 162 | "artwork", help="Download artwork for games installed in opl_dir,\ 163 | if no opl_id are supplied it downloads artwork for all games" 164 | ) 165 | parser.add_argument( 166 | "opl_dir", help="Path to your OPL directory", 167 | type=Path, nargs="?") 168 | parser.add_argument( 169 | "--overwrite", "-o", help="Overwrite existing art files for games", action="store_true") 170 | parser.add_argument("region_codes", help="Region codes/OPL IDs of games to download artwork for", nargs="*" 171 | ) 172 | parser.set_defaults(kind=SubparserKind.OPLM, 173 | cmd=OPLMCommand.ST_ARTWORK) 174 | return subparsers 175 | 176 | def rename_parser(subparsers): 177 | parser = subparsers.add_parser( 178 | "rename", help="Rename the game opl_id with a name taken from the storage,\ 179 | if no opl_id are supplied it renames all games" 180 | ) 181 | parser.add_argument( 182 | "opl_dir", help="Path to your OPL directory", 183 | type=Path, nargs="?") 184 | parser.add_argument("opl_id", 185 | help="OPL-ID of game to rename", 186 | nargs="?") 187 | parser.set_defaults(kind=SubparserKind.OPLM, cmd=OPLMCommand.ST_RENAME) 188 | return subparsers 189 | 190 | storage_parser = subparsers.add_parser( 191 | "storage", help="Art and title storage-related functionality" 192 | ) 193 | storage_subparsers = storage_parser.add_subparsers( 194 | help="Choose your path...") 195 | 196 | reduce(lambda x, y: y(x), [rename_parser, 197 | artwork_parser], storage_subparsers) 198 | 199 | return subparsers 200 | 201 | 202 | def bintools_parser(subparsers): 203 | def bchunk_parser(subparsers): 204 | parser = subparsers.add_parser( 205 | "bin2iso", help="Bin to ISO conversion (uses bchunk, repo: https://github.com/extramaster/bchunk)") 206 | parser.add_argument( 207 | "-p", help=" PSX mode for MODE2/2352: write 2336 bytes from offset 24", action="store_true") 208 | parser.add_argument("src_bin", help="BIN file to convert") 209 | parser.add_argument("src_cue", help="CUE file related to image.bin") 210 | parser.add_argument( 211 | "basename", help="name (without extension) for your new bin/cue files") 212 | parser.set_defaults(kind=SubparserKind.BINTOOLS, 213 | cmd=BinToolsCommand.BCHUNK) 214 | return subparsers 215 | 216 | def binmerge_parser(subparsers): 217 | parser = subparsers.add_parser( 218 | "binmerge", help="Merge multibin/cue into a single bin/cue (uses binmerge, repo: https://github.com/putnam/binmerge)") 219 | parser.add_argument( 220 | "--outdir", "-o", help="output directory. defaults to the same directory as source cue.directory will be created (recursively) if needed.") 221 | parser.add_argument( 222 | "--license", "-l", action="store_true", help="prints license info and exit") 223 | parser.add_argument("--split", "-s", action="store_true", 224 | help="reverses operation, splitting merged files back to individual tracks") 225 | parser.add_argument( 226 | "cuefile", type=Path, help="CUE file pointing to bin files (bin files are expected in the same dir)") 227 | parser.add_argument( 228 | "basename", help="name (without extension) for your new bin/cue files") 229 | parser.set_defaults(kind=SubparserKind.BINTOOLS, 230 | cmd=BinToolsCommand.BINMERGE) 231 | return subparsers 232 | 233 | def cue2pops_parser(subparsers): 234 | cue2pops_parser = subparsers.add_parser( 235 | "cue2pops", help="Turn single cue/bin files into VCD format readable by POPSTARTER (uses a simple Python translation cue2pops-linux, repo: https://github.com/tallero/cue2pops-linux).") 236 | cue2pops_parser.add_argument( 237 | "input_file", type=Path, help="Input cue file") 238 | cue2pops_parser.add_argument( 239 | "output_file", help="output file", nargs="?") 240 | parser.set_defaults(kind=SubparserKind.BINTOOLS, 241 | cmd=BinToolsCommand.CUE2POPS) 242 | return subparsers 243 | 244 | parser = subparsers.add_parser( 245 | "bintools", help="Tools for processing cue/bin games") 246 | subparsers = parser.add_subparsers(help="Choose your path...") 247 | 248 | reduce(lambda x, y: y(x) 249 | , [cue2pops_parser, bchunk_parser, binmerge_parser] 250 | , subparsers) 251 | 252 | return subparsers 253 | 254 | 255 | def main_parser(): 256 | parser = argparse.ArgumentParser() 257 | parser.prog = "pyoplm" 258 | 259 | subparsers = parser.add_subparsers(help="Choose your path...") 260 | parser_list = [list_parser, rename_parser, delete_parser, 261 | fix_parser, init_parser, add_parser, storage_parser, bintools_parser] 262 | 263 | # Attach all parsers to the subparsers object 264 | subparsers = reduce(lambda x, y: y(x), parser_list, subparsers) 265 | 266 | arguments = parser.parse_args() 267 | args = vars(arguments) 268 | kind = args.pop("kind", None) 269 | 270 | if hasattr(arguments, "opl_dir") and arguments.opl_dir: 271 | opl_dir = arguments.opl_dir 272 | elif kind == SubparserKind.BINTOOLS: 273 | pass 274 | else: 275 | try: 276 | opl_dir = Path(os.environ["PYOPLM_OPL_DIR"]) 277 | except KeyError: 278 | print("The argument opl_dir must be supplied either as a command line argument or as an environment variable named 'PYOPLM_OPL_DIR.'", file=sys.stderr) 279 | sys.exit(1) 280 | 281 | if not kind == SubparserKind.BINTOOLS: 282 | if not opl_dir.exists() or not opl_dir.is_dir(): 283 | print("Error: opl_dir directory doesn't exist!") 284 | sys.exit(1) 285 | 286 | if len(sys.argv) == 1: 287 | parser.print_help(sys.stderr) 288 | sys.exit(1) 289 | 290 | if kind == SubparserKind.OPLM: 291 | args.pop("opl_dir", None) 292 | handle_oplm_commands(opl_dir, **args) 293 | elif kind == SubparserKind.BINTOOLS: 294 | if len(sys.argv) == 2: 295 | parser.print_help() 296 | sys.exit(1) 297 | handle_bintools_commands(**args) 298 | 299 | sys.exit(0) 300 | -------------------------------------------------------------------------------- /pyoplm/game.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ### 3 | # Game Class 4 | # 5 | from functools import reduce 6 | from pathlib import Path 7 | import sys 8 | from pyoplm.common import REGION_CODE_REGEX_BYTES, get_iso_id, REGION_CODE_REGEX_STR 9 | from abc import ABC, abstractmethod 10 | 11 | import re 12 | from typing import List 13 | from enum import Enum 14 | from os import path 15 | 16 | 17 | class GameFormat(Enum): 18 | UL = "UL (USBExtreme)" 19 | ISO = "ISO" 20 | POPS = "VCD" 21 | 22 | 23 | class Game(ABC): 24 | # constant values for gametypes 25 | game_format: GameFormat 26 | global REGION_CODE_REGEX_BYTES 27 | 28 | GameStatus = Enum('GameStatuses', ['OK']) 29 | 30 | filedir: Path 31 | filename: str 32 | filetype: str 33 | filepath: Path 34 | id: str 35 | opl_id: str 36 | title: str 37 | size: float 38 | proper_filename_regex = re.compile( 39 | r"^[HhMmPpGgNnCcSsJjTtBbDdAaKk][a-zA-Z]{3}.?\d{3}\.?\d{2}\..{1,32}\.([iI][sS][oO]|[vV][cC][dD])$") 40 | 41 | def __init__(self, filepath: Path): 42 | self.filepath = filepath 43 | self.filename = self.filepath.name 44 | self.filedir = self.filepath.parent 45 | 46 | def __repr__(self): 47 | return f"""\n---------------------------------------- 48 | LANG=en_US.UTF-8 49 | Region code: {self.opl_id} 50 | Size (MB): {self.size} 51 | New Title: {self.title} 52 | Filename: {self.filename} 53 | 54 | Filetype: {self.filetype} 55 | Filedir: {self.filedir} 56 | Type: {self.game_format.value} 57 | ID: {self.id} 58 | Filepath: {self.filepath} 59 | """ 60 | 61 | def __str__(self): 62 | return f"[{self.opl_id}] {self.title}" 63 | 64 | def print_data(self): 65 | print(repr(self)) 66 | 67 | # Generate Serial/ID in OPL Format 68 | def gen_opl_id(self): 69 | oplid = self.id.replace('-', '_') 70 | oplid = oplid.replace('.', '') 71 | try: 72 | oplid = oplid[:8] + "." + oplid[8:] 73 | except: 74 | oplid = None 75 | self.opl_id = oplid 76 | 77 | @abstractmethod 78 | def check_status(self) -> GameStatus: 79 | return self.GameStatus.OK 80 | 81 | @abstractmethod 82 | def rename(self, new_title: str) -> None: 83 | pass 84 | 85 | def fix_if_not_ok(self): 86 | if not (status := self.check_status()): 87 | self.fix_issues(status) 88 | 89 | @abstractmethod 90 | def fix_issues(self, status: GameStatus): 91 | pass 92 | 93 | @abstractmethod 94 | def delete_game(self, opl_dir: Path): 95 | for directory in ["ART", "CFG", "CHT", "VMC"]: 96 | for file in opl_dir.joinpath(directory).glob(f"{self.id}*"): 97 | file.unlink() 98 | 99 | #### 100 | # UL-Format game, child-class of "Game" 101 | 102 | 103 | class ULGame(Game): 104 | # ULConfigGame object 105 | from pyoplm.ul import ULConfigGame, ULConfig 106 | ulcfg: ULConfigGame 107 | filenames: List[Path] 108 | size: float 109 | type: GameFormat = GameFormat.UL 110 | GameStatus = Enum("GameStatus", ["FILE_NOT_EXIST", "OK"]) 111 | crc32: str 112 | 113 | global REGION_CODE_REGEX_STR 114 | 115 | # Chunk size matched USBUtil 116 | CHUNK_SIZE = 1073741824 117 | 118 | # Generate ULGameImage from ulcfg 119 | def __init__(self, ulcfg: ULConfigGame): 120 | self.ulcfg = ulcfg 121 | self.opl_id = self.ulcfg.region_code.replace( 122 | b'ul.', b'').decode('utf-8') 123 | self.id = self.opl_id 124 | self.title = self.ulcfg.name.decode('utf-8') 125 | self.crc32 = self.ulcfg.crc32 126 | self.filenames = self.get_filenames() 127 | self.size = self.get_size() 128 | 129 | def rename(self, new_title: str) -> None: 130 | self.ulcfg.parent_cfg.rename_game(self.opl_id, new_title) 131 | print( 132 | f"The game \'{self.opl_id}\' was renamed to \'{new_title}\'") 133 | 134 | def get_filenames(self): 135 | if hasattr(self, "filenames"): 136 | return self.filenames 137 | else: 138 | crc32 = self.crc32[2:].upper().zfill(8) 139 | def part_format(part): return hex(part)[2:4].zfill(2).upper() 140 | 141 | self.filenames = [self.ulcfg.filedir.joinpath( 142 | f"ul.{crc32}.{self.id}.{part_format(part)}") 143 | for part in range(0, int(self.ulcfg.parts[0]))] 144 | return self.filenames 145 | 146 | def get_size(self): 147 | if hasattr(self, "size"): 148 | return self.size 149 | else: 150 | self.size = reduce(lambda x, y: x + y.stat().st_size / (1024 ^ 2), 151 | self.get_filenames(), 0) 152 | return self.size 153 | 154 | def check_status(self) -> GameStatus: 155 | for file in self.get_filenames(): 156 | if not file.exists(): 157 | return self.GameStatus.FILE_NOT_EXIST 158 | return self.GameStatus.OK 159 | 160 | def fix_issues(self, status: GameStatus): 161 | if status == self.GameStatus.FILE_NOT_EXIST: 162 | print(f"UL Game {self.opl_id} is missing a part. Deleting broken game...") 163 | self.delete_game(self.ulcfg.filedir) 164 | else: 165 | pass 166 | 167 | def delete_game(self, opl_dir: Path) -> None: 168 | print("Deleting game chunks...") 169 | for file in self.get_filenames(): 170 | file.unlink() 171 | print("Done!") 172 | print("Adjusting ul.cfg...") 173 | self.ulcfg.parent_cfg.ulgames.pop(self.ulcfg.region_code) 174 | self.ulcfg.parent_cfg.write() 175 | if not len(self.ulcfg.parent_cfg.ulgames): 176 | print("No more games left, deleting ul.cfg...") 177 | self.ulcfg.parent_cfg.filepath.unlink() 178 | super().delete_game(opl_dir) 179 | 180 | def __repr__(self): 181 | return f"""\n---------------------------------------- 182 | LANG=en_US.UTF-8 183 | Region Code: {self.opl_id} 184 | Size (MB): {self.size} 185 | Title: {self.title} 186 | 187 | Game type: UL 188 | Game dir: {self.filedir} 189 | CRC32: {self.crc32} 190 | ID: {self.id} 191 | Filepath: {self.filepath} 192 | """ 193 | 194 | #### 195 | # Class for ISO-Games (or alike), child-class of "Game" 196 | 197 | 198 | class ISOGame(Game): 199 | GameStatus = Enum("GameStatus", ["WRONG_FILENAME", "OK"]) 200 | # Create Game based on filepath 201 | 202 | def __init__(self, filepath): 203 | self.game_format = GameFormat.ISO 204 | self.filetype = "ISO" 205 | super().__init__(filepath) 206 | self.get_filedata() 207 | 208 | def check_status(self) -> GameStatus: 209 | if not self.proper_filename_regex.findall(self.filename): 210 | return self.GameStatus.WRONG_FILENAME 211 | else: 212 | return self.GameStatus.OK 213 | 214 | def rename(self, new_title: str) -> None: 215 | if len(new_title) > 32: 216 | print(f"Title {new_title} is too long!", 217 | file=sys.stderr) 218 | print( 219 | "Titles longer than 32 characters are not permitted!", file=sys.stderr) 220 | print(f"Skipping {self.opl_id}...", file=sys.stderr) 221 | return 222 | 223 | new_filename = f"{self.opl_id}.{new_title}.{self.filetype}" 224 | new_filepath = self.filepath.parent.joinpath( 225 | new_filename 226 | ) 227 | self.filepath = self.filepath.rename(new_filepath) 228 | 229 | new_filepath.chmod(0o777) 230 | 231 | self.title = new_title 232 | print( 233 | f"The game \'{self.opl_id}\' was renamed to \'{self.title}\'") 234 | 235 | 236 | def fix_issues(self, status: GameStatus) -> None: 237 | if status == self.GameStatus.WRONG_FILENAME: 238 | print(f"Fixing '{self.filename}'...") 239 | self.filepath = self.filepath.rename( 240 | self.filedir.joinpath(f"{self.opl_id}.{self.title}.{self.filetype}") 241 | ) 242 | 243 | self.filepath.chmod(0o777) 244 | self.filename = self.filepath.name 245 | self.gen_opl_id() 246 | self.print_data() 247 | elif status == self.GameStatus.OK: 248 | pass # No action needed 249 | 250 | 251 | # Get data from filename 252 | def get_filedata(self) -> None: 253 | # try to get id out of filename 254 | if (res := REGION_CODE_REGEX_STR.findall(self.filename)): 255 | self.id = res[0] 256 | else: 257 | self.id = get_iso_id(self.filepath) 258 | 259 | if not self.id: 260 | return 261 | 262 | self.gen_opl_id() 263 | self.size = self.filepath.stat().st_size / (1024 ^ 2) 264 | 265 | self.title = REGION_CODE_REGEX_STR.sub('', self.filename) 266 | self.title = re.sub(r".[iI][sS][oO]", "", self.title) 267 | self.title = self.title.strip('._- ') 268 | self.filename = re.sub(r".[iI][sS][oO]", "", self.filename) 269 | 270 | def delete_game(self, opl_dir: Path): 271 | print("Deleting ISO file...") 272 | self.filepath.unlink() 273 | print("Done!") 274 | super().delete_game(opl_dir) 275 | 276 | 277 | class POPSGame(Game): 278 | REGION_CODE_OFFSET = 1086272 279 | GameStatus = Enum("GameStatus", ["WRONG_FILENAME", "OK"]) 280 | 281 | def __init__(self, filepath: Path): 282 | super().__init__(filepath) 283 | self.size = self.filepath.stat().st_size / (1024 ^ 2) 284 | self.filetype = "VCD" 285 | self.game_format = GameFormat.POPS 286 | self.id = get_iso_id(filepath) 287 | self.gen_opl_id() 288 | self.get_title_from_filename() 289 | 290 | def delete_game(self, opl_dir: Path): 291 | from shutil import rmtree 292 | print("Deleting VCD file...") 293 | self.filepath.unlink() 294 | print("Done!") 295 | if self.filedir.joinpath(self.filename[:-4]).exists(): 296 | print("Deleting memory cards and cheats...") 297 | rmtree(self.filedir.joinpath(self.filename[:-4])) 298 | print("Done!") 299 | super().delete_game(opl_dir) 300 | 301 | def get_title_from_filename(self): 302 | self.title = REGION_CODE_REGEX_STR.sub('', self.filename) 303 | self.title = re.sub(r".[vV][cC][dD]", "", self.title) 304 | self.title = self.title.strip('._- ') 305 | 306 | def get_id_from_file(self): 307 | with self.filepath.open('rb') as vcd: 308 | vcd.seek(self.REGION_CODE_OFFSET) 309 | region_code = vcd.read(10) 310 | self.id = (region_code[:8] + b'.' + 311 | region_code[8:]).decode('ascii') 312 | 313 | def check_status(self) -> GameStatus: 314 | if not self.proper_filename_regex.findall(self.filename): 315 | return self.GameStatus.WRONG_FILENAME 316 | else: 317 | return self.GameStatus.OK 318 | 319 | 320 | def fix_issues(self, status: GameStatus) -> None: 321 | if status == self.GameStatus.WRONG_FILENAME: 322 | print(f"Fixing \'{self.filename}\'...") 323 | self.filepath = self.filepath.rename( 324 | self.filedir.joinpath( 325 | f"{self.opl_id}.{self.title}.{self.filetype}") 326 | ) 327 | 328 | pops_data_folder = self.filedir.joinpath( 329 | self.filepath.stem) 330 | if pops_data_folder.exists(): 331 | self.filedir.joinpath(self.filepath.stem).rename( 332 | self.filedir.joinpath( 333 | f"{self.opl_id}.{self.title}") 334 | ) 335 | 336 | self.filepath.chmod(0o777) 337 | self.filename = self.filepath.name 338 | self.gen_opl_id() 339 | self.print_data() 340 | elif status == self.GameStatus.OK: 341 | pass 342 | 343 | 344 | def rename(self, new_title: str) -> None: 345 | if len(new_title) > 32: 346 | print(f"Title {new_title} is too long!", 347 | file=sys.stderr) 348 | print( 349 | "Titles longer than 32 characters are not permitted!", file=sys.stderr) 350 | print(f"Skipping {self.opl_id}...", file=sys.stderr) 351 | return 352 | 353 | new_filename = f"{self.opl_id}.{new_title}.{self.filetype}" 354 | new_filepath = self.filepath.parent.joinpath( 355 | new_filename 356 | ) 357 | self.filepath = self.filepath.rename(new_filepath) 358 | 359 | new_filepath.chmod(0o777) 360 | 361 | self.title = new_title 362 | print( 363 | f"The game \'{self.opl_id}\' was renamed to \'{self.title}\'") 364 | -------------------------------------------------------------------------------- /pyoplm/bchunk.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import getopt 3 | import os 4 | import struct 5 | 6 | VERSION = "1.2.1" 7 | USAGE = ( 8 | "Usage: bchunk [-v] [-r] [-p (PSX)] [-w (wav)] [-s (swabaudio)]\n" 9 | " \n" 10 | "Example: bchunk foo.bin foo.cue foo\n" 11 | " -v Verbose mode\n" 12 | " -r Raw mode for MODE2/2352: write all 2352 bytes from offset 0 (VCD/MPEG)\n" 13 | " -p PSX mode for MODE2/2352: write 2336 bytes from offset 24\n" 14 | " (default MODE2/2352 mode writes 2048 bytes from offset 24)\n" 15 | " -w Output audio files in WAV format\n" 16 | " -s swabaudio: swap byte order in audio tracks\n" 17 | ) 18 | 19 | VERSTR = ( 20 | "binchunker for Windows, version " + VERSION + " by ...\n" 21 | "\tBased upon work by Heikki Hannikainen \n" 22 | "\tReleased under the GNU GPL, version 2 or later (at your option).\n\n" 23 | ) 24 | 25 | CUELLEN = 1024 26 | SECTLEN = 2352 27 | 28 | WAV_RIFF_HLEN = 12 29 | WAV_FORMAT_HLEN = 24 30 | WAV_DATA_HLEN = 8 31 | WAV_HEADER_LEN = WAV_RIFF_HLEN + WAV_FORMAT_HLEN + WAV_DATA_HLEN 32 | 33 | class Args: 34 | def __init__(self, basefile=None, binfile=None, cuefile=None, 35 | verbose=0, psxtruncate=0, raw=0, swabaudio=0, towav=0): 36 | self.basefile = basefile 37 | self.binfile = binfile 38 | self.cuefile = cuefile 39 | self.verbose = verbose 40 | self.psxtruncate = psxtruncate 41 | self.raw = raw 42 | self.swabaudio = swabaudio 43 | self.towav = towav 44 | 45 | class Track: 46 | def __init__(self): 47 | self.num = 0 48 | self.mode = 0 49 | self.audio = 0 50 | self.modes = "" 51 | self.extension = None 52 | self.bstart = -1 53 | self.bsize = -1 54 | self.startsect = -1 55 | self.stopsect = -1 56 | self.start = -1 57 | self.stop = -1 58 | 59 | 60 | def parse_args(argv) -> Args: 61 | args_obj = Args() 62 | 63 | try: 64 | opts, args = getopt.getopt(argv[1:], "swvp?hr") 65 | except getopt.GetoptError as e: 66 | sys.stderr.write(str(e) + "\n") 67 | sys.stderr.write(USAGE) 68 | sys.exit(1) 69 | 70 | for opt, _ in opts: 71 | if opt == "-r": 72 | args_obj.raw = 1 73 | elif opt == "-v": 74 | args_obj.verbose = 1 75 | elif opt == "-w": 76 | args_obj.towav = 1 77 | elif opt == "-p": 78 | args_obj.psxtruncate = 1 79 | elif opt == "-s": 80 | args_obj.swabaudio = 1 81 | elif opt in ("-?", "-h"): 82 | sys.stderr.write(USAGE) 83 | sys.exit(0) 84 | 85 | if len(args) != 3: 86 | sys.stderr.write(USAGE) 87 | sys.exit(1) 88 | 89 | args_obj.binfile, args_obj.cuefile, args_obj.basefile = args[0], args[1], args[2] 90 | return args_obj 91 | 92 | def time2frames(s): 93 | """Convert MM:SS:FF time string to frame number.""" 94 | parts = s.strip().split(":") 95 | if len(parts) != 3: 96 | return -1 97 | try: 98 | mins = int(parts[0]) 99 | secs = int(parts[1]) 100 | frames = int(parts[2]) 101 | except ValueError: 102 | return -1 103 | return 75 * (mins * 60 + secs) + frames 104 | 105 | 106 | def gettrackmode(track, modes, args: Args): 107 | """Parse the track mode string (same logic as C code).""" 108 | raw = args.raw 109 | psxtruncate = args.psxtruncate 110 | towav = args.towav 111 | 112 | modes_upper = modes.strip().upper() 113 | track.audio = 0 114 | 115 | if modes_upper == "MODE1/2352": 116 | track.bstart = 16 117 | track.bsize = 2048 118 | track.extension = "iso" 119 | 120 | elif modes_upper == "MODE2/2352": 121 | track.extension = "iso" 122 | if raw: 123 | # Raw MODE2/2352 124 | track.bstart = 0 125 | track.bsize = 2352 126 | elif psxtruncate: 127 | # PSX: truncate from 2352 to 2336 byte tracks 128 | track.bstart = 0 129 | track.bsize = 2336 130 | else: 131 | # Normal MODE2/2352 132 | track.bstart = 24 133 | track.bsize = 2048 134 | 135 | elif modes_upper == "MODE2/2336": 136 | # WAS 2352 in V1.361B still work? 137 | # what if MODE2/2336 single track bin, still 2352 sectors? 138 | track.bstart = 16 139 | track.bsize = 2336 140 | track.extension = "iso" 141 | 142 | elif modes_upper == "AUDIO": 143 | track.bstart = 0 144 | track.bsize = 2352 145 | track.audio = 1 146 | if towav: 147 | track.extension = "wav" 148 | else: 149 | track.extension = "cdr" 150 | else: 151 | sys.stdout.write("(?) ") 152 | track.bstart = 0 153 | track.bsize = 2352 154 | track.extension = "ugh" 155 | 156 | 157 | def progressbar(f, length): 158 | n = int(length * f) 159 | if n < 0: 160 | n = 0 161 | if n > length: 162 | n = length 163 | return "*" * n + " " * (length - n) 164 | 165 | 166 | def writetrack(bf, track, bname, args: Args): 167 | binfile = args.binfile 168 | swabaudio = args.swabaudio 169 | towav = args.towav 170 | verbose = args.verbose 171 | 172 | fname = f"{bname}{track.num:02d}.{track.extension}" 173 | 174 | print(f"{track.num:2d}: {fname} ", end="") 175 | 176 | try: 177 | f = open(fname, "wb") 178 | except OSError as e: 179 | sys.stderr.write(f" Could not fopen track file: {e}\n") 180 | sys.exit(4) 181 | 182 | try: 183 | bf.seek(track.start, os.SEEK_SET) 184 | except OSError as e: 185 | sys.stderr.write(f" Could not fseek to track location: {e}\n") 186 | sys.exit(4) 187 | 188 | reallen = (track.stopsect - track.startsect + 1) * track.bsize 189 | if verbose: 190 | print() 191 | print( 192 | f" mmc sectors {track.startsect}->{track.stopsect} " 193 | f"({track.stopsect - track.startsect + 1})" 194 | ) 195 | print(f" mmc bytes {track.start}->{track.stop} ({track.stop - track.start + 1})") 196 | print(f" sector data at {track.bstart}, {track.bsize} bytes per sector") 197 | print(f" real data {reallen} bytes") 198 | 199 | # initial padding (same visual behavior) 200 | print(" ", end="") 201 | sys.stdout.flush() 202 | 203 | if track.audio and towav: 204 | # RIFF header 205 | f.write(b"RIFF") 206 | l_val = reallen + WAV_DATA_HLEN + WAV_FORMAT_HLEN + 4 207 | f.write(struct.pack(" len(b): 236 | end = len(b) 237 | for i in range(start, end, 2): 238 | if i + 1 < len(b): 239 | b[i], b[i + 1] = b[i + 1], b[i] 240 | buf = bytes(b) 241 | 242 | data = buf[track.bstart : track.bstart + track.bsize] 243 | 244 | try: 245 | f.write(data) 246 | except OSError as e: 247 | sys.stderr.write(f" Could not write to track: {e}\n") 248 | sys.exit(4) 249 | 250 | sect += 1 251 | realsz += track.bsize 252 | 253 | # Update progress every 500 sectors (like original) 254 | if ((sect - track.startsect) % 500) == 0: 255 | fl = float(realsz) / float(reallen) if reallen > 0 else 0.0 256 | bar = progressbar(fl, 20) 257 | sys.stdout.write( 258 | "\r%4d/%-4d MB [%s] %3.0f %%" 259 | % (realsz // 1024 // 1024, reallen // 1024 // 1024, bar, fl * 100) 260 | ) 261 | sys.stdout.flush() 262 | 263 | fl = float(realsz) / float(reallen) if reallen > 0 else 1.0 264 | bar = progressbar(1.0, 20) 265 | sys.stdout.write( 266 | "\r%4d/%-4d MB [%s] %3.0f %%" 267 | % (realsz // 1024 // 1024, reallen // 1024 // 1024, bar, fl * 100) 268 | ) 269 | sys.stdout.flush() 270 | print() 271 | 272 | try: 273 | f.close() 274 | except OSError as e: 275 | sys.stderr.write(f" Could not fclose track file: {e}\n") 276 | sys.exit(4) 277 | 278 | return 0 279 | 280 | def main(args: Args): 281 | binfile = args.binfile 282 | cuefile = args.cuefile 283 | basefile = args.basefile 284 | verbose = args.verbose 285 | 286 | sys.stdout.write(VERSTR) 287 | 288 | try: 289 | binf = open(binfile, "rb") 290 | except OSError as e: 291 | sys.stderr.write(f"Could not open BIN {binfile}: {e}\n") 292 | return 2 293 | 294 | try: 295 | cuef = open(cuefile, "r", encoding="latin-1") 296 | except OSError as e: 297 | sys.stderr.write(f"Could not open CUE {cuefile}: {e}\n") 298 | binf.close() 299 | return 2 300 | 301 | print("Reading the CUE file:") 302 | 303 | # Skip first line (FILE line) 304 | try: 305 | first = cuef.readline() 306 | except OSError as e: 307 | sys.stderr.write(f"Could not read first line from {cuefile}: {e}\n") 308 | binf.close() 309 | cuef.close() 310 | return 3 311 | if not first: 312 | sys.stderr.write(f"Could not read first line from {cuefile}: unexpected EOF\n") 313 | binf.close() 314 | cuef.close() 315 | return 3 316 | 317 | tracks = [] 318 | track = None 319 | prevtrack = None 320 | 321 | for line in cuef: 322 | s = line.rstrip("\r\n") 323 | 324 | if "TRACK" in s: 325 | print("\nTrack ", end="") 326 | idx = s.find("TRACK") 327 | p_idx = s.find(" ", idx) 328 | if p_idx == -1: 329 | sys.stderr.write("... ouch, no space after TRACK.\n") 330 | continue 331 | p_idx += 1 332 | t_idx = s.find(" ", p_idx) 333 | if t_idx == -1: 334 | sys.stderr.write("... ouch, no space after track number.\n") 335 | continue 336 | 337 | num_str = s[p_idx:t_idx] 338 | 339 | prevtrack = track 340 | track = Track() 341 | tracks.append(track) 342 | 343 | try: 344 | track.num = int(num_str) 345 | except ValueError: 346 | sys.stderr.write("... ouch, invalid track number.\n") 347 | continue 348 | 349 | mode_str = s[t_idx + 1 :].strip() 350 | print(f"{track.num:2d}: {mode_str[:12]} ", end="") 351 | track.modes = mode_str 352 | track.extension = None 353 | track.mode = 0 354 | track.audio = 0 355 | track.bsize = track.bstart = -1 356 | track.startsect = track.stopsect = -1 357 | 358 | gettrackmode(track, mode_str, args) 359 | 360 | elif "INDEX" in s: 361 | idx = s.find("INDEX") 362 | p_idx = s.find(" ", idx) 363 | if p_idx == -1: 364 | print("... ouch, no space after INDEX.") 365 | continue 366 | p_idx += 1 367 | t_idx = s.find(" ", p_idx) 368 | if t_idx == -1: 369 | print("... ouch, no space after index number.") 370 | continue 371 | 372 | index_num_str = s[p_idx:t_idx] 373 | time_str = s[t_idx + 1 :].strip() 374 | print(f" {index_num_str} {time_str}", end="") 375 | if track is None: 376 | continue 377 | track.startsect = time2frames(time_str) 378 | track.start = track.startsect * SECTLEN 379 | if verbose: 380 | print(f" (startsect {track.startsect} ofs {track.start})", end="") 381 | if prevtrack is not None and prevtrack.stopsect < 0: 382 | prevtrack.stopsect = track.startsect 383 | prevtrack.stop = track.start - 1 384 | 385 | if track is not None: 386 | binf.seek(0, os.SEEK_END) 387 | track.stop = binf.tell() 388 | track.stopsect = track.stop // SECTLEN 389 | 390 | print("\n") 391 | 392 | for tr in tracks: 393 | writetrack(binf, tr, basefile, args) 394 | 395 | binf.close() 396 | cuef.close() 397 | 398 | print("End of Conversion\n") 399 | return 0 400 | 401 | 402 | if __name__ == "__main__": 403 | argv = sys.argv 404 | args = parse_args(argv) 405 | sys.exit(main(args)) 406 | -------------------------------------------------------------------------------- /pyoplm/cue2pops_basic_conversion.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # cue2pops.py — Python reimplementation of BIN/CUE -> IMAGE0.VCD (POPS) converter 3 | # Minimal version: default conversion only (no vmode, no trainer, no gap++/gap--) 4 | # Converted with AI, tested on many BIN/CUE files, seems to generate the same files 5 | # with the original C program 6 | # Last modified: 2025-11-05 7 | 8 | import argparse 9 | import os 10 | import sys 11 | import struct 12 | 13 | SECTORSIZE = 2352 14 | HEADERSIZE = 0x100000 # POPS header size and I/O chunk size 15 | 16 | # --- helpers -------------------------------------------------------------------- 17 | def debug_print(debug, *args, **kwargs): 18 | if debug: 19 | print(*args, **kwargs) 20 | 21 | def file_size(path): 22 | try: 23 | return os.path.getsize(path) 24 | except OSError as e: 25 | print(f"Error: Failed to get size for {path}: {e}", file=sys.stderr) 26 | return -1 27 | 28 | def bcd_encode(n): # 0..99 -> one byte BCD 29 | return ((n // 10) << 4) | (n % 10) 30 | 31 | def bcd_decode(b): 32 | return (b >> 4) * 10 + (b & 0x0F) 33 | 34 | def msf_to_lba(mm, ss, ff): 35 | # mm:ss:ff (decimal) to sectors (LBA from 00:00:00) 36 | return mm * 60 * 75 + ss * 75 + ff 37 | 38 | def add_seconds_bcd(mm_bcd, ss_bcd, ff_bcd, delta_seconds): 39 | mm = bcd_decode(mm_bcd) 40 | ss = bcd_decode(ss_bcd) 41 | ff = bcd_decode(ff_bcd) 42 | total = mm * 60 + ss + delta_seconds 43 | if total < 0: 44 | total = 0 45 | mm2 = total // 60 46 | ss2 = total % 60 47 | return bcd_encode(mm2), bcd_encode(ss2), ff_bcd 48 | 49 | def read_cue_text(path): 50 | with open(path, "rb") as f: 51 | raw = f.read() 52 | return raw.decode(errors="ignore") 53 | 54 | def parse_cue(cue_text, cue_path, debug=False): 55 | """ 56 | Minimal parser sufficient to mirror the C tool behavior: 57 | - find FILE "..." BINARY 58 | - ensure TRACK 01 MODE2/2352 exists 59 | - collect per-track INDEX 00 and 01 times (as strings "MM:SS:FF") 60 | - count PREGAP/POSTGAP 61 | - find first AUDIO track boundary for daTrack_ptr 62 | """ 63 | lines = [] 64 | for line in cue_text.splitlines(): 65 | line = line.strip() 66 | if not line: 67 | continue 68 | lines.append(line) 69 | 70 | # Find FILE "..." 71 | bin_path_decl = None 72 | for ln in lines: 73 | if ln.upper().startswith("FILE "): 74 | try: 75 | first_quote = ln.index('"') 76 | second_quote = ln.index('"', first_quote + 1) 77 | bin_path_decl = ln[first_quote + 1:second_quote] 78 | except ValueError: 79 | pass 80 | break 81 | if not bin_path_decl: 82 | raise RuntimeError("Error: The cue sheet is not valid (FILE line not found).") 83 | 84 | # Resolve bin path relative to cue 85 | if os.path.isabs(bin_path_decl): 86 | bin_path = bin_path_decl 87 | else: 88 | bin_path = os.path.join(os.path.dirname(os.path.abspath(cue_path)), bin_path_decl) 89 | 90 | # Verify MODE2/2352 for TRACK 01 91 | cue_upper = cue_text.upper() 92 | if "TRACK 01 MODE2/2352" not in cue_upper: 93 | raise RuntimeError("Error: Looks like your game dump is not MODE2/2352, or the cue is invalid.") 94 | 95 | # Counters 96 | pregap_count = sum(1 for ln in lines if ln.upper().startswith("PREGAP")) 97 | postgap_count = sum(1 for ln in lines if ln.upper().startswith("POSTGAP")) 98 | binary_count = sum(1 for ln in lines if " BINARY" in ln.upper()) 99 | wave_count = sum(1 for ln in lines if ln.upper().endswith(" WAVE")) 100 | 101 | # Tracks 102 | tracks = [] # list of dicts: {'num':int,'type':'DATA'|'AUDIO','index00':'MM:SS:FF' or None,'index01':'MM:SS:FF'} 103 | current_track = None 104 | for ln in lines: 105 | up = ln.upper() 106 | if up.startswith("TRACK "): 107 | parts = up.split() 108 | # TRACK NN MODE2/2352 or TRACK NN AUDIO 109 | num = int(parts[1]) 110 | typ = 'DATA' 111 | if "AUDIO" in parts: 112 | typ = 'AUDIO' 113 | current_track = {'num': num, 'type': typ, 'index00': None, 'index01': None} 114 | tracks.append(current_track) 115 | elif up.startswith("INDEX 00"): 116 | ts = up.split()[-1] 117 | if current_track: 118 | current_track['index00'] = ts 119 | elif up.startswith("INDEX 01"): 120 | ts = up.split()[-1] 121 | if current_track: 122 | current_track['index01'] = ts 123 | 124 | track_count = len(tracks) 125 | index1_count = sum(1 for t in tracks if t.get('index01') is not None) 126 | 127 | # Validate counts as in C 128 | if binary_count == 0: 129 | raise RuntimeError("Error: Unstandard cue sheet") 130 | if track_count == 0 or index1_count != track_count: 131 | raise RuntimeError("Error: Cannot count tracks") 132 | if binary_count != 1 or wave_count != 0: 133 | raise RuntimeError("Error: Split dumps are not supported. Use BinMerge/BinMerger to create a single BIN.") 134 | 135 | # Determine daTrack_ptr (first audio boundary) 136 | daTrack_ptr = 0 137 | first_audio_idx = None 138 | for ti, t in enumerate(tracks): 139 | if t['type'] == 'AUDIO': 140 | first_audio_idx = ti 141 | break 142 | if first_audio_idx is not None: 143 | t = tracks[first_audio_idx] 144 | if t['index00']: 145 | mm, ss, ff = map(int, t['index00'].split(':')) 146 | else: 147 | mm, ss, ff = map(int, t['index01'].split(':')) 148 | daTrack_ptr = msf_to_lba(mm, ss, ff) * SECTORSIZE 149 | debug_print(debug, f"daTrack_ptr from first AUDIO track: LBA={msf_to_lba(mm,ss,ff)} bytes={daTrack_ptr}") 150 | else: 151 | daTrack_ptr = None # set to EOF later (no CDDA) 152 | 153 | return { 154 | 'bin_path': bin_path, 155 | 'tracks': tracks, 156 | 'pregap_count': pregap_count, 157 | 'postgap_count': postgap_count, 158 | 'daTrack_ptr': daTrack_ptr, 159 | } 160 | 161 | # --- POPS header builder (A0/A1/A2 + per-track entries) ------------------------- 162 | def build_pops_header(meta, bin_size, debug=False): 163 | """ 164 | Mirrors the original layout and behavior closely, including the unconditional +2s 165 | nudges and CDRWIN fix. Times in header are BCD. 166 | """ 167 | tracks = meta['tracks'] 168 | pregap_count = meta['pregap_count'] 169 | postgap_count = meta['postgap_count'] 170 | 171 | hdr = bytearray(HEADERSIZE) 172 | 173 | # A0: first track info + disc type 174 | hdr[0] = 0x41 # first track type (assume DATA; replaced per track entries later if needed) 175 | hdr[2] = 0xA0 # descriptor A0 176 | hdr[7] = 0x01 # first track number 177 | hdr[8] = 0x20 # Disc Type = CD-XA001 178 | 179 | # A1: contents 180 | hdr[12] = 0xA1 181 | hdr[17] = bcd_encode(len(tracks)) # number of tracks (BCD) 182 | content_mixed = any(t['type'] == 'AUDIO' for t in tracks) 183 | hdr[10] = 0x01 if content_mixed else 0x41 184 | hdr[20] = hdr[10] 185 | 186 | # A2: lead-in/out 187 | hdr[22] = 0xA2 188 | 189 | # Lead-out calculation (mirrors the C logic) 190 | sector_count_full = (bin_size // SECTORSIZE) + (150 * (pregap_count + postgap_count)) + 150 191 | loM = sector_count_full // 4500 192 | loS = (sector_count_full - loM * 4500) // 75 193 | loF = sector_count_full - loM * 4500 - loS * 75 194 | hdr[27] = bcd_encode(loM) 195 | hdr[28] = bcd_encode(loS) 196 | hdr[29] = bcd_encode(loF) 197 | 198 | # The effective sector count stored twice at 1032 and 1036 (LE32) 199 | sector_count = (bin_size // SECTORSIZE) + (150 * (pregap_count + postgap_count)) 200 | hdr[1032:1036] = struct.pack(" treat full BIN as data (no patchers anyway) 268 | 269 | # Build header 270 | header, fix_CDRWIN = build_pops_header(meta, bin_size, debug=debug) 271 | 272 | print("\nBIN/CUE to IMAGE0.VCD conversion tool (Python, minimal)") 273 | print(f"Input CUE : {cue_path}") 274 | print(f"Input BIN : {bin_path}") 275 | print(f"Output VCD : {out_vcd}\n") 276 | 277 | # Write header 278 | with open(out_vcd, "wb") as f: 279 | f.write(header) 280 | 281 | # Stream BIN (no patching) 282 | print("Saving the virtual CD-ROM image. Please wait...") 283 | with open(out_vcd, "ab") as vcd, open(bin_path, "rb") as binf: 284 | # Prime 285 | first = binf.read(HEADERSIZE) 286 | if not first: 287 | raise RuntimeError("Empty BIN?") 288 | 289 | buf = bytearray(first) 290 | offset = 0 291 | 292 | # Handle CDRWIN padding injection if boundary falls inside this first chunk 293 | injected = False 294 | if fix_CDRWIN and (offset + len(buf) >= daTrack_ptr): 295 | before = daTrack_ptr - offset 296 | vcd.write(buf[:before]) 297 | pad_len = 150 * SECTORSIZE # 2 seconds 298 | vcd.write(bytes(pad_len)) 299 | vcd.write(buf[before:]) 300 | injected = True 301 | else: 302 | vcd.write(buf) 303 | 304 | written = len(first) 305 | total = bin_size 306 | print(f"{written} -> Source bin size") 307 | 308 | # Continue streaming 309 | while True: 310 | chunk = binf.read(HEADERSIZE) 311 | if not chunk: 312 | break 313 | offset = written 314 | buf = bytearray(chunk) 315 | 316 | if fix_CDRWIN and not injected and (offset + len(buf) >= daTrack_ptr): 317 | before = daTrack_ptr - offset 318 | vcd.write(buf[:before]) 319 | pad_len = 150 * SECTORSIZE 320 | vcd.write(bytes(pad_len)) 321 | vcd.write(buf[before:]) 322 | injected = True 323 | else: 324 | vcd.write(buf) 325 | 326 | written += len(chunk) 327 | pct = (written * 100.0) / total 328 | print(f"{written} bytes written\t{pct:.1f}%", end="\r") 329 | 330 | print("\nA POPS virtual CD-ROM image was saved to :") 331 | print(out_vcd) 332 | print() 333 | 334 | def main(): 335 | parser = argparse.ArgumentParser( 336 | description="BIN/CUE -> IMAGE0.VCD (POPS) converter — minimal (no vmode, no trainer, no gap options)." 337 | ) 338 | parser.add_argument("cue", help="Input .cue file") 339 | parser.add_argument("out", nargs="?", help="Optional output .VCD path") 340 | parser.add_argument("--debug", action="store_true", help="Print extra info") 341 | # For backward compatibility with old scripts that pass random tokens, accept & ignore them: 342 | parser.add_argument("--ignore", nargs="*", help=argparse.SUPPRESS, default=[]) 343 | args, extra = parser.parse_known_args() 344 | 345 | cue_path = args.cue 346 | if not os.path.isfile(cue_path): 347 | print(f"Error: No input file {cue_path}", file=sys.stderr) 348 | sys.exit(2) 349 | 350 | out_vcd = args.out 351 | if out_vcd is None: 352 | root, _ = os.path.splitext(cue_path) 353 | out_vcd = root + ".VCD" 354 | 355 | try: 356 | convert(cue_path, out_vcd, debug=args.debug) 357 | except Exception as e: 358 | print(str(e), file=sys.stderr) 359 | sys.exit(1) 360 | 361 | if __name__ == "__main__": 362 | main() 363 | -------------------------------------------------------------------------------- /pyoplm/binmerge.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # binmerge 4 | # 5 | # Takes a cue sheet with multiple binary track files and merges them together, 6 | # generating a corrected cue sheet in the process. 7 | # 8 | # Copyright (C) 2021 Chris Putnam 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 2 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License along 21 | # with this program; if not, write to the Free Software Foundation, Inc., 22 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | # 25 | # Please report any bugs on GitHub: https://github.com/putnam/binmerge 26 | # 27 | # 28 | import argparse, re, os, subprocess, sys, textwrap, traceback 29 | VERBOSE = False 30 | 31 | def print_license(): 32 | print(textwrap.dedent(""" 33 | binmerge 34 | Copyright (C) 2021 Chris Putnam 35 | 36 | This program is free software; you can redistribute it and/or modify 37 | it under the terms of the GNU General Public License as published by 38 | the Free Software Foundation; either version 2 of the License, or 39 | (at your option) any later version. 40 | 41 | This program is distributed in the hope that it will be useful, 42 | but WITHOUT ANY WARRANTY; without even the implied warranty of 43 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 44 | GNU General Public License for more details. 45 | 46 | You should have received a copy of the GNU General Public License along 47 | with this program; if not, write to the Free Software Foundation, Inc., 48 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 49 | 50 | Source code available at: https://github.com/putnam/binmerge 51 | """)) 52 | 53 | def d(s): 54 | if VERBOSE: 55 | print("[DEBUG]\t%s" % s) 56 | 57 | def e(s): 58 | print("[ERROR]\t%s" % s) 59 | 60 | def p(s): 61 | print("[INFO]\t%s" % s) 62 | 63 | class Track: 64 | globalBlocksize = None 65 | 66 | def __init__(self, num, track_type): 67 | self.num = num 68 | self.indexes = [] 69 | self.track_type = track_type 70 | self.sectors = None 71 | self.file_offset = None 72 | 73 | # All possible blocksize types. You cannot mix types on a disc, so we will use the first one we see and lock it in. 74 | # 75 | # AUDIO – Audio/Music (2352) 76 | # CDG – Karaoke CD+G (2448) 77 | # MODE1/2048 – CDROM Mode1 Data (cooked) 78 | # MODE1/2352 – CDROM Mode1 Data (raw) 79 | # MODE2/2336 – CDROM-XA Mode2 Data 80 | # MODE2/2352 – CDROM-XA Mode2 Data 81 | # CDI/2336 – CDI Mode2 Data 82 | # CDI/2352 – CDI Mode2 Data 83 | if not Track.globalBlocksize: 84 | if track_type in ['AUDIO', 'MODE1/2352', 'MODE2/2352', 'CDI/2352']: 85 | Track.globalBlocksize = 2352 86 | elif track_type == 'CDG': 87 | Track.globalBlocksize = 2448 88 | elif track_type == 'MODE1/2048': 89 | Track.globalBlocksize = 2048 90 | elif track_type in ['MODE2/2336', 'CDI/2336']: 91 | Track.globalBlocksize = 2336 92 | d("Locked blocksize to %d" % Track.globalBlocksize) 93 | 94 | class File: 95 | def __init__(self, filename): 96 | self.filename = filename 97 | self.tracks = [] 98 | self.size = os.path.getsize(filename) 99 | 100 | class BinFilesMissingException(Exception): 101 | pass 102 | 103 | def read_cue_file(cue_path): 104 | files = [] 105 | this_track = None 106 | this_file = None 107 | bin_files_missing = False 108 | 109 | f = open(cue_path, 'r') 110 | for line in f: 111 | m = re.search('FILE "?(.*?)"? BINARY', line) 112 | if m: 113 | this_path = os.path.join(os.path.dirname(cue_path), m.group(1)) 114 | if not (os.path.isfile(this_path) or os.access(this_path, os.R_OK)): 115 | e("Bin file not found or not readable: %s" % this_path) 116 | bin_files_missing = True 117 | else: 118 | this_file = File(this_path) 119 | files.append(this_file) 120 | continue 121 | 122 | m = re.search('TRACK (\\d+) ([^\\s]*)', line) 123 | if m and this_file: 124 | this_track = Track(int(m.group(1)), m.group(2)) 125 | this_file.tracks.append(this_track) 126 | continue 127 | 128 | m = re.search('INDEX (\\d+) (\\d+:\\d+:\\d+)', line) 129 | if m and this_track: 130 | this_track.indexes.append({'id': int(m.group(1)), 'stamp': m.group(2), 'file_offset':cuestamp_to_sectors(m.group(2))}) 131 | continue 132 | 133 | if bin_files_missing: 134 | raise BinFilesMissingException 135 | 136 | if len(files) == 1: 137 | # only 1 file, assume splitting, calc sectors of each 138 | next_item_offset = files[0].size // Track.globalBlocksize 139 | for t in reversed(files[0].tracks): 140 | t.sectors = next_item_offset - t.indexes[0]["file_offset"] 141 | next_item_offset = t.indexes[0]["file_offset"] 142 | 143 | for f in files: 144 | d("-- File --") 145 | d("Filename: %s" % f.filename) 146 | d("Size: %d" % f.size) 147 | d("Tracks:") 148 | 149 | for t in f.tracks: 150 | d(" -- Track --") 151 | d(" Num: %d" % t.num) 152 | d(" Type: %s" % t.track_type) 153 | if t.sectors: d(" Sectors: %s" % t.sectors) 154 | d(" Indexes: %s" % repr(t.indexes)) 155 | 156 | return files 157 | 158 | 159 | def sectors_to_cuestamp(sectors): 160 | # 75 sectors per second 161 | minutes = sectors / 4500 162 | fields = sectors % 4500 163 | seconds = fields / 75 164 | fields = sectors % 75 165 | return '%02d:%02d:%02d' % (minutes, seconds, fields) 166 | 167 | def cuestamp_to_sectors(stamp): 168 | # 75 sectors per second 169 | m = re.match("(\\d+):(\\d+):(\\d+)", stamp) 170 | minutes = int(m.group(1)) 171 | seconds = int(m.group(2)) 172 | fields = int(m.group(3)) 173 | return fields + (seconds * 75) + (minutes * 60 * 75) 174 | 175 | # Generates track filename based on redump naming convention 176 | # (Note: prefix may contain a fully qualified path) 177 | def track_filename(prefix, track_num, track_count): 178 | # Redump is strangely inconsistent in their datfiles and cuesheets when it 179 | # comes to track numbers. The naming convention currently seems to be: 180 | # If there are less than 10 tracks: "Track 1", "Track 2", etc. 181 | # If there are more than 10 tracks: "Track 01", "Track 02", etc. 182 | # 183 | # It'd be nice if it were consistently %02d! 184 | # 185 | if track_count > 9: 186 | return "%s (Track %02d).bin" % (prefix, track_num) 187 | return "%s (Track %d).bin" % (prefix, track_num) 188 | 189 | # Generates a 'merged' cuesheet, that is, one bin file with tracks indexed within. 190 | def gen_merged_cuesheet(basename, files): 191 | cuesheet = 'FILE "%s.bin" BINARY\n' % basename 192 | # One sector is (BLOCKSIZE) bytes 193 | sector_pos = 0 194 | for f in files: 195 | for t in f.tracks: 196 | cuesheet += ' TRACK %02d %s\n' % (t.num, t.track_type) 197 | for i in t.indexes: 198 | cuesheet += ' INDEX %02d %s\n' % (i['id'], sectors_to_cuestamp(sector_pos + i['file_offset'])) 199 | sector_pos += f.size / Track.globalBlocksize 200 | return cuesheet 201 | 202 | # Generates a 'split' cuesheet, that is, with one bin file for every track. 203 | def gen_split_cuesheet(basename, merged_file): 204 | cuesheet = "" 205 | for t in merged_file.tracks: 206 | track_fn = track_filename(basename, t.num, len(merged_file.tracks)) 207 | cuesheet += 'FILE "%s" BINARY\n' % track_fn 208 | cuesheet += ' TRACK %02d %s\n' % (t.num, t.track_type) 209 | for i in t.indexes: 210 | sector_pos = i['file_offset'] - t.indexes[0]['file_offset'] 211 | cuesheet += ' INDEX %02d %s\n' % (i['id'], sectors_to_cuestamp(sector_pos)) 212 | return cuesheet 213 | 214 | # Merges files together to new file `merged_filename`, in listed order. 215 | def merge_files(merged_filename, files): 216 | if os.path.exists(merged_filename): 217 | e('Target merged bin path already exists: %s' % merged_filename) 218 | return False 219 | 220 | # cat is actually a bit faster, but this is multi-platform and no special-casing 221 | chunksize = 1024 * 1024 222 | with open(merged_filename, 'wb') as outfile: 223 | for f in files: 224 | with open(f.filename, 'rb') as infile: 225 | while True: 226 | chunk = infile.read(chunksize) 227 | if not chunk: 228 | break 229 | outfile.write(chunk) 230 | return True 231 | 232 | # Writes each track in a File to a new file 233 | def split_files(new_basename, merged_file): 234 | with open(merged_file.filename, 'rb') as infile: 235 | # Check all tracks for potential file-clobbering first before writing anything 236 | for t in merged_file.tracks: 237 | out_name = track_filename(new_basename, t.num, len(merged_file.tracks)) 238 | if os.path.exists(out_name): 239 | e('Target bin path already exists: %s' % out_name) 240 | return False 241 | 242 | for t in merged_file.tracks: 243 | chunksize = 1024 * 1024 244 | out_name = track_filename(new_basename, t.num, len(merged_file.tracks)) 245 | tracksize = t.sectors * Track.globalBlocksize 246 | written = 0 247 | with open(out_name, 'wb') as outfile: 248 | while True: 249 | if chunksize + written > tracksize: 250 | chunksize = tracksize - written 251 | chunk = infile.read(chunksize) 252 | outfile.write(chunk) 253 | written += chunksize 254 | if written == tracksize: 255 | break 256 | return True 257 | 258 | def binmerge(cuefile: str, basename: str, license: bool, verbose: bool, split: bool, outdir: str | bool): 259 | if verbose: 260 | global VERBOSE 261 | VERBOSE = True 262 | 263 | # Resolve relative paths and cwd 264 | cuefile = os.path.abspath(cuefile) 265 | 266 | if not os.path.exists(cuefile): 267 | e("Cue file does not exist: %s" % cuefile) 268 | return 1 269 | 270 | if not os.access(cuefile, os.R_OK): 271 | e("Cue file is not readable: %s" % cuefile) 272 | return 1 273 | 274 | if outdir: 275 | outdir = os.path.abspath(outdir) 276 | p("Output directory: %s" % outdir) 277 | if not os.path.exists(outdir): 278 | try: 279 | p("Output directory did not exist; creating it.") 280 | os.makedirs(outdir) 281 | except: 282 | e("Could not create output directory (permissions?)") 283 | traceback.print_exc() 284 | return 1 285 | else: 286 | outdir = os.path.dirname(cuefile) 287 | p("Output directory: %s" % outdir) 288 | 289 | if not (os.path.exists(outdir) or os.path.isdir(outdir)): 290 | e("Output directory does not exist or is not a directory: %s" % outdir) 291 | return 1 292 | 293 | if not os.access(outdir, os.W_OK): 294 | e("Output directory is not writable: %s" % outdir) 295 | return 1 296 | 297 | p("Opening cue: %s" % cuefile) 298 | try: 299 | cue_map = read_cue_file(cuefile) 300 | except BinFilesMissingException: 301 | e("One or more bin files were missing on disk. Aborting.") 302 | return 1 303 | except Exception as exc: 304 | e("Error parsing cuesheet. Is it valid?") 305 | traceback.print_exc() 306 | return 1 307 | 308 | if split: 309 | cuesheet = gen_split_cuesheet(basename, cue_map[0]) 310 | else: 311 | cuesheet = gen_merged_cuesheet(basename, cue_map) 312 | 313 | if not os.path.exists(outdir): 314 | e("Output dir does not exist") 315 | return 1 316 | 317 | new_cue_fn = os.path.join(outdir, basename+'.cue') 318 | if os.path.exists(new_cue_fn): 319 | e("Output cue file already exists. Quitting. Path: %s" % new_cue_fn) 320 | return 1 321 | 322 | if split: 323 | p("Splitting files...") 324 | if split_files(os.path.join(outdir, basename), cue_map[0]): 325 | p("Wrote %d bin files" % len(cue_map[0].tracks)) 326 | else: 327 | e("Unable to split bin files.") 328 | return 1 329 | else: 330 | p("Merging %d tracks..." % len(cue_map)) 331 | out_path = os.path.join(outdir, basename+'.bin') 332 | if merge_files(out_path, cue_map): 333 | p("Wrote %s" % out_path) 334 | else: 335 | e("Unable to merge bin files.") 336 | return 1 337 | 338 | with open(new_cue_fn, 'w', newline='\r\n') as f: 339 | f.write(cuesheet) 340 | p("Wrote new cue: %s" % new_cue_fn) 341 | return 0 342 | 343 | def main(): 344 | parser = argparse.ArgumentParser(description="Using a cuesheet, merges numerous bin files into a single bin file and produces a new cuesheet with corrected offsets. Works great with Redump. Supports all block modes, but only binary track types.") 345 | parser.add_argument('cuefile', help='path to current cue file (bin files are expected in the same dir)') 346 | parser.add_argument('basename', help='name (without extension) for your new bin/cue files') 347 | 348 | # argparse is bad. make -l work like -h (no args required) 349 | class licenseAction(argparse._StoreTrueAction): 350 | def __call__(self, parser, namespace, values, option_string=None): 351 | print_license() 352 | parser.exit() 353 | 354 | parser.add_argument('-l', '--license', default=False, help='prints license info and exit', action=licenseAction) 355 | parser.add_argument('-v', '--verbose', action='store_true', help='print more verbose messages') 356 | parser.add_argument('-s', '--split', help='reverses operation, splitting merged files back to individual tracks', required=False, action='store_true') 357 | parser.add_argument('-o', '--outdir', default=False, help='output directory. defaults to the same directory as source cue. directory will be created (recursively) if needed.') 358 | 359 | args = parser.parse_args() 360 | 361 | return True if binmerge(args.cuename, args.basename, args.license, args.verbose, args.split, args.outdir) == 0 else False 362 | 363 | if __name__ == "__main__": 364 | if not main(): 365 | sys.exit(1) 366 | -------------------------------------------------------------------------------- /pyoplm/storage.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from dataclasses import dataclass 3 | from functools import reduce 4 | from io import BytesIO 5 | from enum import Enum 6 | from itertools import islice 7 | from pathlib import Path 8 | import sqlite3 9 | import re 10 | from typing import Any, Dict, Iterator, List, Set, Tuple, NewType 11 | from urllib.request import urlopen 12 | from urllib.parse import quote, urljoin 13 | from urllib.error import HTTPError, URLError 14 | from sys import stderr 15 | from PIL import Image 16 | from io import StringIO 17 | import os 18 | 19 | from bs4 import BeautifulSoup, ResultSet 20 | 21 | 22 | def urls_for_odd_type(region_code: str, art_type: str, url=None) -> Iterator[Tuple[str, str]]: 23 | """URL generator for types SCR and BG, which do not follow other 24 | art type's naming conventions in danielb's art backups""" 25 | curr_num = 0 26 | while True: 27 | parts = [url if url else '', "PS2", region_code, 28 | f"{region_code}_{art_type}_{str(curr_num).rjust(2, '0')}"] 29 | 30 | path_no_extension = reduce(urljoin if url else os.path.join, parts) 31 | yield (f"{path_no_extension}.jpg", f"{path_no_extension}.png") 32 | curr_num += 1 33 | 34 | 35 | def csv_delete_cols_to_dict(file: str, cols_to_delete: List[str]) -> Dict[str, str]: 36 | """Read a CSV file, delete columns listed in cols_to_delete from it and create a 37 | dict. Fails if the CSV is left with more than 2 columns. 38 | """ 39 | source = StringIO(urlopen(str(file)).read().decode('utf-8')) 40 | next(source) 41 | output = StringIO() 42 | 43 | reader = list(csv.reader(source)) 44 | headers = reader[0] 45 | 46 | indexes_to_delete = [idx for idx, elem in enumerate( 47 | headers) if elem in cols_to_delete] 48 | result = [[o for idx, o in enumerate( 49 | obj) if idx not in indexes_to_delete] for obj in reader] 50 | 51 | writer = csv.writer(output) 52 | writer.writerows(result) 53 | 54 | output.seek(0) 55 | return dict(csv.reader(output)) 56 | 57 | 58 | @dataclass(unsafe_hash=True, frozen=True, eq=True) 59 | class Artwork: 60 | region_code: str 61 | console: str 62 | art_type: str 63 | file_extension: str 64 | src_filename: str 65 | dest_filename: str 66 | 67 | def get_relative_source_path(self) -> Path: 68 | """Get relative path to the file in the storage, can be 69 | joined with a URL or system path""" 70 | return Path(self.console, self.region_code, self.src_filename) 71 | 72 | def get_relative_destination_path(self) -> Path: 73 | """Get relative path to where this art file will be saved to, 74 | can be joined with a URL or system path""" 75 | return Path("ART", self.dest_filename) 76 | 77 | 78 | class Indexing: 79 | con: sqlite3.Connection 80 | zip_contents_url: str 81 | title_csv_location: str 82 | INDEX_FILENAME: str = "indexed_storage.db" 83 | 84 | ART_FILENAME_PATTERN: str = r'[HMPGNCSJTBDAKs][a-zA-Z]{3}.?\d{3}\.?\d{2}_([A-Z]*(2|_\d\d)?)' 85 | 86 | CREATE_TABLE_ARTWORKS_DDL: str = """ 87 | CREATE TABLE IF NOT EXISTS Artworks ( 88 | region_code VARCHAR(11) NOT NULL, 89 | console VARCHAR(3) 90 | CHECK (console IN ('PS1', 'PS2')) NOT NULL, 91 | art_type VARCHAR(4) 92 | CHECK (art_type IN ('COV', 'COV2', 'ICO', 'SCR' 93 | , 'SCR2', 'LAB', 'BG', 'LGO')) NOT NULL, 94 | file_extension VARCHAR(4) 95 | CHECK (file_extension IN ('png', 'jpg')) NOT NULL, 96 | src_filename VARCHAR(20) NOT NULL, 97 | dest_filename VARCHAR(20) NOT NULL, 98 | PRIMARY KEY (region_code, console ,art_type) 99 | );""" 100 | 101 | CREATE_TABLE_TITLES: str = """ 102 | CREATE TABLE IF NOT EXISTS Titles ( 103 | region_code VARCHAR(11) PRIMARY KEY NOT NULL, 104 | title text 105 | ); 106 | """ 107 | 108 | def __init__(self, opl_dir: Path, zip_contents_url: str, title_csv_location: str): 109 | self.con = sqlite3.connect(opl_dir.joinpath(self.INDEX_FILENAME)) 110 | self.zip_contents_url = zip_contents_url 111 | self.title_csv_location = title_csv_location 112 | cur = self.con.cursor() 113 | _ = cur.execute(self.CREATE_TABLE_TITLES) 114 | _ = cur.execute(self.CREATE_TABLE_ARTWORKS_DDL) 115 | self.con.commit() 116 | # Check if there are no rows in the table 117 | if not int(cur.execute("SELECT COUNT(*) FROM Artworks").fetchone()[0]): 118 | self.index_artwork() 119 | 120 | if not int(cur.execute("SELECT COUNT(*) FROM Titles").fetchone()[0]): 121 | self.index_titles() 122 | 123 | def get_artworks_for_game(self, region_code: str) -> Iterator[Artwork]: 124 | cur = self.con.cursor() 125 | 126 | # I know that the table's columns are just 6 strings, that's why the type annotation is here 127 | console_ps1: list[tuple[str, str, str, str, str, str]] = cur.execute( 128 | "SELECT * FROM Artworks WHERE region_code=? and console='PS1'", (region_code,)).fetchall() 129 | console_ps2: list[tuple[str, str, str, str, str, str]] = cur.execute( 130 | "SELECT * FROM Artworks WHERE region_code=? and console='PS2'", (region_code,)).fetchall() 131 | 132 | # Sometimes PS1 games can be in PS2 folder, and PS2 games can be in PS1 folder 133 | # Magical stuff 134 | return map(lambda x: Artwork(*x), console_ps1 if len(console_ps1) > len(console_ps2) else console_ps2) 135 | 136 | def get_title_for_game(self, region_code: str) -> str | None: 137 | cur = self.con.cursor() 138 | row = cur.execute( 139 | "SELECT title FROM Titles WHERE region_code=?", (region_code,)) 140 | return row.fetchone()[0] if row else None 141 | 142 | def index_titles(self) -> None: 143 | cur = self.con.cursor() 144 | try: 145 | processed_csv = csv_delete_cols_to_dict( 146 | self.title_csv_location, ["ID"]) 147 | 148 | # TODO: Make code cross platform 149 | split_path = self.title_csv_location.split("/") 150 | new_file = "PS2_LIST.CSV" if split_path[-1].startswith( 151 | "PS1") else "PS1_LIST.CSV" 152 | new_path = "/".join(split_path[0:-1] + [new_file]) 153 | 154 | processed_csv.update(csv_delete_cols_to_dict( 155 | new_path, 156 | ["ID"] 157 | )) 158 | except HTTPError as _: 159 | print( 160 | "Cannot find game list in online storage, not indexing titles", file=stderr) 161 | return 162 | except URLError as _: 163 | print( 164 | "Cannot find game list in storage, not indexing titles", file=stderr) 165 | return 166 | 167 | print("Begin indexing titles...") 168 | 169 | _ = cur.executemany("INSERT INTO Titles VALUES(?, ?)", 170 | processed_csv.items()) 171 | self.con.commit() 172 | print("Finished indexing titles") 173 | 174 | def index_artwork(self) -> None: 175 | cur = self.con.cursor() 176 | print("Begin indexing artwork...") 177 | print("Requesting artwork file table...") 178 | try: 179 | contents: StringIO = urlopen(self.zip_contents_url) 180 | except HTTPError as e: 181 | print( 182 | f"Attempt to access storage file list on the web failed, no caching on this run, reason: {e.reason}", file=stderr) 183 | print(f"Error code: {e.code}", file=stderr) 184 | print(f"Response headers: {e.headers}", file=stderr) 185 | return 186 | except URLError as e: 187 | print( 188 | f"Error accessing storage file list on the given URL, no caching on this run, reason: {e.reason}", file=stderr) 189 | return 190 | print("Done!") 191 | print("Parsing artwork file table...") 192 | games_page = BeautifulSoup( 193 | contents.read(), features='lxml') 194 | print("Done!") 195 | 196 | contents.close() 197 | 198 | table = games_page.find('table') 199 | if not table: 200 | raise ValueError( 201 | "STORAGE.CACHING's 'zip_contents_location' key in the 'pyoplm.ini' does not lead to an internet archive zip content view page, please enter a proper link. Disabling caching for this run.") 202 | 203 | rows: ResultSet[Any] = table.find_all('tr') # pyright: ignore 204 | 205 | records = [] 206 | 207 | print("Processing rows...") 208 | for row in rows: 209 | image_path = row.find('td') 210 | if image_path: 211 | path: str = image_path.text.strip() 212 | if path.endswith(('.jpg', '.png')): 213 | split_path = path.split('/') 214 | if len(split_path) < 3: 215 | continue 216 | 217 | game_id = split_path[1] 218 | console = split_path[0] 219 | filename = split_path[2] 220 | art_type_match = re.findall( 221 | self.ART_FILENAME_PATTERN, filename) 222 | if art_type_match: 223 | art_type = art_type_match[0][0] 224 | else: 225 | continue 226 | 227 | # Handle BG and SCR files 228 | if '_' in art_type: 229 | split_art_type = art_type.split('_') 230 | nr = split_art_type[1] 231 | base_type = split_art_type[0] 232 | if int(nr) <= 1 and base_type == 'SCR': 233 | art_type = f"{base_type}{'' if int(nr) == 0 else '2'}" 234 | elif base_type == 'BG' and int(nr) == 0: 235 | art_type = 'BG' 236 | else: 237 | continue 238 | file_extension: str = filename.split('.')[2] 239 | dest_filename = f'{game_id}_{art_type}.{file_extension}' 240 | records.append((game_id, console, art_type, 241 | file_extension, filename, dest_filename)) 242 | print("Done!") 243 | 244 | print("Saving to index database...") 245 | _ = cur.executemany('INSERT INTO Artworks VALUES (?,?,?,?,?,?)', records) 246 | self.con.commit() 247 | print("Done indexing!") 248 | pass 249 | 250 | 251 | class Storage: 252 | """Class which manages all storage-related features such as updating game 253 | names from the CSVs in the backups and placing a game's artwork files into 254 | OPL's ART directory""" 255 | 256 | class OperationState(Enum): 257 | """The storage's operation states""" 258 | FILESYSTEM = 1 259 | ONLINE = 2 260 | DISABLED = 3 261 | 262 | Dimensions: type = NewType("Dimensions", tuple[int, int]) 263 | 264 | operation_state: OperationState 265 | """The Storage's current operation state""" 266 | 267 | storage_location: str | Path 268 | """Location of the backup""" 269 | 270 | cached_game_list: dict[str, str] 271 | 272 | index: Indexing | None 273 | 274 | global urls_for_odd_type 275 | global csv_delete_cols_to_dict 276 | 277 | PS2_TYPES_OF_ART: Set[str] = set( 278 | ("COV", "COV2", "ICO", "LAB", "SCR", "BG", "LGO")) 279 | """All the types of OPL PS2 art files""" 280 | 281 | PS2_ART_SIZES: dict[str, Dimensions] = { 282 | "COV": Dimensions((140, 200)), 283 | "COV2": Dimensions((242, 344)), 284 | "ICO": Dimensions((64, 64)), 285 | "LAB": Dimensions((18, 240)), 286 | "SCR": Dimensions((250, 188)), 287 | "BG": Dimensions((640, 480)), 288 | "SCR2": Dimensions((250, 188)), 289 | "LGO": Dimensions((300, 125)) 290 | } 291 | """Sizes for different types of PS2 art""" 292 | 293 | def __init__(self, backup_location: str | None, opl_dir: Path, indexing_url: str = None): 294 | self.index = None 295 | self.cached_game_list = {} 296 | if not backup_location: 297 | self.operation_state = self.OperationState.DISABLED 298 | return 299 | 300 | self.opl_dir = opl_dir 301 | if backup_location[-1] != "/": 302 | backup_location += "/" 303 | 304 | if (loc := Path(backup_location)).exists(): 305 | self.operation_state = self.OperationState.FILESYSTEM 306 | self.storage_location = loc 307 | if indexing_url: 308 | self.index = Indexing( 309 | opl_dir, indexing_url, self.storage_location.joinpath("PS1_LIST.CSV").as_uri()) 310 | else: 311 | try: 312 | url = urlopen(backup_location) 313 | url.close() 314 | if indexing_url: 315 | self.index = Indexing(opl_dir, indexing_url, urljoin( 316 | backup_location, "PS1_LIST.CSV")) 317 | self.operation_state = self.OperationState.ONLINE 318 | self.storage_location = backup_location 319 | except HTTPError as e: 320 | print( 321 | f"Attempt to access storage on the web failed, reason: {e.reason}") 322 | print(f"Error code: {e.code}", file=stderr) 323 | print(f"Response headers: {e.headers}", file=stderr) 324 | print(f"WARNING: Features depending on storage have been disabled, there were issues finding and accessing the supplied storage.") 325 | self.disable_storage() 326 | except URLError as e: 327 | print( 328 | f"Error accessing web or filesystem storage on the given link, reason: {e.reason}", file=stderr) 329 | print(f"WARNING: Features depending on storage have been disabled, there were issues finding and accessing the supplied storage.") 330 | self.disable_storage() 331 | except Exception as e: 332 | print(e, file=stderr) 333 | print(f"WARNING: Features depending on storage have been disabled, there were issues finding and accessing the supplied storage.") 334 | self.disable_storage() 335 | 336 | def is_enabled(self): 337 | match self.operation_state: 338 | case self.OperationState.DISABLED: 339 | return False 340 | case _: 341 | return True 342 | 343 | def process_game_list_csv(self, file) -> Dict[str, str]: 344 | if not self.cached_game_list: 345 | self.cached_game_list = csv_delete_cols_to_dict(file, ["ID"]) 346 | return self.cached_game_list 347 | 348 | def disable_storage(self): 349 | """Set the Storage's operation state to Disabled, effectively 350 | disabling all Storage dependent features on the app""" 351 | self.operation_state = self.OperationState.DISABLED 352 | 353 | def should_resize(self, art_type: str) -> bool: 354 | """Checks whether an art file should be automatically resized or not 355 | based on its art type""" 356 | return art_type == "COV" or art_type == "LAB"\ 357 | or art_type == "SCR" or art_type == "BG" 358 | 359 | def resize_artwork(self, art_type: str, image_data: bytes, filename: str) -> BytesIO: 360 | file_format = "jpeg" if filename.split(".")[-1] == "jpg" else "png" 361 | output: BytesIO = BytesIO() 362 | if self.should_resize(art_type): 363 | image = Image.open(BytesIO(image_data)) 364 | image = image.resize(self.PS2_ART_SIZES[art_type]) 365 | image.save(output, file_format) 366 | else: 367 | output.write(image_data) 368 | output.seek(0) 369 | return output 370 | 371 | def get_filename_options(self, region_code: str, art_type: str, url: str = None) -> Iterator[Tuple[str, str]]: 372 | if art_type != "SCR" and art_type != "BG": 373 | return [(self.storage_location 374 | + f"PS2/{region_code}/{region_code}_{art_type}{ext}" 375 | for ext in [".png", ".jpg"])] 376 | else: 377 | return urls_for_odd_type(region_code, art_type, url) 378 | 379 | def __get_already_existing_art_types_for_game(self, region_code) -> Set[str]: 380 | existing = self.opl_dir.glob(f"ART/{region_code}*") 381 | return set( 382 | map(lambda x: re.findall( 383 | r'S[a-zA-Z]{3}.?\d{3}\.?\d{2}_([A-Z]*2?)', x.name)[0], existing) 384 | ) 385 | 386 | def get_artwork_for_game(self, region_code: str, overwrite: bool) -> None: 387 | """Retrieves all artwork files related to a title, properly resizes them 388 | and places them in the OPL ART directory.""" 389 | 390 | existing_types = self.__get_already_existing_art_types_for_game( 391 | region_code) 392 | 393 | if self.index: 394 | if self.__get_artwork_for_game_indexed(region_code, overwrite): 395 | return 396 | 397 | for art_type in self.PS2_TYPES_OF_ART: 398 | if art_type in existing_types and not overwrite: 399 | continue 400 | match self.operation_state: 401 | case self.OperationState.ONLINE: 402 | possible_locations = self.get_filename_options( 403 | region_code, art_type, self.storage_location) 404 | 405 | count = 0 406 | 407 | for possibilities in islice(possible_locations, 2 if art_type == "SCR" else 1): 408 | found = False 409 | for possibility in possibilities: 410 | try: 411 | with urlopen(possibility) as dl_art_file: 412 | file_extension = possibility.split( 413 | '.')[-1] 414 | dest_filename = f"{region_code}_{art_type}{'' if count == 0 else '2'}.{file_extension}" 415 | count += 1 416 | 417 | art_file_path = self.opl_dir.joinpath( 418 | "ART", dest_filename) 419 | 420 | if not art_file_path.exists() or overwrite: 421 | art_file = art_file_path.open('wb') 422 | 423 | art_file.write(self.resize_artwork( 424 | art_type, dl_art_file.read(), possibility).read()) 425 | art_file.close() 426 | found = True 427 | break 428 | except HTTPError: 429 | pass 430 | if not found or count > 1: 431 | break 432 | 433 | case self.OperationState.FILESYSTEM: 434 | glob_pattern_suffix = "_*" if art_type == "SCR" and art_type == "BG" else "*" 435 | ps2_art_files: Iterator[Path] = list(self.storage_location.joinpath("PS2", region_code)\ 436 | .glob(f"{region_code}_{art_type}{glob_pattern_suffix}")) 437 | ps1_art_files: Iterator[Path] = list(self.storage_location.joinpath("PS1", region_code)\ 438 | .glob(f"{region_code}_{art_type}{glob_pattern_suffix}")) 439 | 440 | 441 | for art_file in islice(max(ps1_art_files, ps2_art_files, key=len), 2 if art_type == "SCR" else 1): 442 | art_nr = '' 443 | if art_type == "SCR" and art_type == "BG": 444 | art_nr = int(art_file.name[16:18])+1 445 | 446 | dest_filename = f"{region_code}_{art_type}{art_nr}{art_file.suffix}" 447 | dest_file = self.opl_dir.joinpath( 448 | "ART", dest_filename) 449 | 450 | if not dest_file.exists() or overwrite: 451 | if not dest_file.exists(): 452 | dest_file.touch() 453 | 454 | with dest_file.open("wb") as dest,\ 455 | art_file.open("rb") as src: 456 | dest.write(self.resize_artwork( 457 | art_type, src.read(), str(art_file)).read()) 458 | 459 | case self.OperationState.DISABLED: 460 | raise DisabledException( 461 | "Storage features disabled, code should not have reached this point") 462 | 463 | def __get_artwork_for_game_indexed(self, region_code: str, overwrite: bool): 464 | art_count = 0 465 | for artwork in self.index.get_artworks_for_game(region_code): 466 | match self.operation_state: 467 | case self.OperationState.ONLINE: 468 | try: 469 | src_file = urlopen( 470 | urljoin(self.storage_location 471 | , str(artwork.get_relative_source_path())) 472 | ) 473 | except HTTPError: 474 | print(f"Error retrieving file \'{artwork.get_relative_source_path()}\' from online storage, are you sure the ZIP you uploaded is the same with the index link?", file=stderr) 475 | continue 476 | case self.OperationState.FILESYSTEM: 477 | try: 478 | src_file = self.storage_location.joinpath(artwork.get_relative_source_path()).open("rb") 479 | except FileNotFoundError: 480 | print(f"Error retrieving file \'{artwork.get_relative_source_path()}\' from online storage, are you sure the ZIP you uploaded is the same with the index link?", file=stderr) 481 | continue 482 | case self.OperationState.DISABLED: 483 | raise DisabledException( 484 | "Storage features disabled, code should not have reached this point") 485 | 486 | picture_data = src_file.read() 487 | picture_buffer: BytesIO = self.resize_artwork(artwork.art_type, picture_data, artwork.src_filename) 488 | dest_file = self.opl_dir.joinpath( 489 | artwork.get_relative_destination_path()) 490 | 491 | if not dest_file.exists() or overwrite: 492 | if not dest_file.exists(): 493 | dest_file.touch() 494 | 495 | dest_file = dest_file.open("wb") 496 | 497 | 498 | dest_file.write(picture_buffer.read()) 499 | dest_file.close() 500 | 501 | src_file.close() 502 | art_count += 1 503 | return art_count 504 | 505 | 506 | def get_game_title_csv_location(self, console: str = "PS1"): 507 | match self.operation_state: 508 | case self.OperationState.ONLINE: 509 | return f"{self.storage_location}{console}_LIST.CSV" 510 | case self.OperationState.FILESYSTEM: 511 | return 'file://' + \ 512 | quote(str(self.storage_location.joinpath( 513 | "{console}_LIST.CSV"))) 514 | case _: 515 | raise DisabledException( 516 | "Storage features disabled, code should not have reached this point") 517 | 518 | def get_game_title(self, region_code: str) -> str | None: 519 | """Retrieve game title from the storage game title CSVs 520 | 521 | Returns None if title cannot be found 522 | """ 523 | 524 | if self.index: 525 | title = self.index.get_title_for_game(region_code) 526 | if title: 527 | return title 528 | # On the august backup there are PS2 games located in PS1_LIST.CSV and vice versa.... 529 | # Have to search both 530 | for console in ["PS1", "PS2"]: 531 | game_csv_location = self.get_game_title_csv_location(console) 532 | 533 | try: 534 | processed_csv = self.process_game_list_csv( 535 | game_csv_location) 536 | try: 537 | return processed_csv[region_code] 538 | except KeyError: 539 | continue 540 | except HTTPError as e: 541 | print( 542 | "Cannot find game list in online storage, not retrieving name for " + region_code, file=stderr) 543 | except URLError as e: 544 | print( 545 | "Cannot find game list in storage, not retrieving name for " + region_code, file=stderr) 546 | print("Cannot find game " + region_code + 547 | " in PS1_LIST.CSV in the storage, not retrieving name.", file=stderr) 548 | return None 549 | 550 | 551 | class DisabledException(Exception): 552 | pass 553 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------