Repository navigation
Expand file tree
/
Copy paththor_setup.py
More file actions
executable file
·1820 lines (1531 loc) · 68.1 KB
/
Copy paththor_setup.py
File metadata and controls
executable file
·1820 lines (1531 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
thor_setup.py - Setup helper for an AYN Thor Pro (or most Android handhelds),
run from a PC over ADB. Based on the TechDweeb Android handheld guide, using
the iiSU frontend, ARMSX2 (PS2), Eden (Switch) and DroidDeck (Steam + Proton).
Run it with no options for a KIAUH-style menu:
python thor_setup.py
The menu shows the Thor, its SD card and every app's installed version, and
lets you install, update and remove apps, copy games and BIOS files, apply
emulator settings and change device settings.
Created by pdsavas with the assistance of Claude, Anthropic's AI assistant.
https://github.com/pdsavas/Thor-Setup-Script
The older one-shot mode still works when you pass step options:
python thor_setup.py --download # full setup, start to finish
python thor_setup.py --only push # just one step
python thor_setup.py --list-steps
"""
import argparse
import json
import os
import posixpath
import re
import shlex
import shutil
import struct
import subprocess
import sys
import tempfile
import urllib.parse
import urllib.request
import zipfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
APK_DIR = HERE / "apks"
BIOS_DIR = HERE / "bios"
ROMS_DIR = HERE / "roms"
STATE_FILE = HERE / ".thor_state.json"
VERSION = "4.3"
# =====================================================================
# Tweakables
# =====================================================================
# Android keycodes RetroArch uses as joypad button numbers.
K = {
"A": "96", "B": "97", "X": "99", "Y": "100",
"L1": "102", "R1": "103", "L2": "104", "R2": "105",
"L3": "106", "R3": "107", "START": "108", "SELECT": "109",
}
# D-pad: most handhelds report it as a hat ("h0up"). If D-pad hotkeys
# don't work, change these to "19", "20", "21", "22" (Android keycodes).
DPAD = {"UP": "h0up", "DOWN": "h0down", "LEFT": "h0left", "RIGHT": "h0right"}
RETROARCH_SETTINGS = {
# User Interface
"menu_driver": "glui", # Material UI
"menu_widget_scale_auto": "false",
"menu_widget_scale_factor": "0.750000",
"input_overlay_enable": "false",
"builtin_imageviewer_enable": "false", # needed for PICO-8
# Input
"input_player1_analog_dpad_mode": "1", # Left Analog
"input_bind_hold": "0",
"quit_press_twice": "false", # "Confirm Quit" off
"input_block_timeout": "1",
# Hotkeys (the guide's layout)
"input_enable_hotkey_btn": K["SELECT"],
"input_menu_toggle_gamepad_combo": "2", # L3 + R3
"input_menu_toggle_btn": K["A"],
"input_exit_emulator_btn": K["START"],
"input_toggle_fast_forward_btn": K["R2"],
"input_toggle_slowmotion_btn": K["L2"],
"input_volume_up_btn": DPAD["UP"],
"input_volume_down_btn": DPAD["DOWN"],
"input_load_state_btn": K["L1"],
"input_save_state_btn": K["R1"],
"input_state_slot_increase_btn": DPAD["RIGHT"],
"input_state_slot_decrease_btn": DPAD["LEFT"],
"input_screenshot_btn": K["Y"],
# Saving
"savestate_auto_save": "true",
"savestate_auto_load": "true",
"savestate_auto_index": "true",
"cheevos_hardcore_mode_enable": "false",
# Directories are filled in at runtime from the SD card path.
}
# Dolphin: the Thor Pro's Adreno 740 handles 3x + Vulkan comfortably.
DOLPHIN_INI = {"Core": {"GFXBackend": "Vulkan"}}
DOLPHIN_GFX_INI = {
"Settings": {
"InternalResolution": "3",
"ShaderCompilationMode": "2", # Hybrid Ubershaders
"WaitForShadersBeforeStarting": "True", # compile before starting
"AspectRatio": "1", # Force 16:9
"wideScreenHack": "True",
}
}
# Package names used to recognise emulators (pre-installed or otherwise).
EMU_PATTERN = re.compile(
r"retroarch|dolphin|ppsspp|citra|lime3ds|azahar|yuzu|sudachi|\beden|"
r"suyu|skyline|sx2|drastic|melonds|mupen|redream|flycast|duckstation|"
r"mame4droid|m64plus|nethersx2|armsx2|winlator|vita3k|cemu|steamdeck|"
r"hakux|xemu|x1box|droiddeck",
re.I,
)
# Never offer to remove these as "pre-installed emulators".
PROTECTED = re.compile(r"^(android|com\.android|com\.google|com\.qualcomm|"
r"com\.ayn|org\.es_de|com\.iisulauncher)", re.I)
IISU_PKG = "com.iisulauncher"
# ROM folder names (iiSU's accepted folder names; also valid for ES-DE).
# "xbox" isn't an iiSU console yet; hakuX reads that folder itself.
COMMON_SYSTEMS = [
"nes", "snes", "n64", "gb", "gbc", "gba", "nds", "n3ds", "gc", "wii",
"switch", "psx", "ps2", "psp", "genesis", "saturn", "dreamcast",
"arcade", "pico8", "xbox",
]
# hakuX (original Xbox). rfandango/hakuX is the upstream project; the README
# says its GitHub releases are the only official download. Other "hakuX"
# repos are forks or look-alikes.
HAKUX_REPO = "rfandango/hakuX"
# DroidDeck (Steam / PC games, SteamOS-style). Its README says to download it
# only from Droid-Deck/DroidDeck's GitHub releases; droiddeck.org, .com and
# .wiki are unofficial, and other GitHub "DroidDeck" repos are unrelated apps.
DROIDDECK_REPO = "Droid-Deck/DroidDeck"
# Obtainium keeps other apps up to date straight from their GitHub, F-Droid
# etc. pages. Official downloads: ImranR98/Obtainium's GitHub releases.
OBTAINIUM_REPO = "ImranR98/Obtainium"
# JamesDSP audio effects. james34602/JamesDSPManager needs root (it's a Magisk
# module), so this is RootlessJamesDSP, the same engine for unrooted devices.
# Its GitHub releases have no APK; it's published on Google Play and F-Droid.
JAMESDSP_REPO = "timschneeb/RootlessJamesDSP"
JAMESDSP_PKG = "me.timschneeberger.rootlessjamesdsp"
EDEN_API = "https://git.eden-emu.dev/api/v1/repos/eden-emu/eden/releases"
UA = {"User-Agent": "thor-setup/" + VERSION} # for APIs (GitHub, Forgejo)
# Download pages (Dolphin, PPSSPP) may block unfamiliar clients, so look like a browser.
BROWSER_UA = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/128.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
# =====================================================================
# Console helpers
# =====================================================================
ARGS = None
COLOR = False
ANSI = re.compile(r"\x1b\[[0-9;]*m")
def setup_console(no_color=False):
global COLOR
try:
sys.stdout.reconfigure(errors="replace")
except Exception: # noqa: BLE001
pass
if os.name == "nt":
os.system("") # turns on colour codes in Windows consoles
COLOR = (sys.stdout.isatty() and not no_color and not os.environ.get("NO_COLOR"))
def c(text, style):
if not COLOR:
return str(text)
codes = {"green": "32", "yellow": "33", "red": "31", "cyan": "36",
"dim": "2", "bold": "1", "title": "1;36"}
return f"\x1b[{codes[style]}m{text}\x1b[0m"
def say(msg=""):
print(msg, flush=True)
def header(title):
say()
say(c("=" * 64, "cyan"))
say(c(f" {title}", "bold"))
say(c("=" * 64, "cyan"))
def confirm(question, default=True):
if ARGS and ARGS.yes:
return default
hint = "[Y/n]" if default else "[y/N]"
ans = input(f"{question} {hint} ").strip().lower()
if not ans:
return default
return ans.startswith("y")
def pause(msg):
if ARGS and ARGS.yes:
say(f"(--yes) Skipping wait: {msg}")
return
input(f"\n>>> {msg}\n Press Enter when done... ")
def clear():
if sys.stdout.isatty():
os.system("cls" if os.name == "nt" else "clear")
def human_size(n):
for unit in ("B", "KB", "MB", "GB"):
if n < 1024 or unit == "GB":
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1024
# =====================================================================
# ADB helpers
# =====================================================================
def adb_cmd(*args):
return [ARGS.adb] + (["-s", ARGS.serial] if ARGS.serial else []) + list(args)
def adb(*args, check=True):
res = subprocess.run(adb_cmd(*args), capture_output=True, text=True,
encoding="utf-8", errors="replace")
if check and res.returncode != 0:
raise RuntimeError(f"adb {' '.join(args)} failed:\n{res.stderr or res.stdout}")
return (res.stdout or "").strip()
def shell(command, check=True):
return adb("shell", command, check=check)
def remote_exists(path):
return shell(f'[ -e "{path}" ] && echo yes || echo no', check=False) == "yes"
def installed_packages():
out = shell("pm list packages", check=False)
return {l.split(":", 1)[1].strip() for l in out.splitlines() if ":" in l}
def find_pkg(*candidates, pattern=None):
pkgs = installed_packages()
for cand in candidates:
if cand in pkgs:
return cand
if pattern:
for p in sorted(pkgs):
if re.search(pattern, p, re.I):
return p
return None
def package_versions(pkgs):
"""{package: versionName} for the given installed packages (one adb call)."""
pkgs = [p for p in pkgs if p]
if not pkgs:
return {}
loop = ("for p in " + " ".join(shlex.quote(p) for p in pkgs) + "; do "
"v=$(dumpsys package $p | grep -m1 versionName); echo \"$p ${v#*=}\"; done")
out = {}
for line in shell(loop, check=False).splitlines():
pkg, _, ver = line.strip().partition(" ")
if pkg:
out[pkg] = ver.strip()
return out
def launch(pkg):
shell(f"monkey -p {pkg} -c android.intent.category.LAUNCHER 1", check=False)
# =====================================================================
# Web helpers
# =====================================================================
def http_get(url, browser=False):
req = urllib.request.Request(url, headers=BROWSER_UA if browser else UA)
with urllib.request.urlopen(req, timeout=60) as r:
return r.read()
def download(url, dest):
say(f" downloading {url}")
req = urllib.request.Request(url, headers=BROWSER_UA)
tmp = Path(str(dest) + ".part")
with urllib.request.urlopen(req, timeout=300) as r, open(tmp, "wb") as f:
total = int(r.headers.get("Content-Length") or 0)
got, last = 0, -1
while True:
chunk = r.read(1 << 20)
if not chunk:
break
f.write(chunk)
got += len(chunk)
if total and sys.stdout.isatty():
pct = got * 100 // total
if pct != last:
print(f"\r {pct:3d}% {human_size(got)} of {human_size(total)}",
end="", flush=True)
last = pct
if total and sys.stdout.isatty():
print()
# An HTML error page saved as .apk would fail to install later; catch it here.
with open(tmp, "rb") as f:
if f.read(2) != b"PK":
tmp.unlink()
raise RuntimeError(f"{url} didn't return an APK (got a web page instead)")
tmp.replace(dest)
def find_apk_links(html, base, prefer=None):
"""All .apk links in a page (any quoting, & decoded), preferred ones first."""
raw = re.findall(r'href\s*=\s*["\']?([^"\'\s>]+?\.apk)(?=["\'\s>?#])', html, re.I)
raw += re.findall(r'(https?://[^"\'\s<>]+?\.apk)\b', html, re.I)
links = []
for l in raw:
l = urllib.parse.urljoin(base, l.replace("&", "&"))
if l not in links:
links.append(l)
if prefer:
links.sort(key=lambda l: not re.search(prefer, l))
return links
def first_apk_link(page, prefer=None):
html = http_get(page, browser=True).decode("utf-8", "replace")
links = find_apk_links(html, page, prefer)
if not links:
raise RuntimeError(f"no .apk link found on {page}")
return links[0]
# =====================================================================
# Reading an APK's package name and version (binary AndroidManifest.xml)
# =====================================================================
def apk_info(path):
"""(package, versionName) from an APK file, or (None, None) if unreadable."""
try:
with zipfile.ZipFile(path) as z:
return _parse_axml(z.read("AndroidManifest.xml"))
except Exception: # noqa: BLE001
return None, None
def _parse_axml(d):
u16 = lambda o: struct.unpack_from("<H", d, o)[0] # noqa: E731
u32 = lambda o: struct.unpack_from("<I", d, o)[0] # noqa: E731
strings, resids, pos = [], [], 8
while pos + 8 <= len(d):
ctype, hsize, csize = u16(pos), u16(pos + 2), u32(pos + 4)
if csize < 8:
break
if ctype == 0x0001: # string pool
count, flags, sstart = u32(pos + 8), u32(pos + 16), u32(pos + 20)
utf8, base = flags & 0x100, pos + sstart
for i in range(count):
p = base + u32(pos + hsize + 4 * i)
if utf8:
p += 2 if d[p] & 0x80 else 1 # skip char count
n = d[p]
if n & 0x80:
n, p = ((n & 0x7F) << 8) | d[p + 1], p + 2
else:
p += 1
strings.append(d[p:p + n].decode("utf-8", "replace"))
else:
n = u16(p)
p += 2
if n & 0x8000:
n, p = ((n & 0x7FFF) << 16) | u16(p), p + 2
strings.append(d[p:p + 2 * n].decode("utf-16-le", "replace"))
elif ctype == 0x0180: # resource id map
resids = [u32(pos + 8 + 4 * i) for i in range((csize - 8) // 4)]
elif ctype == 0x0102: # start element
ext = pos + hsize
if strings[u32(ext + 4)] == "manifest":
astart, asize, acount = u16(ext + 8), u16(ext + 10), u16(ext + 12)
pkg = ver = None
for i in range(acount):
a = ext + astart + i * asize
name_i, raw, dtype, data = u32(a + 4), u32(a + 8), d[a + 15], u32(a + 16)
name = strings[name_i] if name_i < len(strings) else ""
rid = resids[name_i] if name_i < len(resids) else 0
if raw != 0xFFFFFFFF and raw < len(strings):
val = strings[raw]
elif dtype in (0x10, 0x11):
val = str(data)
else:
val = None
if name == "package":
pkg = val
elif name == "versionName" or rid == 0x0101021C:
ver = val
return pkg, ver
pos += csize
return None, None
# =====================================================================
# Versions
# =====================================================================
def vtuple(s):
m = re.search(r"\d+(?:[._-]\d+)*", s or "")
if not m:
return ()
return tuple(int(x) for x in re.split(r"[._-]", m.group(0)))
def is_newer(latest, installed):
"""True / False, or None when the two versions can't be compared."""
a, b = vtuple(latest), vtuple(installed)
if not a or not b:
return None
n = max(len(a), len(b))
return a + (0,) * (n - len(a)) > b + (0,) * (n - len(b))
def _ver(s):
return tuple(int(x) for x in s.split("."))
# =====================================================================
# Where each app comes from
# =====================================================================
class Release:
def __init__(self, version, url, filename):
self.version, self.url, self.filename = version, url, filename
def choose_apk(name, names, sdk):
"""Pick the right APK from a release's assets for this device."""
low = {n: n.lower() for n in names}
# Skip builds for other hardware / debug builds when there's a choice.
bad = re.compile(r"x86|armeabi|armv7|debug|chromeos|genshin|spoof")
pool = [n for n in names if not bad.search(low[n])] or list(names)
if name == "armsx2":
# e.g. ARMSX2-2.7-a13-armv8.2-sdk33.apk: newest build whose minimum
# SDK the device meets; the armv8.0 "legacy" build only as a fallback.
def sdk_of(n):
m = re.search(r"sdk(\d+)", low[n])
return int(m.group(1)) if m else 0
fits = [n for n in pool if sdk_of(n) <= sdk and "legacy" not in low[n]]
if fits:
return max(fits, key=sdk_of)
legacy = [n for n in pool if "legacy" in low[n]]
return (legacy or pool)[0]
if name == "eden":
# Eden ships Standard / Genshin-spoof / Legacy; Standard is recommended.
std = [n for n in pool if "standard" in low[n]]
if std:
return std[0]
pool = [n for n in pool if "legacy" not in low[n]] or pool
if name == "droiddeck":
# DroidDeck also ships -antutu / -ludashi / -pubg copies of each
# release; the plain DroidDeck-<ver>.apk is the one its README links.
plain = [n for n in pool if not re.search(r"antutu|ludashi|pubg", low[n])]
pool = plain or pool
if name == "obtainium":
# Each release has a normal and an "fdroid" flavour; use the normal one.
pool = [n for n in pool if "fdroid" not in low[n]] or pool
# Generic: prefer non-Play-Store, arm64 / universal Android builds.
pool.sort(key=lambda n: ("play" in low[n],
"arm64" not in low[n] and "aarch64" not in low[n]
and "universal" not in low[n], len(n)))
return pool[0]
def _release_from_assets(key, version, assets):
apks = [a for a in assets if a["name"].lower().endswith(".apk")]
if not apks:
raise RuntimeError("that release has no APK")
best = choose_apk(key, [a["name"] for a in apks], STATE["sdk"])
asset = next(a for a in apks if a["name"] == best)
return Release(version, asset["browser_download_url"], best)
def _url_version(url, pattern=r"(\d+(?:[._]\d+)+|\d{3,})"):
m = re.findall(pattern, urllib.parse.urlparse(url).path)
return m[-1].replace("_", ".") if m else "?"
def latest_github(key, repo):
data = json.loads(http_get(f"https://api.github.com/repos/{repo}/releases/latest"))
return _release_from_assets(key, data.get("tag_name", "?"), data.get("assets", []))
def latest_retroarch():
html = http_get("https://buildbot.libretro.com/stable/").decode("utf-8", "replace")
versions = set(re.findall(r"(\d+\.\d+\.\d+)/", html))
if not versions:
raise RuntimeError("no versions listed")
v = max(versions, key=_ver)
return Release(v, f"https://buildbot.libretro.com/stable/{v}/android/RetroArch_aarch64.apk",
f"RetroArch-{v}-aarch64.apk")
def latest_dolphin():
errors = []
for page in ("https://dolphin-emu.org/download/",
"https://dolphin-emu.org/update/latest/beta"): # fallback feed
try:
url = first_apk_link(page, prefer=r"/releases/")
name = posixpath.basename(urllib.parse.urlparse(url).path)
m = re.search(r"dolphin-([\w.]+?)\.apk", name)
return Release(m.group(1) if m else _url_version(url), url, name)
except Exception as e: # noqa: BLE001
errors.append(str(e))
raise RuntimeError("; ".join(errors))
def latest_ppsspp():
url = first_apk_link("https://www.ppsspp.org/download/")
return Release(_url_version(url), url, posixpath.basename(urllib.parse.urlparse(url).path))
def latest_eden():
# Official Eden server (Forgejo). Try /latest, then the newest stable with an APK.
try:
data = json.loads(http_get(f"{EDEN_API}/latest"))
if any(a["name"].lower().endswith(".apk") for a in data.get("assets", [])):
return _release_from_assets("eden", data.get("tag_name", "?"), data["assets"])
except Exception: # noqa: BLE001
pass
for rel in json.loads(http_get(f"{EDEN_API}?limit=10")):
if rel.get("prerelease") or rel.get("draft"):
continue
if any(a["name"].lower().endswith(".apk") for a in rel.get("assets", [])):
return _release_from_assets("eden", rel.get("tag_name", "?"), rel["assets"])
raise RuntimeError("no stable release with an Android APK found")
def latest_fdroid(pkg):
"""The build F-Droid currently suggests for a package."""
data = json.loads(http_get(f"https://f-droid.org/api/v1/packages/{pkg}"))
code = data["suggestedVersionCode"]
name = next((p["versionName"] for p in data.get("packages", [])
if p.get("versionCode") == code), str(code))
filename = f"{pkg}_{code}.apk"
return Release(name, f"https://f-droid.org/repo/{filename}", filename)
class App:
def __init__(self, key, name, purpose, pattern, latest, page, configure=None):
self.key, self.name, self.purpose = key, name, purpose
self.pattern = re.compile(pattern, re.I)
self.latest, self.page, self.configure = latest, page, configure
APPS = [
App("iisu", "iiSU", "Frontend / home", r"^com\.iisulauncher$|iisu",
lambda: latest_github("iisu", "iisu-network/iiSU"),
"https://github.com/iisu-network/iiSU/releases"),
App("retroarch", "RetroArch", "Retro consoles", r"^com\.retroarch",
latest_retroarch, "https://www.retroarch.com/?page=platforms", "retroarch"),
App("dolphin", "Dolphin", "GameCube / Wii", r"^org\.dolphinemu\.",
latest_dolphin, "https://dolphin-emu.org/download/", "dolphin"),
App("ppsspp", "PPSSPP", "PSP", r"^org\.ppsspp\.",
latest_ppsspp, "https://www.ppsspp.org/download/"),
App("azahar", "Azahar", "3DS", r"azahar",
lambda: latest_github("azahar", "azahar-emu/azahar"),
"https://github.com/azahar-emu/azahar/releases"),
App("armsx2", "ARMSX2", "PS2", r"armsx2",
lambda: latest_github("armsx2", "ARMSX2/ARMSX2"),
"https://github.com/ARMSX2/ARMSX2/releases"),
App("eden", "Eden", "Switch", r"(^|\.)eden(\.|_|$)",
latest_eden, "https://git.eden-emu.dev/eden-emu/eden/releases"),
App("hakux", "hakuX", "Original Xbox", r"hakux",
lambda: latest_github("hakux", HAKUX_REPO),
f"https://github.com/{HAKUX_REPO}/releases"),
App("droiddeck", "DroidDeck", "Steam / PC games", r"droiddeck",
lambda: latest_github("droiddeck", DROIDDECK_REPO),
f"https://github.com/{DROIDDECK_REPO}/releases"),
App("obtainium", "Obtainium", "App updates", r"obtainium",
lambda: latest_github("obtainium", OBTAINIUM_REPO),
f"https://github.com/{OBTAINIUM_REPO}/releases"),
App("jamesdsp", "JamesDSP", "Audio effects", r"jamesdsp",
lambda: latest_fdroid(JAMESDSP_PKG),
f"https://f-droid.org/packages/{JAMESDSP_PKG}/"),
]
APP_BY_KEY = {a.key: a for a in APPS}
# =====================================================================
# Remembering which package belongs to which app
# =====================================================================
STATE = {"sd": None, "sdk": 33, "device": None, "latest": {}}
def load_saved():
try:
return json.loads(STATE_FILE.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return {}
def save_package(key, pkg):
data = load_saved()
data.setdefault("packages", {})[key] = pkg
try:
STATE_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
except OSError:
pass
def app_packages(pkgs=None):
"""{app key: installed package or None}."""
pkgs = installed_packages() if pkgs is None else pkgs
saved = load_saved().get("packages", {})
local = {} # packages named inside APKs we downloaded
for apk in APK_DIR.glob("*.apk") if APK_DIR.exists() else []:
key = apk.name.split("-", 1)[0].lower()
if key in APP_BY_KEY:
pkg, _ = apk_info(apk)
if pkg:
local.setdefault(key, pkg)
out = {}
for app in APPS:
found = None
for cand in (saved.get(app.key), local.get(app.key)):
if cand and cand in pkgs:
found = cand
break
if not found:
found = next((p for p in sorted(pkgs) if app.pattern.search(p)), None)
out[app.key] = found
return out
# =====================================================================
# Config file merging
# =====================================================================
CFG_LINE = re.compile(r'^\s*([A-Za-z0-9_]+)\s*=')
def merge_retroarch_cfg(text, settings):
"""Replace or append key = "value" lines, keeping everything else."""
remaining = dict(settings)
out = []
for line in text.splitlines():
m = CFG_LINE.match(line)
if m and m.group(1) in remaining:
key = m.group(1)
out.append(f'{key} = "{remaining.pop(key)}"')
else:
out.append(line)
for key, val in remaining.items():
out.append(f'{key} = "{val}"')
return "\n".join(out) + "\n"
def merge_ini(text, sections):
"""Case-preserving INI merge (configparser would lowercase keys)."""
todo = {s: dict(kv) for s, kv in sections.items()}
out, current = [], None
def flush(sec):
for k, v in todo.get(sec, {}).items():
out.append(f"{k} = {v}")
todo.pop(sec, None)
for line in text.splitlines():
s = line.strip()
if s.startswith("[") and s.endswith("]"):
if current is not None:
# drop trailing blank lines so new keys stay inside the section
blanks = 0
while out and not out[-1].strip():
out.pop()
blanks += 1
flush(current)
out.extend([""] * blanks)
current = s[1:-1]
out.append(line)
continue
m = re.match(r"^\s*([^=;#]+?)\s*=", line)
if current in todo and m and m.group(1) in todo[current]:
key = m.group(1)
out.append(f"{key} = {todo[current].pop(key)}")
else:
out.append(line)
if current is not None:
flush(current)
for sec, kv in todo.items():
if out and out[-1].strip():
out.append("")
out.append(f"[{sec}]")
for k, v in kv.items():
out.append(f"{k} = {v}")
return "\n".join(out) + "\n"
def edit_remote_file(remote, transform):
"""Pull a file (or start empty), transform its text, push it back."""
with tempfile.TemporaryDirectory() as td:
local = Path(td) / posixpath.basename(remote)
text = ""
if remote_exists(remote):
adb("pull", remote, str(local))
text = local.read_text(encoding="utf-8", errors="replace")
shell(f'cp "{remote}" "{remote}.bak"', check=False)
else:
shell(f'mkdir -p "{posixpath.dirname(remote)}"')
local.write_text(transform(text), encoding="utf-8", newline="\n")
adb("push", str(local), remote)
# =====================================================================
# Device
# =====================================================================
def list_devices():
"""[(serial, state)] from 'adb devices'."""
out = subprocess.run([ARGS.adb, "devices"], capture_output=True, text=True).stdout
return [tuple(l.split()[:2]) for l in out.splitlines()[1:] if len(l.split()) >= 2]
def adb_available():
return bool(shutil.which(ARGS.adb) or Path(ARGS.adb).exists())
def detect_device():
"""Fill STATE with device info. Returns None, or a message saying what's wrong."""
devices = list_devices()
if ARGS.serial:
devices = [d for d in devices if d[0] == ARGS.serial]
if not devices:
return ("No device found. On the Thor: Settings > About device > tap 'Build number' "
"7 times, then Developer options > USB debugging ON. Plug it in and accept "
"the prompt.")
if any(state == "unauthorized" for _, state in devices):
return "The Thor shows as 'unauthorized': unlock it and tap Allow on the USB debugging prompt."
if len(devices) > 1:
return "MULTIPLE"
out = shell("getprop ro.product.brand; getprop ro.product.model; "
"getprop ro.build.version.release; getprop ro.build.version.sdk; "
"echo ---; ls /storage", check=False)
head, _, storage = out.partition("---")
lines = (head.splitlines() + ["", "", "", ""])[:4]
brand, model, release, sdk = (l.strip() for l in lines)
if sdk.isdigit():
STATE["sdk"] = int(sdk)
STATE["device"] = {"brand": brand, "model": model, "android": release,
"serial": devices[0][0]}
sd = next((f"/storage/{n}" for n in storage.split()
if re.fullmatch(r"[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}", n)), None)
STATE["sd"] = sd
return None
def storage_root():
return STATE["sd"] or "/storage/emulated/0"
def free_space(path):
out = shell(f"df -k {shlex.quote(path)} 2>/dev/null | tail -n 1", check=False).split()
try:
return int(out[3]) * 1024, int(out[1]) * 1024
except (IndexError, ValueError):
return None
def home_app():
out = shell("cmd package resolve-activity --brief "
"-a android.intent.action.MAIN -c android.intent.category.HOME", check=False)
comp = (out.splitlines() or [""])[-1].strip()
pkg = comp.split("/")[0] if "/" in comp else ""
return "" if pkg == "android" else pkg # "android" = the "choose an app" prompt
def lock_screen_off():
return shell("locksettings get-disabled", check=False).strip() == "true"
# =====================================================================
# Actions
# =====================================================================
def local_apk(app):
files = sorted(APK_DIR.glob(f"{app.key}-*.apk")) if APK_DIR.exists() else []
return files[-1] if files else None
def fetch_apk(app, rel=None):
"""Make sure the newest APK for an app is in apks/. Returns its path, or None."""
APK_DIR.mkdir(exist_ok=True)
try:
rel = rel or app.latest()
STATE["latest"][app.key] = rel.version
except Exception as e: # noqa: BLE001
have = local_apk(app)
if have:
say(f" couldn't check online ({e}); using {have.name}")
return have
say(c(f" couldn't fetch automatically ({e}).", "red"))
say(f" Get it here: {app.page} - put the APK in apks/ named {app.key}-<anything>.apk")
return None
name = rel.filename
if rel.version.lstrip("vV") not in name: # e.g. Obtainium's app-arm64-v8a-release.apk
name = f"{rel.version}-{name}"
dest = APK_DIR / f"{app.key}-{name}"
if dest.exists():
say(f" newest version ({rel.version}) already downloaded")
else:
say(f" newest version is {rel.version}")
try:
download(rel.url, dest)
except Exception as e: # noqa: BLE001
say(c(f" download failed ({e}). Get it here: {app.page}", "red"))
return local_apk(app)
for old in APK_DIR.glob(f"{app.key}-*.apk"): # don't keep older copies around
if old != dest:
old.unlink()
say(f" removed older {old.name}")
return dest
def grant_storage(pkg):
shell(f"appops set {pkg} MANAGE_EXTERNAL_STORAGE allow", check=False)
def grant_jamesdsp(pkg):
"""The permissions RootlessJamesDSP's own "ADB setup" screen asks for:
DUMP (to read the audio policy), overlay, and permanent audio capture."""
say(" granting JamesDSP's audio permissions over USB ...")
shell(f"pm grant {pkg} android.permission.DUMP", check=False)
shell(f"appops set {pkg} SYSTEM_ALERT_WINDOW allow", check=False)
shell(f"appops set {pkg} PROJECT_MEDIA allow", check=False)
# Extra steps run after an app is installed or updated.
AFTER_INSTALL = {"jamesdsp": grant_jamesdsp}
def install_apk(path, label=None):
"""adb install with plain-English handling of common failures. Returns package or None."""
label = label or path.name
pkg_in_apk, ver_in_apk = apk_info(path)
before = installed_packages()
say(f" Installing {label}" + (f" ({ver_in_apk})" if ver_in_apk else "") + " ...")
res = subprocess.run(adb_cmd("install", "-r", "-g", str(path)),
capture_output=True, text=True, encoding="utf-8", errors="replace")
out = (res.stdout + res.stderr).strip()
if res.returncode != 0 or "Failure" in out:
if "UPDATE_INCOMPATIBLE" in out and pkg_in_apk:
say(c(" A different build of this app is already installed (it was signed "
"by someone else,", "yellow"))
say(c(" e.g. a Play Store or pre-installed copy). It has to be removed first.",
"yellow"))
say(" Removing it deletes that copy's internal data; saves and games on the "
"SD card are kept.")
if confirm(" Remove the existing copy and install this one?", default=False):
shell(f"pm uninstall {pkg_in_apk}", check=False)
return install_apk(path, label)
return None
if "VERSION_DOWNGRADE" in out:
say(c(" The installed copy is newer than this APK - leaving it alone.", "yellow"))
return pkg_in_apk
say(c(f" FAILED: {out.splitlines()[-1] if out else 'unknown error'}", "red"))
return None
say(c(" installed", "green"))
new = installed_packages() - before
pkg = pkg_in_apk or (next(iter(new)) if len(new) == 1 else None)
if pkg:
grant_storage(pkg)
return pkg
def install_app(app, offer_config=True):
say(c(f"\n {app.name}", "bold"))
path = fetch_apk(app)
if not path:
return False
pkg = install_apk(path, app.name)
if not pkg:
return False
save_package(app.key, pkg)
if app.key in AFTER_INSTALL:
AFTER_INSTALL[app.key](pkg)
if offer_config and app.configure and confirm(
f" Apply the guide's {app.name} settings now?", default=True):
CONFIGURE[app.configure]()
return True
def other_local_apks():
"""APKs in apks/ that aren't one of the managed apps."""
if not APK_DIR.exists():
return []
return sorted(p for p in APK_DIR.glob("*.apk")
if p.name.split("-", 1)[0].lower() not in APP_BY_KEY)
def other_emulators(pkgs=None):
pkgs = installed_packages() if pkgs is None else pkgs
return sorted(p for p in pkgs if EMU_PATTERN.search(p) and not PROTECTED.match(p))
def remove_package(pkg, label):
say(f" Removing {label} ({pkg}) ...")
out = shell(f"pm uninstall -k --user 0 {pkg}", check=False)
ok = "Success" in out
say(c(" removed", "green") if ok else c(f" {out or 'failed'}", "red"))
return ok
def removed_packages():
"""Emulators/apps removed for this user that can be restored."""
everything = shell("pm list packages -u", check=False)
allp = {l.split(":", 1)[1].strip() for l in everything.splitlines() if ":" in l}
gone = allp - installed_packages()
return sorted(p for p in gone
if EMU_PATTERN.search(p) or any(a.pattern.search(p) for a in APPS))
def restore_package(pkg):
out = shell(f"cmd package install-existing {pkg}", check=False)
say(c(f" restored {pkg}", "green") if "installed" in out.lower()
else c(f" {out or 'failed'}", "red"))
def local_files(root):
"""Every file under root (sub-folders kept), skipping hidden files like .keep."""
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
for f in sorted(filenames):
if not f.startswith("."):
p = Path(dirpath) / f
out.append((p.relative_to(root).as_posix(), p))
return out
def remote_sizes(remote_dir):
"""{relative path: size} for files already on the device under remote_dir."""
out = shell(f"cd {shlex.quote(remote_dir)} 2>/dev/null && "
"find . -type f -exec stat -c '%s %n' {} + 2>/dev/null", check=False)
sizes = {}
for line in out.splitlines():
size, _, name = line.partition(" ")
if size.isdigit() and name.startswith("./"):
sizes[name[2:]] = int(size)
return sizes
def push_tree(local_root, remote_root, label):
"""Copy a folder file by file, showing each file, and skip files already copied."""
files = local_files(local_root)
if not files:
return 0, 0
on_device = remote_sizes(remote_root)
todo = [(rel, p, p.stat().st_size) for rel, p in files
if on_device.get(rel) != p.stat().st_size]
skipped = len(files) - len(todo)
total = sum(s for _, _, s in todo)
say(f" {label} -> {remote_root}: {len(todo)} to copy ({human_size(total)})"
+ (f", {skipped} already on the card" if skipped else ""))
made, done, failed = set(), 0, 0
for i, (rel, p, size) in enumerate(todo, 1):
remote = f"{remote_root}/{rel}"
parent = posixpath.dirname(remote)
if parent not in made:
shell(f"mkdir -p {shlex.quote(parent)}", check=False)
made.add(parent)
say(f" [{i}/{len(todo)}] {rel} ({human_size(size)}) "
f"- {human_size(done)} of {human_size(total)} done")
# adb's own output isn't captured, so its live percentage shows on big files.
if subprocess.run(adb_cmd("push", str(p), remote)).returncode != 0:
failed += 1
say(c(f" !! failed to copy {rel} - copy again to retry", "red"))
done += size
return len(todo), failed