commit fd21d8c9a69fb0d887e54ed8e1dd8a634af26e88 Author: Patryk Gensch <43010113+patryk025@users.noreply.github.com> Date: Tue Aug 11 00:31:56 2026 +0200 Initialized project with game ingesting diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b445ed0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.gradle/ +build/ +out/ +.idea/ +*.iml +.DS_Store + +# baza i cache pochodnych — generowane, nie wersjonowane +data/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..d68389f --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/Rex-EMoolator"] + path = vendor/Rex-EMoolator + url = https://github.com/patryk025/Rex-EMoolator.git diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8300d4a --- /dev/null +++ b/build.gradle @@ -0,0 +1,85 @@ +plugins { + id 'java' + id 'application' +} + +group = 'pl.genschu.rexcatalog' +version = '0.1.0-SNAPSHOT' + +ext { + gdxVersion = '1.14.2' +} + +repositories { + mavenCentral() +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +dependencies { + // Podstawiane przez dependencySubstitution w settings.gradle na lokalny :core. + // Wersja jest nieistotna — nigdy nie trafia do rozwiązywania z repozytorium. + implementation 'pl.genschu:core:0.1-SNAPSHOT' + + // core loguje przez statyki Gdx.app, więc potrzebny jest headless backend + implementation "com.badlogicgames.gdx:gdx-backend-headless:$gdxVersion" + runtimeOnly "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop" + + implementation 'org.xerial:sqlite-jdbc:3.46.1.3' +} + +application { + mainClass = 'pl.genschu.rexcatalog.Main' +} + +tasks.named('run', JavaExec) { + // ./gradlew run --args="ingest /Users/genszu/Reksio" + systemProperty 'file.encoding', 'UTF-8' + // wersja :core trafia do bazy (copy.core_version, detection.core_version, + // artifact.tool_version) i steruje unieważnianiem cache'u pochodnych + systemProperty 'catalog.coreVersion', + providers.gradleProperty('coreVersion').getOrElse('nieznana') + systemProperty 'catalog.data', + providers.gradleProperty('dataDir').getOrElse("${projectDir}/data") +} + +/** + * Sprawdza, czy commit przypięty w submodule odpowiada tagowi z gradle.properties. + * Pomijane, gdy build celuje w zewnętrzną kopię roboczą (-PemulatorPath). + */ +tasks.register('verifyCoreVersion') { + group = 'verification' + description = 'Weryfikuje, że vendor/Rex-EMoolator stoi na tagu z coreVersion' + + def expected = providers.gradleProperty('coreVersion') + def usingExternal = providers.gradleProperty('emulatorPath').isPresent() + def submodule = file('vendor/Rex-EMoolator') + + doLast { + if (usingExternal.get()) { + logger.lifecycle('verifyCoreVersion: pominięte (-PemulatorPath, kopia robocza)') + return + } + def proc = new ProcessBuilder('git', 'describe', '--tags') + .directory(submodule) + .redirectErrorStream(true) + .start() + def actual = proc.inputStream.text.trim() + proc.waitFor() + + if (actual != expected.get()) { + throw new GradleException( + "Rozjazd wersji :core — submoduł stoi na '${actual}', " + + "a gradle.properties deklaruje '${expected.get()}'.\n" + + "Albo przestaw submoduł, albo zaktualizuj coreVersion.") + } + logger.lifecycle("verifyCoreVersion: :core = ${actual}") + } +} + +tasks.named('check') { + dependsOn 'verifyCoreVersion' +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6eb05f5 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,8 @@ +# Wersja :core, na którą przypięty jest submoduł vendor/Rex-EMoolator. +# Zadanie verifyCoreVersion pilnuje, żeby ta wartość zgadzała się z `git describe` +# w submodule — inaczej łatwo zbumpować jedno i zapomnieć o drugim. +coreVersion=v0.4.3 + +org.gradle.jvmargs=-Xmx2g +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..8cbc0d8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +#Tue Nov 25 14:03:02 CET 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f3b75f3 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..0a52d63 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,22 @@ +rootProject.name = 'rex-catalog' + +// Ścieżka do buildu emulatora. Domyślnie przypięty submoduł (reprodukowalnie, +// tag z gradle.properties). Do pracy na żywej kopii roboczej obu projektów: +// ./gradlew run -PemulatorPath=/Users/genszu/IdeaProjects/Rex-EMoolator +def emulatorPath = providers.gradleProperty('emulatorPath').getOrElse('vendor/Rex-EMoolator') +def emulator = file(emulatorPath) + +if (!new File(emulator, 'settings.gradle').exists()) { + throw new GradleException( + "Nie znaleziono buildu Rex-EMoolator w '${emulator}'.\n" + + "Zainicjuj submoduł: git submodule update --init --recursive") +} + +// Koordynat 'pl.genschu:core' nie istnieje w żadnym repozytorium Maven — jest +// deklarowany wyłącznie po to, żeby go tutaj podstawić lokalnym projektem :core. +// Dzięki temu repo emulatora nie wymaga ani 'group', ani 'maven-publish'. +includeBuild(emulator) { + dependencySubstitution { + substitute module('pl.genschu:core') using project(':core') + } +} diff --git a/src/main/java/pl/genschu/rexcatalog/Headless.java b/src/main/java/pl/genschu/rexcatalog/Headless.java new file mode 100644 index 0000000..0840a0a --- /dev/null +++ b/src/main/java/pl/genschu/rexcatalog/Headless.java @@ -0,0 +1,54 @@ +package pl.genschu.rexcatalog; + +import com.badlogic.gdx.Application; +import com.badlogic.gdx.ApplicationAdapter; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.backends.headless.HeadlessApplication; +import com.badlogic.gdx.backends.headless.HeadlessApplicationConfiguration; + +/** + * Podnosi headless aplikację libGDX, żeby statyki {@code Gdx.app} / {@code Gdx.files} + * były zainicjalizowane. + * + *
Klasy z {@code :core}, których używa katalog, sięgają po {@code Gdx.app} wyłącznie + * do logowania (np. {@code CNVParser}, {@code GameIniResolver}, {@code ImageLoader}), + * ale bez tego wywołania dostalibyśmy NPE na pierwszym logu. Prawdziwy kontekst GL + * pozostaje niedostępny — {@code Gdx.graphics} jest {@code null} — więc katalog nie może + * dotykać {@code Texture} ani {@code FontLoader}; do rasteryzacji służy {@code Pixmap}. + */ +public final class Headless { + + private static boolean started; + + private Headless() { + } + + public static synchronized void boot() { + if (started) { + return; + } + HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration(); + new HeadlessApplication(new ApplicationAdapter() { + }, config); + // core loguje bardzo gadatliwie (CNVParser: log na każdy obiekt) — przy + // indeksowaniu interesują nas tylko błędy. + Gdx.app.setLogLevel(Application.LOG_ERROR); + started = true; + } + + /** + * Zatrzymuje headless aplikację. + * + *
Bezwzględnie konieczne w CLI: {@code HeadlessApplication} tworzy wątek
+ * nie-daemon, więc bez tego wywołania JVM nie kończy pracy nawet po
+ * powrocie z {@code main()} — proces wisi w {@code DestroyJavaVM}, czekając
+ * w nieskończoność na pętlę libGDX.
+ */
+ public static synchronized void shutdown() {
+ if (!started) {
+ return;
+ }
+ Gdx.app.exit();
+ started = false;
+ }
+}
diff --git a/src/main/java/pl/genschu/rexcatalog/Main.java b/src/main/java/pl/genschu/rexcatalog/Main.java
new file mode 100644
index 0000000..28897c0
--- /dev/null
+++ b/src/main/java/pl/genschu/rexcatalog/Main.java
@@ -0,0 +1,185 @@
+package pl.genschu.rexcatalog;
+
+import pl.genschu.rexcatalog.db.Database;
+import pl.genschu.rexcatalog.ingest.Ingestor;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * CLI katalogu. Krok 1: indeksowanie obrazów do SQLite.
+ * REST + MCP siadają później na tej samej bazie.
+ */
+public final class Main {
+
+ private static final String CORE_VERSION =
+ System.getProperty("catalog.coreVersion", "nieznana");
+
+ public static void main(String[] args) throws Exception {
+ if (args.length == 0) {
+ usage();
+ return;
+ }
+ Path dataDir = Path.of(System.getProperty("catalog.data", "data"));
+
+ try {
+ switch (args[0]) {
+ case "ingest" -> ingest(dataDir, args);
+ case "list" -> list(dataDir);
+ case "stats" -> stats(dataDir);
+ default -> usage();
+ }
+ } finally {
+ // bez tego proces wisi po zakończeniu pracy — patrz Headless.shutdown()
+ Headless.shutdown();
+ }
+ }
+
+ private static void ingest(Path dataDir, String[] args) throws Exception {
+ if (args.length < 2) {
+ System.err.println("ingest wymaga co najmniej jednej ścieżki");
+ return;
+ }
+ Headless.boot();
+
+ List SQLite, nie Postgres: cały katalog to jeden plik obok cache'u pochodnych,
+ * więc przeniesienie kolekcji na inną maszynę to skopiowanie katalogu {@code data/}.
+ */
+public final class Database implements AutoCloseable {
+
+ private final Connection connection;
+
+ private Database(Connection connection) {
+ this.connection = connection;
+ }
+
+ public static Database open(Path dataDir) throws Exception {
+ Files.createDirectories(dataDir);
+ Path dbFile = dataDir.resolve("catalog.sqlite");
+
+ Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbFile.toAbsolutePath());
+ try (Statement st = conn.createStatement()) {
+ st.execute("PRAGMA journal_mode = WAL");
+ st.execute("PRAGMA synchronous = NORMAL");
+ st.execute("PRAGMA foreign_keys = ON");
+ }
+ Database db = new Database(conn);
+ db.applySchema();
+ return db;
+ }
+
+ public Connection connection() {
+ return connection;
+ }
+
+ private void applySchema() throws SQLException {
+ try (Statement st = connection.createStatement()) {
+ for (String ddl : SCHEMA) {
+ st.executeUpdate(ddl);
+ }
+ }
+ }
+
+ @Override
+ public void close() throws SQLException {
+ connection.close();
+ }
+
+ /**
+ * Model trójpoziomowy: {@code title} (dzieło) → {@code edition} (wydanie)
+ * → {@code copy} (konkretny plik na dysku).
+ *
+ * Rozdział {@code file} / {@code blob} sprawia, że porównanie dwóch wydań
+ * jest operacją na zbiorach {@code blob_sha1}, a cache pochodnych (odszyfrowany
+ * CNV, PNG z IMG) można kluczować treścią — identyczny plik w trzech obrazach
+ * dekodujemy raz.
+ */
+ private static final String[] SCHEMA = {
+ """
+ CREATE TABLE IF NOT EXISTS title (
+ id INTEGER PRIMARY KEY,
+ slug TEXT NOT NULL UNIQUE,
+ name TEXT NOT NULL,
+ series TEXT,
+ publisher TEXT DEFAULT 'Aidem Media'
+ )
+ """,
+ """
+ CREATE TABLE IF NOT EXISTS edition (
+ id INTEGER PRIMARY KEY,
+ title_id INTEGER REFERENCES title(id),
+ label TEXT,
+ dll_sha1 TEXT UNIQUE,
+ engine_detected TEXT,
+ engine_override TEXT,
+ compiler_detected TEXT,
+ compiler_override TEXT,
+ release_date TEXT,
+ distributor TEXT,
+ notes TEXT
+ )
+ """,
+ """
+ CREATE TABLE IF NOT EXISTS edition_language (
+ edition_id INTEGER NOT NULL REFERENCES edition(id),
+ lang TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('audio', 'text', 'ui')),
+ PRIMARY KEY (edition_id, lang, role)
+ )
+ """,
+ // Kopia to nośnik, nie gra: jedna płyta bywa dwupackiem z dwoma drzewami
+ // gier, więc przypisanie do wydania wisi przy game_root, nie tutaj.
+ // status mówi, czy zawartość w ogóle dało się odczytać.
+ """
+ CREATE TABLE IF NOT EXISTS copy (
+ id INTEGER PRIMARY KEY,
+ container TEXT NOT NULL CHECK (container IN ('iso', 'dir', 'zip')),
+ status TEXT NOT NULL DEFAULT 'ok'
+ CHECK (status IN ('ok', 'installer', 'unreadable')),
+ status_note TEXT,
+ path TEXT NOT NULL UNIQUE,
+ display_name TEXT,
+ size INTEGER,
+ sha256 TEXT,
+ file_count INTEGER,
+ ingested_at TEXT,
+ core_version TEXT,
+
+ source_kind TEXT NOT NULL DEFAULT 'nieznane'
+ CHECK (source_kind IN ('wlasny_zgraj', 'archive_org',
+ 'redump', 'inne', 'nieznane')),
+ source_url TEXT,
+ source_ref TEXT,
+ acquired_at TEXT,
+ rip_tool TEXT,
+ media_note TEXT,
+ verified INTEGER NOT NULL DEFAULT 0,
+ notes TEXT
+ )
+ """,
+ // Poziom pośredni copy → game_root → edition. root_path to '' dla zwykłego
+ // obrazu, a np. 'herkules' / 'odyseusz' dla dwupacka — dwa drzewa gier na
+ // jednej płycie, każde z własnym silnikiem i własnym wydaniem (a więc i tytułem).
+ """
+ CREATE TABLE IF NOT EXISTS game_root (
+ id INTEGER PRIMARY KEY,
+ copy_id INTEGER NOT NULL REFERENCES copy(id) ON DELETE CASCADE,
+ root_path TEXT NOT NULL,
+ edition_id INTEGER REFERENCES edition(id),
+ engine_detected TEXT,
+ engine_override TEXT,
+ UNIQUE (copy_id, root_path)
+ )
+ """,
+ """
+ CREATE TABLE IF NOT EXISTS blob (
+ sha1 TEXT PRIMARY KEY,
+ size INTEGER NOT NULL,
+ format TEXT,
+ encrypted INTEGER NOT NULL DEFAULT 0
+ )
+ """,
+ // path jest kanoniczny (małe litery) — IsoFileSystem normalizuje ścieżki,
+ // a LocalFileSystem zachowuje wielkość liter z dysku. Bez wspólnej postaci
+ // porównanie obrazu z rozpakowanym katalogiem rozjeżdża się na ścieżkach.
+ // path_raw zachowuje oryginał, o ile kontener go zna.
+ """
+ CREATE TABLE IF NOT EXISTS file (
+ copy_id INTEGER NOT NULL REFERENCES copy(id) ON DELETE CASCADE,
+ path TEXT NOT NULL,
+ path_raw TEXT,
+ blob_sha1 TEXT NOT NULL REFERENCES blob(sha1),
+ PRIMARY KEY (copy_id, path)
+ )
+ """,
+ "CREATE INDEX IF NOT EXISTS idx_file_blob ON file(blob_sha1)",
+ "CREATE INDEX IF NOT EXISTS idx_blob_format ON blob(format)",
+ // Każdy detektor dopisuje wiersz z dowodem, zamiast nadpisywać pole.
+ // Dorzucenie detektora kompilera to nowy wiersz, nie migracja schematu.
+ """
+ CREATE TABLE IF NOT EXISTS detection (
+ id INTEGER PRIMARY KEY,
+ copy_id INTEGER NOT NULL REFERENCES copy(id) ON DELETE CASCADE,
+ root_path TEXT NOT NULL DEFAULT '',
+ field TEXT NOT NULL,
+ value TEXT,
+ confidence REAL,
+ evidence TEXT,
+ detector TEXT,
+ core_version TEXT,
+ detected_at TEXT
+ )
+ """,
+ "CREATE INDEX IF NOT EXISTS idx_detection_copy ON detection(copy_id, field)",
+ // tool_version pozwala unieważnić tylko te artefakty, których parser się zmienił
+ """
+ CREATE TABLE IF NOT EXISTS artifact (
+ blob_sha1 TEXT NOT NULL REFERENCES blob(sha1),
+ kind TEXT NOT NULL,
+ path TEXT NOT NULL,
+ tool_version TEXT NOT NULL,
+ created_at TEXT,
+ PRIMARY KEY (blob_sha1, kind)
+ )
+ """
+ };
+}
diff --git a/src/main/java/pl/genschu/rexcatalog/ingest/EngineDetector.java b/src/main/java/pl/genschu/rexcatalog/ingest/EngineDetector.java
new file mode 100644
index 0000000..60d303b
--- /dev/null
+++ b/src/main/java/pl/genschu/rexcatalog/ingest/EngineDetector.java
@@ -0,0 +1,208 @@
+package pl.genschu.rexcatalog.ingest;
+
+import pl.genschu.bloomooemulator.logic.GameFamilies;
+import pl.genschu.bloomooemulator.logic.KnownHashes;
+
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Rozpoznaje silnik w każdym korzeniu gry znalezionym w kopii.
+ *
+ * Kolekcja zawiera co najmniej trzy różne silniki (BlooMoo, Piklib, autorski
+ * KI Engine z Tajemnicy Trzeciego Wymiaru), a płyty bywają dwupackami
+ * z osobnym drzewem gry na katalog. Dlatego detekcja jest łańcuchem sygnatur
+ * uruchamianym per korzeń, a nie pojedynczym sprawdzeniem nazwy biblioteki.
+ *
+ * Tablice hashy pochodzą z {@code :core} ({@link KnownHashes}, {@link GameFamilies}),
+ * więc wydania Piklib/BlooMoo aktualizują się razem z emulatorem. Silniki spoza tej
+ * rodziny dostają samą nazwę — konkretne wydanie ustala człowiek przez override.
+ */
+public final class EngineDetector {
+
+ private EngineDetector() {
+ }
+
+ /** Ustalenie detektora wraz z dowodem, na którym się opiera. */
+ public record Fact(String field, String value, double confidence, String evidence) {
+ }
+
+ /** Jeden korzeń gry w kopii — {@code ""} dla zwykłego obrazu, {@code "herkules"} dla dwupacka. */
+ public record Root(String rootPath, String engine, List Magic bytes biorą się z dokumentacji formatów w repo emulatora
+ * ({@code docs/pl/formats/}) i z podglądu realnych plików.
+ */
+public final class FormatSniffer {
+
+ private FormatSniffer() {
+ }
+
+ /** Ile bajtów początku pliku wystarczy do rozpoznania. */
+ public static final int PROBE_BYTES = 16;
+
+ public record Result(String format, boolean encrypted) {
+ }
+
+ public static Result sniff(String path, byte[] head, int headLength) {
+ boolean encrypted = startsWith(head, headLength, "{<");
+
+ String byMagic = byMagic(head, headLength);
+ if (byMagic != null) {
+ return new Result(byMagic, encrypted);
+ }
+ return new Result(byExtension(path, encrypted), encrypted);
+ }
+
+ private static String byMagic(byte[] head, int len) {
+ if (startsWith(head, len, "PIK\0")) {
+ return "IMG";
+ }
+ if (startsWith(head, len, "NVP\0")) {
+ return "ANN";
+ }
+ if (startsWith(head, len, "RIFF")) {
+ return "WAV";
+ }
+ if (startsWith(head, len, "MZ")) {
+ return "PE";
+ }
+ if (startsWith(head, len, "{<")) {
+ // zaszyfrowany skrypt — konkretny rodzaj rozstrzyga rozszerzenie
+ return null;
+ }
+ return null;
+ }
+
+ private static String byExtension(String path, boolean encrypted) {
+ int dot = path.lastIndexOf('.');
+ if (dot < 0 || dot == path.length() - 1) {
+ return encrypted ? "SCRIPT" : "BIN";
+ }
+ String ext = path.substring(dot + 1).toUpperCase(Locale.ROOT);
+ return switch (ext) {
+ case "CNV", "DEF", "SEQ", "CLASS", "INI" -> ext;
+ case "DTA", "ARR", "IMG", "ANN", "FNT", "SEK", "INE", "MAR" -> ext;
+ case "WAV", "MID", "AVI", "BMP", "TXT", "DLL", "EXE" -> ext;
+ default -> encrypted ? "SCRIPT" : ext;
+ };
+ }
+
+ private static boolean startsWith(byte[] data, int len, String prefix) {
+ if (len < prefix.length()) {
+ return false;
+ }
+ for (int i = 0; i < prefix.length(); i++) {
+ if ((data[i] & 0xFF) != prefix.charAt(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/pl/genschu/rexcatalog/ingest/Ingestor.java b/src/main/java/pl/genschu/rexcatalog/ingest/Ingestor.java
new file mode 100644
index 0000000..a6dabf9
--- /dev/null
+++ b/src/main/java/pl/genschu/rexcatalog/ingest/Ingestor.java
@@ -0,0 +1,375 @@
+package pl.genschu.rexcatalog.ingest;
+
+import pl.genschu.bloomooemulator.engine.filesystem.AssetSourceDispatcher;
+import pl.genschu.bloomooemulator.engine.filesystem.IFileSystem;
+import pl.genschu.rexcatalog.db.Database;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.security.MessageDigest;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Indeksuje pojedynczą kopię (ISO / ZIP / rozpakowany katalog) do bazy katalogu.
+ *
+ * Nic nie rozpakowuje na dysk — czyta przez {@link IFileSystem} z {@code :core},
+ * czyli tę samą implementację ISO9660/Joliet, której używa emulator przy uruchamianiu gry.
+ * Kopia, której nie da się odczytać, i tak trafia do bazy — ze statusem i powodem,
+ * bo „mam ten obraz, ale go nie otwieram" to też fakt wart skatalogowania.
+ */
+public final class Ingestor {
+
+ private final Database db;
+ private final String coreVersion;
+
+ public Ingestor(Database db, String coreVersion) {
+ this.db = db;
+ this.coreVersion = coreVersion;
+ }
+
+ public record RootSummary(String rootPath, String engine, String edition) {
+ }
+
+ public record Result(String path, String container, String status, String statusNote,
+ int fileCount, long bytes, List