@pacoyang/wechaty-puppet-wechat 0.28.6 → 0.28.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.
Files changed (64) hide show
  1. package/dist/examples/demo.js.map +1 -1
  2. package/dist/scripts/retry-unit-tests.js +2 -2
  3. package/dist/scripts/retry-unit-tests.js.map +1 -1
  4. package/dist/src/bridge.d.ts +41 -3
  5. package/dist/src/bridge.d.ts.map +1 -1
  6. package/dist/src/bridge.js +147 -8
  7. package/dist/src/bridge.js.map +1 -1
  8. package/dist/src/bridge.spec.js +8 -8
  9. package/dist/src/bridge.spec.js.map +1 -1
  10. package/dist/src/event.d.ts.map +1 -1
  11. package/dist/src/event.js +10 -2
  12. package/dist/src/event.js.map +1 -1
  13. package/dist/src/event.spec.js +1 -1
  14. package/dist/src/event.spec.js.map +1 -1
  15. package/dist/src/firer.d.ts.map +1 -1
  16. package/dist/src/firer.js +12 -3
  17. package/dist/src/firer.js.map +1 -1
  18. package/dist/src/firer.spec.js +4 -4
  19. package/dist/src/firer.spec.js.map +1 -1
  20. package/dist/src/mod.js +1 -1
  21. package/dist/src/puppet-wechat.d.ts +79 -3
  22. package/dist/src/puppet-wechat.d.ts.map +1 -1
  23. package/dist/src/puppet-wechat.js +343 -53
  24. package/dist/src/puppet-wechat.js.map +1 -1
  25. package/dist/src/puppet-wechat.spec.js +2 -2
  26. package/dist/src/puppet-wechat.spec.js.map +1 -1
  27. package/dist/src/pure-function-helpers/message-extname.js.map +1 -1
  28. package/dist/src/pure-function-helpers/message-filename.js +1 -1
  29. package/dist/src/pure-function-helpers/message-filename.js.map +1 -1
  30. package/dist/src/pure-function-helpers/message-raw-payload-parser.js +5 -5
  31. package/dist/src/pure-function-helpers/message-raw-payload-parser.js.map +1 -1
  32. package/dist/src/pure-function-helpers/mod.js +6 -2
  33. package/dist/src/pure-function-helpers/mod.js.map +1 -1
  34. package/dist/src/pure-function-helpers/normalize-scan-status.js.map +1 -1
  35. package/dist/src/pure-function-helpers/normalize-scan-status.spec.js +2 -2
  36. package/dist/src/pure-function-helpers/normalize-scan-status.spec.js.map +1 -1
  37. package/dist/src/pure-function-helpers/web-message-type.js.map +1 -1
  38. package/dist/src/pure-function-helpers/xml.js.map +1 -1
  39. package/dist/src/session-monitor.d.ts +74 -0
  40. package/dist/src/session-monitor.d.ts.map +1 -0
  41. package/dist/src/session-monitor.js +122 -0
  42. package/dist/src/session-monitor.js.map +1 -0
  43. package/dist/src/version.spec.js +1 -1
  44. package/dist/src/version.spec.js.map +1 -1
  45. package/dist/src/web-schemas.js +2 -2
  46. package/dist/src/web-schemas.js.map +1 -1
  47. package/dist/src/wechaty-bro.js +58 -3
  48. package/dist/tests/puppeteer-contact.spec.js +1 -1
  49. package/dist/tests/puppeteer-contact.spec.js.map +1 -1
  50. package/dist/tests/puppeteer-friendship.spec.js +4 -4
  51. package/dist/tests/puppeteer-friendship.spec.js.map +1 -1
  52. package/dist/tests/puppeteer-message.spec.js +2 -2
  53. package/dist/tests/puppeteer-message.spec.js.map +1 -1
  54. package/dist/tests/puppeteer-room.spec.js +1 -1
  55. package/dist/tests/puppeteer-room.spec.js.map +1 -1
  56. package/dist/tests/puppeteer.spec.js +12 -12
  57. package/dist/tests/puppeteer.spec.js.map +1 -1
  58. package/package.json +1 -1
  59. package/src/bridge.ts +173 -4
  60. package/src/event.ts +9 -1
  61. package/src/firer.ts +12 -3
  62. package/src/puppet-wechat.ts +344 -12
  63. package/src/session-monitor.ts +165 -0
  64. package/src/wechaty-bro.js +58 -3
@@ -39,18 +39,51 @@ const mod_1 = require("./pure-function-helpers/mod");
39
39
  const bridge_1 = require("./bridge");
40
40
  const event_1 = require("./event");
41
41
  const web_schemas_1 = require("./web-schemas");
