kitty-game-composer 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Game Composer public Python SDK."""
2
+ from .api import execute
3
+ from .sdk import RuntimeAdapter, load_manifest, run_project
4
+
5
+ __all__ = ["RuntimeAdapter", "execute", "load_manifest", "run_project"]
gamecomposer/api.py ADDED
@@ -0,0 +1,342 @@
1
+ """Shared API for the CLI, desktop app, and embedding applications."""
2
+ import json
3
+ from urllib.request import urlopen
4
+ from pathlib import Path
5
+
6
+ from .core import load, order
7
+
8
+ LIFECYCLE_ACTIONS = frozenset({"up", "ps", "status", "logs", "stop", "down", "instances"})
9
+
10
+
11
+ def execute(path, action="config", names=(), instance=None, new_instance=False):
12
+ """Run one action.
13
+
14
+ ``instance`` selects which copy of the project a lifecycle action targets
15
+ (default instance ``"1"``); ``new_instance=True`` with ``up`` starts another
16
+ independent copy. ``action="ls"`` ignores ``path`` and returns JSON for
17
+ every Game Composer instance Kiri knows about.
18
+ """
19
+ if action == "ls":
20
+ from .runtime import list_all
21
+ return json.dumps(list_all(), indent=2)
22
+ path = Path(path).resolve()
23
+ if action == "config":
24
+ project = load(path)
25
+ selected = order(project, names or None)
26
+ return json.dumps({**project, "services": {s: project["services"][s] for s in selected}}, indent=2)
27
+ if action not in LIFECYCLE_ACTIONS:
28
+ raise ValueError(f"Unknown action: {action}")
29
+ from .runtime import invoke
30
+ if instance or new_instance:
31
+ return invoke(path, action, names, instance=instance or None, new_instance=bool(new_instance))
32
+ return invoke(path, action, names)
33
+
34
+
35
+ # ------------------------------------------------------------------ registry
36
+ # JSON entry points for the desktop app and SDKs. ``request`` returns an
37
+ # envelope {"ok": true, "data": ...} or {"ok": false, "error": {type, message}}.
38
+ REGISTRY_OPERATIONS = (
39
+ "registry.catalog", "registry.list", "registry.preview",
40
+ "library.list", "library.add", "library.addLocalGame", "library.addLocalFolder", "library.updateGame",
41
+ "library.remove", "library.favorite",
42
+ "manifest.validate", "sandbox.checkName", "sandbox.planTemplate", "sandbox.compose",
43
+ "sandbox.create", "sandbox.list", "sandbox.get", "sandbox.readManifest", "sandbox.saveManifest",
44
+ "manifest.parse", "manifest.dump", "manifest.import", "sandbox.export", "sandbox.duplicate",
45
+ "library.detectLocalGame", "sandbox.createLocal",
46
+ "library.addConsole", "library.addController", "library.updateItem",
47
+ "library.addFromUrl", "library.addUpload", "library.findByUrl", "library.findBySha256",
48
+ "library.inspectUrl", "sandbox.composeFromUrls", "sandbox.createFromUrls",
49
+ "library.cover",
50
+ )
51
+
52
+ # ROM extension -> registry platform. Used only to pre-select a console in the
53
+ # wizard; the library accepts any file, including unknown extensions.
54
+ LOCAL_GAME_PLATFORMS = {
55
+ ".nes": "nes", ".fds": "nes", ".sfc": "snes", ".smc": "snes", ".gb": "gb",
56
+ ".gbc": "gbc", ".gba": "gba", ".md": "md", ".gen": "md",
57
+ ".sms": "sms", ".gg": "gg", ".n64": "n64", ".z64": "n64",
58
+ ".v64": "n64", ".nds": "nds", ".pce": "pce", ".a26": "a2600",
59
+ ".ngp": "ngp", ".ngc": "ngp", ".ws": "ws", ".wsc": "ws", ".vb": "vb",
60
+ ".iso": "psx", ".cue": "psx", ".chd": "psx",
61
+ }
62
+
63
+
64
+ def _dedupe(items):
65
+ seen, result = set(), []
66
+ for item in items:
67
+ key = item.get("id")
68
+ if key in seen:
69
+ continue
70
+ seen.add(key)
71
+ result.append(item)
72
+ return result
73
+
74
+
75
+ def _local_game(path, title, console_id, registry, library):
76
+ """Describe a ROM on disk the way ``compose`` expects, without copying it."""
77
+ from .library import file_sha256, safe_file_name
78
+ rom_path = Path(path).expanduser().resolve()
79
+ if not rom_path.is_file():
80
+ raise ValueError("Choose a ROM file from disk.")
81
+ console = library.console_entry(console_id, registry)
82
+ return {"id": "local-preview", "source": "local", "title": title or rom_path.stem,
83
+ "platform": console["platform"], "fileName": safe_file_name(rom_path.name),
84
+ "sha256": file_sha256(rom_path), "path": str(rom_path)}
85
+
86
+
87
+ def _import_missing_files(document, base):
88
+ """Path sources that cannot be satisfied on this machine: [{path, sha256, reason}]."""
89
+ from .library import file_sha256
90
+ missing = []
91
+ for service in document.get("services", {}).values():
92
+ for component in ("emulator", "game"):
93
+ source = service.get(component, {}).get("source", {})
94
+ if "path" not in source:
95
+ continue
96
+ candidate = base / source["path"][2:] if base is not None else None
97
+ if candidate is None or not candidate.is_file():
98
+ missing.append({"path": source["path"], "sha256": source.get("sha256"), "reason": "missing"})
99
+ elif source.get("sha256") and file_sha256(candidate) != source["sha256"].lower():
100
+ missing.append({"path": source["path"], "sha256": source.get("sha256"), "reason": "checksum"})
101
+ return missing
102
+
103
+
104
+ def _url_assets(payload, registry, library):
105
+ """Fetch, verify and persist both URL assets before any sandbox is written."""
106
+ from .local_catalog import N64_PLATFORM
107
+ from .library import MAX_EMULATOR_BYTES
108
+ platform = payload.get("platform") or N64_PLATFORM
109
+ emulator = library.add_from_url(
110
+ payload["emulatorUrl"], kind="console", name=payload.get("emulatorName") or "gopher64",
111
+ platform=platform, console_id=payload.get("consoleId"), registry=None,
112
+ sha256=payload.get("emulatorSha256"), size=payload.get("emulatorSize"),
113
+ license=payload.get("emulatorLicense") or "GPL-3.0",
114
+ max_bytes=payload.get("emulatorMaxBytes") or MAX_EMULATOR_BYTES,
115
+ )
116
+ game = library.add_from_url(
117
+ payload["gameUrl"], kind="game", name=payload.get("title"),
118
+ platform=platform, console_id=payload.get("consoleId"), registry=None,
119
+ sha256=payload.get("gameSha256"), size=payload.get("gameSize"),
120
+ license=payload.get("gameLicense"),
121
+ )
122
+ return emulator, game
123
+
124
+
125
+ def _compose_url_assets(payload, registry, library, emulator, game):
126
+ """Manifest preview with pinned URL sources; no project, no download."""
127
+ from .local_catalog import N64_CONSOLE_ID, N64_CONTROLLER_ID
128
+ from .preview import compose, validate_text
129
+ from .sandboxes import _dump_yaml, slugify
130
+ console_id = payload.get("consoleId") or N64_CONSOLE_ID
131
+ controller_id = payload.get("controllerId") or N64_CONTROLLER_ID
132
+ parts = library.resolve_parts(console_id, controller_id, payload.get("mapping"))
133
+ descriptor = {"id": "url-game", "title": payload.get("title") or "URL game",
134
+ "platform": payload.get("platform") or "n64", "fileName": game["fileName"]}
135
+ composed = compose(registry, name=slugify(payload.get("name") or "new-sandbox"), game=descriptor, **parts)
136
+ service = composed["document"]["services"][composed["service"]]
137
+ service["emulator"]["source"] = {"url": emulator["url"], "sha256": emulator["sha256"],
138
+ "maxBytes": payload.get("emulatorMaxBytes") or 128 * 1024 ** 2}
139
+ service["game"]["source"] = {"url": game["url"], "sha256": game["sha256"],
140
+ "maxBytes": min(payload.get("gameMaxBytes") or 2 * 1024 ** 3,
141
+ 8 * 1024 ** 3 - 1)}
142
+ text = _dump_yaml(composed["document"])
143
+ checked = validate_text(text)
144
+ return {"manifestText": text, "ok": checked["ok"], "errors": checked["errors"]}
145
+
146
+
147
+ def _context(payload):
148
+ from .library import Library
149
+ from .registry import Registry, cache_dir, data_dir
150
+ from .sandboxes import Sandboxes
151
+ registry = Registry(
152
+ index_url=payload.get("registryUrl") or Registry().index_url,
153
+ cache=Path(payload["cacheDir"]) if payload.get("cacheDir") else cache_dir(),
154
+ )
155
+ root = Path(payload["dataDir"]) if payload.get("dataDir") else data_dir()
156
+ return registry, Library(root), Sandboxes(registry=registry, root=root)
157
+
158
+
159
+ def _dispatch(operation, p):
160
+ from .preview import compose, preview, validate_text
161
+ registry, library, sandboxes = _context(p)
162
+ if operation == "registry.catalog":
163
+ catalog = registry.catalog(refresh=bool(p.get("refresh")))
164
+ index = catalog["index"]
165
+ return {**{k: v for k, v in catalog.items() if k != "index"},
166
+ "entries": index["entries"], "kinds": index.get("kinds"), "policy": index.get("policy")}
167
+ if operation == "registry.list":
168
+ return registry.entries(p.get("kind"), p.get("query", ""), p.get("platform"))
169
+ if operation == "registry.preview":
170
+ return preview(registry, p["kind"], p["id"])
171
+ if operation == "library.list":
172
+ return library.load()
173
+ if operation == "library.cover":
174
+ return library.cover_data(p["id"])
175
+ if operation == "library.add":
176
+ return library.add_from_registry(registry, p["kind"], p["id"], favorite=p.get("favorite", True))
177
+ if operation == "library.addFromUrl":
178
+ return library.add_from_url(
179
+ p["url"], kind=p.get("kind", "game"), name=p.get("name"),
180
+ title=p.get("title"), console_id=p.get("consoleId"), platform=p.get("platform"),
181
+ registry=registry if p.get("consoleId") else None, sha256=p.get("sha256"),
182
+ size=p.get("size"), license=p.get("license"), max_bytes=p.get("maxBytes"),
183
+ )
184
+ if operation == "library.addUpload":
185
+ return library.add_uploaded_file(p["path"], kind=p.get("kind", "game"), name=p.get("name"),
186
+ console_id=p.get("consoleId"),
187
+ registry=registry if p.get("consoleId") else None)
188
+ if operation == "library.inspectUrl":
189
+ return library.inspect_url(p["url"], max_bytes=p.get("maxBytes") or 128 * 1024 ** 2)
190
+ if operation == "library.findByUrl":
191
+ return library.catalog.find_by_url(p.get("kind"), p["url"])
192
+ if operation == "library.findBySha256":
193
+ return library.catalog.find_by_sha256(p["kind"], p["sha256"])
194
+ if operation == "library.addLocalGame":
195
+ return library.add_local_game(p["path"], title=p.get("title"), console_id=p["consoleId"], registry=registry,
196
+ cover_path=p.get("coverPath"), notes=p.get("notes", ""))
197
+ if operation == "library.detectLocalGame":
198
+ candidate = Path(p["path"]).expanduser().resolve()
199
+ if not candidate.is_file():
200
+ raise ValueError("Choose a ROM file from disk.")
201
+ platform = LOCAL_GAME_PLATFORMS.get(candidate.suffix.lower())
202
+ consoles = registry.entries("console")
203
+ matching = [entry for entry in consoles if entry.get("platform") == platform] if platform else []
204
+ controllers = [entry for entry in registry.entries("controller")
205
+ if platform in entry.get("defaultMapping", {})] if platform else []
206
+ known_consoles = [entry for entry in library.load().get("consoles", [])
207
+ if entry.get("platform") == platform] if platform else []
208
+ # An unknown extension (or a platform with no registry console) still
209
+ # gets the full list: the library accepts any game.
210
+ known_controllers = [entry for entry in library.load().get("controllers", [])
211
+ if entry.get("source") == "config" and platform in entry.get("platforms", [])] if platform else []
212
+ return {"path": str(candidate), "title": candidate.stem, "extension": candidate.suffix.lower(),
213
+ "platform": platform, "consoles": _dedupe(known_consoles + matching) or consoles,
214
+ "controllers": _dedupe(known_controllers + controllers) or registry.entries("controller")}
215
+ if operation == "library.addLocalFolder":
216
+ return library.add_local_folder(p["path"], console_id=p["consoleId"], registry=registry)
217
+ if operation == "library.updateGame":
218
+ return library.update_game(p["id"], registry, **p.get("fields", {}))
219
+ if operation == "library.remove":
220
+ library.remove(p["kind"], p["id"])
221
+ return library.load()
222
+ if operation == "library.addConsole":
223
+ return library.add_console_config(registry, base_id=p["baseId"], name=p.get("name"), settings=p.get("settings"))
224
+ if operation == "library.addController":
225
+ return library.add_controller_config(registry, base_id=p["baseId"], name=p.get("name"),
226
+ gamepads=p.get("gamepads"), mapping=p.get("mapping"))
227
+ if operation == "library.updateItem":
228
+ if p["kind"] == "game":
229
+ return library.update_game(p["id"], registry, **p.get("fields", {}))
230
+ return library.update_config(p["kind"], p["id"], registry, **p.get("fields", {}))
231
+ if operation == "library.favorite":
232
+ return library.set_favorite(p["kind"], p["id"], bool(p.get("favorite", True)))
233
+ if operation == "manifest.validate":
234
+ checked = validate_text(p["text"])
235
+ return {"ok": checked["ok"], "errors": checked["errors"]}
236
+ if operation == "manifest.parse":
237
+ checked = validate_text(p["text"])
238
+ return {"ok": checked["ok"], "document": checked["document"], "errors": checked["errors"]}
239
+ if operation == "manifest.dump":
240
+ from .sandboxes import _dump_yaml
241
+ document = p["document"]
242
+ text = _dump_yaml(document)
243
+ checked = validate_text(text)
244
+ return {"manifestText": text, "ok": checked["ok"], "errors": checked["errors"]}
245
+ if operation == "manifest.import":
246
+ if p.get("url"):
247
+ if not p["url"].startswith("https://"):
248
+ raise ValueError("manifest URL must use HTTPS")
249
+ with urlopen(p["url"], timeout=15) as response:
250
+ raw = response.read(2 * 1024 * 1024 + 1)
251
+ if len(raw) > 2 * 1024 * 1024:
252
+ raise ValueError("manifest exceeds 2 MiB")
253
+ text = raw.decode("utf-8")
254
+ else:
255
+ text = Path(p["path"]).expanduser().read_text(encoding="utf-8")
256
+ checked = validate_text(text)
257
+ base = Path(p["baseDir"]).expanduser() if p.get("baseDir") else (
258
+ Path(p["path"]).expanduser().parent if p.get("path") else None)
259
+ missing = _import_missing_files(checked["document"], base) if checked["ok"] else []
260
+ return {"manifestText": text, "ok": checked["ok"], "errors": checked["errors"], "missingFiles": missing}
261
+ if operation == "sandbox.checkName":
262
+ return sandboxes.check_name(p.get("name", ""))
263
+ if operation == "sandbox.planTemplate":
264
+ return sandboxes.plan_template(p["templateId"], overrides=p.get("overrides"), manifest_text=p.get("manifestText"))
265
+ if operation == "sandbox.compose":
266
+ if p.get("localPath"):
267
+ game = _local_game(p["localPath"], p.get("title"), p["consoleId"], registry, library)
268
+ else:
269
+ game = sandboxes._game(p["gameId"], library)
270
+ parts = library.resolve_parts(p.get("consoleId"), p.get("controllerId"), p.get("mapping"))
271
+ from .sandboxes import slugify
272
+ # Same slug Create writes, so the preview name matches the project that would be made.
273
+ composed = compose(registry, name=slugify(p["name"]) if p.get("name") else "new-sandbox", game=game, **parts)
274
+ if p.get("localPath"):
275
+ composed["document"]["services"][composed["service"]]["game"]["source"]["sha256"] = game["sha256"]
276
+ from .sandboxes import _dump_yaml
277
+ text = _dump_yaml(composed["document"])
278
+ return {"manifestText": text, **{k: v for k, v in validate_text(text).items() if k != "document"}}
279
+ if operation == "sandbox.create":
280
+ common = dict(start=bool(p.get("start")))
281
+ if p.get("templateId"):
282
+ return sandboxes.create_from_template(p["templateId"], p["name"], p.get("description", ""),
283
+ overrides=p.get("overrides"), manifest_text=p.get("manifestText"), **common)
284
+ return sandboxes.create_from_parts(p["name"], p.get("description", ""), console_id=p["consoleId"],
285
+ game_id=p["gameId"], controller_id=p["controllerId"],
286
+ mapping=p.get("mapping"), overrides=p.get("overrides"),
287
+ library=library, manifest_text=p.get("manifestText"), **common)
288
+ if operation == "sandbox.composeFromUrls":
289
+ emulator = {"url": p["emulatorUrl"], "sha256": p["emulatorSha256"], "fileName": "emulator"}
290
+ game = {"url": p["gameUrl"], "sha256": p["gameSha256"], "fileName": "game"}
291
+ return _compose_url_assets(p, registry, library, emulator, game)
292
+ if operation == "sandbox.createFromUrls":
293
+ emulator, game = _url_assets(p, registry, library)
294
+ from .local_catalog import N64_CONSOLE_ID, N64_CONTROLLER_ID
295
+ return sandboxes.create_from_url_assets(
296
+ p["name"], p.get("description", ""), emulator=emulator, game=game,
297
+ console_id=p.get("consoleId") or N64_CONSOLE_ID,
298
+ controller_id=p.get("controllerId") or N64_CONTROLLER_ID,
299
+ mapping=p.get("mapping"), library=library, manifest_text=p.get("manifestText"),
300
+ start=bool(p.get("start")))
301
+ if operation == "sandbox.createLocal":
302
+ game = library.add_local_game(p["romPath"], title=p.get("title"), console_id=p["consoleId"],
303
+ registry=registry, cover_path=p.get("coverPath"), notes=p.get("notes", ""))
304
+ return sandboxes.create_from_parts(p["name"], p.get("description", ""), console_id=p["consoleId"],
305
+ game_id=game["id"], controller_id=p["controllerId"], mapping=p.get("mapping"),
306
+ overrides=p.get("overrides"), library=library, manifest_text=p.get("manifestText"), start=bool(p.get("start")))
307
+ if operation == "sandbox.list":
308
+ return sandboxes.list()
309
+ if operation == "sandbox.get":
310
+ return sandboxes.get(p["id"])
311
+ if operation == "sandbox.readManifest":
312
+ return sandboxes.read_manifest(p["id"])
313
+ if operation == "sandbox.saveManifest":
314
+ return sandboxes.save_manifest(p["id"], p["text"])
315
+ if operation == "sandbox.export":
316
+ return sandboxes.export_manifest(p["id"], p["path"], copy_files=bool(p.get("copyFiles", True)))
317
+ if operation == "sandbox.duplicate":
318
+ return sandboxes.duplicate(p["id"], p["name"], p.get("description", ""))
319
+ raise ValueError(f"Unknown operation: {operation}")
320
+
321
+
322
+ def request(operation, payload=None):
323
+ """Run one registry/library/sandbox operation and return a JSON-safe envelope."""
324
+ if operation not in REGISTRY_OPERATIONS:
325
+ return {"ok": False, "error": {"type": "ValueError", "message": f"Unknown operation: {operation}"}}
326
+ if payload is not None and not isinstance(payload, dict):
327
+ return {"ok": False, "error": {"type": "TypeError", "message": "payload must be an object"}}
328
+ try:
329
+ return {"ok": True, "data": _dispatch(operation, payload or {})}
330
+ except KeyError as exc:
331
+ return {"ok": False, "error": {"type": "KeyError", "message": f"missing field {exc.args[0]!r}"}}
332
+ except (ValueError, OSError, RuntimeError) as exc:
333
+ return {"ok": False, "error": {"type": type(exc).__name__, "message": str(exc)}}
334
+
335
+
336
+ def request_json(operation, payload_json="{}"):
337
+ """String in, string out: used by the desktop bridge (``python -c``)."""
338
+ try:
339
+ payload = json.loads(payload_json or "{}")
340
+ except json.JSONDecodeError as exc:
341
+ return json.dumps({"ok": False, "error": {"type": "JSONDecodeError", "message": str(exc)}})
342
+ return json.dumps(request(operation, payload))
@@ -0,0 +1,236 @@
1
+ """SQLite catalog: the durable source of truth for user-added library entries.
2
+
3
+ ``library.json`` stays readable and is written as a mirror, but the database is
4
+ authoritative. On first open an existing ``library.json`` is imported into
5
+ the database without deleting or rewriting the original file. Later, any row
6
+ that appears only in the JSON (for example, copied in while the app was off)
7
+ is added to the database on read, so nothing in an existing library is lost.
8
+
9
+ Every row keeps its provenance: how it was obtained (``registry``, ``url``,
10
+ ``upload``, ``file`` or ``config``), the original URL when there is one, the
11
+ SHA-256 and byte size of the stored asset, a known license, and the time it
12
+ was added.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import sqlite3
18
+ import time
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ from .registry import data_dir
23
+
24
+ SCHEMA_VERSION = 1
25
+ KINDS = ("console", "game", "controller")
26
+ PROVENANCE = ("registry", "url", "upload", "file", "config")
27
+ SECTIONS = {"console": "consoles", "game": "games", "controller": "controllers"}
28
+
29
+
30
+ class CatalogError(ValueError):
31
+ pass
32
+
33
+
34
+ def _empty() -> dict:
35
+ return {"schemaVersion": 1, "consoles": [], "games": [], "controllers": []}
36
+
37
+
38
+ @dataclass
39
+ class CatalogDB:
40
+ """One SQLite database under the user data folder."""
41
+
42
+ root: Path = field(default_factory=data_dir)
43
+ migrated: bool = field(default=False, init=False, repr=False)
44
+
45
+ @property
46
+ def path(self) -> Path:
47
+ return Path(self.root) / "catalog.sqlite3"
48
+
49
+ @property
50
+ def json_path(self) -> Path:
51
+ return Path(self.root) / "library.json"
52
+
53
+ def connect(self) -> sqlite3.Connection:
54
+ self.path.parent.mkdir(parents=True, exist_ok=True)
55
+ connection = sqlite3.connect(self.path)
56
+ connection.row_factory = sqlite3.Row
57
+ connection.execute("PRAGMA journal_mode=WAL")
58
+ connection.execute("PRAGMA foreign_keys=ON")
59
+ connection.executescript(
60
+ """
61
+ CREATE TABLE IF NOT EXISTS catalog_meta (
62
+ key TEXT PRIMARY KEY,
63
+ value TEXT NOT NULL
64
+ );
65
+ CREATE TABLE IF NOT EXISTS catalog_items (
66
+ id TEXT PRIMARY KEY,
67
+ kind TEXT NOT NULL CHECK (kind IN ('console', 'game', 'controller')),
68
+ source TEXT NOT NULL,
69
+ provenance TEXT NOT NULL,
70
+ name TEXT NOT NULL,
71
+ platform TEXT,
72
+ console_id TEXT,
73
+ url TEXT,
74
+ sha256 TEXT,
75
+ size INTEGER,
76
+ license TEXT,
77
+ added_at INTEGER NOT NULL,
78
+ favorite INTEGER NOT NULL DEFAULT 0,
79
+ data TEXT NOT NULL
80
+ );
81
+ CREATE INDEX IF NOT EXISTS catalog_items_kind ON catalog_items(kind);
82
+ CREATE INDEX IF NOT EXISTS catalog_items_sha ON catalog_items(sha256);
83
+ CREATE INDEX IF NOT EXISTS catalog_items_url ON catalog_items(url);
84
+ """
85
+ )
86
+ self._migrate(connection)
87
+ return connection
88
+
89
+ def _migrate(self, connection: sqlite3.Connection) -> None:
90
+ """Import library.json once; later runs only add rows not in the DB."""
91
+ if self.migrated:
92
+ return
93
+ row = connection.execute("SELECT value FROM catalog_meta WHERE key='migratedFromJson'").fetchone()
94
+ first = row is None
95
+ for kind, item in self._json_items():
96
+ self._insert_if_missing(connection, kind, item)
97
+ if first:
98
+ connection.execute("INSERT INTO catalog_meta(key, value) VALUES ('migratedFromJson', ?)",
99
+ (str(int(time.time())),))
100
+ connection.execute("INSERT OR REPLACE INTO catalog_meta(key, value) VALUES ('schemaVersion', ?)",
101
+ (str(SCHEMA_VERSION),))
102
+ connection.commit()
103
+ self.migrated = True
104
+
105
+ def _json_items(self):
106
+ if not self.json_path.is_file():
107
+ return
108
+ try:
109
+ data = json.loads(self.json_path.read_text(encoding="utf-8"))
110
+ except (OSError, json.JSONDecodeError):
111
+ return # a broken mirror must never prevent reading the database
112
+ if not isinstance(data, dict):
113
+ return
114
+ for kind, section in SECTIONS.items():
115
+ for item in data.get(section, []) or []:
116
+ if isinstance(item, dict) and item.get("id"):
117
+ yield kind, item
118
+
119
+ @staticmethod
120
+ def _provenance(item: dict) -> str:
121
+ source = str(item.get("source") or "")
122
+ if source == "url":
123
+ return "url"
124
+ if source in ("config", "registry"):
125
+ return source
126
+ if source in ("upload", "local", "file"):
127
+ return "upload" if source == "upload" else "file"
128
+ return "file"
129
+
130
+ @staticmethod
131
+ def _row(item: dict) -> tuple:
132
+ return (
133
+ item.get("id"), item.get("name") or "", item.get("url"),
134
+ item.get("sha256"), item.get("size"), item.get("license"),
135
+ int(item.get("addedAt") or 0), int(bool(item.get("favorite"))),
136
+ json.dumps(item, sort_keys=True, ensure_ascii=False),
137
+ )
138
+
139
+ def _insert_if_missing(self, connection: sqlite3.Connection, kind: str, item: dict) -> None:
140
+ """Import a JSON entry without ever overwriting an existing DB row."""
141
+ identifier, name, url, sha256, size, license_, added, favorite, data = self._row(item)
142
+ connection.execute(
143
+ """
144
+ INSERT OR IGNORE INTO catalog_items
145
+ (id, kind, source, provenance, name, platform, console_id, url, sha256, size,
146
+ license, added_at, favorite, data)
147
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148
+ """,
149
+ (identifier, kind, item.get("source") or self._provenance(item), self._provenance(item),
150
+ name, item.get("platform"), item.get("consoleId"), url, sha256, size, license_,
151
+ added, favorite, data),
152
+ )
153
+
154
+ def _upsert(self, connection: sqlite3.Connection, kind: str, item: dict) -> None:
155
+ identifier, name, url, sha256, size, license_, added, favorite, data = self._row(item)
156
+ connection.execute(
157
+ """
158
+ INSERT INTO catalog_items
159
+ (id, kind, source, provenance, name, platform, console_id, url, sha256, size,
160
+ license, added_at, favorite, data)
161
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
162
+ ON CONFLICT(id) DO UPDATE SET
163
+ kind=excluded.kind, source=excluded.source, provenance=excluded.provenance,
164
+ name=excluded.name, platform=excluded.platform, console_id=excluded.console_id,
165
+ url=excluded.url, sha256=excluded.sha256, size=excluded.size, license=excluded.license,
166
+ added_at=excluded.added_at, favorite=excluded.favorite, data=excluded.data
167
+ """,
168
+ (identifier, kind, item.get("source") or self._provenance(item), self._provenance(item),
169
+ name, item.get("platform"), item.get("consoleId"), url, sha256, size, license_,
170
+ added, favorite, data),
171
+ )
172
+
173
+ def sync_snapshot(self, data: dict) -> None:
174
+ """Make the database match a full library snapshot (used by Library._save)."""
175
+ wanted = set()
176
+ with self.connect() as connection:
177
+ for kind, section in SECTIONS.items():
178
+ for item in data.get(section, []) or []:
179
+ if not item.get("id"):
180
+ continue
181
+ wanted.add(item["id"])
182
+ self._upsert(connection, kind, item)
183
+ ids = [row[0] for row in connection.execute("SELECT id FROM catalog_items")]
184
+ for identifier in ids:
185
+ if identifier not in wanted:
186
+ connection.execute("DELETE FROM catalog_items WHERE id=?", (identifier,))
187
+
188
+ def snapshot(self) -> dict:
189
+ result = _empty()
190
+ with self.connect() as connection:
191
+ for row in connection.execute("SELECT kind, data FROM catalog_items"):
192
+ section = SECTIONS.get(row["kind"])
193
+ if not section:
194
+ continue
195
+ try:
196
+ item = json.loads(row["data"])
197
+ except (TypeError, json.JSONDecodeError):
198
+ continue
199
+ if isinstance(item, dict) and item.get("id"):
200
+ result[section].append(item)
201
+ for section in ("consoles", "games", "controllers"):
202
+ result[section].sort(key=lambda item: str(item.get("id")))
203
+ return result
204
+
205
+ def find_by_sha256(self, kind: str, digest: str) -> dict | None:
206
+ if kind not in SECTIONS:
207
+ raise CatalogError(f"unknown catalog kind {kind!r}")
208
+ with self.connect() as connection:
209
+ row = connection.execute(
210
+ "SELECT data FROM catalog_items WHERE kind=? AND lower(sha256)=lower(?) LIMIT 1",
211
+ (kind, digest),
212
+ ).fetchone()
213
+ return json.loads(row["data"]) if row else None
214
+
215
+ def find_by_url(self, kind: str | None, url: str) -> dict | None:
216
+ with self.connect() as connection:
217
+ query = "SELECT data FROM catalog_items WHERE url=?"
218
+ params: tuple = (url,)
219
+ if kind is not None:
220
+ if kind not in SECTIONS:
221
+ raise CatalogError(f"unknown catalog kind {kind!r}")
222
+ query += " AND kind=?"
223
+ params = (url, kind)
224
+ row = connection.execute(query + " LIMIT 1", params).fetchone()
225
+ return json.loads(row["data"]) if row else None
226
+
227
+ def row(self, identifier: str) -> dict | None:
228
+ with self.connect() as connection:
229
+ row = connection.execute(
230
+ "SELECT kind, source, provenance, name, platform, console_id, url, sha256, size, "
231
+ "license, added_at, favorite FROM catalog_items WHERE id=?", (identifier,),
232
+ ).fetchone()
233
+ return dict(row) if row else None
234
+
235
+
236
+ __all__ = ["CatalogDB", "CatalogError", "SCHEMA_VERSION", "KINDS", "PROVENANCE"]