@pacoyang/wechaty-puppet-wechat 0.28.5 → 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 (47) hide show
  1. package/dist/examples/demo.js.map +1 -1
  2. package/dist/scripts/retry-unit-tests.js +1 -1
  3. package/dist/scripts/retry-unit-tests.js.map +1 -1
  4. package/dist/src/bridge.d.ts +40 -2
  5. package/dist/src/bridge.d.ts.map +1 -1
  6. package/dist/src/bridge.js +143 -2
  7. package/dist/src/bridge.js.map +1 -1
  8. package/dist/src/bridge.spec.js.map +1 -1
  9. package/dist/src/event.d.ts.map +1 -1
  10. package/dist/src/event.js +9 -1
  11. package/dist/src/event.js.map +1 -1
  12. package/dist/src/event.spec.js.map +1 -1
  13. package/dist/src/firer.d.ts.map +1 -1
  14. package/dist/src/firer.js +12 -3
  15. package/dist/src/firer.js.map +1 -1
  16. package/dist/src/puppet-wechat.d.ts +78 -2
  17. package/dist/src/puppet-wechat.d.ts.map +1 -1
  18. package/dist/src/puppet-wechat.js +302 -16
  19. package/dist/src/puppet-wechat.js.map +1 -1
  20. package/dist/src/puppet-wechat.spec.js.map +1 -1
  21. package/dist/src/pure-function-helpers/message-extname.js.map +1 -1
  22. package/dist/src/pure-function-helpers/message-filename.js.map +1 -1
  23. package/dist/src/pure-function-helpers/message-raw-payload-parser.js.map +1 -1
  24. package/dist/src/pure-function-helpers/normalize-scan-status.js.map +1 -1
  25. package/dist/src/pure-function-helpers/normalize-scan-status.spec.js.map +1 -1
  26. package/dist/src/pure-function-helpers/web-message-type.js.map +1 -1
  27. package/dist/src/pure-function-helpers/xml.js.map +1 -1
  28. package/dist/src/session-monitor.d.ts +74 -0
  29. package/dist/src/session-monitor.d.ts.map +1 -0
  30. package/dist/src/session-monitor.js +122 -0
  31. package/dist/src/session-monitor.js.map +1 -0
  32. package/dist/src/web-schemas.js +2 -2
  33. package/dist/src/web-schemas.js.map +1 -1
  34. package/dist/src/wechaty-bro.js +58 -3
  35. package/dist/tests/puppeteer-friendship.spec.js +2 -2
  36. package/dist/tests/puppeteer-friendship.spec.js.map +1 -1
  37. package/dist/tests/puppeteer-message.spec.js.map +1 -1
  38. package/dist/tests/puppeteer-room.spec.js.map +1 -1
  39. package/dist/tests/puppeteer.spec.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/bridge.ts +176 -4
  42. package/src/event.ts +9 -1
  43. package/src/firer.ts +12 -3
  44. package/src/puppet-wechat.ts +344 -12
  45. package/src/session-monitor.ts +165 -0
  46. package/src/wechaty-bro.js +58 -3
  47. package/tsconfig.json +0 -1
@@ -18,16 +18,44 @@
18
18
  */
19
19
  import { Watchdog } from 'watchdog';
20
20
  import { ContactPayload, FriendshipPayload, FileBox, MessagePayload, MiniProgramPayload, Puppet, PuppetOptions, RoomInvitationPayload, RoomMemberPayload, RoomPayload, UrlLinkPayload, ImageType, EventScanPayload } from 'wechaty-puppet';
21
- import { Bridge } from './bridge';
21
+ import { Bridge, BrowserHealth } from './bridge';
22
+ import { ApiAnswer, SessionHealth } from './session-monitor';
22
23
  import { WebContactRawPayload, WebMessageRawPayload, WebRoomRawMember, WebRoomRawPayload } from './web-schemas';
23
24
  export type ScanFoodType = 'scan' | 'login' | 'logout';