42
+ const HEALTH_CHECK_INTERVAL = 60 * 1000;
43
+ // synccheck is a long poll answered within ~25s, so minutes of silence
44
+ // mean the web app stopped syncing.
45
+ const SYNC_STALL_TIMEOUT = 5 * 60 * 1000;
46
+ const HEALTH_ALERT_INTERVAL = 60 * 60 * 1000;
47
+ // synccheck retcodes (and BaseResponse.Ret values) that mean the server ended
48
+ // the web session: 1100 logged out on the phone, 1101 logged in elsewhere,
49
+ // 1102 session invalid.
50
+ const LOGGED_OUT_RETCODES = ['1100', '1101', '1102'];
51
+ // Each message we send makes the server push a change that the page fetches
52
+ // with webwxsync within a second. A send with no webwxsync for this long
53
+ // means the session stopped receiving although synccheck keeps answering.
54
+ const SEND_SYNC_TIMEOUT = 10 * 60 * 1000;
55
+ // A single failed webwxsync or send is retried by the web app; alert only
56
+ // when they keep failing.
57
+ const API_FAILURES_ALERT = 3;
58
+ // The page can't be asked while it navigates (a reload, the web app's own
59
+ // logout redirect), so one failed check proves nothing. The application
60
+ // restarts the process on this alert, which can cost the login.
61
+ const PAGE_FAILURES_ALERT = 3;
62
+ // One line an hour in the log with what the session reported, so a problem
63
+ // noticed later can be traced back.
64
+ const HEALTH_LOG_INTERVAL = 60 * 60 * 1000;
65
+ // The web app itself ignores a webwxsync or send answering with one of
66
+ // LOGGED_OUT_RETCODES. By default that is only reported, since reloading a
67
+ // session that turns out to be fine risks its login. Set to 1 to log the bot
68
+ // out and reload to the QR code instead, once such answers have been seen
69
+ // to mean what they say.
70
+ const END_SESSION_ON_RET = process.env.WECHATY_PUPPET_WECHAT_END_SESSION_ON_RET === '1';
42
71
  class PuppetWeChat extends wechaty_puppet_1.Puppet {
43
72
  constructor(options = {}) {
44
73
  super(options);
45
74
  this.options = options;
75
+ this.healthAlertTimes = {};
76
+ this.pageFailures = 0;
77
+ this.healthLogTime = 0;
78
+ this.healthChecking = false;
46
79
  this.fileId = 0;
47
80
  this.bridge = new bridge_1.Bridge({
48
81
  endpoint: options.endpoint || process.env.WECHATY_PUPPET_PUPPETEER_ENDPOINT,
49
82
  extspam: options.token || process.env.WECHATY_PUPPET_WECHAT_TOKEN,
50
- head: typeof options.head === 'boolean' ? options.head : config_1.envHead(),
83
+ head: typeof options.head === 'boolean' ? options.head : (0, config_1.envHead)(),
51
84
  launchOptions: options.launchOptions,
52
85
  memory: this.memory,
53
- stealthless: typeof options.stealthless === 'boolean' ? options.stealthless : config_1.envStealthless(),
86
+ stealthless: typeof options.stealthless === 'boolean' ? options.stealthless : (0, config_1.envStealthless)(),
54
87
  });
55
88
  const SCAN_TIMEOUT = 2 * 60 * 1000; // 2 minutes
56
89
  this.scanWatchdog = new watchdog_1.Watchdog(SCAN_TIMEOUT, 'Scan');
@@ -84,18 +117,26 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
84
117
  */
85
118
  const food = {
86
119
  data: 'inited',
87
- timeout: 2 * 60 * 1000,
120
+ timeout: 2 * 60 * 1000, // 2 mins for first login
88
121
  };
89
122
  this.emit('heartbeat', food);
90
123
  /**
91
124
  * Save cookie for every 5 minutes
92
125
  */
93
- const throttleQueue = new rx_queue_1.ThrottleQueue(5 * 60 * 1000);
94
- this.on('heartbeat', data => throttleQueue.next(data));
126
+ if (this.heartbeatListener) {
127
+ this.removeListener('heartbeat', this.heartbeatListener);
128
+ }
129
+ const throttleQueue = this.heartbeatQueue = new rx_queue_1.ThrottleQueue(5 * 60 * 1000);
130
+ this.heartbeatListener = data => throttleQueue.next(data);
131
+ this.on('heartbeat', this.heartbeatListener);
95
132
  throttleQueue.subscribe(async (data) => {
96
133
  config_1.log.verbose('PuppetWeChat', 'start() throttleQueue.subscribe() new item: %s', data);
97
- await this.saveCookie();
134
+ await this.saveCookie().catch(e => {
135
+ config_1.log.error('PuppetWeChat', 'start() saveCookie() rejection: %s', e && e.message);
136
+ });
98
137
  });
138
+ this.initScanWatchdogReset();
139
+ this.startHealthCheck();
99
140
  config_1.log.verbose('PuppetWeChat', 'start() done');
100
141
  // this.emit('start')
101
142
  return;
@@ -123,8 +164,18 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
123
164
  // this.watchdog.sleep()
124
165
  this.scanWatchdog.sleep();
125
166
  // this.watchdog.removeAllListeners()
126
- this.scanWatchdog.removeAllListeners();
167
+ // start() adds the reset listener again
168
+ this.scanWatchdog.removeAllListeners('reset');
127
169
  this.removeAllListeners('watchdog');
170
+ this.stopHealthCheck();
171
+ if (this.heartbeatListener) {
172
+ this.removeListener('heartbeat', this.heartbeatListener);
173
+ this.heartbeatListener = undefined;
174
+ }
175
+ if (this.heartbeatQueue) {
176
+ this.heartbeatQueue.unsubscribe();
177
+ this.heartbeatQueue = undefined;
178
+ }
128
179
  try {
129
180
  await this.bridge.stop();
130
181
  // register the removeListeners micro task at then end of the task queue
@@ -170,6 +221,14 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
170
221
  data: user,
171
222
  type: 'logout',
172
223
  }));
