Commit cf609f86 authored by haohao's avatar haohao

feat: add cloud phone fleet collection and LSPosed module

parent 378fd3f7
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
__pycache__/
devices.json
.env
.env.*
!.env.example
keys/
run/
screenshots/
captures/
profile.local.json
apks/
*.log
*.lock
# 指定 Host 的六台手机共享任务
只使用业务 `2100065094208589824` 下的 **`host-7707546908511705892`**。即使同一个 ResourceSet 中还有其他 Host,也不会在其他 Host 创建或运行实例。这个 Host 的实例总数上限为 **6**,包含已有实例;例如已有 2 台时最多补建 4 台。不会购买新资源。
实例管理、共享队列及 worker 均已合并到 `app.py`,启动命令保持如下。
在项目根目录使用 conda `xhs` 环境。先只读查看计划:
```bash
conda run --no-capture-output -n xhs python -m cloud_phone fleet \
cloud_phone/captures/us2-sample-20261113-143824/tasks.json \
--host-id host-7707546908511705892 --max-instances 6 --plan
```
实际运行:
```bash
conda run --no-capture-output -n xhs python -m cloud_phone fleet \
cloud_phone/captures/us2-sample-20261113-143824/tasks.json \
--host-id host-7707546908511705892 --max-instances 6 \
--output cloud_phone/captures/us2-fleet
```
`--host-id` 默认读取 `instance.defaults.json` 中的 Host,当前即上面这个资源;`--max-instances` 最大只能是 6。每次创建前重新查询该 Host 的容量和已有实例数量。程序仅管理本次实例清单中的手机,保留其他用途的已有实例。中断后沿用相同的 `--output`,以复用已创建的手机和任务进度;创建结果不确定时保留唯一名称并停止,避免重复提交。
所有就绪手机共用一份本地 SQLite 任务队列。每个达人只由一个 worker 领取,任务失败不会自动回队。准备失败的手机不领取任务,其他就绪手机可以继续领取尚未开始的任务。中断时正在执行的任务标记为 `interrupted`,保留供人工核对。出现小红书安全限制、登录要求或无法确认游客状态时停止整个批次,并保留停止原因;再次启动不会自动清除这个停止状态。
程序只读取已保存的 60 条任务快照,不连接或消费 Redis。手机启动小红书前设置并验证代理;只输入 red-id,点联想头像,最多翻 10 页,接口声明无更多时提前结束。沿用单机采集入口的两表转换,逐条打印并保存 `dry_run=true` 数据,不真实上报。
每台手机使用独立的连接配置、状态目录和端口。准备阶段安装应用管理中已有版本的两个 APK、开启内置 Zygisk、绑定已登记的 ADB 公钥,并进行游客与 Hook 检查。镜像不兼容或模块作用域未启用时记录准备失败,不能将单元测试通过当成实机采集成功。完整初始化要求见 [游客主页指南](PROFILE_GUIDE.md)。
输出目录中:
- `instances.json`:目标 Host、本批次实例、唯一创建名称和端口。
- `tasks.sqlite3`:共享任务领取和完成记录。
- `readiness.json`:各手机的准备结果。
- `fleet.json`:成功、失败、待运行数量和停止原因。
- `tasks/`:每个达人独立的接口响应、待上报数据和控制台日志。
- `host-correction.json`:本次误扩展到其他 Host 后的清理记录,保留核对证据。
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# us2 只读任务抽样与测试
2026-11-13 从 Redis db 0 的 `xhs:keyword:package:us2` 请求抽样 100 条。该键实际为 Set,当时只有 **60 条**,全部格式有效;读取前后数量均为 **60**。仅执行 `TYPE`、`SCARD`、`SRANDMEMBER key 100`、`SCARD`,没有弹出、删除、确认或回写任务。数量对比是本次观测值,不代表其他消费者停止运行。
快照保存于 [tasks.json](captures/us2-sample-20261113-143824/tasks.json),包含原始成员、解析后的 `user_id` / `red_id` 和抽样统计。后续批量测试只读此文件,不再连接 Redis。快照和测试输出已被 Git 忽略,目录权限 `0700`,数据文件权限 `0600`。
## 本次设备与实际结果
| 项目 | 本次值 |
| --- | --- |
| 业务 | `2100065094208589824` |
| 指定资源 | `host-7707521068084239123` |
| 新建实例 | `7707541932755082020` |
| 名称 | `autoxhs-us2-20261113-143949` |
| 规格 / 存储 | `samplePro`(平台名称:入门型pro),2 核 / 4GB / 实际 48Gi |
| 镜像 / 布局 | `img-2156621314`(Android 10 / aosp10-lsposed-fixed)/ `mi8` |
| 独立配置 / ADB | `captures/us2-sample-20261113-143824/devices.json` / `127.0.0.1:15553` |
已安装小红书 9.54.0 和采集模块,已开启 Zygisk、启用镜像内 Zygisk LSPosed,修复 ADB `su` 并通过平台重启。检查确认 Zygisk 开关开启且本次 zygote 已加载,SELinux 为 Enforcing,本次未修改该设置。
**本次未完成主页采集。** 新实例上的小红书、LSPosed 管理器、桌面等应用出现 `SIGSEGV`,崩溃栈包含 `AndroidRuntime::javaCreateThreadEtc+72`;界面黑屏且 UI 层级为空。模块作用域尚未配置。批量入口在第 1 条任务的应用启动检查阶段确认小红书本次启动崩溃,按设备故障停止整批;尚未设置该条任务代理、输入 red-id 或点击头像。
| 统计 | 数量 |
| --- | --- |
| 本地样本 | 60 |
| 尝试启动 / 启动失败 | 1 / 1 |
| 成功 / 尚未测试 | 0 / 59 |
| 采集页 / 笔记 / 待上报预览 | 0 / 0 / 0 |
| Redis 消费 / 真实上报 | 0 / 0 |
这次失败属于实例运行环境故障,不能据此判断第 1 条达人任务有效性,也不能当作无更多笔记。没有改用其他实例代替用户指定资源。实例保留供后续诊断;本次启动的本地隧道在收尾时停止,后续运行可按需重建连接。
证据:
- [批次结果](captures/us2-sample-20261113-143824/batch/batch.json):`stop_reason=app_crash`、`finished=false`。
- [完整批次控制台](captures/us2-sample-20261113-143824/batch-console.log)。
- [设备检查](captures/us2-sample-20261113-143824/readiness.json)与[崩溃日志](captures/us2-sample-20261113-143824/crash-startup.log)。
此前其他资源上的单达人成功结果见 [历史实测记录](RUNTIME_DIAGNOSTICS.md),不能代表本次新实例测试成功。
## 复用命令
在项目根目录使用 conda `xhs` 环境。重新抽样时指定一个不存在的新文件;该命令只读 Set,不执行原消费程序:
```bash
conda run --no-capture-output -n xhs python -m cloud_phone snapshot \
--count 100 --output cloud_phone/captures/us2-new-snapshot/tasks.json
```
修复实例运行环境并启用模块的小红书作用域后,复用**现有快照**测试,不需再次读取 Redis。输出目录必须不存在,以保留先前失败证据:
```bash
conda run --no-capture-output -n xhs python -m cloud_phone batch \
cloud_phone/captures/us2-sample-20261113-143824/tasks.json \
--pod-id 7707541932755082020 \
--config cloud_phone/captures/us2-sample-20261113-143824/devices.json \
--output cloud_phone/captures/us2-sample-20261113-143824/batch-retry \
--limit 100 --max-pages 10 --timeout 45
```
每条任务仅输入 red-id,点击头像联想进入主页,最多采集 10 页或在 `has_more=false` 时结束。每页沿用 `http_lanjie_user.py` 的两表字段转换,仅逐条打印并保存 `dry_run=true` 记录,不连接 MySQL、不发送上报请求。登录要求、游客状态无法确认、Hook 未就绪、应用崩溃或代理故障会停止整批;普通的无头像联想等目标失败记录后继续。完整日志与批次结果持续保存在输出目录。
新增只读抽样与本地批次测试共 8 项,当前 `cloud_phone/tests` 合计 **99 项通过**;这些是本地自动化测试,不代表本次云实例端到端采集通过。
"""火山云手机管理、ADB 连接和 Android 操作。"""
from .app import AndroidDevice, CloudPhoneClient, CloudPhoneError
__all__ = ["CloudPhoneClient", "CloudPhoneError", "AndroidDevice"]
from .app import main
raise SystemExit(main())
{
"product_id": "2100065094208589824",
"verified_at": "2026-11-13T06:24:55.021759+00:00",
"apps": [
{
"file": "xhs-9.54.0.apk",
"package": "com.xingin.xhs",
"version_code": 9540805,
"version": "9.54.0",
"sha256": "2c370f3016f6ed69c295a9420431eaeda6a6949d53693b8b6493af51daab5f82",
"md5": "efcf0cd83006b5d5e0ac9c9e7773328b",
"size": 187846799,
"app_name": "xhs_9_54_0",
"app_type": 3,
"app_id": "7707467106849299242",
"version_id": "7707536723638655787",
"outcome": "verified",
"platform_download_copy": true
},
{
"file": "app-debug.apk",
"package": "com.autoxhs.userposted",
"version_code": 1,
"version": "1.0.0",
"sha256": "1a2a54f3a538398926e2a1882d001bfb62db22c2e2217472010aff1e3a311df4",
"md5": "a015f1bf3c0c23f6695c5cc44cd98635",
"size": 27853,
"app_name": "autoxhs_user_posted_1_0_0",
"app_type": 0,
"app_id": "7707535133091863350",
"version_id": "7707535133091879734",
"outcome": "verified",
"platform_download_copy": true
}
]
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"region": "cn-north-1",
"state_dir": "run/adb-tunnels",
"adb_key_path": "keys/adbkey",
"tunnel_ttl_seconds": 86400,
"renew_before_seconds": 900,
"health_interval_seconds": 30,
"adb_connect_timeout_seconds": 30,
"ssh_start_timeout_seconds": 15,
"retry_seconds": 10,
"devices": []
}
#!/system/bin/sh
# 通过平台 root 执行;启用内置 Zygisk 和现有 Zygisk 版 LSPosed。
set -eu
[ "$(id -u)" = 0 ] || { echo 'ERROR: root required' >&2; exit 1; }
command -v magisk >/dev/null 2>&1 || {
echo 'ERROR: built-in Magisk not found' >&2
exit 1
}
[ -f /data/adb/modules/zygisk_lsposed/module.prop ] || {
echo 'ERROR: install Zygisk LSPosed first' >&2
exit 1
}
# Riru 和内置 Zygisk 不同时使用;保留模块文件,便于回退。
for module in riru-core riru_lsposed; do
if [ -d "/data/adb/modules/$module" ]; then
touch "/data/adb/modules/$module/disable"
fi
done
magisk --sqlite "INSERT OR REPLACE INTO settings (key,value) VALUES ('zygisk',1);"
rm -f /data/adb/modules/zygisk_lsposed/disable /data/adb/modules/zygisk_lsposed/remove
state=$(magisk --sqlite "SELECT value FROM settings WHERE key='zygisk';")
[ "$state" = 'value=1' ] || {
echo 'ERROR: Zygisk setting could not be verified' >&2
exit 1
}
echo 'Zygisk enabled; Zygisk LSPosed enabled; reboot through the cloud platform next.'
#!/system/bin/sh
# Optional repair for the aosp10-lsposed-fixed image, run explicitly as root.
# Its Magisk socket is present, but 0700 parent directories block ADB shell.
set -eu
[ "$(id -u)" = 0 ] || { echo 'Run this script as platform root.' >&2; exit 1; }
MAGISK_TMP=/debug_ramdisk
[ -S "$MAGISK_TMP/.magisk/device/socket" ] || {
echo 'Expected built-in Magisk socket is missing; image was not modified.' >&2
exit 1
}
# Allow traversal without allowing directory listing or file writes.
chmod 711 "$MAGISK_TMP/.magisk" "$MAGISK_TMP/.magisk/device"
# Authorize only the Android ADB shell UID, using Magisk's normal policy table.
"$MAGISK_TMP/magisk" --sqlite \
"INSERT OR REPLACE INTO policies(uid,policy,until,logging,notification) VALUES(2000,2,0,1,0);"
if [ "${1:-}" = --install ]; then
destination=/data/adb/service.d/autoxhs-adb-su.sh
mkdir -p /data/adb/service.d
if [ "$0" != "$destination" ]; then
cp "$0" "$destination"
fi
chmod 700 "$destination"
fi
{
"product_id": "2100065094208589824",
"region": "cn-north-1",
"create": {
"image_id": "img-2156621314",
"host_id": "host-7707546908511705892",
"dc": "zjwz-ctcucm-02-yzm83nph",
"configuration_code": "elementaryPro",
"resource_type": 200,
"display_layout_id": "mi8",
"overlay_settings": [
{"settings_type": "secure", "settings_name": "navigationbar_switch", "settings_value": "on", "settings_value_type": "string"},
{"settings_type": "secure", "settings_name": "statusbar_switch", "settings_value": "on", "settings_value_type": "string"}
]
}
}
{
"product_id": "2100065094208589824",
"region": "cn-north-1",
"create": {
"image_id": "img-2156621314",
"host_id": "host-7707546908511705892",
"dc": "zjwz-ctcucm-02-yzm83nph",
"configuration_code": "elementaryPro",
"resource_type": 200,
"display_layout_id": "mi8",
"overlay_settings": [
{"settings_type": "secure", "settings_name": "navigationbar_switch", "settings_value": "on", "settings_value_type": "string"},
{"settings_type": "secure", "settings_name": "statusbar_switch", "settings_value": "on", "settings_value_type": "string"}
]
}
}
{
"VOLCENGINE_ACCESS_KEY": "",
"VOLCENGINE_SECRET_KEY": "",
"KDL_SECRET_ID": "",
"KDL_SIGNATURE": "",
"KDL_PROXY_USERNAME": "",
"KDL_PROXY_PASSWORD": ""
}
import io
import json
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from types import SimpleNamespace
from cloud_phone.app import load_tasks, run_batch
class BatchTests(unittest.TestCase):
def test_snapshot_requires_read_only_and_deduplicates_tasks(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "tasks.json"
task = {"user_id": "6a322d47000000000f03bc05", "red_id": "63067421961"}
path.write_text(json.dumps({"read_only": True, "tasks": [task, task]}))
self.assertEqual(load_tasks(path), [task])
path.write_text(json.dumps({"read_only": False, "tasks": [task]}))
with self.assertRaises(ValueError):
load_tasks(path)
def test_invalid_snapshot_is_rejected_before_running_phone(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "tasks.json"
path.write_text(json.dumps({"read_only": True, "tasks": [
{"user_id": "bad", "red_id": "123"}]}))
with self.assertRaises(ValueError):
load_tasks(path)
def test_login_required_stops_entire_batch_without_retry(self):
with tempfile.TemporaryDirectory() as directory:
calls = []
def execute(command, **kwargs):
calls.append(command)
kwargs["stdout"].write("接口要求登录,已停止采集\n")
return SimpleNamespace(returncode=1)
tasks = [{"user_id": "6a322d47000000000f03bc05", "red_id": str(i)} for i in (1, 2)]
with redirect_stdout(io.StringIO()):
state = run_batch(tasks, output=Path(directory)/"batch", product_id="business",
pod_id="phone", config="devices.json", execute=execute)
self.assertEqual(len(calls), 1)
self.assertEqual(state["stop_reason"], "login_required")
self.assertEqual(state["unattempted"], 1)
self.assertFalse(state["redis_connected"])
self.assertTrue(state["dry_run"])
def test_safety_restriction_stops_remaining_tasks(self):
with tempfile.TemporaryDirectory() as directory:
calls = []
def execute(command, **kwargs):
calls.append(command)
kwargs["stdout"].write("小红书显示安全限制,已停止采集\n")
return SimpleNamespace(returncode=1)
tasks = [{"user_id": "6a322d47000000000f03bc05", "red_id": str(i)} for i in (1, 2)]
with redirect_stdout(io.StringIO()):
state = run_batch(tasks, output=Path(directory) / "batch", product_id="business",
pod_id="phone", config="devices.json", execute=execute)
self.assertEqual(len(calls), 1)
self.assertEqual(state["stop_reason"], "safety_restriction")
self.assertEqual(state["unattempted"], 1)
self.assertFalse(state["finished"])
def test_success_counts_rows_and_moves_to_next_local_task(self):
with tempfile.TemporaryDirectory() as directory:
calls = []
def execute(command, **kwargs):
calls.append(command)
folder=Path(command[command.index("--output")+1])
(folder/"profile_test.json").write_text(json.dumps({"dry_run":True,
"pages_collected":1,"notes_collected":3,"report_preview_rows":6,
"collection":{"completion_reason":"no_more"}}))
return SimpleNamespace(returncode=0)
tasks = [{"user_id": "6a322d47000000000f03bc05", "red_id": str(i)} for i in (1, 2)]
with redirect_stdout(io.StringIO()):
state=run_batch(tasks, output=Path(directory)/"batch", product_id="business",
pod_id="phone", config="devices.json", execute=execute)
self.assertTrue(state["finished"])
self.assertEqual(state["succeeded"],2)
self.assertEqual(state["report_rows"],12)
self.assertEqual(state["notes"],6)
self.assertEqual(len(calls),2)
self.assertEqual(calls[0][calls[0].index("--max-pages")+1],"10")
self.assertEqual((Path(directory)/"batch"/"001-6a322d47000000000f03bc05"/"console.log").stat().st_mode & 0o777,0o600)
This diff is collapsed.
import io
import json
import unittest
from contextlib import redirect_stdout
from cloud_phone.app import print_posted_response
class FlushedConsole(io.StringIO):
def __init__(self):
super().__init__()
self.flushed = False
def flush(self):
self.flushed = True
super().flush()
class ConsoleResponseTests(unittest.TestCase):
def test_full_json_is_printed_without_logcat_truncation_or_header_leak(self):
payload = {"code": 0, "data": {"notes": [{"title": "完整中文笔记" * 6000}]}}
record = {"user_id": "6a322d47000000000f03bc05", "pid": 7, "status": 200,
"cursor": "", "captured_at_ms": 110, "response_json": payload,
"response_body": json.dumps(payload),
"url": "https://example.invalid/?session=private-session",
"final_url": "https://example.invalid/?signature=private-signature",
"request_headers": [["Authorization", "private-authorization"]],
"response_headers": [["Set-Cookie", "private-cookie"]]}
console = FlushedConsole()
with redirect_stdout(console):
print_posted_response("posted_new.json", record)
event = json.loads(console.getvalue())
self.assertEqual(event["path"], "/api/sns/v4/note/user/posted")
self.assertEqual(event["response_json"], payload)
self.assertIn("完整中文笔记", console.getvalue())
self.assertNotIn("private-", console.getvalue())
self.assertNotIn("response_body", event)
self.assertTrue(console.flushed)
def test_non_json_error_preserves_body_and_only_error_flags(self):
console = io.StringIO()
record = {"status": 502, "response_body": "<html>网关错误</html>",
"network_error": "Failed https://example.invalid/?session=private-session",
"capture_error": "private-error", "body_truncated": True}
with redirect_stdout(console):
print_posted_response("posted_error.json", record)
event = json.loads(console.getvalue())
self.assertEqual(event["response_body"], record["response_body"])
self.assertTrue(event["network_error"])
self.assertTrue(event["capture_error"])
self.assertTrue(event["body_truncated"])
self.assertNotIn("private-", console.getvalue())
if __name__ == "__main__":
unittest.main()
This diff is collapsed.
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from cloud_phone.app import CloudPhoneError
from cloud_phone.app import collect_pages
UID = "6a322d47000000000f03bc05"
ACK = {"request_id": "visit", "pid": 7, "started_at_ms": 100}
def page(index, more=True):
return (f"posted_{index}.json", {
"user_id": UID, "pid": 7, "captured_at_ms": 100 + index,
"cursor": "" if index == 1 else f"c{index - 1}", "status": 200,
"response_json": {"code": 0, "success": True, "data": {
"notes": [{"id": f"n{index}", "cursor": f"c{index}"}], "has_more": more}}})
class PaginationTests(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.device = MagicMock()
self.device.hook_pid.return_value = 7
self.emit = MagicMock()
self.received = MagicMock()
def collect(self, first, **kwargs):
return collect_pages(self.device, UID, ACK, first, output=self.folder.name,
on_response=self.received, on_page=self.emit, **kwargs)
def test_first_page_no_more_stops_without_swiping(self):
state = self.collect(page(1, False))
self.assertEqual(state["completion_reason"], "no_more")
self.assertEqual(len(state["pages"]), 1)
self.device.swipe_list.assert_not_called()
self.emit.assert_called_once()
def test_swipes_until_second_real_response_then_stops(self):
first, second = page(1), page(2, False)
self.device.read_records.side_effect = [[first], [first, second]]
with patch("cloud_phone.app.time.sleep"):
state = self.collect(first)
self.assertEqual(state["swipe_count"], 1)
self.assertEqual(len(state["pages"]), 2)
self.assertTrue(state["completed"])
self.received.assert_called_once_with(*second)
def test_ten_responses_include_first_page_and_do_not_consume_eleventh(self):
self.device.read_records.return_value = [page(i) for i in range(1, 12)]
state = self.collect(page(1))
self.assertEqual(state["completion_reason"], "max_pages")
self.assertEqual(len(state["pages"]), 10)
self.assertEqual(self.emit.call_count, 10)
self.device.swipe_list.assert_not_called()
def test_duplicate_cursor_does_not_count_as_another_page(self):
duplicate = page(2)
duplicate = ("posted_duplicate.json", duplicate[1])
self.device.read_records.return_value = [page(1), page(2), duplicate, page(3, False)]
state = self.collect(page(1))
self.assertEqual(len(state["pages"]), 3)
self.assertEqual(self.emit.call_count, 3)
def test_login_required_is_emitted_and_stops_before_more_gestures(self):
name, record = page(2)
record["response_json"] = {"code": -100, "msg": "请登录账号"}
self.device.read_records.return_value = [(name, record)]
with self.assertRaisesRegex(CloudPhoneError, "要求登录"):
self.collect(page(1))
self.received.assert_called_once_with(name, record)
self.device.swipe_list.assert_not_called()
saved = json.loads((Path(self.folder.name) / "collection_visit.json").read_text())
self.assertFalse(saved["completed"])
def test_new_visit_and_unrelated_cursor_are_rejected(self):
for cursor in ("", "wrong"):
with self.subTest(cursor=cursor):
name, record = page(2)
record["cursor"] = cursor
self.device.read_records.return_value = [(name, record)]
with self.assertRaises(CloudPhoneError):
self.collect(page(1))
self.device.swipe_list.assert_not_called()
def test_stale_or_other_users_do_not_emit_or_complete(self):
old = page(2)
old[1]["captured_at_ms"] = 99
other = page(2)
other[1]["user_id"] = "other"
self.device.read_records.return_value = [old, other]
with patch("cloud_phone.app.time.monotonic", side_effect=[0, 0, 2]):
with self.assertRaises(TimeoutError):
self.collect(page(1), idle_timeout=1)
self.received.assert_not_called()
self.device.swipe_list.assert_not_called()
def test_process_change_stops_without_swiping(self):
self.device.hook_pid.return_value = 8
with self.assertRaisesRegex(CloudPhoneError, "进程已变化"):
self.collect(page(1))
self.device.swipe_list.assert_not_called()
def test_missing_has_more_is_failure_not_no_more(self):
first = page(1)
del first[1]["response_json"]["data"]["has_more"]
with self.assertRaisesRegex(CloudPhoneError, "has_more"):
self.collect(first)
if __name__ == "__main__":
unittest.main()
This diff is collapsed.
import io
import json
import tempfile
import unittest
from collections import deque
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import MagicMock
from cloud_phone.app import CloudPhoneError
from cloud_phone.app import ProxyEndpoint
from cloud_phone.app import ProxyNetworkError, ProxySession, run_with_proxy
class Phone:
pod_id = "phone"
def __init__(self, events):
self.events = events
self.statuses = deque()
self.records = {"old": {}}
self.clear_result = "Success"
self.has_curl = True
def shell(self, command, **kwargs):
if command.startswith("command -v"):
return "/system/bin/curl" if self.has_curl else ""
if command.startswith("curl "):
self.events.append("probe")
result = self.statuses.popleft() if self.statuses else "204"
if isinstance(result, Exception):
raise result
return result
if command.startswith("pm clear"):
self.events.append("clear")
return self.clear_result
if command.startswith("am force-stop"):
self.events.append("stop")
elif command.startswith("am start"):
self.events.append("start")
return ""
class ProxySessionTests(unittest.TestCase):
def setUp(self):
self.events = []
self.phone = Phone(self.events)
self.client = MagicMock(product_id="business")
self.client.get_proxy.return_value = [{"ProxyStatus": 1}]
self.client.set_proxy.side_effect = lambda *a, **k: (
self.events.append("set") or {"Verified": True, "TaskId": "task"})
self.provider = MagicMock()
self.provider.acquire.side_effect = lambda **k: (
self.events.append("acquire") or ProxyEndpoint("proxy.example", 1234, "u", "private-password"))
self.now = 1000
self.mono = 0
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / "proxy.json"
self.session = self.make_session()
def make_session(self):
return ProxySession(client=self.client, device=self.phone, provider=self.provider,
state_path=self.path, clock=lambda: self.now, monotonic=lambda: self.mono)
def start(self, session, proxy, retries):
session.check()
self.phone.shell("am start -n example")
return retries
def run_session(self, operation=None):
with redirect_stdout(io.StringIO()):
return run_with_proxy(self.session, operation or self.start)
def advance(self, seconds):
self.now += seconds
self.mono += seconds
def test_first_launch_requires_platform_and_phone_network(self):
self.assertEqual(self.run_session(), 0)
self.assertEqual(self.events, ["stop", "acquire", "set", "probe", "start"])
state = json.loads(self.path.read_text())
self.assertEqual(state["expires_at"], 2800)
self.assertEqual(state["status"], "healthy")
self.assertNotIn("private-password", self.path.read_text())
self.assertEqual(self.path.stat().st_mode & 0o777, 0o600)
def test_bad_candidate_is_cleared_and_replaced_before_first_launch(self):
self.phone.statuses.extend(["000", "407", "204"])
self.assertEqual(self.run_session(), 1)
self.assertEqual(self.events, ["stop", "acquire", "set", "probe", "probe", "stop",
"stop", "clear", "acquire", "set", "probe", "start"])
self.assertEqual(self.phone.records, {})
def test_expiry_mid_operation_restarts_the_visit(self):
def operation(session, proxy, retries):
self.start(session, proxy, retries)
if retries == 0:
self.advance(1800)
session.check()
return retries
self.assertEqual(self.run_session(operation), 1)
self.assertEqual(self.events.count("start"), 2)
self.assertEqual(self.events.count("clear"), 1)
self.assertLess(self.events.index("clear"), self.events.index("acquire", 2))
def test_previous_expired_lease_is_reset_across_processes(self):
self.run_session()
self.events.clear()
self.advance(1801)
self.session = self.make_session()
self.run_session()
self.assertEqual(self.events[:3], ["stop", "clear", "acquire"])
def test_previous_live_proxy_failure_is_detected_before_replacement(self):
self.run_session()
self.events.clear()
self.phone.statuses.extend(["000", "000", "204"])
self.session = self.make_session()
self.run_session()
self.assertEqual(self.events[:5], ["stop", "probe", "probe", "clear", "acquire"])
def test_health_check_is_throttled_but_expiry_is_always_checked(self):
self.session.prepare()
self.events.clear()
self.advance(29)
self.session.check()
self.assertEqual(self.events, [])
self.advance(1)
self.session.check()
self.assertEqual(self.events, ["probe"])
self.advance(1770)
with self.assertRaisesRegex(ProxyNetworkError, "proxy_expired"):
self.session.check()
def test_adb_transport_failure_does_not_clear_data_or_retry(self):
self.phone.statuses.append(RuntimeError("private shell output"))
with self.assertRaisesRegex(CloudPhoneError, "ADB 可能断开") as error:
self.run_session()
self.assertNotIn("private", str(error.exception))
self.assertEqual(self.provider.acquire.call_count, 1)
self.assertNotIn("clear", self.events)
self.assertNotIn("start", self.events)
def test_interrupted_probe_with_recovered_adb_does_not_clear_next_run(self):
self.phone.statuses.append(RuntimeError("ADB unavailable"))
with self.assertRaises(CloudPhoneError):
self.run_session()
self.events.clear()
self.session = self.make_session()
self.run_session()
self.assertNotIn("clear", self.events)
self.assertEqual(self.events[-1], "start")
def test_login_required_does_not_trigger_proxy_recovery(self):
def operation(*args):
raise CloudPhoneError("接口要求登录")
with self.assertRaisesRegex(CloudPhoneError, "接口要求登录"):
self.run_session(operation)
self.assertEqual(self.provider.acquire.call_count, 1)
self.assertNotIn("clear", self.events)
def test_ui_timeout_on_working_network_does_not_clear(self):
def operation(*args):
raise TimeoutError("没有头像")
with self.assertRaisesRegex(TimeoutError, "没有头像"):
self.run_session(operation)
self.assertEqual(self.provider.acquire.call_count, 1)
self.assertNotIn("clear", self.events)
def test_timeout_with_confirmed_network_failure_recovers(self):
def operation(session, proxy, retries):
if retries == 0:
self.phone.statuses.extend(["000", "000"])
raise TimeoutError("等待响应")
return retries
self.assertEqual(self.run_session(operation), 1)
self.assertEqual(self.events.count("clear"), 1)
def test_pending_platform_task_timeout_is_not_resubmitted(self):
self.client.set_proxy.side_effect = TimeoutError("任务未完成")
with self.assertRaisesRegex(TimeoutError, "任务未完成"):
self.run_session()
self.assertEqual(self.client.set_proxy.call_count, 1)
self.assertNotIn("clear", self.events)
self.assertNotIn("start", self.events)
def test_clear_failure_prevents_acquiring_replacement(self):
self.session.state = {"status": "needs_reset"}
self.phone.clear_result = "Failed"
with self.assertRaisesRegex(CloudPhoneError, "清空小红书数据"):
self.run_session()
self.provider.acquire.assert_not_called()
def test_missing_probe_tool_prevents_acquire_and_launch(self):
self.phone.has_curl = False
with self.assertRaisesRegex(CloudPhoneError, "缺少 curl"):
self.run_session()
self.provider.acquire.assert_not_called()
self.assertNotIn("start", self.events)
def test_lease_expiring_during_platform_apply_is_not_used(self):
def apply(*args, **kwargs):
self.advance(1800)
return {"Verified": True}
self.client.set_proxy.side_effect = apply
with self.assertRaisesRegex(CloudPhoneError, "最多重新获取两次"):
self.run_session()
self.assertEqual(self.provider.acquire.call_count, 3)
self.assertNotIn("start", self.events)
def test_continuous_outage_stops_after_two_recoveries(self):
self.phone.statuses.extend(["000"] * 6)
with self.assertRaisesRegex(CloudPhoneError, "最多重新获取两次"):
self.run_session()
self.assertEqual(self.provider.acquire.call_count, 3)
self.assertNotIn("start", self.events)
self.assertEqual(json.loads(self.path.read_text())["status"], "needs_reset")
import io
import json
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import MagicMock, patch
from cloud_phone.app import CloudPhoneError
from cloud_phone.app import publish, verify_apps
def apk():
return {"path": "/local/test.apk", "file": "test.apk", "package": "example.capture",
"version_code": 2, "version": "2.0", "sha256": "abc", "md5": "1234",
"size": 10, "app_name": "capture", "app_type": 0, "parse_flag": 1}
def app(md5="1234"):
return {"AppId": "existing-app", "AppName": "capture", "PackageName": "example.capture",
"LatestVersion": {"MD5": md5, "VersionId": "v2",
"DownloadUrl": "https://imagestore.example/app.apk?secret=private"}}
class PublishApksTests(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.root = Path(self.folder.name)
self.client = MagicMock(product_id="business")
self.backup = patch("cloud_phone.app.backup_apk",
return_value=("private-key", "https://source.example?secret=private"))
self.backup_mock = self.backup.start()
self.addCleanup(self.backup.stop)
here = patch("cloud_phone.app.HERE", self.root)
here.start()
self.addCleanup(here.stop)
def run_publish(self):
return publish(self.client, MagicMock(), "bucket", [apk()],
release_path=self.root / "release.json")
def test_existing_matching_version_is_reused_without_platform_mutation_or_url_output(self):
self.client.all_rows.return_value = [app()]
with redirect_stdout(io.StringIO()) as console:
release = self.run_publish()
self.client.call.assert_not_called()
self.client.wait_task.assert_not_called()
self.backup_mock.assert_not_called()
self.assertEqual(release["apps"][0]["outcome"], "already_present")
self.assertTrue(release["apps"][0]["platform_download_copy"])
self.assertNotIn("secret=private", console.getvalue())
self.assertEqual((self.root / "release.json").stat().st_mode & 0o777, 0o600)
def test_console_upload_can_be_verified_without_tos_or_platform_mutation(self):
self.client.all_rows.return_value = [app()]
with redirect_stdout(io.StringIO()) as console:
release = verify_apps(self.client, [apk()], release_path=self.root / "release.json")
self.client.call.assert_not_called()
self.client.wait_task.assert_not_called()
self.backup_mock.assert_not_called()
self.assertEqual(release["apps"][0]["outcome"], "verified")
self.assertNotIn("secret=private", console.getvalue())
self.assertNotIn("source_url_expires_at", release["apps"][0])
def test_verify_mismatch_does_not_write_success_manifest(self):
self.client.all_rows.return_value = [app("wrong")]
with self.assertRaisesRegex(CloudPhoneError, "MD5"):
verify_apps(self.client, [apk()], release_path=self.root / "release.json")
self.client.call.assert_not_called()
self.assertFalse((self.root / "release.json").exists())
def test_pending_task_is_resumed_without_resubmitting_and_verified_before_release(self):
self.client.all_rows.side_effect = [[app("old")], [app()]]
pending = self.root / "run/apk_upload_business_abc.json"
pending.parent.mkdir()
pending.write_text(json.dumps({"task_id": "pending-task"}))
with redirect_stdout(io.StringIO()):
release = self.run_publish()
self.client.call.assert_not_called()
self.client.wait_task.assert_called_once_with("pending-task", timeout=900, interval=3)
self.assertEqual(release["apps"][0]["version_id"], "v2")
def test_new_version_task_is_saved_and_md5_mismatch_prevents_success_manifest(self):
self.client.all_rows.side_effect = [[app("old")], [app("wrong")]]
self.client.call.return_value = {"TaskId": "new-task"}
with redirect_stdout(io.StringIO()), self.assertRaisesRegex(CloudPhoneError, "MD5"):
self.run_publish()
options = self.client.call.call_args.kwargs
self.assertEqual(options["app_id"], "existing-app")
self.assertEqual(options["app_mode"], "Private")
pending = self.root / "run/apk_upload_business_abc.json"
self.assertEqual(json.loads(pending.read_text())["task_id"], "new-task")
self.assertEqual(pending.stat().st_mode & 0o777, 0o600)
self.assertFalse((self.root / "release.json").exists())
if __name__ == "__main__":
unittest.main()
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, call
from cloud_phone.app import read_connection, sample_set
class SnapshotTests(unittest.TestCase):
def test_only_read_commands_are_sent_and_insufficient_tasks_are_not_duplicated(self):
client = MagicMock()
client.type.return_value = "set"
client.scard.return_value = 1
client.srandmember.return_value = ["6a322d47000000000f03bc05:::63067421961"]
result = sample_set(client)
self.assertEqual(client.mock_calls, [call.type("xhs:keyword:package:us2"),
call.scard("xhs:keyword:package:us2"), call.srandmember("xhs:keyword:package:us2",100),
call.scard("xhs:keyword:package:us2")])
self.assertEqual(result["sampled"],1)
self.assertEqual(result["tasks"][0]["red_id"],"63067421961")
self.assertEqual(result["cardinality_before"],result["cardinality_after"])
def test_wrong_type_does_not_read_or_consume_members(self):
client = MagicMock()
client.type.return_value = "list"
with self.assertRaises(ValueError):
sample_set(client)
self.assertEqual(client.mock_calls,[call.type("xhs:keyword:package:us2")])
def test_connection_is_parsed_without_executing_source(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory)/"worker.py"
path.write_text("raise RuntimeError('must not run')\ncommon_redis0=Redis(host='example.com',db=0,password='test')\n")
config=read_connection(path)
self.assertEqual(config["host"],"example.com")
path.write_text("common_redis0=Redis(host=get_secret())\n")
with self.assertRaises(ValueError):
read_connection(path)
def test_invalid_entries_are_preserved_but_not_scheduled(self):
client=MagicMock()
client.type.return_value="set"
client.scard.return_value=1
client.srandmember.return_value=["broken"]
result=sample_set(client)
self.assertEqual(result["tasks"],[])
self.assertEqual(result["invalid"][0]["raw"],"broken")
import ast
import io
import json
import tempfile
import unittest
from contextlib import redirect_stdout
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
from zoneinfo import ZoneInfo
from cloud_phone.app import ReportPreview, TABLES, transform_note
def note():
return {"id": "note1", "user": {"userid": "author", "nickname": "达人"},
"title": "标题", "desc": "正文", "type": "video", "create_time": 1704038400,
"comments_count": 3, "share_count": 4, "collected_count": 5, "likes": 6,
"images_list": [{"url": "first"}, {"url": ""}, {"url": "last"}],
"video_info_v2": {"media": {"stream": {
"h264": [{"duration": 1234, "backup_urls": ["url"]}],
"h265": [{"duration": 5678, "backup_urls": ["url2"]}]}}}}
class ReportPreviewTests(unittest.TestCase):
def test_mapping_matches_the_reference_note_processing_block(self):
# 只执行参考文件的纯笔记转换块;不导入它,不创建 Redis/MySQL 客户端。
tree = ast.parse((Path(__file__).resolve().parents[2] / "http_lanjie_user.py").read_text())
loop = next(n for n in ast.walk(tree) if isinstance(n, ast.For)
and isinstance(n.target, ast.Name) and n.target.id == "note")
namespace = {"notes": [note()], "posted_dic_list": [], "posted_dic_list_v2": [],
"time": SimpleNamespace(time=lambda: 123),
"xxx": lambda t: datetime.fromtimestamp(t, ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d")}
exec(compile(ast.Module(body=[loop], type_ignores=[]), "reference_conversion", "exec"), namespace)
actual = transform_note(note(), now=123)
self.assertEqual(actual, (namespace["posted_dic_list"][0], namespace["posted_dic_list_v2"][0]))
self.assertEqual(actual[0]["cover"], "last")
self.assertEqual(actual[0]["duration"], 5678)
self.assertEqual(actual[0]["pt"], "20240101")
def test_normal_note_and_missing_fields_do_not_reuse_previous_values(self):
transform_note(note())
empty = {**note(), "images_list": [], "video_info_v2": {}, "type": "normal",
"title": None, "desc": None}
row, v2 = transform_note(empty)
self.assertEqual((row["cover"], row["duration"], row["video_desc"]), ("", 0, ""))
self.assertEqual(v2["video_id"], "author1704038400")
self.assertEqual(v2["video_id_tag"], "note1")
def test_rows_are_printed_for_both_tables_and_deduplicated_across_pages(self):
with tempfile.TemporaryDirectory() as folder, redirect_stdout(io.StringIO()) as console:
path = Path(folder) / "report.jsonl"
preview = ReportPreview(path)
record = {"user_id": "author", "request_headers": {"secret": "never print"},
"response_json": {"data": {"notes": [note()]}}}
preview.page("first.json", record, 1)
preview.page("second.json", record, 2)
events = [json.loads(line) for line in console.getvalue().splitlines()]
self.assertEqual([e["table"] for e in events], list(TABLES))
self.assertTrue(all(e["dry_run"] for e in events))
self.assertEqual(path.read_text(), console.getvalue())
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
self.assertNotIn("never print", console.getvalue())
self.assertEqual(preview.rows, 2)
def test_invalid_identity_or_timestamp_is_rejected(self):
for changes in [{"id": None}, {"user": {}}, {"create_time": None}]:
with self.subTest(changes=changes), self.assertRaises(ValueError):
transform_note({**note(), **changes})
if __name__ == "__main__":
unittest.main()
import unittest
import xml.etree.ElementTree as ET
from unittest.mock import MagicMock
from cloud_phone.app import valid_page
from cloud_phone.app import run_with_proxy
from cloud_phone.app import (SafetyRestrictionError,
check_response_restriction, check_ui_restriction)
class RestrictionTests(unittest.TestCase):
def test_error_message_precedes_network_recovery(self):
for field in ("msg", "message", "error_msg", "error_message"):
with self.subTest(field=field), self.assertRaises(SafetyRestrictionError):
valid_page({"network_error": True, "status": 407,
"response_json": {field: "当前访问受到安全限制"}})
def test_note_content_is_not_treated_as_a_restriction(self):
check_response_restriction({"code": 0, "data": {"notes": [
{"title": "安全限制", "desc": "当前访问受到安全限制"}]}})
def test_visible_title_is_detected_but_hidden_other_app_and_input_are_ignored(self):
template = '<hierarchy><node package="{package}" class="{cls}" text="安全限制" visible-to-user="{visible}" /></hierarchy>'
for package, cls, visible in (
("com.xingin.xhs", "android.widget.TextView", "false"),
("another.app", "android.widget.TextView", "true"),
("com.xingin.xhs", "android.widget.EditText", "true"),
):
check_ui_restriction(ET.fromstring(template.format(package=package, cls=cls, visible=visible)))
with self.assertRaises(SafetyRestrictionError):
check_ui_restriction(ET.fromstring(template.format(
package="com.xingin.xhs", cls="android.widget.TextView", visible="true")))
def test_restriction_does_not_invalidate_or_replace_proxy(self):
session = MagicMock()
operation = MagicMock(side_effect=SafetyRestrictionError("ui"))
with self.assertRaises(SafetyRestrictionError):
run_with_proxy(session, operation)
session.prepare.assert_called_once()
operation.assert_called_once()
session.invalidate.assert_not_called()
if __name__ == "__main__":
unittest.main()
This diff is collapsed.
.gradle/
**/build/
local.properties
captures/
__pycache__/
This diff is collapsed.
plugins {
id 'com.android.application'
}
android {
namespace 'com.autoxhs.userposted'
compileSdk 35
defaultConfig {
applicationId 'com.autoxhs.userposted'
minSdk 27
targetSdk 35
versionCode 1
versionName '1.0.0'
}
buildTypes {
release {
minifyEnabled false
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
}
dependencies {
// Provided by LSPosed; never include the Xposed API or a second OkHttp in the APK.
compileOnly files('libs/api-82.jar')
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="false"
android:label="XHS 达人笔记采集"
android:supportsRtl="true">
<meta-data android:name="xposedmodule" android:value="true" />
<meta-data android:name="xposeddescription"
android:value="采集小红书达人主页 posted 接口的请求和响应 JSON" />
<meta-data android:name="xposedminversion" android:value="82" />
<meta-data android:name="xposedscope" android:resource="@array/xposed_scope" />
</application>
</manifest>
com.autoxhs.userposted.UserPostedHook
package com.autoxhs.userposted;
import android.os.Process;
import android.util.Log;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** Serial, bounded disk writer; no file I/O in the HTTP interceptor. */
final class CaptureWriter {
private final File directory;
private final AtomicLong sequence = new AtomicLong();
private final ThreadPoolExecutor executor;
CaptureWriter(File filesDirectory) {
directory = new File(filesDirectory, "xhs_user_posted");
executor = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(8), task -> {
Thread thread = new Thread(task, "xhs-posted-writer");
thread.setDaemon(true);
return thread;
}, (task, pool) -> Log.e(UserPostedHook.TAG, "Capture queue full; record dropped"));
executor.allowCoreThreadTimeOut(true);
}
File directory() {
return directory;
}
void controlResult(String filename, JSONObject record) {
executor.execute(() -> {
try {
writeAtomic(new File(directory, filename), record.toString(2));
} catch (Exception exception) {
UserPostedHook.report("control result write failed", exception);
}
});
}
void status(String state, String error) {
executor.execute(() -> {
try {
JSONObject status = new JSONObject();
status.put("state", state);
status.put("pid", Process.myPid());
status.put("updated_at_ms", System.currentTimeMillis());
status.put("endpoint", UserPostedHook.TARGET_PATH);
if (error != null) {
status.put("error", error);
}
writeAtomic(new File(directory, "status.json"), status.toString(2));
} catch (Exception exception) {
UserPostedHook.report("status write failed", exception);
}
});
}
void submit(JSONObject record) {
String filename = "posted_" + System.currentTimeMillis() + "_"
+ Process.myPid() + "_" + sequence.incrementAndGet() + ".json";
executor.execute(() -> {
try {
writeAtomic(new File(directory, filename), record.toString(2));
JSONObject json = record.optJSONObject("response_json");
JSONObject data = json == null ? null : json.optJSONObject("data");
int notes = data == null || data.optJSONArray("notes") == null
? 0 : data.optJSONArray("notes").length();
Log.i(UserPostedHook.TAG, "Saved " + filename
+ " user_id=" + record.optString("user_id")
+ " status=" + record.optInt("status") + " notes=" + notes);
} catch (Exception exception) {
UserPostedHook.report("capture write failed", exception);
}
});
}
private void writeAtomic(File destination, String text) throws IOException {
if (!directory.isDirectory() && !directory.mkdirs()) {
throw new IOException("Cannot create " + directory);
}
File temporary = new File(directory, destination.getName() + ".tmp");
try (FileOutputStream stream = new FileOutputStream(temporary)) {
stream.write(text.getBytes(StandardCharsets.UTF_8));
stream.flush();
stream.getFD().sync();
}
if (!temporary.renameTo(destination)) {
throw new IOException("Cannot rename " + temporary + " to " + destination);
}
}
}
package com.autoxhs.userposted;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Process;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicBoolean;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/** LSPosed legacy API entry point. Runs inside the target app's main process. */
public final class UserPostedHook implements IXposedHookLoadPackage {
static final String TAG = "XhsUserPosted";
static final String TARGET_PACKAGE = "com.xingin.xhs";
static final String TARGET_PATH = "/api/sns/v4/note/user/posted";
static final long MAX_BODY_BYTES = 5L * 1024 * 1024;
private static final String FRAME_KEY = TAG + ".frame";
private static final AtomicBoolean INSTALLED = new AtomicBoolean();
private static final ThreadLocal<Integer> DEPTH = new ThreadLocal<>();
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam pkg) {
if (!TARGET_PACKAGE.equals(pkg.packageName)
|| !TARGET_PACKAGE.equals(pkg.processName)) {
return;
}
XposedHelpers.findAndHookMethod(Application.class, "attach", Context.class,
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) {
Context context = (Context) param.args[0];
install((Application) param.thisObject, context.getClassLoader());
}
});
}
private static void install(Application context, ClassLoader loader) {
if (!INSTALLED.compareAndSet(false, true)) {
return;
}
try {
CaptureWriter writer = new CaptureWriter(context.getFilesDir());
try {
ProfileLauncher.install(context, writer);
} catch (Throwable error) {
report("profile launcher installation failed", error);
}
Class<?> chain = XposedHelpers.findClass(
"okhttp3.internal.http.RealInterceptorChain", loader);
Class<?> request = XposedHelpers.findClass("okhttp3.Request", loader);
// Hook only the single-argument overload. Its nested interceptor calls
// unwind to the outer response after OkHttp's gzip decompression.
XposedHelpers.findAndHookMethod(chain, "proceed", request, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) {
try {
String url = String.valueOf(call(param.args[0], "url"));
if (!matches(url)) {
return;
}
Integer depth = DEPTH.get();
int previous = depth == null ? 0 : depth;
Frame frame = new Frame(previous, System.nanoTime());
if (previous == 0) {
frame.record = requestRecord(param.args[0], url);
}
param.setObjectExtra(FRAME_KEY, frame);
DEPTH.set(previous + 1);
} catch (Throwable error) {
report("request inspection failed", error);
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) {
Frame frame = (Frame) param.getObjectExtra(FRAME_KEY);
if (frame == null) {
return;
}
if (frame.previousDepth == 0) {
DEPTH.remove();
} else {
DEPTH.set(frame.previousDepth);
return;
}
// Observe the original result/exception; never replace either.
try {
JSONObject record = frame.record;
record.put("duration_ms", (System.nanoTime() - frame.startedNs) / 1_000_000);
if (param.hasThrowable()) {
record.put("network_error", param.getThrowable().toString());
} else if (param.getResult() != null) {
captureResponse(record, param.getResult());
}
writer.submit(record);
} catch (Throwable error) {
report("response inspection failed", error);
}
}
});
Log.i(TAG, "Hook ready pid=" + Process.myPid() + " output=" + writer.directory());
writer.status("ready", null);
} catch (Throwable error) {
INSTALLED.set(false);
report("hook installation failed", error);
}
}
static boolean matches(String url) {
Uri uri = Uri.parse(url);
String host = uri.getHost();
return host != null
&& (host.equals("xiaohongshu.com") || host.endsWith(".xiaohongshu.com"))
&& TARGET_PATH.equals(uri.getPath());
}
private static JSONObject requestRecord(Object request, String url) throws Exception {
Uri uri = Uri.parse(url);
JSONObject query = new JSONObject();
for (String name : uri.getQueryParameterNames()) {
query.put(name, new JSONArray(uri.getQueryParameters(name)));
}
JSONObject record = new JSONObject();
record.put("schema_version", 1);
record.put("captured_at_ms", System.currentTimeMillis());
record.put("pid", Process.myPid());
record.put("url", url);
record.put("method", String.valueOf(call(request, "method")));
record.put("user_id", uri.getQueryParameter("user_id"));
record.put("cursor", uri.getQueryParameter("cursor"));
record.put("query", query);
record.put("request_headers", headers(call(request, "headers")));
return record;
}
private static void captureResponse(JSONObject record, Object response) throws Exception {
record.put("status", call(response, "code"));
record.put("response_headers", headers(call(response, "headers")));
Object finalRequest = call(response, "request");
record.put("final_url", String.valueOf(call(finalRequest, "url")));
record.put("request_headers", headers(call(finalRequest, "headers")));
Object body = call(response, "body");
if (body == null) {
record.put("response_body", JSONObject.NULL);
return;
}
try {
// peekBody copies bytes without consuming or rebuilding the app's body.
Object peek = call(response, "peekBody", MAX_BODY_BYTES + 1);
long length = ((Number) call(peek, "contentLength")).longValue();
record.put("body_limit_bytes", MAX_BODY_BYTES);
if (length > MAX_BODY_BYTES) {
record.put("body_truncated", true);
record.put("capture_error", "Response exceeds the 5 MiB capture limit; body skipped");
call(peek, "close");
return;
}
String text = String.valueOf(call(peek, "string"));
record.put("body_truncated", false);
record.put("response_body", text);
try {
record.put("response_json", new JSONObject(text));
} catch (Exception ignored) {
// Preserve non-JSON server errors in response_body as well.
}
} catch (Throwable error) {
record.put("capture_error", error.toString());
report("body peek failed", error);
}
}
private static JSONArray headers(Object headers) throws Exception {
JSONArray entries = new JSONArray();
int size = ((Number) call(headers, "size")).intValue();
for (int i = 0; i < size; i++) {
JSONArray pair = new JSONArray();
pair.put(String.valueOf(call(headers, "name", i)));
pair.put(String.valueOf(call(headers, "value", i)));
entries.put(pair);
}
return entries;
}
private static Object call(Object target, String method, Object... arguments) {
return XposedHelpers.callMethod(target, method, arguments);
}
static void report(String message, Throwable error) {
Log.e(TAG, message, error);
XposedBridge.log(TAG + ": " + message + ": " + error);
}
private static final class Frame {
final int previousDepth;
final long startedNs;
JSONObject record;
Frame(int previousDepth, long startedNs) {
this.previousDepth = previousDepth;
this.startedNs = startedNs;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="xposed_scope">
<item>com.xingin.xhs</item>
</string-array>
</resources>
plugins {
id 'com.android.application' version '8.7.3' apply false
}
This diff is collapsed.
#!/usr/bin/env python3
"""Export LSPosed captures over the existing ADB server; use conda's xhs env."""
import argparse
import json
import os
import shlex
from pathlib import Path
REMOTE_DIRECTORY = "/data/user/0/com.xingin.xhs/files/xhs_user_posted"
def summary(record):
payload = record.get("response_json") or {}
if not isinstance(payload, dict):
payload = {}
data = payload.get("data") or {}
if not isinstance(data, dict):
data = {}
notes = data.get("notes")
return {
"user_id": record.get("user_id"),
"status": record.get("status"),
"code": payload.get("code"),
"notes": len(notes) if isinstance(notes, list) else 0,
"has_more": data.get("has_more"),
"cursor": record.get("cursor"),
"capture_error": record.get("capture_error"),
"network_error": record.get("network_error"),
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--serial", help="ADB device serial; auto-select when only one is online")
parser.add_argument("--adb-host", default=os.environ.get("XHS_ADB_SERVER_HOST", "127.0.0.1"))
parser.add_argument("--adb-port", type=int,
default=int(os.environ.get("XHS_ADB_SERVER_PORT", "5037")))
parser.add_argument("--output", type=Path, default=Path(__file__).parent / "captures")
parser.add_argument("--user-id", help="Export only captures for this user_id")
args = parser.parse_args()
import adbutils
client = adbutils.AdbClient(host=args.adb_host, port=args.adb_port, socket_timeout=15)
device = client.device(serial=args.serial)
def root_shell(command):
result = device.shell2(["su", "-c", command], timeout=15)
if result.returncode != 0:
raise RuntimeError(result.output.strip())
return result.output
status = root_shell("cat " + shlex.quote(REMOTE_DIRECTORY + "/status.json"))
print("Hook status:", json.dumps(json.loads(status), ensure_ascii=False))
names = root_shell("ls -1 " + shlex.quote(REMOTE_DIRECTORY)).splitlines()
args.output.mkdir(parents=True, exist_ok=True)
count = 0
for name in sorted(names):
if not name.startswith("posted_") or not name.endswith(".json") or "/" in name:
continue
text = root_shell("cat " + shlex.quote(REMOTE_DIRECTORY + "/" + name))
record = json.loads(text)
if args.user_id and record.get("user_id") != args.user_id:
continue
destination = args.output / name
destination.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
destination.chmod(0o600)
count += 1
print(name, json.dumps(summary(record), ensure_ascii=False))
print(f"Exported {count} captures to {args.output.resolve()}")
if __name__ == "__main__":
try:
main()
except Exception as error:
raise SystemExit(f"Export failed: {error}") from error
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=false
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
#!/usr/bin/env python3
"""Open a profile through LSPosed via ADB, optionally collect up to ten responses."""
import argparse
import json
import os
import re
import shlex
import time
import uuid
from pathlib import Path
try:
from .collect_profile import AdbProfileDevice, collect_current_profile, write_private_json
from .export_captures import REMOTE_DIRECTORY
except ImportError:
from collect_profile import AdbProfileDevice, collect_current_profile, write_private_json
from export_captures import REMOTE_DIRECTORY
ACTION = "com.autoxhs.userposted.OPEN_PROFILE"
PACKAGE = "com.xingin.xhs"
LAUNCHER = PACKAGE + "/.index.v2.IndexActivityV2"
def read_control(device, name):
path = shlex.quote(REMOTE_DIRECTORY + "/" + name)
text = device.shell(f"if [ -f {path} ]; then cat {path}; fi", root=True)
return json.loads(text) if text.strip() else None
def open_profile(device, user_id, timeout=30, *, require_guest=False):
"""Return a correlated resume acknowledgement with the phone's start time.
Loading is verified separately by a fresh posted response in --collect mode.
"""
if not re.fullmatch(r"[0-9a-f]{24}", user_id):
raise ValueError("Expected a 24-character lowercase user_id; red_id is not supported")
if timeout <= 0:
raise ValueError("timeout must be positive")
activities = device.shell("dumpsys activity activities")
foreground = [line for line in activities.splitlines() if "ResumedActivity:" in line]
if not any(PACKAGE + "/" in line for line in foreground):
device.shell("am start -n " + LAUNCHER, root=True)
deadline = time.monotonic() + timeout
while True:
try:
pid = device.hook_pid()
except (RuntimeError, ValueError):
pid = None
ready = read_control(device, "launcher_status.json")
if (pid is not None and ready and ready.get("pid") == pid
and ready.get("state") == "ready" and ready.get("action") == ACTION
and ready.get("close_old_profiles_before_open") is True
and (not require_guest or ready.get("supports_guest_check") is True)):
break
if time.monotonic() >= deadline:
raise TimeoutError("Profile Hook not ready; enable the updated module and restart XHS")
time.sleep(.25)
request_id = uuid.uuid4().hex
command = (f"am broadcast -a {ACTION} -p {PACKAGE}"
f" --es user_id {shlex.quote(user_id)} --es request_id {request_id}")
if require_guest:
command += " --ez require_guest true"
device.shell(command, root=True)
while True:
ack = read_control(device, "launch_" + request_id + ".json")
if ack:
if (ack.get("request_id") != request_id or ack.get("pid") != pid
or ack.get("user_id") != user_id):
raise RuntimeError("Profile acknowledgement does not match this command")
if ack.get("state") == "error":
raise RuntimeError(ack.get("error", "Profile launch failed"))
if ack.get("state") == "resumed":
if require_guest and ack.get("is_logged_in") is not False:
raise RuntimeError("Guest profile acknowledgement did not confirm logged-out state")
if ack.get("actual_user_id") != user_id or not ack.get("started_at_ms"):
raise RuntimeError("Profile did not initialize the requested user_id")
if (ack.get("closed_old_profile_count") != ack.get("old_profile_count")
or not ack.get("old_profiles_closed_at_ms")
or ack["old_profiles_closed_at_ms"] > ack["started_at_ms"]):
raise RuntimeError("Old profiles were not closed before opening the new profile")
if device.hook_pid() != pid:
raise RuntimeError("App process changed during launch")
device.ensure_profile()
return ack
if time.monotonic() >= deadline:
raise TimeoutError("No matching profile resume acknowledgement within the timeout")
time.sleep(.25)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--user-id", required=True, help="24-character internal user_id, not red_id")
parser.add_argument("--serial")
parser.add_argument("--adb-host", default=os.environ.get("XHS_ADB_SERVER_HOST", "127.0.0.1"))
parser.add_argument("--adb-port", type=int, default=int(os.environ.get("XHS_ADB_SERVER_PORT", "5037")))
parser.add_argument("--timeout", type=float, default=30)
parser.add_argument("--collect", action="store_true", help="Collect fresh posted responses after opening")
parser.add_argument("--red-id", help="Optionally verify the visible profile number")
parser.add_argument("--output", type=Path, default=Path(__file__).parent / "captures")
parser.add_argument("--idle-timeout", type=float, default=60)
parser.add_argument("--total-timeout", type=float, default=300)
args = parser.parse_args()
device = AdbProfileDevice(args.serial, args.adb_host, args.adb_port)
ack = open_profile(device, args.user_id, args.timeout)
write_private_json(args.output / ("launch_" + ack["request_id"] + ".json"), ack)
print(json.dumps(ack, ensure_ascii=False), flush=True)
if args.collect:
state = collect_current_profile(
device, args.user_id, red_id=args.red_id, output=args.output,
since_ms=ack["started_at_ms"], idle_timeout=args.idle_timeout,
total_timeout=args.total_timeout)
print(json.dumps(state, ensure_ascii=False), flush=True)
if __name__ == "__main__":
try:
main()
except Exception as error:
raise SystemExit(f"Open profile failed: {error}") from error
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = 'XhsUserPostedHook'
include ':app'
"""Verify request limits, end-of-list handling, and ADB driver stopping."""
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from collect_profile import CollectionProgress, collect_current_profile, select_visit
def response(index, has_more=True, user_id="user-1", pid=123, cursor=None):
data = {"notes": [{"id": f"note-{index}"}]}
if has_more is not None:
data["has_more"] = has_more
return f"posted_{index}_{pid}_{index}.json", {
"user_id": user_id, "pid": pid, "captured_at_ms": index,
"cursor": ("" if index == 1 else str(index - 1)) if cursor is None else cursor,
"status": 200, "response_json": {"code": 0, "data": data},
}
class FakeDevice:
serial = "test-device"
def __init__(self, batches):
self.batches = iter(batches)
self.current = []
self.swipes = 0
def ensure_profile(self):
pass
def verify_red_id(self, red_id):
pass
def hook_pid(self):
return 123
def read_records(self, pid):
self.current = next(self.batches, self.current)
return self.current
def swipe_list(self):
self.swipes += 1
class CollectionTests(unittest.TestCase):
def test_no_more_counts_as_ten_and_preserves_actual_count(self):
state = CollectionProgress("user-1")
state.consume([response(1), response(2, False)])
self.assertTrue(state.completed)
self.assertEqual(state.actual_fetch_count, 2)
self.assertEqual(state.completed_fetch_count, 10)
self.assertEqual(state.completion_reason, "no_more")
def test_first_page_empty_and_no_more_also_finishes(self):
name, record = response(1, False)
record["response_json"]["data"]["notes"] = []
state = CollectionProgress("user-1")
state.consume([(name, record)])
self.assertEqual(state.completed_fetch_count, 10)
self.assertEqual(state.actual_fetch_count, 1)
def test_ten_request_limit_ignores_later_records(self):
state = CollectionProgress("user-1")
state.consume([response(i) for i in range(1, 13)])
state.consume([response(13)])
self.assertEqual(state.actual_fetch_count, 10)
self.assertEqual(len(state.capture_files), 10)
self.assertEqual(state.completion_reason, "request_limit")
def test_duplicate_other_user_and_errors_do_not_advance_count(self):
state = CollectionProgress("user-1")
error_name, error = response(2, False)
error["status"] = 403
malformed_name, malformed = response(3, False)
malformed["response_json"]["data"] = None
state.consume([response(1), response(1), response(4, False, user_id="other"),
(error_name, error), (malformed_name, malformed)])
self.assertFalse(state.completed)
self.assertEqual(state.actual_fetch_count, 1)
self.assertEqual(state.failed_request_count, 2)
def test_missing_flag_and_empty_page_do_not_assume_no_more(self):
name, record = response(1, None)
record["response_json"]["data"]["notes"] = []
state = CollectionProgress("user-1")
state.consume([(name, record)])
self.assertFalse(state.completed)
self.assertEqual(state.completed_fetch_count, 1)
def test_old_visit_process_and_before_since_are_excluded(self):
records = [response(1, False), response(2), response(3, cursor=""), response(4),
response(5, pid=456, cursor=""), response(6, user_id="other", cursor="")]
visit = select_visit(records, "user-1", 123)
self.assertEqual([r[1]["captured_at_ms"] for r in visit], [3, 4])
self.assertEqual(select_visit(records, "user-1", 123, since_ms=4), [])
def test_driver_stops_swiping_after_no_more_response(self):
device = FakeDevice([[response(1)], [response(1), response(2, False)]])
with tempfile.TemporaryDirectory() as temporary, patch("collect_profile.time.sleep"):
state = collect_current_profile(device, "user-1", output=temporary)
self.assertEqual(device.swipes, 1)
self.assertEqual(state["completed_fetch_count"], 10)
self.assertEqual(len(list(Path(temporary).glob("posted_*.json"))), 2)
def test_no_more_on_initial_page_does_not_swipe(self):
device = FakeDevice([[response(1, False)]])
with tempfile.TemporaryDirectory() as temporary:
state = collect_current_profile(device, "user-1", output=temporary)
self.assertEqual(device.swipes, 0)
self.assertEqual(state["completed_fetch_count"], 10)
def test_driver_stops_at_ten_successful_requests(self):
records = [response(i) for i in range(1, 12)]
device = FakeDevice([records[:i] for i in range(1, 12)])
with tempfile.TemporaryDirectory() as temporary, patch("collect_profile.time.sleep"):
state = collect_current_profile(device, "user-1", output=temporary)
self.assertEqual(device.swipes, 9)
self.assertEqual(state["actual_fetch_count"], 10)
def test_timeout_keeps_collection_incomplete(self):
device = FakeDevice([[]])
with tempfile.TemporaryDirectory() as temporary, patch("collect_profile.time.monotonic", side_effect=[0, 61]):
with self.assertRaises(TimeoutError):
collect_current_profile(device, "user-1", output=temporary)
state = json.loads(next(Path(temporary).glob("collection_*.json")).read_text())
self.assertFalse(state["completed"])
self.assertEqual(state["completed_fetch_count"], 0)
if __name__ == "__main__":
unittest.main()
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment