mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 07:46:01 +00:00
fix(battlenet): drop the unused runtime drive and list its games under the runtime path (#3188)
* fix(battlenet): drop the unused runtime drive and list its games under the runtime path * fix(battlenet): read product.db paths decoded and keep alias-saved folders * fix(battlenet): keep drives for paths that climb out of the runtime * fix(battlenet): keep a drive referenced with any separator spelling * fix(battlenet): check decoded config values before dropping a drive
This commit is contained in:
1 parent
1b80b506cb
commit
19d8819137
4 files changed
+244
-5
No files matched your search
@@ -207,7 +207,8 @@ object BattleNet {
|
||||
val taken = HashSet<File>()
|
||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||
for ((code, game) in games) {
|
||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
||||
val want = saved[code]?.let { runCatching { File(it).canonicalFile }.getOrNull() } ?: continue
|
||||
val keep = options(game.first, game.second).firstOrNull { runCatching { it.canonicalFile }.getOrNull() == want }?.takeIf { it !in taken } ?: continue
|
||||
out[code] = keep
|
||||
taken.add(keep)
|
||||
}
|
||||
@@ -245,9 +246,12 @@ object BattleNet {
|
||||
}
|
||||
}.trimEnd('/')
|
||||
if (mapped?.startsWith("/") == true) {
|
||||
val host = File("$target/$relative")
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
if (runCatching { host.canonicalFile.startsWith(rootfs.canonicalFile) }.getOrDefault(false)) return host
|
||||
runCatching {
|
||||
val home = rootfs.canonicalFile.toPath()
|
||||
val host = File("$target/$relative").canonicalFile.toPath()
|
||||
if (host.startsWith(home)) File(rootfs, home.relativize(host).toString()) else null
|
||||
}.getOrNull()?.let { return it }
|
||||
}
|
||||
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
||||
}
|
||||
|
||||
@@ -236,6 +236,21 @@ class BattleNetTest {
|
||||
assertNull(BattleNet.hostFolder(context, "D:\\..\\etc"))
|
||||
}
|
||||
|
||||
@Test fun aDriveAtAnAliasOfTheAppDataFolderListsTheGameUnderTheRuntimePath() {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val data = context.filesDir.parentFile!!
|
||||
val alias = File(data.parentFile, "alias-" + data.name)
|
||||
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
|
||||
try {
|
||||
val devices = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() }
|
||||
java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), alias.absoluteFile.toPath())
|
||||
val game = File(root, "root/Games/Stores/Battle.net/StarCraft").apply { mkdirs() }
|
||||
val drive = "D:\\" + data.absoluteFile.toPath().relativize(game.absoluteFile.toPath()).joinToString("\\")
|
||||
assertEquals(game.path, BattleNet.hostFolder(context, drive)?.path)
|
||||
} finally {
|
||||
java.nio.file.Files.delete(alias.toPath())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
@@ -294,6 +309,21 @@ class BattleNetTest {
|
||||
assertEquals(mapOf("WoWF" to root), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to "/elsewhere")))
|
||||
}
|
||||
|
||||
@Test fun aFolderSavedThroughAnAliasOfTheAppDataFolderIsKept() {
|
||||
val data = context.filesDir.parentFile!!
|
||||
val root = File(context.filesDir, "World of Warcraft").apply { mkdirs() }
|
||||
val foreverDir = File(root, "_forever_").apply { mkdirs() }
|
||||
val forever = BattleNet.title("wow_forever")!!
|
||||
val alias = File(data.parentFile, "alias-" + data.name)
|
||||
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
|
||||
try {
|
||||
val saved = File(alias, data.absoluteFile.toPath().relativize(foreverDir.absoluteFile.toPath()).toString()).path
|
||||
assertEquals(mapOf("WoWF" to foreverDir), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to saved)))
|
||||
} finally {
|
||||
java.nio.file.Files.delete(alias.toPath())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theListedFolderIsRememberedAcrossScans() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
|
||||
|
||||
@@ -636,11 +636,115 @@ def move_installs(root):
|
||||
return False
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
write_bytes(path, moved)
|
||||
return True
|
||||
|
||||
|
||||
def rootfs_drives(root):
|
||||
host = rootfs()
|
||||
folder = dosdevices(root)
|
||||
if not host:
|
||||
return {}
|
||||
try:
|
||||
names = sorted(os.listdir(folder))
|
||||
except OSError:
|
||||
return {}
|
||||
drives = {}
|
||||
for name in names:
|
||||
link = os.path.join(folder, name)
|
||||
if len(name) == 2 and name[0].lower() in DRIVES and name[1] == ":" and os.path.islink(link):
|
||||
target = os.path.realpath(link)
|
||||
if inside(host, target):
|
||||
drives[name[0].lower()] = host[len(target):].strip("/")
|
||||
return drives
|
||||
|
||||
|
||||
def write_bytes(path, data):
|
||||
with open(path + ".tmp", "wb") as f:
|
||||
f.write(moved)
|
||||
f.write(data)
|
||||
shutil.copymode(path, path + ".tmp")
|
||||
os.replace(path + ".tmp", path)
|
||||
return True
|
||||
|
||||
|
||||
def install_folders(root):
|
||||
try:
|
||||
with open(os.path.join(drive_c(root), *PRODUCT_DB), "rb") as f:
|
||||
data = f.read()
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
folders = []
|
||||
rewrite_field(data, INSTALL_FOLDER, lambda value: folders.append(value) or value)
|
||||
return folders
|
||||
|
||||
|
||||
def json_strings(value):
|
||||
if isinstance(value, str):
|
||||
yield value
|
||||
elif isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
yield key
|
||||
yield from json_strings(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
yield from json_strings(item)
|
||||
|
||||
|
||||
def escapes(tail):
|
||||
depth = 0
|
||||
for part in re.split(rb"[\\/]+", tail):
|
||||
if part == b"..":
|
||||
depth -= 1
|
||||
if depth < 0:
|
||||
return True
|
||||
elif part and part != b".":
|
||||
depth += 1
|
||||
return False
|
||||
|
||||
|
||||
def drop_rootfs_drives(root):
|
||||
pfx = os.path.join(prefix(root), "pfx")
|
||||
drives = rootfs_drives(root)
|
||||
if not drives or wine_processes(pfx):
|
||||
return []
|
||||
try:
|
||||
folders = install_folders(root)
|
||||
except ValueError:
|
||||
return []
|
||||
texts = {}
|
||||
for path in (os.path.join(pfx, "system.reg"), os.path.join(pfx, "user.reg"), os.path.join(drive_c(root), *CONFIG)):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
texts[path] = f.read()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
sep = rb"(?:\\\\|/)"
|
||||
changed = dict(texts)
|
||||
for letter, rest in drives.items():
|
||||
head = rb"(?<![A-Za-z0-9])[" + letter.encode() + letter.upper().encode() + rb"]:"
|
||||
inner = b"".join(sep + re.escape(part.encode()) for part in rest.split("/") if part)
|
||||
for path in changed:
|
||||
changed[path] = re.sub(head + inner + rb"(?=(" + sep + rb"[^\"\r\n]*))",
|
||||
lambda m: m.group(0) if escapes(m.group(1)) else b"Z:", changed[path])
|
||||
for path, data in changed.items():
|
||||
if data != texts[path]:
|
||||
write_bytes(path, data)
|
||||
seen = list(changed.values())
|
||||
config = os.path.join(drive_c(root), *CONFIG)
|
||||
if config in changed:
|
||||
try:
|
||||
seen += [text.encode("utf-8", "replace") for text in json_strings(json.loads(changed[config].decode("utf-8-sig")))]
|
||||
except ValueError:
|
||||
return []
|
||||
dropped = []
|
||||
for letter in sorted(drives):
|
||||
drive = letter.encode() + letter.upper().encode()
|
||||
used = rb"(?<![A-Za-z0-9])[" + drive + rb"]:[\\/]"
|
||||
if any(re.match(rb"[" + drive + rb"]:[\\/]", folder.lstrip()) for folder in folders):
|
||||
continue
|
||||
if not any(re.search(used, data) for data in seen):
|
||||
os.unlink(os.path.join(dosdevices(root), letter + ":"))
|
||||
dropped.append(letter)
|
||||
return dropped
|
||||
|
||||
|
||||
def wow_folders(root):
|
||||
@@ -756,6 +860,11 @@ def configure(root, library=None):
|
||||
say("Battle.net's installed games now use the Wine drive of their volume")
|
||||
except OSError as error:
|
||||
say("Battle.net's installed games not moved to their Wine drive: %s" % error)
|
||||
try:
|
||||
for letter in drop_rootfs_drives(root):
|
||||
say("Wine drive %s: held the runtime and is no longer used; removed" % letter.upper())
|
||||
except OSError as error:
|
||||
say("Battle.net's unused runtime drive not removed: %s" % error)
|
||||
try:
|
||||
wallpaper(root)
|
||||
except OSError as error:
|
||||
|
||||
@@ -408,6 +408,102 @@ class DriveTest(Temp):
|
||||
+ sd + gone + self.field(7, b"tail"))
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
|
||||
def rootfs_prefix(self):
|
||||
rootfs = self.card / "files/linuxfs"
|
||||
game = rootfs / "root/Games/Stores/Battle.net/World of Warcraft"
|
||||
game.mkdir(parents=True)
|
||||
card = self.tmp / "sd"
|
||||
card.mkdir()
|
||||
self.devices.mkdir(parents=True)
|
||||
for letter, target in (("d", self.card), ("e", card), ("s", self.card)):
|
||||
os.symlink(str(target), self.devices / (letter + ":"))
|
||||
pfx = self.devices.parent
|
||||
system = pfx / "system.reg"
|
||||
system.write_text('[Software\\\\Uninstall\\\\wow] 1\n'
|
||||
'"InstallLocation"="D:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Stores\\\\Battle.net\\\\World of Warcraft"\n'
|
||||
'"DisplayIcon"="\\"d:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Wow.exe\\""\n'
|
||||
'"Card"="E:\\\\Diablo"\n"Other"="AD:\\\\files\\\\linuxfs\\\\x"\n')
|
||||
system.chmod(0o640)
|
||||
config = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"Client": {"Install": {"DefaultInstallPath": "D:\\files\\linuxfs\\root\\Games\\Stores\\Battle.net"}}}))
|
||||
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"))
|
||||
return rootfs, system, config
|
||||
|
||||
def test_an_unused_drive_holding_the_native_rootfs_is_removed_once_its_paths_use_the_root_drive(self):
|
||||
rootfs, system, config = self.rootfs_prefix()
|
||||
before = system.read_text()
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertEqual(system.read_text(), before)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])]
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.running = []
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
|
||||
self.assertEqual(sorted(os.listdir(self.devices)), ["e:", "s:"])
|
||||
self.assertEqual(system.read_text(), before.replace("D:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root")
|
||||
.replace("d:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root"))
|
||||
self.assertEqual(system.stat().st_mode & 0o777, 0o640)
|
||||
self.assertEqual(json.loads(config.read_text())["Client"]["Install"]["DefaultInstallPath"], "Z:\\root\\Games\\Stores\\Battle.net")
|
||||
self.assertTrue(self.card.is_dir())
|
||||
self.assertTrue((rootfs / "root/Games/Stores/Battle.net/World of Warcraft").is_dir())
|
||||
|
||||
def test_a_drive_holding_the_native_rootfs_stays_while_a_path_outside_the_runtime_uses_it(self):
|
||||
rootfs, system, _ = self.rootfs_prefix()
|
||||
system.write_text(system.read_text() + '"Elsewhere"="D:\\\\Other\\\\Game"\n')
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
|
||||
self.assertIn('"Elsewhere"="D:\\\\Other\\\\Game"', system.read_text())
|
||||
|
||||
def test_a_drive_holding_the_native_rootfs_stays_while_a_game_outside_the_runtime_is_installed_on_it(self):
|
||||
rootfs, _, _ = self.rootfs_prefix()
|
||||
for folder in ("D:/Other/" + "x" * 40, "D:\\Other\\" + "x" * 39, " D:/Other/" + "x" * 39):
|
||||
with self.subTest(folder=folder):
|
||||
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"),
|
||||
self.product("other", folder))
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
|
||||
def test_a_path_that_climbs_out_of_the_runtime_keeps_its_drive(self):
|
||||
rootfs, system, _ = self.rootfs_prefix()
|
||||
up = '"Up"="D:\\\\files\\\\linuxfs\\\\root\\\\..\\\\..\\\\Other"\n'
|
||||
system.write_text(system.read_text() + up)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertIn(up, system.read_text())
|
||||
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
|
||||
|
||||
def test_a_config_path_with_escaped_characters_keeps_its_drive(self):
|
||||
rootfs, _, config = self.rootfs_prefix()
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
settings = config.read_text()
|
||||
for text in (settings[:-1] + ', "Other": "D:\\/Other\\/Game"}', settings[:-1] + ', "Other": "D\\u003a/Other/Game"}', '{"Client": '):
|
||||
with self.subTest(text=text):
|
||||
config.write_text(text)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
config.write_text(settings)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
|
||||
|
||||
def test_an_unreadable_database_keeps_the_drive(self):
|
||||
rootfs, _, _ = self.rootfs_prefix()
|
||||
path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db"
|
||||
path.write_bytes(b"\x0a\xff")
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
|
||||
def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self):
|
||||
game = self.library / "World of Warcraft"
|
||||
game.mkdir()
|
||||
|
||||
Reference in new issue
Block a user