224
+ }
225
+ /**
226
+ * stop() removes the dog's reset listener, so add it on every start(),
227
+ * or the QR code page would stop refreshing after the first restart.
228
+ */
229
+ initScanWatchdogReset() {
230
+ const dog = this.scanWatchdog;
231
+ dog.removeAllListeners('reset');
173
232
  dog.on('reset', async (food, timePast) => {
174
233
  config_1.log.warn('PuppetWeChat', 'initScanWatchdog() on(reset) lastFood: %s, timePast: %s', food.data, timePast);
175
234
  try {
@@ -190,6 +249,221 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
190
249
  }
191
250
  });
192
251
  }
252
+ startHealthCheck() {
253
+ this.stopHealthCheck();
254
+ this.healthTimer = setInterval(() => {
255
+ this.checkHealth().catch(e => {
256
+ config_1.log.error('PuppetWeChat', 'checkHealth() rejection: %s', e && e.message);
257
+ });
258
+ }, HEALTH_CHECK_INTERVAL);
259
+ }
260
+ stopHealthCheck() {
261
+ if (this.healthTimer) {
262
+ clearInterval(this.healthTimer);
263
+ this.healthTimer = undefined;
264
+ }
265
+ }
266
+ /**
267
+ * What the page and its cookies say about the session, for monitoring and
268
+ * for people looking into a problem. Cookie values are never included.
269
+ */
270
+ async healthReport() {
271
+ const report = {
272
+ cookieNames: [],
273
+ hasDataTicket: false,
274
+ lastSyncCheckFailure: this.lastSyncCheckFailure,
275
+ logonoff: this.logonoff(),
276
+ page: null,
277
+ pageAlive: false,
278
+ session: this.bridge.monitor.health(),
279
+ };
280
+ try {
281
+ report.page = await this.bridge.health();
282
+ report.pageAlive = true;
283
+ }
284
+ catch (e) {
285
+ report.error = (e && e.message) || String(e);
286
+ return report;
287
+ }
288
+ try {
289
+ const cookieList = await this.bridge.cookies();
290
+ report.cookieNames = cookieList.map(c => c.name);
291
+ report.hasDataTicket = cookieList.some(c => c.name === 'webwx_data_ticket' && !!c.value);
292
+ }
293
+ catch (e) {
294
+ report.error = (e && e.message) || String(e);
295
+ }
296
+ return report;
297
+ }
298
+ /**
299
+ * The page never reports a logout by itself: a session the server ended
300
+ * used to look logged in until something reloaded the page. Check what the
301
+ * page sees once a minute and act on it.
302
+ */
303
+ async checkHealth() {
304
+ if (this.state.off() || !this.logonoff()) {
305
+ return;
306
+ }
307
+ // a page that takes long to answer must not pile up checks
308
+ if (this.healthChecking) {
309
+ return;
310
+ }
311
+ this.healthChecking = true;
312
+ try {
313
+ await this.checkHealthOnce();
314
+ }
315
+ finally {
316
+ this.healthChecking = false;
317
+ }
318
+ }
319
+ async checkHealthOnce() {
320
+ const report = await this.healthReport();
321
+ if (!report.pageAlive) {
322
+ this.pageFailures++;
323
+ const current = this.bridge.currentPage();
324
+ const closed = !current || current.isClosed();
325
+ config_1.log.warn('PuppetWeChat', 'checkHealth() page did not answer (%s in a row, closed: %s): %s', this.pageFailures, closed, report.error);
326
+ if (closed || this.pageFailures >= PAGE_FAILURES_ALERT) {
327
+ this.healthAlert('page', `page gone: ${report.error}`);
328
+ }
329
+ return;
330
+ }
331
+ this.pageFailures = 0;
332
+ this.healthClear('page');
333
+ const session = report.session;
334
+ const now = session.now;
335
+ const sync = session.syncCheck;
336
+ const minutesSince = (time) => Math.round((now - time) / 60000);
337
+ if (now - this.healthLogTime > HEALTH_LOG_INTERVAL) {
338
+ this.healthLogTime = now;
339
+ const ago = (time) => time ? `${Math.round((now - time) / 1000)}s ago` : 'never';
340
+ config_1.log.info('PuppetWeChat', 'health: synccheck %s %s, webwxsync %s %s, send %s %s, received %s, rooms %s, ticket %s', sync ? sync.retcode : '-', ago(sync && sync.time), session.lastSync ? session.lastSync.ret : '-', ago(session.lastSync && session.lastSync.time), session.lastSend ? session.lastSend.ret : '-', ago(session.lastSend && session.lastSend.time), ago(session.lastReceived), report.page ? report.page.roomCount : '-', report.hasDataTicket);
341
+ }
342
+ const ended = [session.lastSync, session.lastSend].find(a => a && LOGGED_OUT_RETCODES.includes(a.ret));
343
+ if (ended) {
344
+ if (END_SESSION_ON_RET) {
345
+ await this.sessionEnded(`${ended.api} Ret ${ended.ret}`);
346
+ return;
347
+ }
348
+ this.healthAlert('session', `${ended.api} answered Ret ${ended.ret}: WeChat reports the session as ended while the page still shows it logged in. Reload the page to get a QR code.`);
349
+ }
350
+ else {
351
+ this.healthClear('session');
352
+ }
353
+ // before the first answer, count from the login
354
+ const lastSyncCheck = sync ? sync.time : session.since;
355
+ if (now - lastSyncCheck > SYNC_STALL_TIMEOUT) {
356
+ this.healthAlert('sync', sync
357
+ ? `synccheck stalled: no answer for ${minutesSince(lastSyncCheck)} minutes`
358
+ : `synccheck stalled: none answered in the ${minutesSince(lastSyncCheck)} minutes since login`);
359
+ }
360
+ else {
361
+ this.healthClear('sync');
362
+ }
363
+ for (const [kind, answer] of [['webwxsync', session.lastSync], ['send', session.lastSend]]) {
364
+ if (answer && answer.failures >= API_FAILURES_ALERT) {
365
+ this.healthAlert(kind, `${answer.api} keeps failing: ${answer.ret}, ${answer.failures} times in a row`);
366
+ }
367
+ else {
368
+ this.healthClear(kind);
369
+ }
370
+ }
371
+ const sent = session.sentWithoutSync;
372
+ if (sent && now - sent > SEND_SYNC_TIMEOUT) {
373
+ const received = session.lastReceived
374
+ ? `, last message received ${minutesSince(session.lastReceived)} minutes ago`
375
+ : '';
376
+ this.healthAlert('receive', `not receiving messages: nothing came from the server in the ${minutesSince(sent)} minutes since a message was sent${received}`);
377
+ }
378
+ else {
379
+ this.healthClear('receive');
380
+ }
381
+ if (!report.hasDataTicket) {
382
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login');
383
+ }
384
+ else {
385
+ this.healthClear('ticket');
386
+ }
387
+ }
388
+ /**
389
+ * Log every time, emit an error at most once an hour per kind, so the
390
+ * application can notify someone without flooding them.
391
+ */
392
+ healthAlert(kind, message) {
393
+ config_1.log.warn('PuppetWeChat', 'health: %s', message);
394
+ const last = this.healthAlertTimes[kind];
395
+ if (last && Date.now() - last < HEALTH_ALERT_INTERVAL) {
396
+ return;
397
+ }
398
+ this.healthAlertTimes[kind] = Date.now();
399
+ this.emit('error', { data: `health: ${message}` });
400
+ }
401
+ healthClear(kind) {
402
+ if (this.healthAlertTimes[kind]) {
403
+ config_1.log.info('PuppetWeChat', 'health: %s recovered', kind);
404
+ delete this.healthAlertTimes[kind];
405
+ }
406
+ }
407
+ /**
408
+ * The server ended the session: mark the bot logged out with the reason.
409
+ * The web app goes to its login page by itself after a synccheck retcode.
410
+ * It stays where it is after a failing webwxsync or send, so with
411
+ * END_SESSION_ON_RET the page is reloaded then, which shows the QR code.
412
+ */
413
+ async sessionEnded(reason, reload = true) {
414
+ if (!this.id) {
415
+ return;
416
+ }
417
+ config_1.log.warn('PuppetWeChat', 'sessionEnded() the server ended the web session: %s', reason);
418
+ this.logoutLocally(reason);
419
+ if (!reload) {
420
+ return;
421
+ }
422
+ await this.bridge.reload().catch(e => {
423
+ config_1.log.error('PuppetWeChat', 'sessionEnded() reload rejection: %s', e && e.message);
424
+ });
425
+ }
426
+ /**
427
+ * A failed webwxsync or send answer, as the bridge saw it. Remember it for
428
+ * the logout reason; the minute's check decides what to report.
429
+ */
430
+ onApiRet(data) {
431
+ config_1.log.warn('PuppetWeChat', 'onApiRet() %s answered %s (%s in a row)', data.api, data.ret, data.failures);
432
+ this.lastApiFailure = data;
433
+ if (LOGGED_OUT_RETCODES.includes(data.ret)) {
434
+ // don't wait for the minute to pass
435
+ this.checkHealth().catch(e => {
436
+ config_1.log.error('PuppetWeChat', 'onApiRet() checkHealth() rejection: %s', e && e.message);
437
+ });
438
+ }
439
+ }
440
+ onSyncCheck(data) {
441
+ config_1.log.warn('PuppetWeChat', 'onSyncCheck() retcode %s selector %s', data.retcode, data.selector);
442
+ this.lastSyncCheckFailure = { ...data, time: Date.now() };
443
+ if (LOGGED_OUT_RETCODES.includes(data.retcode)) {
444
+ // act now rather than at the next minute's check; the web app is
445
+ // already on its way to the login page
446
+ this.sessionEnded(`synccheck retcode ${data.retcode}`, false).catch(e => {
447
+ config_1.log.error('PuppetWeChat', 'onSyncCheck() sessionEnded() rejection: %s', e && e.message);
448
+ });
449
+ }
450
+ }
451
+ /**
452
+ * Mark the bot logged out without telling the page to log out: used when
453
+ * the server has already ended the session.
454
+ */
455
+ logoutLocally(reason) {
456
+ const user = this.id;
457
+ if (!user) {
458
+ return;
459
+ }
460
+ this.id = undefined;
461
+ this.emit('logout', { contactId: user, data: reason });
462
+ }
463
+ async roomTopicList() {
464
+ const list = await this.bridge.roomTopicList();
465
+ return list.map(r => ({ ...r, topic: (0, mod_1.plainText)(r.topic || '') }));
466
+ }
193
467
  async initBridge() {
194
468
  config_1.log.verbose('PuppetWeChat', 'initBridge()');
195
469
  if (this.state.off()) {
@@ -206,6 +480,8 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
206
480
  this.bridge.on('logout', event_1.Event.onLogout.bind(this));
207
481
  this.bridge.on('message', event_1.Event.onMessage.bind(this));
208
482
  this.bridge.on('scan', event_1.Event.onScan.bind(this));
483
+ this.bridge.on('synccheck', this.onSyncCheck.bind(this));
484
+ this.bridge.on('apiret', this.onApiRet.bind(this));
209
485
  this.bridge.on('unload', event_1.Event.onUnload.bind(this));
210
486
  try {
211
487
  await this.bridge.start();
@@ -250,11 +526,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
250
526
  }
251
527
  async messageRawPayloadParser(rawPayload) {
252
528
  config_1.log.verbose('PuppetWeChat', 'messageRawPayloadParser(%s) @ %s', rawPayload, this);
253
- const payload = mod_1.messageRawPayloadParser(rawPayload);
529
+ const payload = (0, mod_1.messageRawPayloadParser)(rawPayload);
254
530
  return payload;
255
531
  }
256
532
  async messageRecall(messageId) {
257
- return wechaty_puppet_1.throwUnsupportedError(messageId);
533
+ return (0, wechaty_puppet_1.throwUnsupportedError)(messageId);
258
534
  }
259
535
  async messageFile(messageId) {
260
536
  const rawPayload = await this.messageRawPayload(messageId);
@@ -262,11 +538,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
262
538
  return fileBox;
263
539
  }
264
540
  async messageUrl(messageId) {
265
- return wechaty_puppet_1.throwUnsupportedError(messageId);
541
+ return (0, wechaty_puppet_1.throwUnsupportedError)(messageId);
266
542
  }
267
543
  async messageMiniProgram(messageId) {
268
544
  config_1.log.verbose('PuppetWeChat', 'messageMiniProgram(%s)', messageId);
269
- return wechaty_puppet_1.throwUnsupportedError(messageId);
545
+ return (0, wechaty_puppet_1.throwUnsupportedError)(messageId);
270
546
  }
271
547
  async messageRawPayloadToFile(rawPayload) {
272
548
  let url = await this.messageRawPayloadToUrl(rawPayload);
@@ -276,7 +552,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
276
552
  // use http instead of https, because https will only success on the very first request!
277
553
  url = url.replace(/^https/i, 'http');
278
554
  const parsedUrl = new url_1.default.URL(url);
279
- const msgFileName = mod_1.messageFilename(rawPayload);
555
+ const msgFileName = (0, mod_1.messageFilename)(rawPayload);
280
556
  if (!msgFileName) {
281
557
  throw new Error('no filename');
282
558
  }
@@ -286,12 +562,12 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
286
562
  // 'Accept-Encoding': 'gzip, deflate, sdch',
287
563
  // 'Accept-Encoding': 'gzip, deflate, sdch, br', // MsgType.IMAGE | VIDEO
288
564
  'Accept-Encoding': 'identity;q=1, *;q=0',
289
- 'Accept-Language': 'zh-CN,zh;q=0.8',
565
+ 'Accept-Language': 'zh-CN,zh;q=0.8', // MsgType.IMAGE | VIDEO
290
566
  // 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.6,en-US;q=0.4,en;q=0.2',
291
567
  Cookie: cookies.map(c => `${c.name}=${c.value}`).join('; '),
292
568
  // Accept: 'image/webp,image/*,*/*;q=0.8',
293
569
  // Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', // MsgType.IMAGE | VIDEO
294
- Host: parsedUrl.hostname,
570
+ Host: parsedUrl.hostname, // 'wx.qq.com', // MsgType.VIDEO | IMAGE
295
571
  Range: 'bytes=0-',
296
572
  // Referer: protocol + '//wx.qq.com/',
297
573
  Referer: url,
@@ -306,11 +582,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
306
582
  return fileBox;
307
583
  }
308
584
  async messageSendUrl(conversationId, urlLinkPayload) {
309
- wechaty_puppet_1.throwUnsupportedError(conversationId, urlLinkPayload);
585
+ (0, wechaty_puppet_1.throwUnsupportedError)(conversationId, urlLinkPayload);
310
586
  }
311
587
  async messageSendMiniProgram(conversationId, miniProgramPayload) {
312
588
  config_1.log.verbose('PuppetWeChat', 'messageSendMiniProgram("%s", %s)', conversationId, JSON.stringify(miniProgramPayload));
313
- wechaty_puppet_1.throwUnsupportedError(conversationId, miniProgramPayload);
589
+ (0, wechaty_puppet_1.throwUnsupportedError)(conversationId, miniProgramPayload);
314
590
  }
315
591
  /**
316
592
  * TODO: Test this function if it could work...
@@ -348,8 +624,8 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
348
624
  // In room msg, the content prefix sender:, need to be removed,
349
625
  // otherwise the forwarded sender will display the source message sender,
350
626
  // causing self () to determine the error
351
- newMsg.Content = mod_1.unescapeHtml(rawPayload.Content.replace(/^@\w+:<br\/>/, '')).replace(/^[\w-]+:<br\/>/, '');
352
- newMsg.MMIsChatRoom = mod_1.isRoomId(conversationId);
627
+ newMsg.Content = (0, mod_1.unescapeHtml)(rawPayload.Content.replace(/^@\w+:<br\/>/, '')).replace(/^[\w-]+:<br\/>/, '');
628
+ newMsg.MMIsChatRoom = (0, mod_1.isRoomId)(conversationId);
353
629
  // The following parameters need to be overridden after calling createMessage()
354
630
  rawPayload = Object.assign(rawPayload, newMsg);
355
631
  // for (let i = 0; i < sendToList.length; i++) {
@@ -364,8 +640,8 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
364
640
  const patchData = newMsg;
365
641
  try {
366
642
  const ret = await this.bridge.forward(baseData, patchData);
367
- if (!ret) {
368
- throw new Error('forward failed');
643
+ if (ret !== true) {
644
+ throw new Error('forward failed: ' + (ret || 'page error') + this.bridge.lastSendFailure());
369
645
  }
370
646
  }
371
647
  catch (e) {
@@ -384,13 +660,18 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
384
660
  }
385
661
  }
386
662
  async login(userId) {
663
+ // failures of the session before this one say nothing about a later logout
664
+ this.lastSyncCheckFailure = undefined;
665
+ this.lastApiFailure = undefined;
666
+ this.pageFailures = 0;
667
+ this.bridge.monitor.reset(userId);
387
668
  return super.login(userId);
388
669
  }
389
670
  /**
390
671
  * logout from browser, then server will emit `logout` event
391
672
  */
392
- async logout() {
393
- config_1.log.verbose('PuppetWeChat', 'logout()');
673
+ async logout(reason = 'logout()') {
674
+ config_1.log.verbose('PuppetWeChat', 'logout(%s)', reason);
394
675
  const user = this.selfId();
395
676
  if (!user) {
396
677
  config_1.log.warn('PuppetWeChat', 'logout() without self()');
@@ -405,7 +686,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
405
686
  }
406
687
  finally {
407
688
  this.id = undefined;
408
- this.emit('logout', { contactId: user, data: 'logout()' });
689
+ this.emit('logout', { contactId: user, data: reason });
409
690
  }
410
691
  }
411
692
  /**
@@ -415,13 +696,13 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
415
696
  *
416
697
  */
417
698
  async contactSelfQRCode() {
418
- return wechaty_puppet_1.throwUnsupportedError();
699
+ return (0, wechaty_puppet_1.throwUnsupportedError)();
419
700
  }
420
701
  async contactSelfName(name) {
421
- return wechaty_puppet_1.throwUnsupportedError(name);
702
+ return (0, wechaty_puppet_1.throwUnsupportedError)(name);
422
703
  }
423
704
  async contactSelfSignature(signature) {
424
- return wechaty_puppet_1.throwUnsupportedError(signature);
705
+ return (0, wechaty_puppet_1.throwUnsupportedError)(signature);
425
706
  }
426
707
  /**
427
708
  *
@@ -454,16 +735,16 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
454
735
  // MMActualSender??? MMPeerUserName??? `getUserContact(message.MMActualSender,message.MMPeerUserName).HeadImgUrl`
455
736
  // uin: rawPayload.Uin, // stable id: 4763975 || getCookie("wxuin")
456
737
  return {
457
- address: rawPayload.Alias,
738
+ address: rawPayload.Alias, // XXX: need a stable address for user
458
739
  alias: rawPayload.RemarkName,
459
740
  avatar: rawPayload.HeadImgUrl,
460
741
  city: rawPayload.City,
461
742
  friend: rawPayload.stranger === undefined
462
743
  ? undefined
463
- : !rawPayload.stranger,
744
+ : !rawPayload.stranger, // assign by injectio.js
464
745
  gender: rawPayload.Sex,
465
746
  id: rawPayload.UserName,
466
- name: mod_1.plainText(rawPayload.NickName || ''),
747
+ name: (0, mod_1.plainText)(rawPayload.NickName || ''),
467
748
  province: rawPayload.Province,
468
749
  signature: rawPayload.Signature,
469
750
  star: !!rawPayload.StarFriend,
@@ -476,7 +757,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
476
757
  type: (!!rawPayload.UserName && !rawPayload.UserName.startsWith('@@') && !!(rawPayload.VerifyFlag & 8))
477
758
  ? wechaty_puppet_1.ContactType.Official
478
759
  : wechaty_puppet_1.ContactType.Personal,
479
- weixin: rawPayload.Alias,
760
+ weixin: rawPayload.Alias, // Wechat ID
480
761
  };
481
762
  }
482
763
  ding(data) {
@@ -617,7 +898,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
617
898
  adminIdList: [],
618
899
  id,
619
900
  memberIdList,
620
- topic: mod_1.plainText(rawPayload.NickName || ''),
901
+ topic: (0, mod_1.plainText)(rawPayload.NickName || ''),
902
+ // aliasDict,
903
+ // nameMap,
904
+ // roomAliasMap,
905
+ // contactAliasMap,
621
906
  };
622
907
  // console.log(roomPayload)
623
908
  return roomPayload;
@@ -643,7 +928,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
643
928
  return wechaty_puppet_1.FileBox.fromUrl(payload.avatar);
644
929
  }
645
930
  config_1.log.warn('PuppetWeChat', 'roomAvatar() avatar not found, use the chatie default.');
646
- return config_1.qrCodeForChatie();
931
+ return (0, config_1.qrCodeForChatie)();
647
932
  }
648
933
  async roomAdd(roomId, contactId) {
649
934
  try {
@@ -691,7 +976,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
691
976
  config_1.log.warn('PuppetWeChat', 'roomQuit(%s) not supported by Web API', roomId);
692
977
  }
693
978
  async roomQRCode(roomId) {
694
- return wechaty_puppet_1.throwUnsupportedError(roomId);
979
+ return (0, wechaty_puppet_1.throwUnsupportedError)(roomId);
695
980
  }
696
981
  async roomMemberList(roomId) {
697
982
  config_1.log.verbose('PuppetWeChat', 'roommemberList(%s)', roomId);
@@ -728,13 +1013,13 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
728
1013
  *
729
1014
  */
730
1015
  async roomInvitationAccept(roomInvitationId) {
731
- return wechaty_puppet_1.throwUnsupportedError(roomInvitationId);
1016
+ return (0, wechaty_puppet_1.throwUnsupportedError)(roomInvitationId);
732
1017
  }
733
1018
  async roomInvitationRawPayload(roomInvitationId) {
734
- return wechaty_puppet_1.throwUnsupportedError(roomInvitationId);
1019
+ return (0, wechaty_puppet_1.throwUnsupportedError)(roomInvitationId);
735
1020
  }
736
1021
  async roomInvitationRawPayloadParser(rawPayload) {
737
- return wechaty_puppet_1.throwUnsupportedError(rawPayload);
1022
+ return (0, wechaty_puppet_1.throwUnsupportedError)(rawPayload);
738
1023
  }
739
1024
  /**
740
1025
  *
@@ -785,10 +1070,10 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
785
1070
  }
786
1071
  }
787
1072
  async friendshipSearchPhone(phone) {
788
- throw wechaty_puppet_1.throwUnsupportedError(phone);
1073
+ throw (0, wechaty_puppet_1.throwUnsupportedError)(phone);
789
1074
  }
790
1075
  async friendshipSearchWeixin(weixin) {
791
- throw wechaty_puppet_1.throwUnsupportedError(weixin);
1076
+ throw (0, wechaty_puppet_1.throwUnsupportedError)(weixin);
792
1077
  }
793
1078
  async friendshipAdd(contactId, hello) {
794
1079
  try {
@@ -981,13 +1266,13 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
981
1266
  case '.jpg':
982
1267
  case '.png':
983
1268
  case '.gif':
984
- mediatype = "pic" /* Image */;
1269
+ mediatype = "pic" /* WebMediaType.Image */;
985
1270
  break;
986
1271
  case '.mp4':
987
- mediatype = "video" /* Video */;
1272
+ mediatype = "video" /* WebMediaType.Video */;
988
1273
  break;
989
1274
  default:
990
- mediatype = "doc" /* Attachment */;
1275
+ mediatype = "doc" /* WebMediaType.Attachment */;
991
1276
  }
992
1277
  const buffer = await new Promise((resolve, reject) => {
993
1278
  file.pipe(new bl_1.default((err, data) => {
@@ -1003,13 +1288,13 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1003
1288
  const MAX_FILE_SIZE = 100 * 1024 * 1024;
1004
1289
  const LARGE_FILE_SIZE = 25 * 1024 * 1024;
1005
1290
  const MAX_VIDEO_SIZE = 20 * 1024 * 1024;
1006
- if (mediatype === "video" /* Video */ && buffer.length > MAX_VIDEO_SIZE) {
1291
+ if (mediatype === "video" /* WebMediaType.Video */ && buffer.length > MAX_VIDEO_SIZE) {
1007
1292
  throw new Error(`Sending video files is not allowed to exceed ${MAX_VIDEO_SIZE / 1024 / 1024}MB`);
1008
1293
  }
1009
1294
  if (buffer.length > MAX_FILE_SIZE) {
1010
1295
  throw new Error(`Sending files is not allowed to exceed ${MAX_FILE_SIZE / 1024 / 1024}MB`);
1011
1296
  }
1012
- const fileMd5 = md5_1.default(buffer);
1297
+ const fileMd5 = (0, md5_1.default)(buffer);
1013
1298
  const baseRequest = await this.getBaseRequest();
1014
1299
  const passTicket = await this.bridge.getPassticket();
1015
1300
  const uploadMediaUrl = await this.bridge.getUploadMediaUrl();
@@ -1017,6 +1302,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1017
1302
  const cookie = await this.bridge.cookies();
1018
1303
  const first = cookie.find(c => c.name === 'webwx_data_ticket');
1019
1304
  const webwxDataTicket = first && first.value;
1305
+ if (!webwxDataTicket) {
1306
+ // without it the upload form can't even be built
1307
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login');
1308
+ throw new Error('webwx_data_ticket missing: log in again to send files');
1309
+ }
1020
1310
  const size = buffer.length;
1021
1311
  const fromUserName = this.selfId();
1022
1312
  const id = 'WU_FILE_' + this.fileId;
@@ -1036,7 +1326,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1036
1326
  DataLen: size,
1037
1327
  FileMd5: fileMd5,
1038
1328
  FromUserName: fromUserName,
1039
- MediaType: "doc" /* Attachment */,
1329
+ MediaType: "doc" /* WebMediaType.Attachment */,
1040
1330
  Signature: '',
1041
1331
  StartPos: 0,
1042
1332
  ToUserName: toUserName,
@@ -1048,7 +1338,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1048
1338
  FileMd5: fileMd5,
1049
1339
  FileName: filename,
1050
1340
  FileSize: size,
1051
- FileType: 7,
1341
+ FileType: 7, // If do not have this parameter, the api will fail
1052
1342
  FromUserName: fromUserName,
1053
1343
  ToUserName: toUserName,
1054
1344
  };
@@ -1243,13 +1533,13 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1243
1533
  config_1.log.error('PuppetWeChat', 'sendMedia() exception: %s', e.message);
1244
1534
  throw e;
1245
1535
  }
1246
- if (!ret) {
1247
- throw new Error('sendMedia fail');
1536
+ if (ret !== true) {
1537
+ throw new Error('sendMedia failed: ' + (ret || 'page error') + this.bridge.lastSendFailure());
1248
1538
  }
1249
1539
  }
1250
1540
  async messageSendContact(conversationId, contactId) {
1251
1541
  config_1.log.verbose('PuppetWeChat', 'messageSend("%s", %s)', conversationId, contactId);
1252
- return wechaty_puppet_1.throwUnsupportedError();
1542
+ return (0, wechaty_puppet_1.throwUnsupportedError)();
1253
1543
  }
1254
1544
  async messageImage(messageId, imageType) {
1255
1545
  config_1.log.verbose('PuppetWeChat', 'messageImage(%s, %s)', messageId, imageType);
@@ -1257,7 +1547,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1257
1547
  }
1258
1548
  async messageContact(messageId) {
1259
1549
  config_1.log.verbose('PuppetWeChat', 'messageContact(%s)', messageId);
1260
- return wechaty_puppet_1.throwUnsupportedError(messageId);
1550
+ return (0, wechaty_puppet_1.throwUnsupportedError)(messageId);
1261
1551
  }
1262
1552
  /**
1263
1553
  *
@@ -1265,16 +1555,16 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1265
1555
  *
1266
1556
  */
1267
1557
  async tagContactAdd(tagId, contactId) {
1268
- return wechaty_puppet_1.throwUnsupportedError(tagId, contactId);
1558
+ return (0, wechaty_puppet_1.throwUnsupportedError)(tagId, contactId);
1269
1559
  }
1270
1560
  async tagContactRemove(tagId, contactId) {
1271
- return wechaty_puppet_1.throwUnsupportedError(tagId, contactId);
1561
+ return (0, wechaty_puppet_1.throwUnsupportedError)(tagId, contactId);
1272
1562
  }
1273
1563
  async tagContactDelete(tagId) {
1274
- return wechaty_puppet_1.throwUnsupportedError(tagId);
1564
+ return (0, wechaty_puppet_1.throwUnsupportedError)(tagId);
1275
1565
  }
1276
1566
  async tagContactList(contactId) {
1277
- return wechaty_puppet_1.throwUnsupportedError(contactId);
1567
+ return (0, wechaty_puppet_1.throwUnsupportedError)(contactId);
1278
1568
  }
1279
1569
  }
1280
1570
  exports.PuppetWeChat = PuppetWeChat;