25
+ export interface PuppetWeChatHealth {
26
+ logonoff: boolean;
27
+ pageAlive: boolean;
28
+ page: null | BrowserHealth;
29
+ session: SessionHealth;
30
+ error?: string;
31
+ cookieNames: string[];
32
+ hasDataTicket: boolean;
33
+ lastSyncCheckFailure?: {
34
+ retcode: string;
35
+ selector: string;
36
+ time: number;
37
+ };
38
+ }
24
39
  export declare class PuppetWeChat extends Puppet {
25
40
  options: PuppetOptions;
26
41
  static readonly VERSION = "0.0.0";
27
42
  bridge: Bridge;
28
43
  scanPayload?: EventScanPayload;
29
44
  scanWatchdog: Watchdog<ScanFoodType>;
45
+ lastSyncCheckFailure?: {
46
+ retcode: string;
47
+ selector: string;
48
+ time: number;
49
+ };
50
+ lastApiFailure?: ApiAnswer;
30
51
  private fileId;
52
+ private healthTimer?;
53
+ private healthAlertTimes;
54
+ private pageFailures;
55
+ private healthLogTime;
56
+ private healthChecking;
57
+ private heartbeatListener?;
58
+ private heartbeatQueue?;
31
59
  constructor(options?: PuppetOptions);
32
60
  start(): Promise<void>;
33
61
  stop(): Promise<void>;
@@ -39,6 +67,54 @@ export declare class PuppetWeChat extends Puppet {
39
67
  * so we need to refresh the page after a while
40
68
  */
41
69
  private initWatchdogForScan;
70
+ /**
71
+ * stop() removes the dog's reset listener, so add it on every start(),
72
+ * or the QR code page would stop refreshing after the first restart.
73
+ */
74
+ private initScanWatchdogReset;
75
+ private startHealthCheck;
76
+ private stopHealthCheck;
77
+ /**
78
+ * What the page and its cookies say about the session, for monitoring and
79
+ * for people looking into a problem. Cookie values are never included.
80
+ */
81
+ healthReport(): Promise<PuppetWeChatHealth>;
82
+ /**
83
+ * The page never reports a logout by itself: a session the server ended
84
+ * used to look logged in until something reloaded the page. Check what the
85
+ * page sees once a minute and act on it.
86
+ */
87
+ private checkHealth;
88
+ private checkHealthOnce;
89
+ /**
90
+ * Log every time, emit an error at most once an hour per kind, so the
91
+ * application can notify someone without flooding them.
92
+ */
93
+ private healthAlert;
94
+ private healthClear;
95
+ /**
96
+ * The server ended the session: mark the bot logged out with the reason.
97
+ * The web app goes to its login page by itself after a synccheck retcode.
98
+ * It stays where it is after a failing webwxsync or send, so with
99
+ * END_SESSION_ON_RET the page is reloaded then, which shows the QR code.
100
+ */
101
+ private sessionEnded;
102
+ /**
103
+ * A failed webwxsync or send answer, as the bridge saw it. Remember it for
104
+ * the logout reason; the minute's check decides what to report.
105
+ */
106
+ private onApiRet;
107
+ private onSyncCheck;
108
+ /**
109
+ * Mark the bot logged out without telling the page to log out: used when
110
+ * the server has already ended the session.
111
+ */
112
+ private logoutLocally;
113
+ roomTopicList(): Promise<Array<{
114
+ id: string;
115
+ topic: string;
116
+ memberCount: number;
117
+ }>>;
42
118
  private initBridge;
43
119
  private getBaseRequest;
44
120
  unref(): void;
@@ -65,7 +141,7 @@ export declare class PuppetWeChat extends Puppet {
65
141
  /**
66
142
  * logout from browser, then server will emit `logout` event
67
143
  */
68
- logout(): Promise<void>;
144
+ logout(reason?: string): Promise<void>;
69
145
  /**
70
146
  *
71
147
  * ContactSelf
@@ -1 +1 @@
1
- {"version":3,"file":"puppet-wechat.d.ts","sourceRoot":"","sources":["../../src/puppet-wechat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAoBH,OAAO,EACL,QAAQ,EAET,MAAwB,UAAU,CAAA;AAEnC,OAAO,EACL,cAAc,EAGd,iBAAiB,EAKjB,OAAO,EAEP,cAAc,EAGd,kBAAkB,EAElB,MAAM,EACN,aAAa,EAEb,qBAAqB,EACrB,iBAAiB,EACjB,WAAW,EAIX,cAAc,EACd,SAAS,EACT,gBAAgB,EACjB,MAAgC,gBAAgB,CAAA;AAmBjD,OAAO,EACL,MAAM,EAEP,MAAgC,UAAU,CAAA;AAK3C,OAAO,EAEL,oBAAoB,EAGpB,oBAAoB,EAGpB,gBAAgB,EAChB,iBAAiB,EAClB,MAAgC,eAAe,CAAA;AAEhD,MAAM,MAAM,YAAY,GAAK,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAA;AAExD,qBAAa,YAAa,SAAQ,MAAM;IAY7B,OAAO,EAAE,aAAa;IAV/B,gBAAuB,OAAO,WAAU;IAEjC,MAAM,EAAE,MAAM,CAAA;IAEd,WAAW,CAAC,EAAG,gBAAgB,CAAA;IAC/B,YAAY,EAAG,QAAQ,CAAC,YAAY,CAAC,CAAA;IAE5C,OAAO,CAAC,MAAM,CAAQ;gBAGb,OAAO,GAAE,aAAkB;IAoBvB,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;IAiEvB,IAAI,IAAK,OAAO,CAAC,IAAI,CAAC;IAmCnC;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB;YAkDb,UAAU;YAoCV,cAAc;IAWrB,KAAK,IAAK,I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;YAcR,OAAO;IAIR,UAAU,IAAK,OAAO,CAAC,IAAI,CAAC;IAMzC,OAAO,CAAC,SAAS;YAiBH,sBAAsB;YAgGtB,WAAW;IA6PZ,eAAe,CAC1B,cAAc,EAAG,MAAM,EACvB,IAAI,EAAa,OAAO,GACvB,OAAO,CAAC,IAAI,CAAC;IAsDH,kBAAkB,CAC7B,cAAc,EAAG,MAAM,EACvB,SAAS,EAAQ,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC;IAKH,YAAY,CAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;IAKxE,cAAc,CAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAKhE;;;;OAIG;IACU,aAAa,CAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/D,gBAAgB,CAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE,gBAAgB,CAAE,KAAK,EAAE,MAAM,GAAI,OAAO,CAAC,IAAI,CAAC;IAIhD,cAAc,CAAE,SAAS,CAAC,EAAE,MAAM,GAAI,OAAO,CAAC,MAAM,EAAE,CAAC;CAIrE;AAED,eAAe,YAAY,CAAA"}
@@ -39,10 +39,43 @@ 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,
@@ -90,12 +123,20 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
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();
@@ -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,
@@ -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
  /**
@@ -454,13 +735,13 @@ 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
747
  name: (0, mod_1.plainText)(rawPayload.NickName || ''),
@@ -1021,6 +1302,11 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1021
1302
  const cookie = await this.bridge.cookies();
1022
1303
  const first = cookie.find(c => c.name === 'webwx_data_ticket');
1023
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
+ }
1024
1310
  const size = buffer.length;
1025
1311
  const fromUserName = this.selfId();
1026
1312
  const id = 'WU_FILE_' + this.fileId;
@@ -1052,7 +1338,7 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1052
1338
  FileMd5: fileMd5,
1053
1339
  FileName: filename,
1054
1340
  FileSize: size,
1055
- FileType: 7,
1341
+ FileType: 7, // If do not have this parameter, the api will fail
1056
1342
  FromUserName: fromUserName,
1057
1343
  ToUserName: toUserName,
1058
1344
  };
@@ -1247,8 +1533,8 @@ class PuppetWeChat extends wechaty_puppet_1.Puppet {
1247
1533
  config_1.log.error('PuppetWeChat', 'sendMedia() exception: %s', e.message);
1248
1534
  throw e;
1249
1535
  }
1250
- if (!ret) {
1251
- throw new Error('sendMedia fail');
1536
+ if (ret !== true) {
1537
+ throw new Error('sendMedia failed: ' + (ret || 'page error') + this.bridge.lastSendFailure());
1252
1538
  }
1253
1539
  }
1254
1540
  async messageSendContact(conversationId, contactId) {