ludex-core 0.60.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.
- ludex/__init__.py +3 -0
- ludex/_acquire_worker.py +43 -0
- ludex/accounts.py +125 -0
- ludex/acquire.py +91 -0
- ludex/errors.py +13 -0
- ludex/executables.py +45 -0
- ludex/find.py +42 -0
- ludex/game_settings.py +142 -0
- ludex/installed.py +28 -0
- ludex/jobs.py +298 -0
- ludex/launch.py +194 -0
- ludex/library.py +407 -0
- ludex/loader.py +152 -0
- ludex/metadata.py +192 -0
- ludex/paths.py +68 -0
- ludex/playtime.py +84 -0
- ludex/plugin_manager.py +268 -0
- ludex/plugins.py +286 -0
- ludex/private_io.py +40 -0
- ludex/provider_settings.py +73 -0
- ludex/refresh.py +53 -0
- ludex/runners.py +64 -0
- ludex/services.py +101 -0
- ludex/sources/__init__.py +1 -0
- ludex/sources/epic.py +122 -0
- ludex/sources/heroic.py +112 -0
- ludex/sources/local.py +121 -0
- ludex/sources/rawg.py +117 -0
- ludex/sources/shortcuts.py +76 -0
- ludex/sources/steam.py +374 -0
- ludex/sources/steam_cache.py +113 -0
- ludex/storage.py +138 -0
- ludex/switches.py +54 -0
- ludex_core-0.60.0.dist-info/METADATA +27 -0
- ludex_core-0.60.0.dist-info/RECORD +39 -0
- ludex_core-0.60.0.dist-info/WHEEL +5 -0
- ludex_core-0.60.0.dist-info/entry_points.txt +7 -0
- ludex_core-0.60.0.dist-info/licenses/LICENSE +674 -0
- ludex_core-0.60.0.dist-info/top_level.txt +1 -0
ludex/__init__.py
ADDED
ludex/_acquire_worker.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The detached process behind a ``download`` job: ``python -m ludex._acquire_worker STORE ID --to DIR [--title T]``.
|
|
2
|
+
|
|
3
|
+
Private to the core; it exists so a download never depends on a frontend being installed.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .acquire import acquire_game, format_acquired, job_reporter
|
|
13
|
+
from .errors import LudexError
|
|
14
|
+
from .loader import load_providers
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
parser = argparse.ArgumentParser(prog="ludex._acquire_worker")
|
|
19
|
+
parser.add_argument("store")
|
|
20
|
+
parser.add_argument("store_id")
|
|
21
|
+
parser.add_argument("--to", required=True)
|
|
22
|
+
parser.add_argument("--title", default="")
|
|
23
|
+
args = parser.parse_args(argv)
|
|
24
|
+
previous_umask = os.umask(0o077)
|
|
25
|
+
try:
|
|
26
|
+
providers, _ = load_providers()
|
|
27
|
+
result = acquire_game(
|
|
28
|
+
providers, args.store, args.store_id, args.title, Path(args.to), job_reporter(lambda message: print(message, file=sys.stderr))
|
|
29
|
+
)
|
|
30
|
+
except LudexError as exc:
|
|
31
|
+
print(f"error: {exc.message}", file=sys.stderr)
|
|
32
|
+
return 1
|
|
33
|
+
except PermissionError as exc:
|
|
34
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
35
|
+
return 1
|
|
36
|
+
finally:
|
|
37
|
+
os.umask(previous_umask)
|
|
38
|
+
print(format_acquired(result))
|
|
39
|
+
return 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
raise SystemExit(main())
|
ludex/accounts.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from types import MappingProxyType
|
|
8
|
+
from typing import Any, Mapping
|
|
9
|
+
|
|
10
|
+
from .errors import LudexError
|
|
11
|
+
from .paths import StatePaths
|
|
12
|
+
from .plugins import ConfigField
|
|
13
|
+
from .private_io import read_json_private, write_json_private
|
|
14
|
+
|
|
15
|
+
_NAME = re.compile(r"[a-z][a-z0-9_-]{0,31}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Account:
|
|
20
|
+
name: str
|
|
21
|
+
source: str
|
|
22
|
+
config: Mapping[str, str]
|
|
23
|
+
|
|
24
|
+
def __repr__(self) -> str:
|
|
25
|
+
return f"Account(name={self.name!r}, source={self.source!r})"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _load(paths: StatePaths) -> dict[str, Any]:
|
|
29
|
+
"""Accounts keyed ``source:name``. Files written before names were per source used ``name``."""
|
|
30
|
+
if not paths.accounts.exists() and not paths.accounts.is_symlink():
|
|
31
|
+
return {}
|
|
32
|
+
try:
|
|
33
|
+
data = read_json_private(paths.accounts)
|
|
34
|
+
except ValueError as exc:
|
|
35
|
+
raise LudexError("accounts_corrupt", "accounts file is unreadable") from exc
|
|
36
|
+
if not isinstance(data, dict):
|
|
37
|
+
raise LudexError("accounts_corrupt", "accounts file is unreadable")
|
|
38
|
+
return {
|
|
39
|
+
key if ":" in key or not isinstance(entry, dict) else f"{entry.get('source')}:{key}": entry
|
|
40
|
+
for key, entry in data.items()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _check_name(name: str) -> None:
|
|
45
|
+
if not isinstance(name, str) or not _NAME.fullmatch(name):
|
|
46
|
+
raise LudexError("invalid_account_name", "account name must match [a-z][a-z0-9_-]{0,31}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _resolve(data: dict[str, Any], ref: str) -> str:
|
|
50
|
+
"""``source:name`` or a bare name that is unique across sources."""
|
|
51
|
+
if ref in data:
|
|
52
|
+
return ref
|
|
53
|
+
matches = [key for key in data if ":" not in ref and key.partition(":")[2] == ref]
|
|
54
|
+
if len(matches) > 1:
|
|
55
|
+
raise LudexError("account_ambiguous", f"account {ref} exists for several sources; use one of: {', '.join(sorted(matches))}")
|
|
56
|
+
if not matches:
|
|
57
|
+
raise LudexError("account_not_found", f"account {ref} not found")
|
|
58
|
+
return matches[0]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def add_account(paths: StatePaths, name: str, source: str, config: Mapping[str, str]) -> None:
|
|
62
|
+
_check_name(name)
|
|
63
|
+
data = _load(paths)
|
|
64
|
+
key = f"{source}:{name}"
|
|
65
|
+
if key in data:
|
|
66
|
+
raise LudexError("account_exists", f"account {name} already exists for source {source}")
|
|
67
|
+
data[key] = {"source": source, "config": dict(config)}
|
|
68
|
+
write_json_private(paths.accounts, data)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_account(paths: StatePaths, ref: str) -> Account:
|
|
72
|
+
data = _load(paths)
|
|
73
|
+
key = _resolve(data, ref)
|
|
74
|
+
entry = data[key]
|
|
75
|
+
if not isinstance(entry, dict) or not isinstance(entry.get("source"), str):
|
|
76
|
+
raise LudexError("account_not_found", f"account {ref} not found")
|
|
77
|
+
config = entry.get("config")
|
|
78
|
+
if not isinstance(config, dict):
|
|
79
|
+
config = {}
|
|
80
|
+
from .provider_settings import get_values # plugin-wide settings sit under the account's own fields
|
|
81
|
+
|
|
82
|
+
merged = {**get_values(paths, entry["source"]), **{str(k): str(v) for k, v in config.items()}}
|
|
83
|
+
return Account(key.partition(":")[2], entry["source"], MappingProxyType(merged))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def list_accounts(paths: StatePaths) -> list[tuple[str, str]]:
|
|
87
|
+
data = _load(paths)
|
|
88
|
+
return sorted(
|
|
89
|
+
(key.partition(":")[2], entry["source"])
|
|
90
|
+
for key, entry in data.items()
|
|
91
|
+
if isinstance(entry, dict) and isinstance(entry.get("source"), str)
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def remove_account(paths: StatePaths, ref: str) -> None:
|
|
96
|
+
data = _load(paths)
|
|
97
|
+
del data[_resolve(data, ref)]
|
|
98
|
+
write_json_private(paths.accounts, data)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def update_account(
|
|
102
|
+
paths: StatePaths, ref: str, fields: Sequence[ConfigField], values: Mapping[str, str], unset: Sequence[str] = ()
|
|
103
|
+
) -> list[str]:
|
|
104
|
+
"""Change an account's configuration in place (records are untouched). Returns the keys changed."""
|
|
105
|
+
known = {f.name: f for f in fields}
|
|
106
|
+
for key in [*values, *unset]:
|
|
107
|
+
if key not in known:
|
|
108
|
+
raise LudexError("unknown_field", f"this account's source has no field {key}")
|
|
109
|
+
for key, value in values.items():
|
|
110
|
+
if not value:
|
|
111
|
+
raise LudexError("empty_value", f"field {key} must not be empty")
|
|
112
|
+
values = {key: known[key].clean(value) for key, value in values.items()}
|
|
113
|
+
for key in unset:
|
|
114
|
+
if not known[key].optional:
|
|
115
|
+
raise LudexError("required_field", f"field {key} is required; set a new value instead")
|
|
116
|
+
data = _load(paths)
|
|
117
|
+
key = _resolve(data, ref)
|
|
118
|
+
entry = data[key]
|
|
119
|
+
config = dict(entry["config"]) if isinstance(entry.get("config"), dict) else {}
|
|
120
|
+
config.update(values)
|
|
121
|
+
for name in unset:
|
|
122
|
+
config.pop(name, None)
|
|
123
|
+
entry["config"] = config
|
|
124
|
+
write_json_private(paths.accounts, data)
|
|
125
|
+
return sorted({*values, *unset})
|
ludex/acquire.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Run a provider's acquire capability and check what it returns."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sqlite3
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .errors import LudexError
|
|
12
|
+
from .jobs import PROGRESS_ENV, Job, ProgressWriter, start_job
|
|
13
|
+
from .plugins import AcquireRequest, AcquireResult, Provider, Report
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def acquire_game(
|
|
17
|
+
providers: Mapping[str, Provider],
|
|
18
|
+
store: str,
|
|
19
|
+
store_id: str,
|
|
20
|
+
title: str,
|
|
21
|
+
destination: Path,
|
|
22
|
+
report: Report = lambda message, done=None, total=None: None,
|
|
23
|
+
) -> AcquireResult:
|
|
24
|
+
"""Ask ``store``'s provider to put the game under ``destination``; the result is verified."""
|
|
25
|
+
provider = providers.get(store)
|
|
26
|
+
if provider is None or provider.acquire is None:
|
|
27
|
+
raise LudexError("not_acquirable", f"provider {store} cannot acquire games")
|
|
28
|
+
destination = destination.expanduser()
|
|
29
|
+
try:
|
|
30
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
except OSError:
|
|
32
|
+
raise LudexError("destination_unwritable", "the destination directory cannot be created") from None
|
|
33
|
+
root = destination.resolve()
|
|
34
|
+
try:
|
|
35
|
+
result = provider.acquire(AcquireRequest(store_id, title, root), report)
|
|
36
|
+
except LudexError:
|
|
37
|
+
raise
|
|
38
|
+
except Exception as exc:
|
|
39
|
+
raise LudexError("acquire_failed", f"provider {store} failed ({type(exc).__name__})") from None
|
|
40
|
+
if (
|
|
41
|
+
not isinstance(result, AcquireResult)
|
|
42
|
+
or not isinstance(result.directory, Path)
|
|
43
|
+
or not isinstance(result.hints, Mapping)
|
|
44
|
+
or not all(isinstance(k, str) and isinstance(v, str) for k, v in result.hints.items())
|
|
45
|
+
):
|
|
46
|
+
raise LudexError("acquire_failed", f"provider {store} returned an invalid result")
|
|
47
|
+
directory = result.directory.resolve()
|
|
48
|
+
if not directory.is_dir() or not directory.is_relative_to(root):
|
|
49
|
+
raise LudexError("acquire_failed", f"provider {store} returned a directory outside the destination")
|
|
50
|
+
return AcquireResult(directory, dict(result.hints))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def download_game(
|
|
54
|
+
conn: sqlite3.Connection, providers: Mapping[str, Provider], store: str, store_id: str, title: str, destination: Path, log_dir: Path
|
|
55
|
+
) -> Job:
|
|
56
|
+
"""Run :func:`acquire_game` in the background as a ``download`` job (see ``ludex.jobs``): ``ludex acquire`` in its own process.
|
|
57
|
+
|
|
58
|
+
The game is not in the library yet, so the job has no game (``game_id`` 0). One running download per ``store:store_id``.
|
|
59
|
+
"""
|
|
60
|
+
provider = providers.get(store)
|
|
61
|
+
if provider is None or provider.acquire is None:
|
|
62
|
+
raise LudexError("not_acquirable", f"provider {store} cannot acquire games")
|
|
63
|
+
argv = [sys.executable, "-m", "ludex._acquire_worker", store, store_id, "--to", str(destination.expanduser())]
|
|
64
|
+
if title:
|
|
65
|
+
argv += ["--title", title]
|
|
66
|
+
return start_job(conn, "download", 0, f"{store}:{store_id}", title or store_id, argv, log_dir)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def format_acquired(result: AcquireResult) -> str:
|
|
70
|
+
"""The human line for a finished acquisition: the directory, then the sorted hints."""
|
|
71
|
+
hints = "".join(f"\n {key}={value}" for key, value in sorted(result.hints.items()))
|
|
72
|
+
return f"acquired into {result.directory}{hints}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def job_reporter(echo: Callable[[str], None]) -> Report:
|
|
76
|
+
"""The ``report`` for ``ludex acquire``: each report goes to ``echo`` (the job's log) and, inside a download job, to its progress file."""
|
|
77
|
+
path = os.environ.get(PROGRESS_ENV)
|
|
78
|
+
writer = ProgressWriter(Path(path)) if path else None
|
|
79
|
+
last = [0.0]
|
|
80
|
+
|
|
81
|
+
def report(message: str, done: float | None = None, total: float | None = None) -> None:
|
|
82
|
+
if writer is not None:
|
|
83
|
+
writer(message, done, total)
|
|
84
|
+
if done is not None and total and done < total:
|
|
85
|
+
if time.time() - last[0] < 0.25:
|
|
86
|
+
return # a plugin may report on every chunk; the log gets a few lines a second at most
|
|
87
|
+
last[0] = time.time()
|
|
88
|
+
percent = f" {int(min(done, total) / total * 100)}%" if isinstance(done, (int, float)) and isinstance(total, (int, float)) and total > 0 else ""
|
|
89
|
+
echo(f"{message}{percent}")
|
|
90
|
+
|
|
91
|
+
return report
|
ludex/errors.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LudexError(Exception):
|
|
5
|
+
"""Error that crosses the core boundary with a stable ``code`` and a printable ``message``.
|
|
6
|
+
|
|
7
|
+
``code`` is lowercase snake_case and part of the ``--json`` contract.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, code: str, message: str):
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
self.code = code
|
|
13
|
+
self.message = message
|
ludex/executables.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Find the files in a game folder that could be its executable, best guess first."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .storage import normalize_title
|
|
9
|
+
|
|
10
|
+
_SUFFIXES = {".exe", ".sh", ".appimage", ".x86_64"}
|
|
11
|
+
# installers, uninstallers, redistributables and crash reporters are never the game
|
|
12
|
+
_NOISE = re.compile(r"(unins|uninst|vc_?redist|vcredist|dxsetup|dotnet|ndp\d|oalinst|crashhandler|crashreport|crashpad|ue4prereq|directx|physx|setup)", re.I)
|
|
13
|
+
_MAX_DEPTH = 3
|
|
14
|
+
_MAX_VISITED = 5000 # a game folder can hold tens of thousands of files; stop looking after this many entries
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def find_executables(folder: Path, title: str = "", limit: int = 30) -> list[Path]:
|
|
18
|
+
"""Candidate executables under ``folder`` (``.exe``, ``.sh``, ``.AppImage``, ``.x86_64``; at most three levels deep).
|
|
19
|
+
|
|
20
|
+
Best guess first: nearer the top, then a name that shares a word with ``title``, then bigger. Paths are relative to ``folder``.
|
|
21
|
+
ponytail: stops after 5000 entries, so a huge folder may hide some; type the path instead.
|
|
22
|
+
"""
|
|
23
|
+
words = set(normalize_title(title).split())
|
|
24
|
+
found: list[tuple[tuple[int, int, int, str], Path]] = []
|
|
25
|
+
visited = 0
|
|
26
|
+
root = str(folder)
|
|
27
|
+
for current, dirs, files in os.walk(root):
|
|
28
|
+
depth = Path(current).relative_to(root).parts.__len__()
|
|
29
|
+
dirs[:] = sorted(d for d in dirs if not d.startswith(".")) if depth < _MAX_DEPTH else []
|
|
30
|
+
for name in files:
|
|
31
|
+
visited += 1
|
|
32
|
+
if visited > _MAX_VISITED:
|
|
33
|
+
break
|
|
34
|
+
path = Path(current) / name
|
|
35
|
+
if path.suffix.lower() not in _SUFFIXES or _NOISE.search(name) or not path.is_file():
|
|
36
|
+
continue
|
|
37
|
+
shared = len(words & set(normalize_title(path.stem).split()))
|
|
38
|
+
try:
|
|
39
|
+
size = path.stat().st_size
|
|
40
|
+
except OSError:
|
|
41
|
+
continue
|
|
42
|
+
found.append(((depth, -shared, -size, name.lower()), path.relative_to(root)))
|
|
43
|
+
if visited > _MAX_VISITED:
|
|
44
|
+
break
|
|
45
|
+
return [path for _, path in sorted(found, key=lambda item: item[0])[:limit]]
|
ludex/find.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Search the stores' catalogs through every provider that has the search capability."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sqlite3
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .plugins import Provider, SearchHit
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def owned_keys(conn: sqlite3.Connection) -> set[tuple[str, str]]:
|
|
12
|
+
return {(row["store"], row["store_id"]) for row in conn.execute("SELECT store, store_id FROM ownership WHERE removed = 0")}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def find_games(
|
|
16
|
+
providers: Mapping[str, Provider], query: str, owned: set[tuple[str, str]]
|
|
17
|
+
) -> tuple[list[dict[str, Any]], dict[str, str]]:
|
|
18
|
+
"""Return ``(hits, {provider: reason})``; each hit says whether you already own it."""
|
|
19
|
+
hits: list[dict[str, Any]] = []
|
|
20
|
+
problems: dict[str, str] = {}
|
|
21
|
+
for name, provider in sorted(providers.items()):
|
|
22
|
+
if provider.search is None:
|
|
23
|
+
continue
|
|
24
|
+
try:
|
|
25
|
+
found = list(provider.search(query))
|
|
26
|
+
except Exception as exc:
|
|
27
|
+
problems[name] = getattr(exc, "message", f"failed ({type(exc).__name__})")
|
|
28
|
+
continue
|
|
29
|
+
skipped = 0
|
|
30
|
+
for hit in found:
|
|
31
|
+
if not isinstance(hit, SearchHit):
|
|
32
|
+
continue
|
|
33
|
+
secure = hit.url.startswith("https://")
|
|
34
|
+
if not secure and provider.acquire is None: # ludex would open the link, so only https
|
|
35
|
+
skipped += 1
|
|
36
|
+
continue
|
|
37
|
+
# a plugin that downloads itself needs no link: keep the hit, drop a link that is not https
|
|
38
|
+
hits.append({"store": hit.store, "store_id": hit.store_id, "title": hit.title, "url": hit.url if secure else "",
|
|
39
|
+
"price": hit.price, "owned": (hit.store, hit.store_id) in owned})
|
|
40
|
+
if skipped:
|
|
41
|
+
problems[name] = f"{skipped} result{'s' if skipped != 1 else ''} skipped (link is not https)"
|
|
42
|
+
return hits, problems
|
ludex/game_settings.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Per-game launch settings (runner, prefix, executable, arguments, environment).
|
|
2
|
+
|
|
3
|
+
Keyed by (store, store_id) so imports never touch them; they are deleted only when the last
|
|
4
|
+
ownership record of that game copy is deleted (``library.delete_account_records``).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import sqlite3
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .errors import LudexError
|
|
15
|
+
from .library import get_game
|
|
16
|
+
from .runners import resolve_runner
|
|
17
|
+
|
|
18
|
+
_ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class GameSettings:
|
|
23
|
+
runner: str | None = None
|
|
24
|
+
prefix: str | None = None
|
|
25
|
+
executable: str | None = None
|
|
26
|
+
args: tuple[str, ...] = ()
|
|
27
|
+
env: dict[str, str] = field(default_factory=dict)
|
|
28
|
+
|
|
29
|
+
def as_dict(self) -> dict[str, object]:
|
|
30
|
+
return {"runner": self.runner, "prefix": self.prefix, "executable": self.executable, "args": list(self.args), "env": dict(self.env)}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_settings(conn: sqlite3.Connection, store: str, store_id: str) -> GameSettings:
|
|
34
|
+
row = conn.execute("SELECT * FROM game_settings WHERE store = ? AND store_id = ?", (store, store_id)).fetchone()
|
|
35
|
+
if row is None:
|
|
36
|
+
return GameSettings()
|
|
37
|
+
return GameSettings(row["runner"], row["prefix"], row["executable"], tuple(json.loads(row["args_json"])), json.loads(row["env_json"]))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def pick_copy(conn: sqlite3.Connection, game_id: int, store: str | None = None) -> tuple[str, str]:
|
|
41
|
+
"""The (store, store_id) of the game's one owned copy, or the one in ``store``."""
|
|
42
|
+
copies = sorted(
|
|
43
|
+
{(o["store"], o["store_id"]) for o in get_game(conn, game_id)["ownership"] if not o["removed"]}
|
|
44
|
+
)
|
|
45
|
+
if store is not None:
|
|
46
|
+
copies = [c for c in copies if c[0] == store]
|
|
47
|
+
if not copies:
|
|
48
|
+
raise LudexError("not_owned", f"game {game_id} has no owned copy" + (f" in {store}" if store else ""))
|
|
49
|
+
if len(copies) > 1:
|
|
50
|
+
raise LudexError("copy_ambiguous", f"game {game_id} has copies in {', '.join(sorted({c[0] for c in copies}))}; pass --store")
|
|
51
|
+
return copies[0]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _clean(value: str, what: str) -> str:
|
|
55
|
+
if "\0" in value or not value.strip():
|
|
56
|
+
raise LudexError("invalid_setting", f"{what} must be non-empty text without NUL")
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def update_settings(
|
|
61
|
+
conn: sqlite3.Connection,
|
|
62
|
+
store: str,
|
|
63
|
+
store_id: str,
|
|
64
|
+
*,
|
|
65
|
+
runner: str | None = None,
|
|
66
|
+
prefix: str | None = None,
|
|
67
|
+
executable: str | None = None,
|
|
68
|
+
args: list[str] | None = None,
|
|
69
|
+
env: dict[str, str] | None = None,
|
|
70
|
+
unset_env: list[str] = (),
|
|
71
|
+
clear: bool = False,
|
|
72
|
+
) -> GameSettings:
|
|
73
|
+
"""Change the given settings (``None`` leaves one alone); ``clear`` first resets everything."""
|
|
74
|
+
current = GameSettings() if clear else get_settings(conn, store, store_id)
|
|
75
|
+
if runner is not None:
|
|
76
|
+
found = resolve_runner(_clean(runner, "runner"))
|
|
77
|
+
runner = str(found.path) if found.origin == "path" else found.name
|
|
78
|
+
if prefix is not None:
|
|
79
|
+
prefix = str(Path(_clean(prefix, "prefix")).expanduser())
|
|
80
|
+
if not Path(prefix).is_absolute():
|
|
81
|
+
raise LudexError("invalid_setting", "prefix must be an absolute path")
|
|
82
|
+
merged_env = {k: v for k, v in current.env.items() if k not in set(unset_env)}
|
|
83
|
+
for key, value in (env or {}).items():
|
|
84
|
+
if not _ENV_NAME.match(key) or "\0" in value:
|
|
85
|
+
raise LudexError("invalid_setting", f"invalid environment variable {key!r}")
|
|
86
|
+
merged_env[key] = value
|
|
87
|
+
result = GameSettings(
|
|
88
|
+
runner if runner is not None else current.runner,
|
|
89
|
+
prefix if prefix is not None else current.prefix,
|
|
90
|
+
_clean(executable, "executable") if executable is not None else current.executable,
|
|
91
|
+
tuple(_clean(a, "argument") for a in args) if args is not None else current.args,
|
|
92
|
+
merged_env,
|
|
93
|
+
)
|
|
94
|
+
with conn:
|
|
95
|
+
conn.execute(
|
|
96
|
+
"INSERT INTO game_settings(store, store_id, runner, prefix, executable, args_json, env_json) "
|
|
97
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(store, store_id) DO UPDATE SET runner = excluded.runner, "
|
|
98
|
+
"prefix = excluded.prefix, executable = excluded.executable, args_json = excluded.args_json, "
|
|
99
|
+
"env_json = excluded.env_json",
|
|
100
|
+
(store, store_id, result.runner, result.prefix, result.executable, json.dumps(list(result.args)), json.dumps(result.env)),
|
|
101
|
+
)
|
|
102
|
+
return result
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def default_download_dir() -> Path:
|
|
106
|
+
return Path.home() / "Games"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_download_dir(conn: sqlite3.Connection, default: Path) -> Path:
|
|
110
|
+
"""The folder downloads from a store's release catalog go to by default (a setting, else ``default``)."""
|
|
111
|
+
row = conn.execute("SELECT value FROM meta WHERE key = 'download_dir'").fetchone()
|
|
112
|
+
return Path(row["value"]) if row else default
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def set_download_dir(conn: sqlite3.Connection, path: str | None) -> None:
|
|
116
|
+
"""Set the default download folder; ``None`` goes back to the built-in one."""
|
|
117
|
+
with conn:
|
|
118
|
+
if path is None:
|
|
119
|
+
conn.execute("DELETE FROM meta WHERE key = 'download_dir'")
|
|
120
|
+
return
|
|
121
|
+
folder = Path(_clean(path, "download folder")).expanduser()
|
|
122
|
+
if not folder.is_absolute():
|
|
123
|
+
raise LudexError("invalid_setting", "the download folder must be an absolute path")
|
|
124
|
+
conn.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('download_dir', ?)", (str(folder),))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def get_prefix_root(conn: sqlite3.Connection, default: Path) -> Path:
|
|
128
|
+
"""The folder default Wine prefixes are created in (a setting, else ``default``)."""
|
|
129
|
+
row = conn.execute("SELECT value FROM meta WHERE key = 'prefix_dir'").fetchone()
|
|
130
|
+
return Path(row["value"]) if row else default
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def set_prefix_root(conn: sqlite3.Connection, path: str | None) -> None:
|
|
134
|
+
"""Set the default prefix folder; ``None`` goes back to the built-in one."""
|
|
135
|
+
with conn:
|
|
136
|
+
if path is None:
|
|
137
|
+
conn.execute("DELETE FROM meta WHERE key = 'prefix_dir'")
|
|
138
|
+
return
|
|
139
|
+
folder = Path(_clean(path, "prefix folder")).expanduser()
|
|
140
|
+
if not folder.is_absolute():
|
|
141
|
+
raise LudexError("invalid_setting", "the prefix folder must be an absolute path")
|
|
142
|
+
conn.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('prefix_dir', ?)", (str(folder),))
|
ludex/installed.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Which owned games are installed right now, asked live from the providers that can tell."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
|
|
6
|
+
from .accounts import get_account, list_accounts
|
|
7
|
+
from .paths import StatePaths
|
|
8
|
+
from .plugins import Provider
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def installed_keys(paths: StatePaths, providers: Mapping[str, Provider]) -> tuple[set[tuple[str, str]], dict[str, str]]:
|
|
12
|
+
"""Return ``({(store, store_id)}, {account ref: reason})`` over every account whose provider can tell.
|
|
13
|
+
|
|
14
|
+
A failing account is reported by its secret-free reason and skipped; the rest still count.
|
|
15
|
+
"""
|
|
16
|
+
keys: set[tuple[str, str]] = set()
|
|
17
|
+
problems: dict[str, str] = {}
|
|
18
|
+
for name, source in list_accounts(paths):
|
|
19
|
+
provider = providers.get(source)
|
|
20
|
+
if provider is None or provider.installed is None:
|
|
21
|
+
continue
|
|
22
|
+
ref = f"{source}:{name}"
|
|
23
|
+
try:
|
|
24
|
+
ids = provider.installed(get_account(paths, ref).config)
|
|
25
|
+
keys.update((source, str(store_id)) for store_id in ids)
|
|
26
|
+
except Exception as exc:
|
|
27
|
+
problems[ref] = getattr(exc, "message", f"failed ({type(exc).__name__})")
|
|
28
|
+
return keys, problems
|