@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
package/src/event.ts CHANGED
@@ -91,7 +91,15 @@ async function onScan (
91
91
 
92
92
  if (this.logonoff()) {
93
93
  log.verbose('PuppetWeChatEvent', 'onScan() there has user when got a scan event. emit logout and set it to null')
94
- await this.logout()
94
+ const failure = this.lastSyncCheckFailure
95
+ const api = this.lastApiFailure
96
+ const reason = [
97
+ 'page showed a QR code',
98
+ failure && `last synccheck retcode ${failure.retcode} at ${new Date(failure.time).toISOString()}`,
99
+ api && `last failed ${api.api} answered ${api.ret} at ${new Date(api.time).toISOString()}`,
100
+ ].filter(Boolean).join('; ')
101
+ log.warn('PuppetWeChatEvent', 'onScan() logged out: %s', reason)
102
+ await this.logout(reason)
95
103
  }
96
104
 
97
105
  // feed watchDog a `scan` type of food
package/src/firer.ts CHANGED
@@ -370,9 +370,18 @@ export class Firer {
370
370
  timestamp,
371
371
  })
372
372
 
373
- setTimeout(async () => {
374
- await this.puppet.roomPayloadDirty(roomId)
375
- await this.puppet.roomPayload(roomId)
373
+ setTimeout(() => {
374
+ // newer wechaty-puppet releases replaced roomPayloadDirty(id) with
375
+ // dirtyPayload(type, id); calling the missing one was an unhandled rejection
376
+ const puppet = this.puppet as any
377
+ const dirty = typeof puppet.dirtyPayload === 'function'
378
+ ? puppet.dirtyPayload(3 /* PayloadType.Room */, roomId)
379
+ : puppet.roomPayloadDirty(roomId)
380
+ Promise.resolve(dirty)
381
+ .then(() => this.puppet.roomPayload(roomId))
382
+ .catch((e: Error) => {
383
+ log.warn('PuppetWeChatFirer', 'checkRoomLeave() reload room %s rejection: %s', roomId, e && e.message)
384
+ })
376
385
  }, 10 * 1000) // reload the room data, especially for memberList
377
386
 
378
387
  return true
@@ -89,8 +89,13 @@ import {
89
89
 
90
90
  import {
91
91
  Bridge,
92
+ BrowserHealth,
92
93
  Cookie,
93
94
  } from './bridge'
95
+ import {
96
+ ApiAnswer,
97
+ SessionHealth,
98
+ } from './session-monitor'
94
99
  import {
95
100
  Event,
96
101
  } from './event'
@@ -109,6 +114,49 @@ import {
109
114
 
110
115
  export type ScanFoodType = 'scan' | 'login' | 'logout'
111
116
 
117
+ export interface PuppetWeChatHealth {
118
+ logonoff : boolean,
119
+ pageAlive : boolean,
120
+ // what the page itself says (read from it, null while it loads)
121
+ page : null | BrowserHealth,
122
+ // what the session's own requests say (watched from outside the page)
123
+ session : SessionHealth,
124
+ error? : string,
125
+ cookieNames : string[],
126
+ hasDataTicket : boolean,
127
+ lastSyncCheckFailure? : { retcode: string, selector: string, time: number },
128
+ }
129
+
130
+ const HEALTH_CHECK_INTERVAL = 60 * 1000
131
+ // synccheck is a long poll answered within ~25s, so minutes of silence
132
+ // mean the web app stopped syncing.
133
+ const SYNC_STALL_TIMEOUT = 5 * 60 * 1000
134
+ const HEALTH_ALERT_INTERVAL = 60 * 60 * 1000
135
+ // synccheck retcodes (and BaseResponse.Ret values) that mean the server ended
136
+ // the web session: 1100 logged out on the phone, 1101 logged in elsewhere,
137
+ // 1102 session invalid.
138
+ const LOGGED_OUT_RETCODES = ['1100', '1101', '1102']
139
+ // Each message we send makes the server push a change that the page fetches
140
+ // with webwxsync within a second. A send with no webwxsync for this long
141
+ // means the session stopped receiving although synccheck keeps answering.
142
+ const SEND_SYNC_TIMEOUT = 10 * 60 * 1000
143
+ // A single failed webwxsync or send is retried by the web app; alert only
144
+ // when they keep failing.
145
+ const API_FAILURES_ALERT = 3
146
+ // The page can't be asked while it navigates (a reload, the web app's own
147
+ // logout redirect), so one failed check proves nothing. The application
148
+ // restarts the process on this alert, which can cost the login.
149
+ const PAGE_FAILURES_ALERT = 3
150
+ // One line an hour in the log with what the session reported, so a problem
151
+ // noticed later can be traced back.
152
+ const HEALTH_LOG_INTERVAL = 60 * 60 * 1000
153
+ // The web app itself ignores a webwxsync or send answering with one of
154
+ // LOGGED_OUT_RETCODES. By default that is only reported, since reloading a
155
+ // session that turns out to be fine risks its login. Set to 1 to log the bot
156
+ // out and reload to the QR code instead, once such answers have been seen
157
+ // to mean what they say.
158
+ const END_SESSION_ON_RET = process.env.WECHATY_PUPPET_WECHAT_END_SESSION_ON_RET === '1'
159
+
112
160
  export class PuppetWeChat extends Puppet {
113
161
 
114
162
  public static readonly VERSION = VERSION
@@ -118,8 +166,19 @@ export class PuppetWeChat extends Puppet {
118
166
  public scanPayload? : EventScanPayload
119
167
  public scanWatchdog : Watchdog<ScanFoodType>
120
168
 
169
+ public lastSyncCheckFailure? : { retcode: string, selector: string, time: number }
170
+ public lastApiFailure? : ApiAnswer
171
+
121
172
  private fileId: number
122
173
 
174
+ private healthTimer? : ReturnType<typeof setInterval>
175
+ private healthAlertTimes : { [key: string]: number } = {}
176
+ private pageFailures = 0
177
+ private healthLogTime = 0
178
+ private healthChecking = false
179
+ private heartbeatListener? : (data: any) => void
180
+ private heartbeatQueue? : ThrottleQueue
181
+
123
182
  constructor (
124
183
  public options: PuppetOptions = {},
125
184
  ) {
@@ -183,13 +242,22 @@ export class PuppetWeChat extends Puppet {
183
242
  /**
184
243
  * Save cookie for every 5 minutes
185
244
  */
186
- const throttleQueue = new ThrottleQueue(5 * 60 * 1000)
187
- this.on('heartbeat', data => throttleQueue.next(data))
245
+ if (this.heartbeatListener) {
246
+ this.removeListener('heartbeat', this.heartbeatListener)
247
+ }
248
+ const throttleQueue = this.heartbeatQueue = new ThrottleQueue(5 * 60 * 1000)
249
+ this.heartbeatListener = data => throttleQueue.next(data)
250
+ this.on('heartbeat', this.heartbeatListener)
188
251
  throttleQueue.subscribe(async (data: any) => {
189
252
  log.verbose('PuppetWeChat', 'start() throttleQueue.subscribe() new item: %s', data)
190
- await this.saveCookie()
253
+ await this.saveCookie().catch(e => {
254
+ log.error('PuppetWeChat', 'start() saveCookie() rejection: %s', e && e.message)
255
+ })
191
256
  })
192
257
 
258
+ this.initScanWatchdogReset()
259
+ this.startHealthCheck()
260
+
193
261
  log.verbose('PuppetWeChat', 'start() done')
194
262
 
195
263
  // this.emit('start')
@@ -224,9 +292,20 @@ export class PuppetWeChat extends Puppet {
224
292
  // this.watchdog.sleep()
225
293
  this.scanWatchdog.sleep()
226
294
  // this.watchdog.removeAllListeners()
227
- this.scanWatchdog.removeAllListeners()
295
+ // start() adds the reset listener again
296
+ this.scanWatchdog.removeAllListeners('reset')
228
297
  this.removeAllListeners('watchdog')
229
298
 
299
+ this.stopHealthCheck()
300
+ if (this.heartbeatListener) {
301
+ this.removeListener('heartbeat', this.heartbeatListener)
302
+ this.heartbeatListener = undefined
303
+ }
304
+ if (this.heartbeatQueue) {
305
+ this.heartbeatQueue.unsubscribe()
306
+ this.heartbeatQueue = undefined
307
+ }
308
+
230
309
  try {
231
310
  await this.bridge.stop()
232
311
  // register the removeListeners micro task at then end of the task queue
@@ -276,6 +355,15 @@ export class PuppetWeChat extends Puppet {
276
355
  data: user,
277
356
  type: 'logout',
278
357
  }))
358
+ }
359
+
360
+ /**
361
+ * stop() removes the dog's reset listener, so add it on every start(),
362
+ * or the QR code page would stop refreshing after the first restart.
363
+ */
364
+ private initScanWatchdogReset (): void {
365
+ const dog = this.scanWatchdog
366
+ dog.removeAllListeners('reset')
279
367
 
280
368
  dog.on('reset', async (food, timePast) => {
281
369
  log.warn('PuppetWeChat', 'initScanWatchdog() on(reset) lastFood: %s, timePast: %s',
@@ -298,6 +386,238 @@ export class PuppetWeChat extends Puppet {
298
386
  })
299
387
  }
300
388
 
389
+ private startHealthCheck (): void {
390
+ this.stopHealthCheck()
391
+ this.healthTimer = setInterval(() => {
392
+ this.checkHealth().catch(e => {
393
+ log.error('PuppetWeChat', 'checkHealth() rejection: %s', e && e.message)
394
+ })
395
+ }, HEALTH_CHECK_INTERVAL)
396
+ }
397
+
398
+ private stopHealthCheck (): void {
399
+ if (this.healthTimer) {
400
+ clearInterval(this.healthTimer)
401
+ this.healthTimer = undefined
402
+ }
403
+ }
404
+
405
+ /**
406
+ * What the page and its cookies say about the session, for monitoring and
407
+ * for people looking into a problem. Cookie values are never included.
408
+ */
409
+ public async healthReport (): Promise<PuppetWeChatHealth> {
410
+ const report: PuppetWeChatHealth = {
411
+ cookieNames : [],
412
+ hasDataTicket : false,
413
+ lastSyncCheckFailure : this.lastSyncCheckFailure,
414
+ logonoff : this.logonoff(),
415
+ page : null,
416
+ pageAlive : false,
417
+ session : this.bridge.monitor.health(),
418
+ }
419
+ try {
420
+ report.page = await this.bridge.health()
421
+ report.pageAlive = true
422
+ } catch (e) {
423
+ report.error = (e && e.message) || String(e)
424
+ return report
425
+ }
426
+ try {
427
+ const cookieList = await this.bridge.cookies()
428
+ report.cookieNames = cookieList.map(c => c.name)
429
+ report.hasDataTicket = cookieList.some(c => c.name === 'webwx_data_ticket' && !!c.value)
430
+ } catch (e) {
431
+ report.error = (e && e.message) || String(e)
432
+ }
433
+ return report
434
+ }
435
+
436
+ /**
437
+ * The page never reports a logout by itself: a session the server ended
438
+ * used to look logged in until something reloaded the page. Check what the
439
+ * page sees once a minute and act on it.
440
+ */
441
+ private async checkHealth (): Promise<void> {
442
+ if (this.state.off() || !this.logonoff()) {
443
+ return
444
+ }
445
+ // a page that takes long to answer must not pile up checks
446
+ if (this.healthChecking) {
447
+ return
448
+ }
449
+ this.healthChecking = true
450
+ try {
451
+ await this.checkHealthOnce()
452
+ } finally {
453
+ this.healthChecking = false
454
+ }
455
+ }
456
+
457
+ private async checkHealthOnce (): Promise<void> {
458
+ const report = await this.healthReport()
459
+
460
+ if (!report.pageAlive) {
461
+ this.pageFailures++
462
+ const current = this.bridge.currentPage()
463
+ const closed = !current || current.isClosed()
464
+ log.warn('PuppetWeChat', 'checkHealth() page did not answer (%s in a row, closed: %s): %s',
465
+ this.pageFailures, closed, report.error)
466
+ if (closed || this.pageFailures >= PAGE_FAILURES_ALERT) {
467
+ this.healthAlert('page', `page gone: ${report.error}`)
468
+ }
469
+ return
470
+ }
471
+ this.pageFailures = 0
472
+ this.healthClear('page')
473
+
474
+ const session = report.session
475
+ const now = session.now
476
+ const sync = session.syncCheck
477
+ const minutesSince = (time: number) => Math.round((now - time) / 60000)
478
+
479
+ if (now - this.healthLogTime > HEALTH_LOG_INTERVAL) {
480
+ this.healthLogTime = now
481
+ const ago = (time?: null | number) => time ? `${Math.round((now - time) / 1000)}s ago` : 'never'
482
+ log.info('PuppetWeChat', 'health: synccheck %s %s, webwxsync %s %s, send %s %s, received %s, rooms %s, ticket %s',
483
+ sync ? sync.retcode : '-', ago(sync && sync.time),
484
+ session.lastSync ? session.lastSync.ret : '-', ago(session.lastSync && session.lastSync.time),
485
+ session.lastSend ? session.lastSend.ret : '-', ago(session.lastSend && session.lastSend.time),
486
+ ago(session.lastReceived), report.page ? report.page.roomCount : '-', report.hasDataTicket)
487
+ }
488
+
489
+ const ended = [session.lastSync, session.lastSend].find(a => a && LOGGED_OUT_RETCODES.includes(a.ret))
490
+ if (ended) {
491
+ if (END_SESSION_ON_RET) {
492
+ await this.sessionEnded(`${ended.api} Ret ${ended.ret}`)
493
+ return
494
+ }
495
+ 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.`)
496
+ } else {
497
+ this.healthClear('session')
498
+ }
499
+
500
+ // before the first answer, count from the login
501
+ const lastSyncCheck = sync ? sync.time : session.since
502
+ if (now - lastSyncCheck > SYNC_STALL_TIMEOUT) {
503
+ this.healthAlert('sync', sync
504
+ ? `synccheck stalled: no answer for ${minutesSince(lastSyncCheck)} minutes`
505
+ : `synccheck stalled: none answered in the ${minutesSince(lastSyncCheck)} minutes since login`)
506
+ } else {
507
+ this.healthClear('sync')
508
+ }
509
+
510
+ for (const [kind, answer] of [['webwxsync', session.lastSync], ['send', session.lastSend]] as const) {
511
+ if (answer && answer.failures >= API_FAILURES_ALERT) {
512
+ this.healthAlert(kind, `${answer.api} keeps failing: ${answer.ret}, ${answer.failures} times in a row`)
513
+ } else {
514
+ this.healthClear(kind)
515
+ }
516
+ }
517
+
518
+ const sent = session.sentWithoutSync
519
+ if (sent && now - sent > SEND_SYNC_TIMEOUT) {
520
+ const received = session.lastReceived
521
+ ? `, last message received ${minutesSince(session.lastReceived)} minutes ago`
522
+ : ''
523
+ this.healthAlert('receive', `not receiving messages: nothing came from the server in the ${minutesSince(sent)} minutes since a message was sent${received}`)
524
+ } else {
525
+ this.healthClear('receive')
526
+ }
527
+
528
+ if (!report.hasDataTicket) {
529
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login')
530
+ } else {
531
+ this.healthClear('ticket')
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Log every time, emit an error at most once an hour per kind, so the
537
+ * application can notify someone without flooding them.
538
+ */
539
+ private healthAlert (kind: string, message: string): void {
540
+ log.warn('PuppetWeChat', 'health: %s', message)
541
+ const last = this.healthAlertTimes[kind]
542
+ if (last && Date.now() - last < HEALTH_ALERT_INTERVAL) {
543
+ return
544
+ }
545
+ this.healthAlertTimes[kind] = Date.now()
546
+ this.emit('error', { data: `health: ${message}` })
547
+ }
548
+
549
+ private healthClear (kind: string): void {
550
+ if (this.healthAlertTimes[kind]) {
551
+ log.info('PuppetWeChat', 'health: %s recovered', kind)
552
+ delete this.healthAlertTimes[kind]
553
+ }
554
+ }
555
+
556
+ /**
557
+ * The server ended the session: mark the bot logged out with the reason.
558
+ * The web app goes to its login page by itself after a synccheck retcode.
559
+ * It stays where it is after a failing webwxsync or send, so with
560
+ * END_SESSION_ON_RET the page is reloaded then, which shows the QR code.
561
+ */
562
+ private async sessionEnded (reason: string, reload = true): Promise<void> {
563
+ if (!this.id) {
564
+ return
565
+ }
566
+ log.warn('PuppetWeChat', 'sessionEnded() the server ended the web session: %s', reason)
567
+ this.logoutLocally(reason)
568
+ if (!reload) {
569
+ return
570
+ }
571
+ await this.bridge.reload().catch(e => {
572
+ log.error('PuppetWeChat', 'sessionEnded() reload rejection: %s', e && e.message)
573
+ })
574
+ }
575
+
576
+ /**
577
+ * A failed webwxsync or send answer, as the bridge saw it. Remember it for
578
+ * the logout reason; the minute's check decides what to report.
579
+ */
580
+ private onApiRet (data: ApiAnswer): void {
581
+ log.warn('PuppetWeChat', 'onApiRet() %s answered %s (%s in a row)', data.api, data.ret, data.failures)
582
+ this.lastApiFailure = data
583
+ if (LOGGED_OUT_RETCODES.includes(data.ret)) {
584
+ // don't wait for the minute to pass
585
+ this.checkHealth().catch(e => {
586
+ log.error('PuppetWeChat', 'onApiRet() checkHealth() rejection: %s', e && e.message)
587
+ })
588
+ }
589
+ }
590
+
591
+ private onSyncCheck (data: { retcode: string, selector: string }): void {
592
+ log.warn('PuppetWeChat', 'onSyncCheck() retcode %s selector %s', data.retcode, data.selector)
593
+ this.lastSyncCheckFailure = { ...data, time: Date.now() }
594
+ if (LOGGED_OUT_RETCODES.includes(data.retcode)) {
595
+ // act now rather than at the next minute's check; the web app is
596
+ // already on its way to the login page
597
+ this.sessionEnded(`synccheck retcode ${data.retcode}`, false).catch(e => {
598
+ log.error('PuppetWeChat', 'onSyncCheck() sessionEnded() rejection: %s', e && e.message)
599
+ })
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Mark the bot logged out without telling the page to log out: used when
605
+ * the server has already ended the session.
606
+ */
607
+ private logoutLocally (reason: string): void {
608
+ const user = this.id
609
+ if (!user) {
610
+ return
611
+ }
612
+ this.id = undefined
613
+ this.emit('logout', { contactId: user, data: reason })
614
+ }
615
+
616
+ public async roomTopicList (): Promise<Array<{ id: string, topic: string, memberCount: number }>> {
617
+ const list = await this.bridge.roomTopicList()
618
+ return list.map(r => ({ ...r, topic: plainText(r.topic || '') }))
619
+ }
620
+
301
621
  private async initBridge (): Promise<Bridge> {
302
622
  log.verbose('PuppetWeChat', 'initBridge()')
303
623
 
@@ -317,6 +637,8 @@ export class PuppetWeChat extends Puppet {
317
637
  this.bridge.on('logout', Event.onLogout.bind(this))
318
638
  this.bridge.on('message', Event.onMessage.bind(this))
319
639
  this.bridge.on('scan', Event.onScan.bind(this))
640
+ this.bridge.on('synccheck', this.onSyncCheck.bind(this))
641
+ this.bridge.on('apiret', this.onApiRet.bind(this))
320
642
  this.bridge.on('unload', Event.onUnload.bind(this))
321
643
 
322
644
  try {
@@ -533,8 +855,8 @@ export class PuppetWeChat extends Puppet {
533
855
 
534
856
  try {
535
857
  const ret = await this.bridge.forward(baseData, patchData)
536
- if (!ret) {
537
- throw new Error('forward failed')
858
+ if (ret !== true) {
859
+ throw new Error('forward failed: ' + (ret || 'page error') + this.bridge.lastSendFailure())
538
860
  }
539
861
  } catch (e) {
540
862
  log.error('PuppetWeChat', 'forward() exception: %s', e.message)
@@ -557,14 +879,19 @@ export class PuppetWeChat extends Puppet {
557
879
  }
558
880
 
559
881
  public async login (userId: string): Promise<void> {
882
+ // failures of the session before this one say nothing about a later logout
883
+ this.lastSyncCheckFailure = undefined
884
+ this.lastApiFailure = undefined
885
+ this.pageFailures = 0
886
+ this.bridge.monitor.reset(userId)
560
887
  return super.login(userId)
561
888
  }
562
889
 
563
890
  /**
564
891
  * logout from browser, then server will emit `logout` event
565
892
  */
566
- public async logout (): Promise<void> {
567
- log.verbose('PuppetWeChat', 'logout()')
893
+ public async logout (reason = 'logout()'): Promise<void> {
894
+ log.verbose('PuppetWeChat', 'logout(%s)', reason)
568
895
 
569
896
  const user = this.selfId()
570
897
  if (!user) {
@@ -579,7 +906,7 @@ export class PuppetWeChat extends Puppet {
579
906
  throw e
580
907
  } finally {
581
908
  this.id = undefined
582
- this.emit('logout', { contactId: user, data: 'logout()' })
909
+ this.emit('logout', { contactId: user, data: reason })
583
910
  }
584
911
  }
585
912
 
@@ -1370,6 +1697,11 @@ export class PuppetWeChat extends Puppet {
1370
1697
  const cookie = await this.bridge.cookies()
1371
1698
  const first = cookie.find(c => c.name === 'webwx_data_ticket')
1372
1699
  const webwxDataTicket = first && first.value
1700
+ if (!webwxDataTicket) {
1701
+ // without it the upload form can't even be built
1702
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login')
1703
+ throw new Error('webwx_data_ticket missing: log in again to send files')
1704
+ }
1373
1705
  const size = buffer.length
1374
1706
  const fromUserName = this.selfId()
1375
1707
  const id = 'WU_FILE_' + this.fileId
@@ -1603,15 +1935,15 @@ export class PuppetWeChat extends Puppet {
1603
1935
  mediaData.MediaId,
1604
1936
  mediaData.MsgType,
1605
1937
  )
1606
- let ret = false
1938
+ let ret: true | string | false = false
1607
1939
  try {
1608
1940
  ret = await this.bridge.sendMedia(mediaData)
1609
1941
  } catch (e) {
1610
1942
  log.error('PuppetWeChat', 'sendMedia() exception: %s', e.message)
1611
1943
  throw e
1612
1944
  }
1613
- if (!ret) {
1614
- throw new Error('sendMedia fail')
1945
+ if (ret !== true) {
1946
+ throw new Error('sendMedia failed: ' + (ret || 'page error') + this.bridge.lastSendFailure())
1615
1947
  }
1616
1948
  }
1617
1949
 
@@ -0,0 +1,165 @@
1
+ /**
2
+ * What the web session's own requests say about its health, read from
3
+ * outside the page.
4
+ *
5
+ * The web app long-polls `synccheck` (answered within ~25s) and fetches new
6
+ * messages with `webwxsync` when synccheck reports a change. It carries on
7
+ * after a failing webwxsync and only marks a failed send in its own chat
8
+ * window, so nothing tells Node. Bridge feeds the answers of those requests
9
+ * in here as the browser reports them; nothing is added to or changed in the
10
+ * page for this.
11
+ */
12
+
13
+ export interface SyncCheckAnswer {
14
+ retcode : string,
15
+ selector : string,
16
+ time : number,
17
+ }
18
+
19
+ export interface ApiAnswer {
20
+ api : string,
21
+ // failed answers in a row for this kind of call (webwxsync, or any send)
22
+ failures : number,
23
+ // BaseResponse.Ret, or what went wrong with the request itself
24
+ ret : string,
25
+ time : number,
26
+ }
27
+
28
+ export interface SessionHealth {
29
+ now : number,
30
+ // when the monitor was last reset: the login it is watching
31
+ since : number,
32
+ syncCheck : null | SyncCheckAnswer,
33
+ lastSync : null | ApiAnswer,
34
+ lastSend : null | ApiAnswer,
35
+ // last time webwxsync brought a message from someone else
36
+ lastReceived : null | number,
37
+ // when the first message since the last webwxsync answer was sent
38
+ sentWithoutSync : null | number,
39
+ }
40
+
41
+ // webwxsync and the calls that send a message, by the last part of their path
42
+ const API_REGEX = /\/(webwxsync|webwxsendmsg|webwxsendappmsg|webwxsendmsgimg|webwxsendvideomsg|webwxsendemoticon)(\?|$)/
43
+ const SYNCCHECK_REGEX = /\/synccheck(\?|$)/
44
+ // window.synccheck={retcode:"0",selector:"2"}
45
+ const SYNCCHECK_BODY_REGEX = /retcode\s*:\s*"?(\d+)"?\s*,\s*selector\s*:\s*"?(\d+)"?/
46
+ // a notice that a chat was opened on the phone, not a message
47
+ const MSGTYPE_STATUSNOTIFY = 51
48
+
49
+ export type WatchedCall = 'synccheck' | string
50
+
51
+ /**
52
+ * The call a request URL makes, when it is one we watch.
53
+ */
54
+ export function watchedCall (url: string): undefined | WatchedCall {
55
+ if (SYNCCHECK_REGEX.test(url)) {
56
+ return 'synccheck'
57
+ }
58
+ const match = API_REGEX.exec(url)
59
+ return match ? match[1] : undefined
60
+ }
61
+
62
+ export function parseSyncCheck (body: string): undefined | { retcode: string, selector: string } {
63
+ const match = SYNCCHECK_BODY_REGEX.exec(body)
64
+ return match ? { retcode: match[1], selector: match[2] } : undefined
65
+ }
66
+
67
+ export class SessionMonitor {
68
+
69
+ private since = Date.now()
70
+ private selfId? : string
71
+ private syncCheck : null | SyncCheckAnswer = null
72
+ private lastSync : null | ApiAnswer = null
73
+ private lastSend : null | ApiAnswer = null
74
+ private lastReceived : null | number = null
75
+ private sentWithoutSync : null | number = null
76
+
77
+ /**
78
+ * A new login: what the session before it left behind says nothing about
79
+ * this one.
80
+ */
81
+ public reset (selfId?: string): void {
82
+ this.since = Date.now()
83
+ this.selfId = selfId
84
+ this.syncCheck = null
85
+ this.lastSync = null
86
+ this.lastSend = null
87
+ this.lastReceived = null
88
+ this.sentWithoutSync = null
89
+ }
90
+
91
+ /**
92
+ * The page went to another document: requests in flight are gone, so a
93
+ * send still waiting for its sync would wait for ever.
94
+ */
95
+ public navigated (): void {
96
+ this.sentWithoutSync = null
97
+ }
98
+
99
+ public onSyncCheck (answer: { retcode: string, selector: string }): SyncCheckAnswer {
100
+ this.syncCheck = { ...answer, time: Date.now() }
101
+ return this.syncCheck
102
+ }
103
+
104
+ /**
105
+ * An answer of webwxsync or of a send. `started` is when its request left.
106
+ * `messages` are webwxsync's new messages.
107
+ */
108
+ public onApiAnswer (
109
+ api : string,
110
+ ret : string,
111
+ started : number,
112
+ messages : Array<{ FromUserName?: string, MsgType?: number }> = [],
113
+ ): ApiAnswer {
114
+ const isSync = api === 'webwxsync'
115
+ const previous = isSync ? this.lastSync : this.lastSend
116
+ const failures = ret === '0' ? 0 : ((previous && previous.failures) || 0) + 1
117
+ const answer = { api, failures, ret, time: Date.now() }
118
+
119
+ if (isSync) {
120
+ this.lastSync = answer
121
+ } else {
122
+ this.lastSend = answer
123
+ }
124
+ if (ret !== '0') {
125
+ return answer
126
+ }
127
+
128
+ if (!isSync) {
129
+ // Each send makes the server report a change, which the page fetches
130
+ // with webwxsync within a second. That sync can be answered before the
131
+ // send's own answer arrives: one answered since the request left
132
+ // already covers it. Otherwise wait for one, from the first send on.
133
+ const sync = this.lastSync
134
+ const covered = !!sync && sync.ret === '0' && sync.time > started
135
+ if (!covered && !this.sentWithoutSync) {
136
+ this.sentWithoutSync = answer.time
137
+ }
138
+ return answer
139
+ }
140
+
141
+ this.sentWithoutSync = null
142
+ const fromOthers = messages.some(m =>
143
+ m.MsgType !== MSGTYPE_STATUSNOTIFY && !!m.FromUserName && m.FromUserName !== this.selfId,
144
+ )
145
+ if (fromOthers) {
146
+ this.lastReceived = answer.time
147
+ }
148
+ return answer
149
+ }
150
+
151
+ public health (): SessionHealth {
152
+ return {
153
+ lastReceived : this.lastReceived,
154
+ lastSend : this.lastSend,
155
+ lastSync : this.lastSync,
156
+ now : Date.now(),
157
+ sentWithoutSync : this.sentWithoutSync,
158
+ since : this.since,
159
+ syncCheck : this.syncCheck,
160
+ }
161
+ }
162
+
163
+ }
164
+
165
+ export default SessionMonitor