channel-worker 2.5.132 → 2.5.133

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.
@@ -388,29 +388,8 @@ class CommandPoller {
388
388
  return;
389
389
  }
390
390
 
391
- // Danh sách page đã liên kết với tài khoản Shopee — đi CHUNG lượt này vì
392
- // nó dùng đúng phiên vừa mở, thêm một request chứ không thêm lần mở
393
- // profile. LỖI MỀM: đọc hỏng thì mất phần cảnh báo liên kết, không được
394
- // kéo theo cả lượt đồng bộ click/đơn (đó mới là việc chính).
395
- let mediaAccounts = null;
396
- let mediaError = null;
397
- try {
398
- const media = await report.fetchSocialMediaAccounts(conn.context, {
399
- log: (message) => console.log(message),
400
- });
401
- if (media.status === 'ok') mediaAccounts = media.accounts;
402
- else mediaError = media.reason || media.status;
403
- } catch (err) {
404
- mediaError = String(err.message || err).slice(0, 200);
405
- }
406
- if (mediaError) console.warn(`[shopee-report] không đọc được danh sách liên kết: ${mediaError}`);
407
-
408
391
  const saved = await this.api.affiliateReportResult(result.rows, {
409
392
  clicks: clickResult.rows,
410
- // `null` = KHÔNG đọc được, khác hẳn `[]` = đọc được và tài khoản chưa
411
- // liên kết page nào. API phải phân biệt để không xoá sạch bản ghi cũ
412
- // chỉ vì một lượt đọc hỏng.
413
- media_accounts: mediaAccounts,
414
393
  last_report_date: result.last_report_date,
415
394
  last_update_time: result.last_update_time,
416
395
  from: result.from,
@@ -427,8 +406,6 @@ class CommandPoller {
427
406
  click_saved: saved?.click_saved || 0,
428
407
  click_matched: saved?.click_matched || 0,
429
408
  click_unmatched: saved?.click_unmatched || 0,
430
- media_accounts: mediaAccounts ? mediaAccounts.length : null,
431
- media_error: mediaError || undefined,
432
409
  last_report_date: result.last_report_date,
433
410
  },
434
411
  });
@@ -183,78 +183,4 @@ async function fetchClickReport(ctx, {
183
183
  }
184
184
  }
185
185
 
