| 1 | import json |
| 2 | import os |
| 3 | from pathlib import Path |
| 4 | import sys |
| 5 | import tempfile |
| 6 | |
| 7 | |
| 8 | data = json.load(sys.stdin) |
| 9 | path = Path(data["hostRoot"]) / "config/qBittorrent/config/qBittorrent.conf" |
| 10 | for directory in (path.parent.parent, path.parent): |
| 11 | directory.mkdir(parents=True, exist_ok=True) |
| 12 | os.chown(directory, data["uid"], data["uid"]) |
| 13 | directory.chmod(0o750) |
| 14 | lines = path.read_text().splitlines() if path.exists() else [] |
| 15 | |
| 16 | for section, key, value in ( |
| 17 | ("BitTorrent", "Session\\DefaultSavePath", "/data/media/Seedbox"), |
| 18 | ("BitTorrent", "Session\\TempPath", "/data/media/Seedbox"), |
| 19 | ("Preferences", "WebUI\\AuthSubnetWhitelist", "10.88.0.1/32"), |
| 20 | ("Preferences", "WebUI\\AuthSubnetWhitelistEnabled", "true"), |
| 21 | ("Preferences", "WebUI\\HostHeaderValidation", "false"), |
| 22 | ): |
| 23 | header = f"[{section}]" |
| 24 | if header not in lines: |
| 25 | lines += [header] |
| 26 | start = lines.index(header) + 1 |
| 27 | end = next((i for i in range(start, len(lines)) if lines[i].startswith("[")), len(lines)) |
| 28 | current = next((i for i in range(start, end) if lines[i].startswith(key + "=")), None) |
| 29 | entry = key + "=" + value |
| 30 | if current is None: |
| 31 | lines.insert(end, entry) |
| 32 | else: |
| 33 | lines[current] = entry |
| 34 | |
| 35 | content = "\n".join(lines) + "\n" |
| 36 | if not path.exists() or path.read_text() != content: |
| 37 | with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False) as file: |
| 38 | pending = Path(file.name) |
| 39 | file.write(content) |
| 40 | os.chown(pending, data["uid"], data["uid"]) |
| 41 | pending.chmod(0o600) |
| 42 | pending.replace(path) |