@chainlesschain/personal-data-hub 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +432 -0
- package/__tests__/adapters/social-kuaishou-adb-collector.test.js +276 -0
- package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +141 -0
- package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +178 -0
- package/__tests__/adapters/social-toutiao-adb-api-client.test.js +537 -0
- package/__tests__/adapters/social-toutiao-adb-collector.test.js +285 -0
- package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +163 -0
- package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +196 -0
- package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +351 -0
- package/lib/adapters/social-kuaishou-adb/api-client.js +397 -0
- package/lib/adapters/social-kuaishou-adb/collector.js +196 -0
- package/lib/adapters/social-kuaishou-adb/cookies-extension.js +261 -0
- package/lib/adapters/social-kuaishou-adb/index.js +53 -0
- package/lib/adapters/social-kuaishou-adb/snapshot-builder.js +145 -0
- package/lib/adapters/social-toutiao-adb/api-client.js +377 -0
- package/lib/adapters/social-toutiao-adb/collector.js +200 -0
- package/lib/adapters/social-toutiao-adb/cookies-extension.js +266 -0
- package/lib/adapters/social-toutiao-adb/index.js +52 -0
- package/lib/adapters/social-toutiao-adb/snapshot-builder.js +148 -0
- package/lib/adapters/social-xiaohongshu-adb/api-client.js +36 -5
- package/lib/adapters/social-xiaohongshu-adb/collector.js +102 -51
- package/package.json +5 -1
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Phase 6d (Kuaishou C 路径 — 2026-05-25): Node-side KuaishouApiClient.
|
|
5
|
+
*
|
|
6
|
+
* Byte-parity port of KuaishouApiClient.kt. **Profile from cookie (no
|
|
7
|
+
* HTTP) + 3 GraphQL POST endpoints (all signed)**:
|
|
8
|
+
* - `kuaishou.web.cp.api_ph` cookie payload → ProfileInfo (parseProfileFromCookie)
|
|
9
|
+
* - `/graphql` visionFeedRecommend — watch history (signed)
|
|
10
|
+
* - `/graphql` visionProfilePhotoList — user's posted photos (signed)
|
|
11
|
+
* - `/graphql` visionSearchPhoto — search history (signed)
|
|
12
|
+
*
|
|
13
|
+
* **signProvider injection (Phase 6d)**: defaults to NULL_SIGN_PROVIDER —
|
|
14
|
+
* signUrl returns null, so the 3 signed endpoints short-circuit with
|
|
15
|
+
* lastErrorCode=-99. Desktop wiring injects KuaishouSignBridge.
|
|
16
|
+
*
|
|
17
|
+
* **GraphQL nuances**:
|
|
18
|
+
* - POST `/graphql` with body `{operationName, variables, query}`
|
|
19
|
+
* - Body MUST match exactly what was signed (NS_sig3 hashes body bytes)
|
|
20
|
+
* - signedHeaders returns kpf/kpn that must be sent verbatim
|
|
21
|
+
*
|
|
22
|
+
* **Anti-bot signal**: User-Agent must be desktop Chrome 120+. Referer +
|
|
23
|
+
* Origin = https://www.kuaishou.com/. Without `kpf`/`kpn` headers
|
|
24
|
+
* GraphQL endpoint returns 403/Errors.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const { NULL_SIGN_PROVIDER } = require("../../sign-providers");
|
|
28
|
+
|
|
29
|
+
const DEFAULT_BASE_URL = "https://www.kuaishou.com/";
|
|
30
|
+
|
|
31
|
+
const BROWSER_UA =
|
|
32
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
|
|
33
|
+
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
|
34
|
+
|
|
35
|
+
const BROWSER_HEADERS = Object.freeze({
|
|
36
|
+
"User-Agent": BROWSER_UA,
|
|
37
|
+
Referer: "https://www.kuaishou.com/",
|
|
38
|
+
Origin: "https://www.kuaishou.com",
|
|
39
|
+
Accept: "application/json, text/plain, */*",
|
|
40
|
+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
|
41
|
+
"Content-Type": "application/json",
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const OP_FEED_RECOMMEND = "visionFeedRecommend";
|
|
45
|
+
const OP_PROFILE_PHOTOS = "visionProfilePhotoList";
|
|
46
|
+
const OP_SEARCH_PHOTO = "visionSearchPhoto";
|
|
47
|
+
|
|
48
|
+
function normalizeMs(v) {
|
|
49
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v <= 0) return 0;
|
|
50
|
+
return v > 1e12 ? v : v * 1000;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
class KuaishouApiClient {
|
|
54
|
+
constructor(opts = {}) {
|
|
55
|
+
this.baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
|
|
56
|
+
if (!this.baseUrl.endsWith("/")) this.baseUrl += "/";
|
|
57
|
+
this._fetch = opts.fetch || globalThis.fetch;
|
|
58
|
+
if (typeof this._fetch !== "function") {
|
|
59
|
+
throw new Error(
|
|
60
|
+
"KuaishouApiClient: fetch not available — pass opts.fetch or run on Node 18+",
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
this._now = opts.now || Date.now;
|
|
64
|
+
this.signProvider = opts.signProvider || NULL_SIGN_PROVIDER;
|
|
65
|
+
this.lastErrorCode = 0;
|
|
66
|
+
this.lastErrorMessage = null;
|
|
67
|
+
this._bridgeHits = 0;
|
|
68
|
+
this._fallbackHits = 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Extract uid from cookie. Mirror of Kotlin extractUid:
|
|
73
|
+
* 1. `userId=N` direct cookie
|
|
74
|
+
* 2. Nested user_id / uid / userId inside `kuaishou.web.cp.api_ph`
|
|
75
|
+
* URL-encoded JSON
|
|
76
|
+
*/
|
|
77
|
+
extractUid(cookie) {
|
|
78
|
+
if (typeof cookie !== "string" || cookie.length === 0) {
|
|
79
|
+
this._setLastError(-1, "cookie 为空");
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
const direct = /(?:^|; ?)userId=(\d+)/.exec(cookie);
|
|
83
|
+
if (direct && direct[1] && direct[1] !== "0") {
|
|
84
|
+
this._clearLastError();
|
|
85
|
+
return direct[1];
|
|
86
|
+
}
|
|
87
|
+
const cpMatch = /(?:^|; ?)kuaishou\.web\.cp\.api_ph=([^;]+)/.exec(cookie);
|
|
88
|
+
if (cpMatch && cpMatch[1]) {
|
|
89
|
+
const embedded = extractEmbeddedUid(cpMatch[1]);
|
|
90
|
+
if (embedded) {
|
|
91
|
+
this._clearLastError();
|
|
92
|
+
return embedded;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
this._setLastError(
|
|
96
|
+
-7,
|
|
97
|
+
"cookie 缺 userId / kuaishou.web.cp.api_ph 嵌套 user_id — 登录未完成或仅游客态",
|
|
98
|
+
);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Parse profile from cookie's `kuaishou.web.cp.api_ph` URL-encoded JSON.
|
|
104
|
+
* NO HTTP — this is purely cookie-derived (Kuaishou's passport writes
|
|
105
|
+
* the full profile JSON into the cookie at login time).
|
|
106
|
+
*
|
|
107
|
+
* Returns null if api_ph absent / un-decodable / lacks user_id.
|
|
108
|
+
*/
|
|
109
|
+
async fetchProfile(cookie) {
|
|
110
|
+
if (typeof cookie !== "string" || cookie.length === 0) {
|
|
111
|
+
this._setLastError(-1, "cookie 为空");
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const cpMatch = /(?:^|; ?)kuaishou\.web\.cp\.api_ph=([^;]+)/.exec(cookie);
|
|
115
|
+
if (!cpMatch || !cpMatch[1]) {
|
|
116
|
+
this._setLastError(
|
|
117
|
+
-8,
|
|
118
|
+
"cookie 缺 kuaishou.web.cp.api_ph (profile 解析需要)",
|
|
119
|
+
);
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
let decoded;
|
|
123
|
+
try {
|
|
124
|
+
decoded = decodeURIComponent(cpMatch[1]);
|
|
125
|
+
} catch {
|
|
126
|
+
decoded = cpMatch[1];
|
|
127
|
+
}
|
|
128
|
+
const trimmed = decoded.trimStart();
|
|
129
|
+
if (!trimmed.startsWith("{")) {
|
|
130
|
+
this._setLastError(
|
|
131
|
+
-9,
|
|
132
|
+
"kuaishou.web.cp.api_ph 解码后非 JSON (likely base64 — v0.3 加 fallback)",
|
|
133
|
+
);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
let obj;
|
|
137
|
+
try {
|
|
138
|
+
obj = JSON.parse(decoded);
|
|
139
|
+
} catch (e) {
|
|
140
|
+
this._setLastError(-3, "parse: " + (e.message || String(e)));
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
const uid =
|
|
144
|
+
pickString(obj.user_id) ||
|
|
145
|
+
pickString(obj.userId) ||
|
|
146
|
+
(Number.isFinite(obj.user_id) && obj.user_id > 0 && String(obj.user_id)) ||
|
|
147
|
+
(Number.isFinite(obj.userId) && obj.userId > 0 && String(obj.userId)) ||
|
|
148
|
+
null;
|
|
149
|
+
if (!uid || uid === "0") {
|
|
150
|
+
this._setLastError(
|
|
151
|
+
-7,
|
|
152
|
+
`api_ph JSON 缺 user_id (keys=[${Object.keys(obj).join(",")}])`,
|
|
153
|
+
);
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
this._clearLastError();
|
|
157
|
+
return {
|
|
158
|
+
uid,
|
|
159
|
+
nickname:
|
|
160
|
+
pickString(obj.user_name) ||
|
|
161
|
+
pickString(obj.userName) ||
|
|
162
|
+
pickString(obj.nickname) ||
|
|
163
|
+
"(unnamed)",
|
|
164
|
+
kuaishouId:
|
|
165
|
+
pickString(obj.kuaishou_id) || pickString(obj.kuaishouId) || null,
|
|
166
|
+
avatarUrl:
|
|
167
|
+
pickString(obj.headurl) ||
|
|
168
|
+
pickString(obj.headUrl) ||
|
|
169
|
+
pickString(obj.avatar) ||
|
|
170
|
+
null,
|
|
171
|
+
sex: pickString(obj.sex) || pickString(obj.gender) || null,
|
|
172
|
+
city: pickString(obj.city) || null,
|
|
173
|
+
constellation: pickString(obj.constellation) || null,
|
|
174
|
+
description:
|
|
175
|
+
pickString(obj.description) || pickString(obj.signature) || null,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async _signedGraphQL(cookie, operationName, variables) {
|
|
180
|
+
const body = JSON.stringify({
|
|
181
|
+
operationName,
|
|
182
|
+
variables,
|
|
183
|
+
query: "",
|
|
184
|
+
});
|
|
185
|
+
const rawUrl = new URL("graphql", this.baseUrl);
|
|
186
|
+
const purpose = `${operationName}|${body}`;
|
|
187
|
+
// signProvider.signUrl + signedHeaders sequential. KuaishouSignBridge
|
|
188
|
+
// caches kpf/kpn from signUrl call so signedHeaders returns them.
|
|
189
|
+
const signedUrl = await this.signProvider.signUrl(rawUrl, purpose);
|
|
190
|
+
if (!signedUrl) {
|
|
191
|
+
this._setLastError(
|
|
192
|
+
-99,
|
|
193
|
+
"__NS_sig3 unavailable (signProvider returned null — bridge not warm or rotated)",
|
|
194
|
+
);
|
|
195
|
+
this._fallbackHits += 1;
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
const extraHeaders = await this.signProvider.signedHeaders(rawUrl, purpose);
|
|
199
|
+
this._bridgeHits += 1;
|
|
200
|
+
const headers = { ...BROWSER_HEADERS, ...extraHeaders, Cookie: cookie };
|
|
201
|
+
try {
|
|
202
|
+
const resp = await this._fetch(signedUrl.toString(), {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers,
|
|
205
|
+
body,
|
|
206
|
+
});
|
|
207
|
+
const respBody = await resp.text();
|
|
208
|
+
if (!resp.ok) {
|
|
209
|
+
this._setLastError(resp.status, `HTTP ${resp.status}`);
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
const trimmed = respBody.trimStart();
|
|
213
|
+
if (!trimmed.startsWith("{")) {
|
|
214
|
+
this._setLastError(
|
|
215
|
+
-4,
|
|
216
|
+
"non-json (cookie expired or anti-bot triggered)",
|
|
217
|
+
);
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
let obj;
|
|
221
|
+
try {
|
|
222
|
+
obj = JSON.parse(respBody);
|
|
223
|
+
} catch (e) {
|
|
224
|
+
this._setLastError(-3, "parse: " + (e.message || String(e)));
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
// GraphQL errors come back as {errors: [...]} with HTTP 200.
|
|
228
|
+
if (Array.isArray(obj.errors) && obj.errors.length > 0) {
|
|
229
|
+
const first = obj.errors[0];
|
|
230
|
+
const msg = (first && first.message) || "graphql error";
|
|
231
|
+
this._setLastError(-5, "graphql: " + msg);
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
this._clearLastError();
|
|
235
|
+
return obj.data || null;
|
|
236
|
+
} catch (e) {
|
|
237
|
+
this._setLastError(-2, "IO: " + (e.message || String(e)));
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* /graphql visionFeedRecommend — watch history (recommended feed user
|
|
244
|
+
* dwelled on). Requires __NS_sig3.
|
|
245
|
+
*/
|
|
246
|
+
async fetchWatchHistory(cookie, opts = {}) {
|
|
247
|
+
const limit =
|
|
248
|
+
Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : 50;
|
|
249
|
+
const data = await this._signedGraphQL(cookie, OP_FEED_RECOMMEND, {
|
|
250
|
+
pcursor: "",
|
|
251
|
+
count: limit,
|
|
252
|
+
});
|
|
253
|
+
if (!data) return [];
|
|
254
|
+
const feeds =
|
|
255
|
+
(data.visionFeedRecommend && data.visionFeedRecommend.feeds) || [];
|
|
256
|
+
return extractPhotoList(feeds, limit, (item, photo, photoId, caption, ts) => ({
|
|
257
|
+
photoId,
|
|
258
|
+
caption,
|
|
259
|
+
authorName:
|
|
260
|
+
(item.author && item.author.name) || null,
|
|
261
|
+
authorId:
|
|
262
|
+
(item.author && item.author.id) || null,
|
|
263
|
+
viewedAt: ts,
|
|
264
|
+
duration: Number.isFinite(photo.duration) ? photo.duration : 0,
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* /graphql visionProfilePhotoList — user's own posted photos. Requires
|
|
270
|
+
* __NS_sig3.
|
|
271
|
+
*/
|
|
272
|
+
async fetchProfilePhotos(cookie, userId, opts = {}) {
|
|
273
|
+
const limit =
|
|
274
|
+
Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : 100;
|
|
275
|
+
const data = await this._signedGraphQL(cookie, OP_PROFILE_PHOTOS, {
|
|
276
|
+
userId,
|
|
277
|
+
pcursor: "",
|
|
278
|
+
count: limit,
|
|
279
|
+
page: "profile",
|
|
280
|
+
});
|
|
281
|
+
if (!data) return [];
|
|
282
|
+
const feeds =
|
|
283
|
+
(data.visionProfilePhotoList && data.visionProfilePhotoList.feeds) || [];
|
|
284
|
+
return extractPhotoList(feeds, limit, (_item, _photo, photoId, caption, ts) => ({
|
|
285
|
+
photoId,
|
|
286
|
+
caption,
|
|
287
|
+
postedAt: ts,
|
|
288
|
+
}));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* /graphql visionSearchPhoto — user's recent search keywords. Requires
|
|
293
|
+
* __NS_sig3.
|
|
294
|
+
*
|
|
295
|
+
* Two response shapes observed: data.recentSearchList vs data.history.
|
|
296
|
+
*/
|
|
297
|
+
async fetchSearchHistory(cookie, opts = {}) {
|
|
298
|
+
const limit =
|
|
299
|
+
Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : 50;
|
|
300
|
+
const data = await this._signedGraphQL(cookie, OP_SEARCH_PHOTO, {
|
|
301
|
+
keyword: "",
|
|
302
|
+
pcursor: "",
|
|
303
|
+
page: "search",
|
|
304
|
+
});
|
|
305
|
+
if (!data) return [];
|
|
306
|
+
const root = data.visionSearchPhoto || {};
|
|
307
|
+
const arr = Array.isArray(root.recentSearchList)
|
|
308
|
+
? root.recentSearchList
|
|
309
|
+
: Array.isArray(root.history)
|
|
310
|
+
? root.history
|
|
311
|
+
: [];
|
|
312
|
+
const out = [];
|
|
313
|
+
const cap = Math.min(limit, arr.length);
|
|
314
|
+
const now = this._now();
|
|
315
|
+
for (let i = 0; i < cap; i++) {
|
|
316
|
+
const raw = arr[i];
|
|
317
|
+
let keyword = null;
|
|
318
|
+
let ts = 0;
|
|
319
|
+
if (raw && typeof raw === "object") {
|
|
320
|
+
keyword = raw.keyword || raw.query || null;
|
|
321
|
+
ts = normalizeMs(raw.time || raw.searchTime || 0);
|
|
322
|
+
} else if (typeof raw === "string") {
|
|
323
|
+
keyword = raw;
|
|
324
|
+
ts = now - i * 1000;
|
|
325
|
+
}
|
|
326
|
+
if (!keyword) continue;
|
|
327
|
+
out.push({ keyword, searchedAt: ts });
|
|
328
|
+
}
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
_setLastError(code, message) {
|
|
333
|
+
this.lastErrorCode = code;
|
|
334
|
+
this.lastErrorMessage = message;
|
|
335
|
+
}
|
|
336
|
+
_clearLastError() {
|
|
337
|
+
this.lastErrorCode = 0;
|
|
338
|
+
this.lastErrorMessage = null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function extractPhotoList(feeds, limit, build) {
|
|
343
|
+
if (!Array.isArray(feeds)) return [];
|
|
344
|
+
const out = [];
|
|
345
|
+
const cap = Math.min(limit, feeds.length);
|
|
346
|
+
for (let i = 0; i < cap; i++) {
|
|
347
|
+
const item = feeds[i];
|
|
348
|
+
if (!item || typeof item !== "object") continue;
|
|
349
|
+
// Kuaishou GraphQL nests the photo under `photo`; flat fallback.
|
|
350
|
+
const photo =
|
|
351
|
+
item.photo && typeof item.photo === "object" ? item.photo : item;
|
|
352
|
+
const photoId = pickString(photo.id);
|
|
353
|
+
if (!photoId) continue;
|
|
354
|
+
const caption = pickString(photo.caption) || "(no caption)";
|
|
355
|
+
const ts = normalizeMs(photo.timestamp || photo.createTime || 0);
|
|
356
|
+
const built = build(item, photo, photoId, caption, ts);
|
|
357
|
+
if (built) out.push(built);
|
|
358
|
+
}
|
|
359
|
+
return out;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function extractEmbeddedUid(cpRaw) {
|
|
363
|
+
let decoded;
|
|
364
|
+
try {
|
|
365
|
+
decoded = decodeURIComponent(cpRaw);
|
|
366
|
+
} catch {
|
|
367
|
+
decoded = cpRaw;
|
|
368
|
+
}
|
|
369
|
+
for (const pat of [
|
|
370
|
+
/"?user_id"?\s*:\s*"?(\d+)"?/,
|
|
371
|
+
/"?uid"?\s*:\s*"?(\d+)"?/,
|
|
372
|
+
/"?userId"?\s*:\s*"?(\d+)"?/,
|
|
373
|
+
]) {
|
|
374
|
+
const m = pat.exec(decoded);
|
|
375
|
+
if (m && m[1] && m[1] !== "0") return m[1];
|
|
376
|
+
}
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function pickString(v) {
|
|
381
|
+
if (typeof v !== "string") return null;
|
|
382
|
+
return v.length > 0 ? v : null;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
module.exports = {
|
|
386
|
+
KuaishouApiClient,
|
|
387
|
+
_internals: {
|
|
388
|
+
BROWSER_UA,
|
|
389
|
+
BROWSER_HEADERS,
|
|
390
|
+
OP_FEED_RECOMMEND,
|
|
391
|
+
OP_PROFILE_PHOTOS,
|
|
392
|
+
OP_SEARCH_PHOTO,
|
|
393
|
+
normalizeMs,
|
|
394
|
+
extractPhotoList,
|
|
395
|
+
extractEmbeddedUid,
|
|
396
|
+
},
|
|
397
|
+
};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Phase 6d (Kuaishou C 路径 — 2026-05-25): end-to-end orchestrator.
|
|
5
|
+
*
|
|
6
|
+
* bridge.invoke("kuaishou.cookies") ← Phase 6d cookies extension
|
|
7
|
+
* │
|
|
8
|
+
* ▼ {cookie, uid, diagnostic}
|
|
9
|
+
* KuaishouApiClient.fetchProfile ← cookie parse (no HTTP)
|
|
10
|
+
* │
|
|
11
|
+
* ▼ ProfileInfo
|
|
12
|
+
* signProvider.warmUp(cookie) ← Phase 6d bridge ready
|
|
13
|
+
* │
|
|
14
|
+
* ▼
|
|
15
|
+
* fetchWatchHistory + fetchProfilePhotos + fetchSearchHistory
|
|
16
|
+
* │ (parallel, GraphQL POST + __NS_sig3 + kpf/kpn)
|
|
17
|
+
* ▼ 3 arrays (partial-failure OK)
|
|
18
|
+
* buildSnapshot + writeSnapshotJson ← schemaVersion=1
|
|
19
|
+
* │
|
|
20
|
+
* ▼
|
|
21
|
+
* registry.syncAdapter("social-kuaishou", { inputPath })
|
|
22
|
+
*
|
|
23
|
+
* Mirror of social-toutiao-adb but with GraphQL POST signing + dual
|
|
24
|
+
* URL/header bridge contract.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const { KuaishouApiClient } = require("./api-client");
|
|
28
|
+
const {
|
|
29
|
+
buildSnapshot,
|
|
30
|
+
writeSnapshotJson,
|
|
31
|
+
cleanupSnapshotJson,
|
|
32
|
+
} = require("./snapshot-builder");
|
|
33
|
+
|
|
34
|
+
async function collect(bridge, opts = {}) {
|
|
35
|
+
if (!bridge || typeof bridge.invoke !== "function") {
|
|
36
|
+
throw new TypeError(
|
|
37
|
+
"KuaishouAdbCollector.collect: bridge must expose invoke(method, params)",
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
const now = opts.now || Date.now;
|
|
41
|
+
const signProvider = opts.signProvider || undefined;
|
|
42
|
+
const client =
|
|
43
|
+
opts.apiClient || new KuaishouApiClient({ now, signProvider });
|
|
44
|
+
const limits = opts.limits || {};
|
|
45
|
+
|
|
46
|
+
const cookieResult = await bridge.invoke("kuaishou.cookies");
|
|
47
|
+
if (
|
|
48
|
+
!cookieResult ||
|
|
49
|
+
typeof cookieResult.cookie !== "string"
|
|
50
|
+
) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
"KuaishouAdbCollector.collect: bridge.invoke('kuaishou.cookies') returned malformed payload — got cookie=" +
|
|
53
|
+
typeof cookieResult?.cookie,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
const { cookie, uid: cookieUid, diagnostic: cookieDiagnostic } = cookieResult;
|
|
57
|
+
|
|
58
|
+
if (signProvider && typeof signProvider.warmUp === "function") {
|
|
59
|
+
try {
|
|
60
|
+
await signProvider.warmUp(cookie);
|
|
61
|
+
} catch (e) {
|
|
62
|
+
client._setLastError(
|
|
63
|
+
-98,
|
|
64
|
+
`signProvider warm-up failed: ${e && e.message ? e.message : String(e)}`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
// fetchProfile — pure cookie parse, no HTTP, no _sig.
|
|
71
|
+
const profile = await client.fetchProfile(cookie);
|
|
72
|
+
if (!profile) {
|
|
73
|
+
// Cookie lacks api_ph or parse failed. Emit empty snapshot using
|
|
74
|
+
// cookie-derived uid (or sentinel).
|
|
75
|
+
const uid = cookieUid || "unknown-user";
|
|
76
|
+
const snapshot = buildSnapshot({
|
|
77
|
+
uid,
|
|
78
|
+
displayName: opts.displayName,
|
|
79
|
+
snapshottedAt: now(),
|
|
80
|
+
});
|
|
81
|
+
const snapshotPath = writeSnapshotJson(snapshot, { dir: opts.stagingDir });
|
|
82
|
+
return {
|
|
83
|
+
snapshotPath,
|
|
84
|
+
uid: cookieUid,
|
|
85
|
+
nickname: null,
|
|
86
|
+
eventCounts: { profile: 0, watch: 0, collect: 0, search: 0, total: 0 },
|
|
87
|
+
lastErrorCode: client.lastErrorCode,
|
|
88
|
+
lastErrorMessage: client.lastErrorMessage,
|
|
89
|
+
cookieDiagnostic: cookieDiagnostic || null,
|
|
90
|
+
profileFetchFailed: true,
|
|
91
|
+
signProviderUsed: signProvider
|
|
92
|
+
? signProvider.constructor.name
|
|
93
|
+
: "none",
|
|
94
|
+
signProviderHits: client._bridgeHits,
|
|
95
|
+
signProviderFallbacks: client._fallbackHits,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Parallel 3 signed endpoints — partial failure tolerated.
|
|
100
|
+
const [watch, collectPosts, search] = await Promise.all([
|
|
101
|
+
client.fetchWatchHistory(cookie, {
|
|
102
|
+
limit: Number.isInteger(limits.watch) ? limits.watch : undefined,
|
|
103
|
+
}),
|
|
104
|
+
client.fetchProfilePhotos(cookie, profile.uid, {
|
|
105
|
+
limit: Number.isInteger(limits.collect)
|
|
106
|
+
? limits.collect
|
|
107
|
+
: undefined,
|
|
108
|
+
}),
|
|
109
|
+
client.fetchSearchHistory(cookie, {
|
|
110
|
+
limit: Number.isInteger(limits.search) ? limits.search : undefined,
|
|
111
|
+
}),
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
const snapshot = buildSnapshot({
|
|
115
|
+
uid: profile.uid,
|
|
116
|
+
displayName: opts.displayName || profile.nickname,
|
|
117
|
+
profile,
|
|
118
|
+
watch,
|
|
119
|
+
collect: collectPosts,
|
|
120
|
+
search,
|
|
121
|
+
snapshottedAt: now(),
|
|
122
|
+
});
|
|
123
|
+
const snapshotPath = writeSnapshotJson(snapshot, { dir: opts.stagingDir });
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
snapshotPath,
|
|
127
|
+
uid: profile.uid,
|
|
128
|
+
nickname: profile.nickname,
|
|
129
|
+
eventCounts: {
|
|
130
|
+
profile: 1,
|
|
131
|
+
watch: watch.length,
|
|
132
|
+
collect: collectPosts.length,
|
|
133
|
+
search: search.length,
|
|
134
|
+
total: snapshot.events.length,
|
|
135
|
+
},
|
|
136
|
+
lastErrorCode: client.lastErrorCode,
|
|
137
|
+
lastErrorMessage: client.lastErrorMessage,
|
|
138
|
+
cookieDiagnostic: cookieDiagnostic || null,
|
|
139
|
+
profileFetchFailed: false,
|
|
140
|
+
signProviderUsed: signProvider ? signProvider.constructor.name : "none",
|
|
141
|
+
signProviderHits: client._bridgeHits,
|
|
142
|
+
signProviderFallbacks: client._fallbackHits,
|
|
143
|
+
};
|
|
144
|
+
} finally {
|
|
145
|
+
if (signProvider && typeof signProvider.shutdown === "function") {
|
|
146
|
+
try {
|
|
147
|
+
await signProvider.shutdown();
|
|
148
|
+
} catch (_e) {
|
|
149
|
+
// Best-effort
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function collectAndSync(bridge, registry, opts = {}) {
|
|
156
|
+
if (!registry || typeof registry.syncAdapter !== "function") {
|
|
157
|
+
throw new TypeError(
|
|
158
|
+
"KuaishouAdbCollector.collectAndSync: registry must expose syncAdapter(name, options)",
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const collectResult = await collect(bridge, opts);
|
|
162
|
+
let syncReport = null;
|
|
163
|
+
let cleanupFailed = false;
|
|
164
|
+
try {
|
|
165
|
+
syncReport = await registry.syncAdapter("social-kuaishou", {
|
|
166
|
+
inputPath: collectResult.snapshotPath,
|
|
167
|
+
});
|
|
168
|
+
} finally {
|
|
169
|
+
try {
|
|
170
|
+
cleanupSnapshotJson(collectResult.snapshotPath);
|
|
171
|
+
} catch (_e) {
|
|
172
|
+
cleanupFailed = true;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
...syncReport,
|
|
177
|
+
kuaishou: {
|
|
178
|
+
uid: collectResult.uid,
|
|
179
|
+
nickname: collectResult.nickname,
|
|
180
|
+
eventCounts: collectResult.eventCounts,
|
|
181
|
+
lastErrorCode: collectResult.lastErrorCode,
|
|
182
|
+
lastErrorMessage: collectResult.lastErrorMessage,
|
|
183
|
+
cookieDiagnostic: collectResult.cookieDiagnostic,
|
|
184
|
+
profileFetchFailed: collectResult.profileFetchFailed,
|
|
185
|
+
signProviderUsed: collectResult.signProviderUsed,
|
|
186
|
+
signProviderHits: collectResult.signProviderHits,
|
|
187
|
+
signProviderFallbacks: collectResult.signProviderFallbacks,
|
|
188
|
+
cleanupFailed,
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = {
|
|
194
|
+
collect,
|
|
195
|
+
collectAndSync,
|
|
196
|
+
};
|