186
- // Danh sách tài khoản mạng xã hội ĐÃ LIÊN KẾT với tài khoản affiliate — cùng
187
- // thứ trang `account_setting` hiện ở tab "Media Information".
188
- //
189
- // KHÔNG mở account_setting và KHÔNG bấm tab: đo thật 22/09/2026 trên phiên
190
- // Shopee1, endpoint này trả đủ dữ liệu khi gọi từ MỘT tab affiliate bất kỳ
191
- // (thử từ /dashboard). Đi đường DOM thì phải mở thêm trang, bấm đúng nhãn
192
- // tiếng Anh "Media Information", và nhãn đó đổi theo ngôn ngữ giao diện.
193
- //
194
- // Mỗi dòng có `user_id` là ID Facebook THẬT của page (vd 1298751909986110) —
195
- // đúng con số nằm trong link `facebook.com/profile.php?id=…`. Nhờ vậy việc so
196
- // khớp với kênh của mình không phải parse URL, vốn có nhiều biến thể
197
- // (?referral_source=…, /<handle>/, m.facebook.com…).
198
- //
199
- // `platform`: 6 = Facebook, 3 = TikTok (đo được trên tài khoản thật; các mã
200
- // khác giữ nguyên số để sau này đọc lại, không đoán tên).
201
- const SM_PLATFORM = { 6: 'facebook', 3: 'tiktok' };
202
-
203
- async function fetchSocialMediaAccounts(ctx, { timeoutMs = 45000, log = null } = {}) {
204
- let page = findAffiliatePage(ctx.pages());
205
- let opened = false;
206
- if (!page) {
207
- page = await ctx.newPage();
208
- opened = true;
209
- }
210
-
211
- try {
212
- if (!page.url().includes('affiliate.shopee.vn/')) {
213
- await page.goto('https://affiliate.shopee.vn/offer/product_offer', {
214
- waitUntil: 'domcontentloaded', timeout: timeoutMs,
215
- }).catch(() => {});
216
- await sleep(1500);
217
- }
218
- if (isBlockedState(page.url(), null)) {
219
- return { status: 'needs_verify', accounts: [], reason: 'session at captcha/login — re-verify via VNC' };
220
- }
221
-
222
- const result = await page.evaluate(async () => {
223
- try {
224
- const r = await fetch('/api/v3/affiliates/social_media_accounts', { credentials: 'include' });
225
- return { status: r.status, json: await r.json().catch(() => null) };
226
- } catch (e) {
227
- return { status: 0, error: String(e?.message || e) };
228
- }
229
- });
230
-
231
- if (isBlockedState(page.url(), result) || result.json?.code === 90309999) {
232
- return { status: 'needs_verify', accounts: [], reason: `blocked while reading media info (http ${result.status}, code ${result.json?.code})` };
233
- }
234
- if (result.status !== 200 || result.json?.code !== 0) {
235
- return { status: 'failed', accounts: [], reason: result.json?.msg || result.error || `media info HTTP ${result.status}` };
236
- }
237
-
238
- const list = Array.isArray(result.json?.data?.accounts) ? result.json.data.accounts : [];
239
- const accounts = list.map((row) => ({
240
- media_user_id: String(row.user_id || row.unique_id || '').trim(),
241
- media_name: String(row.user_name || '').trim(),
242
- website_url: String(row.website_url || '').trim(),
243
- platform_code: Number(row.platform) || 0,
244
- platform: SM_PLATFORM[Number(row.platform)] || 'other',
245
- link_status: Number(row.link_status) || 0,
246
- facebook_page_type: Number(row.facebook_page_type) || 0,
247
- partner_link_status: Number(row.partner_link_status) || 0,
248
- follower_number: Number(row.follower_number) || 0,
249
- // Shopee trả giây, không phải mili-giây.
250
- verification_time: Number(row.verification_time) || 0,
251
- })).filter((a) => a.media_user_id || a.website_url);
252
-
253
- if (log) log(`[shopee-report] media: ${accounts.length} tài khoản liên kết (${accounts.filter((a) => a.platform === 'facebook').length} Facebook)`);
254
- return { status: 'ok', accounts };
255
- } finally {
256
- if (opened) await page.close().catch(() => {});
257
- }
258
- }
259
-
260
- module.exports = { fetchConversionReport, fetchClickReport, fetchSocialMediaAccounts, reportWindow, SM_PLATFORM };
186
+ module.exports = { fetchConversionReport, fetchClickReport, reportWindow };
@@ -436,6 +436,29 @@ function cleanSubId(v) {
436
436
  // `/opaanlp/` — KHÁC hẳn `long_link` của offer list (universal-link + chữ ký
437
437
  // Google Ads, không qua đường ghi nhận affiliate nên không ra hoa hồng).
438
438
  //
439
+ // Vì sao Shopee không trả link — gom mọi chỗ nó có thể nhét lý do vào.
440
+ //
441
+ // Nó KHÔNG phải lúc nào cũng dùng `errors[]` của GraphQL: đã gặp lượt trả
442
+ // `code 599` + `data: null` (ca sub-id có gạch dưới, 09/09/2026) với
443
+ // `businessCode` nằm thẳng trong thân. Đọc không ra thì in nguyên văn đã cắt
444
+ // ngắn — còn hơn một câu rỗng nghĩa bắt người sau mở trình duyệt ra mò lại.
445
+ function linkFailureReason(res, wanted = 0) {
446
+ const j = res && res.json;
447
+ const bits = [];
448
+ if (res && res.error) bits.push(String(res.error));
449
+ if (res && res.status && res.status !== 200) bits.push(`http ${res.status}`);
450
+ const msg = j?.errors?.[0]?.message || j?.msg || j?.message || j?.error_msg;
451
+ if (msg) bits.push(String(msg));
452
+ for (const k of ['businessCode', 'business_code', 'code', 'error']) {
453
+ const v = j?.[k];
454
+ if (v !== undefined && v !== null && v !== 0 && v !== '') { bits.push(`${k} ${v}`); break; }
455
+ }
456
+ if (!bits.length) {
457
+ bits.push(`Shopee trả 0 link cho ${wanted} sản phẩm: ${JSON.stringify(j ?? res ?? null).slice(0, 300)}`);
458
+ }
459
+ return bits.join(' · ').slice(0, 500);
460
+ }
461
+
439
462
  // subIds: mảng tối đa 5 phần tử. Quy ước của mình: [kênh, video, đợt].
440
463
  async function generateOfferLink(ctx, { items = [], subIds = [], timeoutMs = 45000, log = null } = {}) {
441
464
  const list = (items || [])
@@ -483,27 +506,53 @@ async function generateOfferLink(ctx, { items = [], subIds = [], timeoutMs = 450
483
506
  }
484
507
  const err = res.json?.errors?.[0]?.message;
485
508
  if (err) return { status: 'failed', links: [], reason: err };
486
- const rows = res.json?.data?.productOfferLinks || [];
487
- return {
488
- status: 'ok',
489
- sub_ids: subs,
490
- links: rows.map((r) => ({ item_id: String(r.itemId), shop_id: String(r.shopId), link: r.productOfferLink })),
491
- };
509
+
510
+ // CHỈ nhận link của đúng những món đã hỏi, và chỉ nhận dòng CÓ link.
511
+ // Shopee trả `itemId` kèm từng link nên khớp được — không khớp mà vẫn lấy
512
+ // là có ngày ghi link của món khác vào bài, mà `workerLink` bên API khoá
513
+ // theo chính `item_id` này nên sai một chỗ là sai hết chuỗi.
514
+ const wanted = new Set(list.map((it) => it.itemId));
515
+ const rows = Array.isArray(res.json?.data?.productOfferLinks) ? res.json.data.productOfferLinks : [];
516
+ const links = rows
517
+ .map((r) => ({
518
+ item_id: String(r?.itemId ?? ''),
519
+ shop_id: String(r?.shopId ?? ''),
520
+ link: String(r?.productOfferLink || ''),
521
+ }))
522
+ .filter((r) => wanted.has(r.item_id) && r.link);
523
+ const missing = list.map((it) => it.itemId).filter((id) => !links.some((l) => l.item_id === id));
524
+
525
+ // KHÔNG có link nào = THẤT BẠI, không phải "xong với 0 kết quả". Bản đầu
526
+ // trả `status: 'ok'` cho ca này nên lệnh ghi 'done' và giao diện chỉ nói
527
+ // được "Worker không trả về link" — mù nguyên nhân. Mọi kiểu Shopee từ
528
+ // chối mà không đi qua `errors[]` (http 5xx, `data: null`, businessCode
529
+ // nằm trong thân) đều rơi vào đây.
530
+ if (!links.length) {
531
+ return { status: 'failed', links: [], sub_ids: subs, reason: linkFailureReason(res, list.length) };
532
+ }
533
+ if (missing.length && log) log(`[shopee] thiếu link cho ${missing.length}/${list.length} món: ${missing.join(', ')}`);
534
+ return { status: 'ok', sub_ids: subs, links, missing };
492
535
  } finally {
493
536
  if (opened) await page.close().catch(() => {});
494
537
  }
495
538
  }
496
539
 
540
+ // Dạng `-i.<shop>.<item>` neo hai đầu: mở bằng `-` hoặc `/`, đóng ở cuối
541
+ // đường dẫn. Cùng một luật với `api/services/ShopeeUrl.js` (ghi chú dài ở đó)
542
+ // — hai bên lệch nhau thì cùng một link cho ra hai mã sản phẩm khác nhau tuỳ
543
+ // đường đi. Đo 23/09/2026: bản cũ đọc "Mini.2.4G" ra shop 2 / item 4.
544
+ const I_FORM = /[-/]i\.(\d+)\.(\d+)\/?(?:[?#]|$)/;
545
+
497
546
  // Parse a Shopee product URL → { shop_id, item_id }. Accepts
498
547
  // /product/<shop>/<item> and i.<shop>.<item> forms.
499
548
  function parseProductUrl(url = '') {
500
549
  // `/opaanlp/` là đích của link affiliate (đo 12/09: link rút gọn s.shopee.vn
501
550
  // đá về đúng dạng này) — vẫn là một sản phẩm, vẫn lấy được shop/item.
502
- let m = url.match(/\/(?:product|opaanlp)\/(\d+)\/(\d+)/);
551
+ let m = String(url || '').match(/\/(?:product|opaanlp)\/(\d+)\/(\d+)/);
503
552
  if (m) return { shop_id: m[1], item_id: m[2] };
504
- m = url.match(/i\.(\d+)\.(\d+)/);
553
+ m = String(url || '').match(I_FORM);
505
554
  if (m) return { shop_id: m[1], item_id: m[2] };
506
555
  return null;
507
556
  }
508
557
 
509
- module.exports = { ingestProduct, scrapeOffers, generateOfferLink, cleanSubId, parseProductUrl, parseOfferRow, parsePdpItem, categoryGroup, pctToNumber, AFFILIATE_CATEGORIES, applyFilters, isBlockedState, findAffiliatePage, pruneTabs, isJunkTab };
558
+ module.exports = { ingestProduct, scrapeOffers, generateOfferLink, linkFailureReason, cleanSubId, parseProductUrl, parseOfferRow, parsePdpItem, categoryGroup, pctToNumber, AFFILIATE_CATEGORIES, applyFilters, isBlockedState, findAffiliatePage, pruneTabs, isJunkTab };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "channel-worker",
3
- "version": "2.5.132",
3
+ "version": "2.5.133",
4
4
  "description": "Channel Manager worker daemon — runs on remote machines to execute video pipeline jobs",
5
5
  "main": "lib/daemon.js",
6
6
  "bin": {
@@ -38,7 +38,7 @@ function parseViews(txt) {
38
38
  // 09/09 tìm được tab để so trước/sau. Bản riêng còn thiếu cả bộ lọc "anchor
39
39
  // của bài trong bảng tin" (gốc 2 link page lạ sáng 10/09) nên có thể quét
40
40
  // nhầm tab Reels của page KHÁC mà không hay.
41
- const { discoverReelsTabUrl, discoverReelsTabUrls, openReelsTabWithTiles, parsePageRef, readPageIdFromDom } = require('./upload_facebook').__testables;
41
+ const { discoverReelsTabUrl, discoverReelsTabUrls, openReelsTabWithTiles, parsePageRef } = require('./upload_facebook').__testables;
42
42
 
43
43
  // Số người theo dõi của page, đọc ngay trên chính trang đang đứng (header hiện
44
44
  // ở mọi tab của page/profile) — không tốn thêm lượt mở profile nào. Ô
@@ -821,20 +821,6 @@ async function run({ page, payload, log }) {
821
821
  // được với danh sách page đã liên kết bên Shopee. Không có thì bỏ qua, lượt
822
822
  // ghi số liệu không phụ thuộc vào nó.
823
823
  const pageRef = opened.verified ? parsePageRef(opened.url) : null;
824
- // URL chỉ có TÊN RIÊNG thì chưa đủ để đối chiếu với Shopee: 6/8 page đang liên
825
- // kết bên đó lưu dạng `profile.php?id=…`, không mang tên riêng. Thiếu số ID là
826
- // kênh bị báo "chưa liên kết" oan. Đọc thêm từ chính trang đang mở (đã chứng
827
- // minh có tile ⇒ đúng page của kênh). Đọc hỏng thì giữ nguyên tên riêng, không
828
- // làm hỏng lượt ghi số liệu.
829
- if (pageRef && !pageRef.id) {
830
- const hit = await readPageIdFromDom(page).catch(() => null);
831
- if (hit) {
832
- pageRef.id = hit.id;
833
- log('info', `[fb-stats] page id đọc từ trang: ${hit.id} (${hit.sources} nguồn khớp: ${hit.from.join(', ')})`);
834
- } else {
835
- log('warn', '[fb-stats] URL chỉ có tên riêng và KHÔNG đọc được id từ trang — kênh sẽ hiện "chưa rõ Page" thay vì báo sai liên kết');
836
- }
837
- }
838
824
  if (pageRef) log('info', `[fb-stats] page: ${pageRef.id ? `id ${pageRef.id}` : `handle ${pageRef.handle}`}`);
839
825
 
840
826
  const d = await log.apiRequest('POST', '/analytics/post-stats', {
@@ -1155,73 +1155,6 @@ function parsePageRef(reelsTabUrl) {
1155
1155
  return { id: '', handle: seg, url: raw };
1156
1156
  }
1157
1157
 
1158
- // ID page ĐỌC TỪ CHÍNH TRANG, cho ca URL chỉ có tên riêng (`/<handle>/?sk=reels_tab`).
1159
- //
1160
- // Vì sao cần: bên Shopee, 6/8 page đang liên kết được lưu dạng
1161
- // `profile.php?id=…`, KHÔNG có tên riêng trong link. Kênh nào chỉ biết tên riêng
1162
- // thì không có gì để so → bị báo "chưa liên kết" OAN (đo bằng
1163
- // services/AffiliateMediaLink 22/09). Dạng tên riêng có thật: ca "Chuyện Nghề
1164
- // Nhà Nông" 14/09 — dạng profile.php ra 0 tile, chỉ `/chuyennghenhanong/` chạy.
1165
- //
1166
- // CHỈ gọi khi đang đứng trên trang tab Reels ĐÃ chứng minh có tile. Đứng ở trang
1167
- // khác thì mấy khoá dưới đây là của trang đó, không phải của page mình.
1168
- //
1169
- // Đo thật 22/09 trên 6 profile của đàn (Toc-xinh, Meo-luoi, Tam-cai-tao-nha,
1170
- // Beo-banh-beo, duong-nhan-cung-anh, Do-nghe-len-hinh):
1171
- // `profile_id` == `actorID` == ID page trong URL ở CẢ 6/6.
1172
- // ⛔ `delegate_page_id` LUÔN là một số KHÁC (vd page 61591917189886 →
1173
- // delegate 1240255979169594). Bắt nhầm khoá này là ghi sai danh tính rồi
1174
- // báo sai liên kết cho đúng cái kênh mình định cứu.
1175
- //
1176
- // Cổng an toàn: phải có **ít nhất hai nguồn độc lập cùng ra một số** mới nhận.
1177
- // Một khoá JSON đứng lẻ không đủ — trang Facebook đầy số 15-16 chữ số, và nếu
1178
- // profile đang đăng nhập bằng tài khoản CÁ NHÂN quản lý page thì `userID` là của
1179
- // người, không phải của page. Hai nguồn khớp nhau thì khả năng cùng sai rất thấp.
1180
- const PAGE_ID_JSON_KEYS = ['profile_id', 'actorID', 'pageID'];
1181
-
1182
- async function readPageIdFromDom(page) {
1183
- const votes = await page.evaluate((keys) => {
1184
- const out = {};
1185
- const add = (src, v) => {
1186
- if (!/^\d{5,25}$/.test(String(v || ''))) return;
1187
- (out[src] = out[src] || []).push(String(v));
1188
- };
1189
- // Nguồn 1: anchor profile.php NGOÀI bảng tin. Anchor trong feed là của bài
1190
- // người khác — đúng cái bẫy đã đẻ ra 2 link sai sáng 10/09.
1191
- for (const a of document.querySelectorAll('a[href]')) {
1192
- const href = a.getAttribute('href') || '';
1193
- if (/[?&]__cft__|[?&]__tn__/.test(href)) continue;
1194
- if (a.closest("[role='feed'], [role='article'], [aria-posinset]")) continue;
1195
- const m = href.match(/profile\.php\?id=(\d{5,25})/);
1196
- if (m) add('anchor', m[1]);
1197
- }
1198
- // Nguồn 2..n: khoá JSON trong bundle. `delegate_page_id` cố ý KHÔNG có mặt.
1199
- const html = document.documentElement.innerHTML;
1200
- for (const key of keys) {
1201
- const re = new RegExp(`"${key}"\\s*:\\s*"?(\\d{5,25})"?`, 'g');
1202
- let m; let n = 0;
1203
- while ((m = re.exec(html)) && n < 8) { add(key, m[1]); n++; }
1204
- }
1205
- return out;
1206
- }, PAGE_ID_JSON_KEYS).catch(() => ({}));
1207
-
1208
- // Đếm theo NGUỒN, không theo số lần xuất hiện: một khoá lặp 8 lần trong bundle
1209
- // vẫn chỉ là MỘT nguồn, không được tự nó đủ phiếu.
1210
- const bySource = new Map();
1211
- for (const [src, vals] of Object.entries(votes || {})) {
1212
- for (const v of new Set(vals)) {
1213
- if (!bySource.has(v)) bySource.set(v, new Set());
1214
- bySource.get(v).add(src);
1215
- }
1216
- }
1217
- let best = null;
1218
- for (const [id, srcs] of bySource) {
1219
- if (srcs.size < 2) continue;
1220
- if (!best || srcs.size > best.sources) best = { id, sources: srcs.size, from: [...srcs].sort() };
1221
- }
1222
- return best;
1223
- }
1224
-
1225
1158
  async function hasVisibleReelComposer(page) {
1226
1159
  return page.evaluate(() => {
1227
1160
  for (const dlg of document.querySelectorAll("[role='dialog']")) {
@@ -3758,7 +3691,6 @@ module.exports.__testables = {
3758
3691
  pickReelsTabUrl,
3759
3692
  pickReelsTabUrls,
3760
3693
  parsePageRef,
3761
- readPageIdFromDom,
3762
3694
  discoverReelsTabUrls,
3763
3695
  openReelsTabWithTiles,
3764
3696
  networkIdVerdict,