209 lines
8.0 KiB
Python
209 lines
8.0 KiB
Python
"""从已登录的 DramaBox App 读取设备身份。令牌只进入本地会话文件。"""
|
|
import re
|
|
import tempfile
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from server.services.adb import Adb
|
|
|
|
PACKAGE = "com.storymatrix.drama"
|
|
PREFS = f"/data/data/{PACKAGE}/files/drama.datastore.preferences_pb"
|
|
APPSFLYER = f"/data/data/{PACKAGE}/shared_prefs/appsflyer-data.xml"
|
|
|
|
|
|
def read_app_login(serial: str) -> dict:
|
|
serial = (serial or "").strip()
|
|
if not serial:
|
|
raise RuntimeError("请选择设备")
|
|
adb = Adb.locate()
|
|
adb._ready(serial)
|
|
with tempfile.TemporaryDirectory(prefix="dramabox-login-") as tmp:
|
|
root = Path(tmp)
|
|
prefs_path = root / "drama.pb"
|
|
flyer_path = root / "af.xml"
|
|
_pull(adb, serial, PREFS, prefs_path)
|
|
prefs = _parse_prefs(prefs_path.read_bytes())
|
|
try:
|
|
_pull(adb, serial, APPSFLYER, flyer_path)
|
|
afid = _xml_string(flyer_path.read_text(encoding="utf-8", errors="replace"), "AF_INSTALLATION")
|
|
except RuntimeError:
|
|
afid = ""
|
|
token = str(prefs.get("sp.user.token") or "")
|
|
if not token.startswith("Bearer "):
|
|
raise RuntimeError("这台设备上的 DramaBox 还没有登录,请先在 App 里登录后再读取")
|
|
device_id = str(prefs.get("google.ad.id") or "")
|
|
android_id = str(prefs.get("google.android.id") or "")
|
|
user_id = str(prefs.get("sp.user.id") or "")
|
|
if not device_id or not android_id or not user_id:
|
|
raise RuntimeError("登录信息不完整,请在 App 里重新打开一次后再读取")
|
|
brand = _prop(adb, serial, "ro.product.brand") or "OPPO"
|
|
model = _prop(adb, serial, "ro.product.model") or "PJJ110"
|
|
manufacturer = _prop(adb, serial, "ro.product.manufacturer") or brand
|
|
release = _prop(adb, serial, "ro.build.version.release") or "12"
|
|
build_id = _prop(adb, serial, "ro.build.id")
|
|
locale = _prop(adb, serial, "persist.sys.locale") or _prop(adb, serial, "ro.product.locale")
|
|
language = str(prefs.get("language.origin") or "zhHans")
|
|
current = str(prefs.get("sp.current.user_language") or "")
|
|
if not locale or "_" not in locale:
|
|
locale = "zh_CN" if current.startswith("zh") or language.startswith("zh") else (current or "en_US")
|
|
resolution = _resolution(adb, serial)
|
|
status = str(prefs.get(f"user.membership.status.uid.{user_id}") or "")
|
|
vip = prefs.get(f"user.vip.uid.{user_id}") is True or "paid" in status.lower()
|
|
return {
|
|
"token": token,
|
|
"device_id": device_id,
|
|
"android_id": android_id,
|
|
"user_id": user_id,
|
|
"name": str(prefs.get("sp.user.name") or ""),
|
|
"cid": str(prefs.get("sp.tf.chid") or ""),
|
|
"nchid": str(prefs.get("sp.native.channel.code") or "DRA1000042"),
|
|
"mchid": str(prefs.get("sp.tf.m.chid") or ""),
|
|
"mbid": str(prefs.get("sp.tf.m.bid") or prefs.get("sp.tf.chbid") or ""),
|
|
"language": language,
|
|
"current_language": current or (language[:2] if language else "en"),
|
|
"country_code": str(prefs.get("google.country.code") or ""),
|
|
"install_time": str(prefs.get("sp.app.install.time.stamp") or ""),
|
|
"instance_id": str(prefs.get("firebase.analytics.app_instance_id") or ""),
|
|
"device_score": str(prefs.get("device.score") if prefs.get("device.score") is not None else ""),
|
|
"lat": "1" if prefs.get("google.ad.is.tracking") else "0",
|
|
"afid": afid,
|
|
"brand": brand,
|
|
"model": model,
|
|
"manufacturer": manufacturer,
|
|
"os_version": release,
|
|
"build": f"Build/{build_id}" if build_id else "",
|
|
"locale": locale,
|
|
"resolution": resolution,
|
|
"vip": vip,
|
|
}
|
|
|
|
|
|
def _pull(adb: Adb, serial: str, remote: str, dest: Path) -> None:
|
|
last = _pull_once(adb, serial, remote, dest)
|
|
if last is None:
|
|
return
|
|
adb._run(["-s", serial, "root"], timeout=20)
|
|
if ":" in serial:
|
|
adb._run(["connect", serial], timeout=15)
|
|
for _ in range(6):
|
|
last = _pull_once(adb, serial, remote, dest)
|
|
if last is None:
|
|
return
|
|
time.sleep(0.4)
|
|
staged = _stage_with_su(adb, serial, remote)
|
|
if staged:
|
|
pulled = _pull_once(adb, serial, staged, dest)
|
|
adb._run(["-s", serial, "shell", f"rm -f {staged}"], timeout=10)
|
|
if pulled is None:
|
|
return
|
|
last = pulled or last
|
|
detail = "读不到应用私有目录。未 root 的设备无法获取登录信息。请使用已 root 的手机,或带 root 的模拟器。"
|
|
if last:
|
|
detail = f"{detail} {last}"
|
|
raise RuntimeError(detail)
|
|
|
|
|
|
def _pull_once(adb: Adb, serial: str, remote: str, dest: Path) -> str | None:
|
|
if dest.is_file():
|
|
dest.unlink()
|
|
proc = adb._run(["-s", serial, "pull", remote, str(dest)], timeout=30)
|
|
if dest.is_file() and dest.stat().st_size > 0:
|
|
return None
|
|
return (proc.stderr or b"").decode("utf-8", "replace").strip() or "pull 失败"
|
|
|
|
|
|
def _stage_with_su(adb: Adb, serial: str, remote: str) -> str:
|
|
tmp = "/data/local/tmp/dramabox-login.bin"
|
|
command = f"cp {remote} {tmp} && chmod 644 {tmp}"
|
|
for line in (f"su -c '{command}'", f"su 0 sh -c '{command}'"):
|
|
adb._run(["-s", serial, "shell", line], timeout=15)
|
|
_, text, _ = adb._shell(serial, ["stat", "-c", "%s", tmp], timeout=8)
|
|
size = text.strip()
|
|
if size.isdigit() and int(size) > 0:
|
|
return tmp
|
|
return ""
|
|
|
|
|
|
def _prop(adb: Adb, serial: str, name: str) -> str:
|
|
_, text, _ = adb._shell(serial, ["getprop", name], timeout=8)
|
|
return text.strip()
|
|
|
|
|
|
def _resolution(adb: Adb, serial: str) -> str:
|
|
_, text, _ = adb._shell(serial, ["wm", "size"], timeout=8)
|
|
match = re.search(r"(\d+)x(\d+)", text)
|
|
if not match:
|
|
return ""
|
|
return f"{match.group(1)}x{match.group(2)}"
|
|
|
|
|
|
def _xml_string(text: str, name: str) -> str:
|
|
match = re.search(rf'<string name="{re.escape(name)}">(.*?)</string>', text, re.S)
|
|
return match.group(1).strip() if match else ""
|
|
|
|
|
|
def _varint(buf: bytes, index: int) -> tuple[int, int]:
|
|
value = 0
|
|
shift = 0
|
|
while index < len(buf) and shift <= 63:
|
|
byte = buf[index]
|
|
index += 1
|
|
value |= (byte & 0x7F) << shift
|
|
if byte < 128:
|
|
return value, index
|
|
shift += 7
|
|
raise ValueError("登录信息格式无法识别")
|
|
|
|
|
|
def _fields(buf: bytes) -> list[tuple[int, object]]:
|
|
index = 0
|
|
found = []
|
|
while index < len(buf):
|
|
try:
|
|
key, index = _varint(buf, index)
|
|
except ValueError:
|
|
break
|
|
field, wire = key >> 3, key & 7
|
|
if wire == 0:
|
|
value, index = _varint(buf, index)
|
|
found.append((field, value))
|
|
elif wire == 2:
|
|
length, index = _varint(buf, index)
|
|
found.append((field, buf[index : index + length]))
|
|
index += length
|
|
elif wire == 5 and index + 4 <= len(buf):
|
|
found.append((field, buf[index : index + 4]))
|
|
index += 4
|
|
elif wire == 1 and index + 8 <= len(buf):
|
|
found.append((field, buf[index : index + 8]))
|
|
index += 8
|
|
else:
|
|
break
|
|
return found
|
|
|
|
|
|
def _parse_prefs(data: bytes) -> dict:
|
|
result = {}
|
|
for field, payload in _fields(data):
|
|
if field != 1 or not isinstance(payload, (bytes, bytearray)):
|
|
continue
|
|
name = None
|
|
value = None
|
|
for part_field, part in _fields(payload):
|
|
if part_field == 1 and isinstance(part, (bytes, bytearray)):
|
|
name = part.decode("utf-8", "replace")
|
|
elif part_field == 2 and isinstance(part, (bytes, bytearray)):
|
|
inner = _fields(part)
|
|
if not inner:
|
|
continue
|
|
value_field, raw = inner[0]
|
|
if value_field == 1:
|
|
value = bool(raw)
|
|
elif value_field in (3, 4):
|
|
value = int(raw)
|
|
elif value_field == 5 and isinstance(raw, (bytes, bytearray)):
|
|
value = raw.decode("utf-8", "replace")
|
|
if name:
|
|
result[name] = value
|
|
return result
|