@pacoyang/wechaty-puppet-wechat 0.28.6 → 0.28.8

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 (79) 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 +82 -4
  5. package/dist/src/bridge.d.ts.map +1 -1
  6. package/dist/src/bridge.js +282 -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/config.d.ts +0 -1
  11. package/dist/src/config.d.ts.map +1 -1
  12. package/dist/src/config.js +5 -5
  13. package/dist/src/config.js.map +1 -1
  14. package/dist/src/event.d.ts.map +1 -1
  15. package/dist/src/event.js +10 -2
  16. package/dist/src/event.js.map +1 -1
  17. package/dist/src/event.spec.js +1 -1
  18. package/dist/src/event.spec.js.map +1 -1
  19. package/dist/src/firer.d.ts.map +1 -1
  20. package/dist/src/firer.js +12 -3
  21. package/dist/src/firer.js.map +1 -1
  22. package/dist/src/firer.spec.js +4 -4
  23. package/dist/src/firer.spec.js.map +1 -1
  24. package/dist/src/mod.js +1 -1
  25. package/dist/src/puppet-wechat.d.ts +108 -3
  26. package/dist/src/puppet-wechat.d.ts.map +1 -1
  27. package/dist/src/puppet-wechat.js +524 -54
  28. package/dist/src/puppet-wechat.js.map +1 -1
  29. package/dist/src/puppet-wechat.spec.js +2 -2
  30. package/dist/src/puppet-wechat.spec.js.map +1 -1
  31. package/dist/src/pure-function-helpers/is-type.js +2 -3
  32. package/dist/src/pure-function-helpers/is-type.js.map +1 -1
  33. package/dist/src/pure-function-helpers/message-extname.js +1 -2
  34. package/dist/src/pure-function-helpers/message-extname.js.map +1 -1
  35. package/dist/src/pure-function-helpers/message-filename.js +2 -3
  36. package/dist/src/pure-function-helpers/message-filename.js.map +1 -1
  37. package/dist/src/pure-function-helpers/message-raw-payload-parser.js +6 -7
  38. package/dist/src/pure-function-helpers/message-raw-payload-parser.js.map +1 -1
  39. package/dist/src/pure-function-helpers/mod.js +6 -2
  40. package/dist/src/pure-function-helpers/mod.js.map +1 -1
  41. package/dist/src/pure-function-helpers/normalize-scan-status.js +1 -2
  42. package/dist/src/pure-function-helpers/normalize-scan-status.js.map +1 -1
  43. package/dist/src/pure-function-helpers/normalize-scan-status.spec.js +2 -2
  44. package/dist/src/pure-function-helpers/normalize-scan-status.spec.js.map +1 -1
  45. package/dist/src/pure-function-helpers/web-message-type.js +1 -2
  46. package/dist/src/pure-function-helpers/web-message-type.js.map +1 -1
  47. package/dist/src/pure-function-helpers/xml.js +6 -7
  48. package/dist/src/pure-function-helpers/xml.js.map +1 -1
  49. package/dist/src/session-monitor.d.ts +90 -0
  50. package/dist/src/session-monitor.d.ts.map +1 -0
  51. package/dist/src/session-monitor.js +173 -0
  52. package/dist/src/session-monitor.js.map +1 -0
  53. package/dist/src/session-monitor.spec.d.ts +3 -0
  54. package/dist/src/session-monitor.spec.d.ts.map +1 -0
  55. package/dist/src/session-monitor.spec.js +65 -0
  56. package/dist/src/session-monitor.spec.js.map +1 -0
  57. package/dist/src/version.spec.js +1 -1
  58. package/dist/src/version.spec.js.map +1 -1
  59. package/dist/src/web-schemas.js +2 -2
  60. package/dist/src/web-schemas.js.map +1 -1
  61. package/dist/src/wechaty-bro.js +58 -3
  62. package/dist/tests/puppeteer-contact.spec.js +1 -1
  63. package/dist/tests/puppeteer-contact.spec.js.map +1 -1
  64. package/dist/tests/puppeteer-friendship.spec.js +4 -4
  65. package/dist/tests/puppeteer-friendship.spec.js.map +1 -1
  66. package/dist/tests/puppeteer-message.spec.js +2 -2
  67. package/dist/tests/puppeteer-message.spec.js.map +1 -1
  68. package/dist/tests/puppeteer-room.spec.js +1 -1
  69. package/dist/tests/puppeteer-room.spec.js.map +1 -1
  70. package/dist/tests/puppeteer.spec.js +12 -12
  71. package/dist/tests/puppeteer.spec.js.map +1 -1
  72. package/package.json +1 -1
  73. package/src/bridge.ts +327 -4
  74. package/src/event.ts +9 -1
  75. package/src/firer.ts +12 -3
  76. package/src/puppet-wechat.ts +540 -13
  77. package/src/session-monitor.spec.ts +80 -0
  78. package/src/session-monitor.ts +219 -0
  79. package/src/wechaty-bro.js +58 -3
@@ -89,8 +89,17 @@ import {
89
89
 
90
90
  import {
91
91
  Bridge,
92
+ BrowserHealth,
92
93
  Cookie,
94
+ LoginPageState,
93
95
  } from './bridge'
96
+ import {
97
+ ApiAnswer,
98
+ REFUSED_AFTER,
99
+ SessionHealth,
100
+ isRefusalCandidate,
101
+ refusedSession,
102
+ } from './session-monitor'
94
103
  import {
95
104
  Event,
96
105
  } from './event'
@@ -109,6 +118,67 @@ import {
109
118
 
110
119
  export type ScanFoodType = 'scan' | 'login' | 'logout'
111
120
 
121
+ export interface PuppetWeChatHealth {
122
+ logonoff : boolean,
123
+ pageAlive : boolean,
124
+ // what the page itself says (read from it, null while it loads)
125
+ page : null | BrowserHealth,
126
+ // what the login page is showing while logged out (null when logged in or loading)
127
+ loginPage : null | LoginPageState,
128
+ // what the session's own requests say (watched from outside the page)
129
+ session : SessionHealth,
130
+ error? : string,
131
+ cookieNames : string[],
132
+ hasDataTicket : boolean,
133
+ // whether wxuin and webwx_auth_ticket are present to request phone confirmation
134
+ hasPhoneTicket : boolean,
135
+ lastSyncCheckFailure? : { retcode: string, selector: string, time: number },
136
+ }
137
+
138
+ export interface PhoneConfirmResult {
139
+ mode : 'phone' | 'qrcode',
140
+ canConfirmOnPhone : boolean,
141
+ waitingForPhone : boolean,
142
+ qrcodeUrl : null | string,
143
+ }
144
+
145
+ const HEALTH_CHECK_INTERVAL = 60 * 1000
146
+ // synccheck is a long poll answered within ~25s, so minutes of silence
147
+ // mean the web app stopped syncing.
148
+ const SYNC_STALL_TIMEOUT = 5 * 60 * 1000
149
+ const HEALTH_ALERT_INTERVAL = 60 * 60 * 1000
150
+ // synccheck retcodes (and BaseResponse.Ret values) that mean the server ended
151
+ // the web session: 1100 logged out on the phone, 1101 logged in elsewhere,
152
+ // 1102 session invalid.
153
+ const LOGGED_OUT_RETCODES = ['1100', '1101', '1102']
154
+ // Each message we send makes the server push a change that the page fetches
155
+ // with webwxsync within a second. A send with no webwxsync for this long
156
+ // means the session stopped receiving although synccheck keeps answering.
157
+ const SEND_SYNC_TIMEOUT = 10 * 60 * 1000
158
+ // A single failed webwxsync or send is retried by the web app; alert only
159
+ // when they keep failing.
160
+ const API_FAILURES_ALERT = 3
161
+ // The page can't be asked while it navigates (a reload, the web app's own
162
+ // logout redirect), so one failed check proves nothing. The application
163
+ // restarts the process on this alert, which can cost the login.
164
+ const PAGE_FAILURES_ALERT = 3
165
+ // One line an hour in the log with what the session reported, so a problem
166
+ // noticed later can be traced back.
167
+ const HEALTH_LOG_INTERVAL = 60 * 60 * 1000
168
+ // The web app itself ignores a webwxsync or send answering with one of
169
+ // LOGGED_OUT_RETCODES. By default that is only reported, since reloading a
170
+ // session that turns out to be fine risks its login. Set to 1 to log the bot
171
+ // out and reload to the QR code instead, once such answers have been seen
172
+ // to mean what they say.
173
+ const END_SESSION_ON_RET = process.env.WECHATY_PUPPET_WECHAT_END_SESSION_ON_RET === '1'
174
+ // A session the server refuses (see refusedSession) is left for a new login
175
+ // unless this is 0: then it is only reported, as before.
176
+ const END_REFUSED_SESSION = process.env.WECHATY_PUPPET_WECHAT_END_REFUSED_SESSION !== '0'
177
+ // Keep the login page quiet while waiting for a person to trigger login from
178
+ // the console, instead of reloading every 2 minutes in the background. Set to
179
+ // 1 to restore the legacy scan watchdog reload loop.
180
+ const SCAN_WATCHDOG_ENABLED = process.env.WECHATY_PUPPET_WECHAT_SCAN_WATCHDOG === '1'
181
+
112
182
  export class PuppetWeChat extends Puppet {
113
183
 
114
184
  public static readonly VERSION = VERSION
@@ -118,8 +188,19 @@ export class PuppetWeChat extends Puppet {
118
188
  public scanPayload? : EventScanPayload
119
189
  public scanWatchdog : Watchdog<ScanFoodType>
120
190
 
191
+ public lastSyncCheckFailure? : { retcode: string, selector: string, time: number }
192
+ public lastApiFailure? : ApiAnswer
193
+
121
194
  private fileId: number
122
195
 
196
+ private healthTimer? : ReturnType<typeof setInterval>
197
+ private healthAlertTimes : { [key: string]: number } = {}
198
+ private pageFailures = 0
199
+ private healthLogTime = 0
200
+ private healthChecking = false
201
+ private heartbeatListener? : (data: any) => void
202
+ private heartbeatQueue? : ThrottleQueue
203
+
123
204
  constructor (
124
205
  public options: PuppetOptions = {},
125
206
  ) {
@@ -138,7 +219,11 @@ export class PuppetWeChat extends Puppet {
138
219
  const SCAN_TIMEOUT = 2 * 60 * 1000 // 2 minutes
139
220
  this.scanWatchdog = new Watchdog<ScanFoodType>(SCAN_TIMEOUT, 'Scan')
140
221
 
141
- this.initWatchdogForScan()
222
+ if (SCAN_WATCHDOG_ENABLED) {
223
+ this.initWatchdogForScan()
224
+ } else {
225
+ this.scanWatchdog.sleep()
226
+ }
142
227
  }
143
228
 
144
229
  public async start (): Promise<void> {
@@ -183,13 +268,24 @@ export class PuppetWeChat extends Puppet {
183
268
  /**
184
269
  * Save cookie for every 5 minutes
185
270
  */
186
- const throttleQueue = new ThrottleQueue(5 * 60 * 1000)
187
- this.on('heartbeat', data => throttleQueue.next(data))
271
+ if (this.heartbeatListener) {
272
+ this.removeListener('heartbeat', this.heartbeatListener)
273
+ }
274
+ const throttleQueue = this.heartbeatQueue = new ThrottleQueue(5 * 60 * 1000)
275
+ this.heartbeatListener = data => throttleQueue.next(data)
276
+ this.on('heartbeat', this.heartbeatListener)
188
277
  throttleQueue.subscribe(async (data: any) => {
189
278
  log.verbose('PuppetWeChat', 'start() throttleQueue.subscribe() new item: %s', data)
190
- await this.saveCookie()
279
+ await this.saveCookie().catch(e => {
280
+ log.error('PuppetWeChat', 'start() saveCookie() rejection: %s', e && e.message)
281
+ })
191
282
  })
192
283
 
284
+ if (SCAN_WATCHDOG_ENABLED) {
285
+ this.initScanWatchdogReset()
286
+ }
287
+ this.startHealthCheck()
288
+
193
289
  log.verbose('PuppetWeChat', 'start() done')
194
290
 
195
291
  // this.emit('start')
@@ -224,9 +320,20 @@ export class PuppetWeChat extends Puppet {
224
320
  // this.watchdog.sleep()
225
321
  this.scanWatchdog.sleep()
226
322
  // this.watchdog.removeAllListeners()
227
- this.scanWatchdog.removeAllListeners()
323
+ // start() adds the reset listener again
324
+ this.scanWatchdog.removeAllListeners('reset')
228
325
  this.removeAllListeners('watchdog')
229
326
 
327
+ this.stopHealthCheck()
328
+ if (this.heartbeatListener) {
329
+ this.removeListener('heartbeat', this.heartbeatListener)
330
+ this.heartbeatListener = undefined
331
+ }
332
+ if (this.heartbeatQueue) {
333
+ this.heartbeatQueue.unsubscribe()
334
+ this.heartbeatQueue = undefined
335
+ }
336
+
230
337
  try {
231
338
  await this.bridge.stop()
232
339
  // register the removeListeners micro task at then end of the task queue
@@ -276,6 +383,15 @@ export class PuppetWeChat extends Puppet {
276
383
  data: user,
277
384
  type: 'logout',
278
385
  }))
386
+ }
387
+
388
+ /**
389
+ * stop() removes the dog's reset listener, so add it on every start(),
390
+ * or the QR code page would stop refreshing after the first restart.
391
+ */
392
+ private initScanWatchdogReset (): void {
393
+ const dog = this.scanWatchdog
394
+ dog.removeAllListeners('reset')
279
395
 
280
396
  dog.on('reset', async (food, timePast) => {
281
397
  log.warn('PuppetWeChat', 'initScanWatchdog() on(reset) lastFood: %s, timePast: %s',
@@ -298,6 +414,405 @@ export class PuppetWeChat extends Puppet {
298
414
  })
299
415
  }
300
416
 
417
+ private startHealthCheck (): void {
418
+ this.stopHealthCheck()
419
+ this.healthTimer = setInterval(() => {
420
+ this.checkHealth().catch(e => {
421
+ log.error('PuppetWeChat', 'checkHealth() rejection: %s', e && e.message)
422
+ })
423
+ }, HEALTH_CHECK_INTERVAL)
424
+ }
425
+
426
+ private stopHealthCheck (): void {
427
+ if (this.healthTimer) {
428
+ clearInterval(this.healthTimer)
429
+ this.healthTimer = undefined
430
+ }
431
+ }
432
+
433
+ /**
434
+ * What the page and its cookies say about the session, for monitoring and
435
+ * for people looking into a problem. Cookie values are never included.
436
+ */
437
+ public async healthReport (): Promise<PuppetWeChatHealth> {
438
+ const report: PuppetWeChatHealth = {
439
+ cookieNames : [],
440
+ hasDataTicket : false,
441
+ hasPhoneTicket : false,
442
+ lastSyncCheckFailure : this.lastSyncCheckFailure,
443
+ loginPage : null,
444
+ logonoff : this.logonoff(),
445
+ page : null,
446
+ pageAlive : false,
447
+ session : this.bridge.monitor.health(),
448
+ }
449
+ try {
450
+ report.page = await this.bridge.health()
451
+ report.pageAlive = true
452
+ } catch (e) {
453
+ report.error = (e && e.message) || String(e)
454
+ return report
455
+ }
456
+ try {
457
+ const cookieList = await this.bridge.cookies()
458
+ report.cookieNames = cookieList.map(c => c.name)
459
+ report.hasDataTicket = cookieList.some(c => c.name === 'webwx_data_ticket' && !!c.value)
460
+ report.hasPhoneTicket = cookieList.some(c => c.name === 'wxuin' && !!c.value)
461
+ && cookieList.some(c => c.name === 'webwx_auth_ticket' && !!c.value)
462
+ } catch (e) {
463
+ report.error = (e && e.message) || String(e)
464
+ }
465
+ if (!report.logonoff) {
466
+ try {
467
+ report.loginPage = await this.bridge.loginPageState()
468
+ } catch (e) {
469
+ // page may be navigating
470
+ }
471
+ }
472
+ return report
473
+ }
474
+
475
+ /**
476
+ * The page never reports a logout by itself: a session the server ended
477
+ * used to look logged in until something reloaded the page. Check what the
478
+ * page sees once a minute and act on it.
479
+ */
480
+ private async checkHealth (): Promise<void> {
481
+ if (this.state.off() || !this.logonoff()) {
482
+ return
483
+ }
484
+ // a page that takes long to answer must not pile up checks
485
+ if (this.healthChecking) {
486
+ return
487
+ }
488
+ this.healthChecking = true
489
+ try {
490
+ await this.checkHealthOnce()
491
+ } finally {
492
+ this.healthChecking = false
493
+ }
494
+ }
495
+
496
+ private async checkHealthOnce (): Promise<void> {
497
+ const report = await this.healthReport()
498
+
499
+ if (!report.pageAlive) {
500
+ this.pageFailures++
501
+ const current = this.bridge.currentPage()
502
+ const closed = !current || current.isClosed()
503
+ log.warn('PuppetWeChat', 'checkHealth() page did not answer (%s in a row, closed: %s): %s',
504
+ this.pageFailures, closed, report.error)
505
+ if (closed || this.pageFailures >= PAGE_FAILURES_ALERT) {
506
+ this.healthAlert('page', `page gone: ${report.error}`)
507
+ }
508
+ return
509
+ }
510
+ this.pageFailures = 0
511
+ this.healthClear('page')
512
+
513
+ const session = report.session
514
+ const now = session.now
515
+ const sync = session.syncCheck
516
+ const minutesSince = (time: number) => Math.round((now - time) / 60000)
517
+
518
+ if (now - this.healthLogTime > HEALTH_LOG_INTERVAL) {
519
+ this.healthLogTime = now
520
+ const ago = (time?: null | number) => time ? `${Math.round((now - time) / 1000)}s ago` : 'never'
521
+ log.info('PuppetWeChat', 'health: synccheck %s %s, webwxsync %s %s, send %s %s, received %s, rooms %s, ticket %s',
522
+ sync ? sync.retcode : '-', ago(sync && sync.time),
523
+ session.lastSync ? session.lastSync.ret : '-', ago(session.lastSync && session.lastSync.time),
524
+ session.lastSend ? session.lastSend.ret : '-', ago(session.lastSend && session.lastSend.time),
525
+ ago(session.lastReceived), report.page ? report.page.roomCount : '-', report.hasDataTicket)
526
+ }
527
+
528
+ const ended = [session.lastSync, session.lastSend].find(a => a && LOGGED_OUT_RETCODES.includes(a.ret))
529
+ if (ended) {
530
+ if (END_SESSION_ON_RET) {
531
+ await this.sessionEnded(`${ended.api} Ret ${ended.ret}`)
532
+ return
533
+ }
534
+ 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.`)
535
+ } else {
536
+ this.healthClear('session')
537
+ }
538
+
539
+ const refused = refusedSession(session)
540
+ if (refused) {
541
+ if (END_REFUSED_SESSION) {
542
+ await this.sessionEnded(`the server refuses the session: ${refused}`)
543
+ return
544
+ }
545
+ this.healthAlert('refused', `the server refuses the session: ${refused}. Messages are neither sent nor received.`)
546
+ } else {
547
+ this.healthClear('refused')
548
+ }
549
+
550
+ // before the first answer, count from the login
551
+ const lastSyncCheck = sync ? sync.time : session.since
552
+ if (now - lastSyncCheck > SYNC_STALL_TIMEOUT) {
553
+ this.healthAlert('sync', sync
554
+ ? `synccheck stalled: no answer for ${minutesSince(lastSyncCheck)} minutes`
555
+ : `synccheck stalled: none answered in the ${minutesSince(lastSyncCheck)} minutes since login`)
556
+ } else {
557
+ this.healthClear('sync')
558
+ }
559
+
560
+ for (const [kind, answer] of [['webwxsync', session.lastSync], ['send', session.lastSend]] as const) {
561
+ if (answer && answer.failures >= API_FAILURES_ALERT) {
562
+ // When automatic ending of refused sessions is on, stay quiet during
563
+ // the 3-minute refusal grace window instead of sending a noisy API
564
+ // alert right before sessionEnded(). If failures stay below the
565
+ // refusal count past REFUSED_AFTER, alert normally.
566
+ const inRefusalGrace = END_REFUSED_SESSION
567
+ && isRefusalCandidate(answer)
568
+ && answer.failingSince !== null
569
+ && (now - answer.failingSince) < REFUSED_AFTER
570
+ if (inRefusalGrace) {
571
+ log.warn('PuppetWeChat', 'health: %s failing with Ret %s (%s in a row), waiting for refusal threshold',
572
+ answer.api, answer.ret, answer.failures)
573
+ } else {
574
+ this.healthAlert(kind, `${answer.api} keeps failing: ${answer.ret}, ${answer.failures} times in a row`)
575
+ }
576
+ } else {
577
+ this.healthClear(kind)
578
+ }
579
+ }
580
+
581
+ const sent = session.sentWithoutSync
582
+ if (sent && now - sent > SEND_SYNC_TIMEOUT) {
583
+ const received = session.lastReceived
584
+ ? `, last message received ${minutesSince(session.lastReceived)} minutes ago`
585
+ : ''
586
+ this.healthAlert('receive', `not receiving messages: nothing came from the server in the ${minutesSince(sent)} minutes since a message was sent${received}`)
587
+ } else {
588
+ this.healthClear('receive')
589
+ }
590
+
591
+ if (!report.hasDataTicket) {
592
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login')
593
+ } else {
594
+ this.healthClear('ticket')
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Log every time, emit an error at most once an hour per kind, so the
600
+ * application can notify someone without flooding them.
601
+ */
602
+ private healthAlert (kind: string, message: string): void {
603
+ log.warn('PuppetWeChat', 'health: %s', message)
604
+ const last = this.healthAlertTimes[kind]
605
+ if (last && Date.now() - last < HEALTH_ALERT_INTERVAL) {
606
+ return
607
+ }
608
+ this.healthAlertTimes[kind] = Date.now()
609
+ this.emit('error', { data: `health: ${message}` })
610
+ }
611
+
612
+ private healthClear (kind: string): void {
613
+ if (this.healthAlertTimes[kind]) {
614
+ log.info('PuppetWeChat', 'health: %s recovered', kind)
615
+ delete this.healthAlertTimes[kind]
616
+ }
617
+ }
618
+
619
+ /**
620
+ * The server ended the session: mark the bot logged out with the reason.
621
+ * The web app goes to its login page by itself after a synccheck retcode.
622
+ * It stays where it is after a failing webwxsync or send: then the
623
+ * session's cookies are dropped, which brings the login page (a plain
624
+ * reload would bring back the same session), where the page waits quietly
625
+ * until a person triggers login confirmation or a QR code from the console.
626
+ */
627
+ private async sessionEnded (reason: string, reload = true): Promise<void> {
628
+ if (!this.id) {
629
+ return
630
+ }
631
+ log.warn('PuppetWeChat', 'sessionEnded() the server ended the web session: %s', reason)
632
+ this.logoutLocally(reason)
633
+ if (!reload) {
634
+ return
635
+ }
636
+ try {
637
+ await this.bridge.dropSession()
638
+ await this.saveCookie().catch(e => {
639
+ log.error('PuppetWeChat', 'sessionEnded() saveCookie() rejection: %s', e && e.message)
640
+ })
641
+ } catch (e) {
642
+ log.error('PuppetWeChat', 'sessionEnded() dropSession() rejection: %s', e && e.message)
643
+ try {
644
+ await this.bridge.reload()
645
+ } catch (e) {
646
+ log.error('PuppetWeChat', 'sessionEnded() reload rejection: %s', e && e.message)
647
+ }
648
+ }
649
+ }
650
+
651
+ private async waitForLoginPage (
652
+ predicate: (state: LoginPageState) => boolean = () => true,
653
+ timeoutMs = 8000,
654
+ ): Promise<null | LoginPageState> {
655
+ const deadline = Date.now() + timeoutMs
656
+ let last: null | LoginPageState = null
657
+ while (Date.now() < deadline) {
658
+ if (this.logonoff()) {
659
+ return null
660
+ }
661
+ try {
662
+ last = await this.bridge.loginPageState()
663
+ if (last && predicate(last)) {
664
+ return last
665
+ }
666
+ } catch (e) {
667
+ // page may still be navigating
668
+ }
669
+ await new Promise(resolve => setTimeout(resolve, 400))
670
+ }
671
+ return last
672
+ }
673
+
674
+ /**
675
+ * Drop the current web session (even if the page still thinks it is logged
676
+ * in) and land on the login page without automatically nagging the phone.
677
+ */
678
+ public async forceRelogin (preferQrcode = false): Promise<null | LoginPageState> {
679
+ if (this.id) {
680
+ this.logoutLocally('manual relogin')
681
+ }
682
+ await this.bridge.dropSession(preferQrcode)
683
+ await this.saveCookie().catch(e => {
684
+ log.error('PuppetWeChat', 'forceRelogin() saveCookie() rejection: %s', e && e.message)
685
+ })
686
+ return this.waitForLoginPage()
687
+ }
688
+
689
+ /**
690
+ * Trigger a one-tap phone login confirmation on demand. If the server
691
+ * refuses or no phone auth ticket is present, falls back to a fresh QR code
692
+ * and reports which mode is now active on the login page.
693
+ */
694
+ public async requestPhoneConfirm (): Promise<PhoneConfirmResult> {
695
+ if (this.id) {
696
+ await this.forceRelogin(false)
697
+ }
698
+ let state = await this.waitForLoginPage(() => true, 4000)
699
+ if (!state) {
700
+ state = await this.forceRelogin(false)
701
+ }
702
+ if (!state) {
703
+ throw new Error('Login page is not ready yet')
704
+ }
705
+ if (!state.canConfirmOnPhone) {
706
+ const offered = await this.bridge.offerConfirmOnPhone()
707
+ if (!offered) {
708
+ const qr = await this.requestLoginQrcode()
709
+ return {
710
+ canConfirmOnPhone : false,
711
+ mode : 'qrcode',
712
+ qrcodeUrl : qr.qrcodeUrl,
713
+ waitingForPhone : false,
714
+ }
715
+ }
716
+ await this.bridge.reload()
717
+ state = await this.waitForLoginPage(s => s.canConfirmOnPhone || s.hasQrcode)
718
+ }
719
+ if (!state || !state.canConfirmOnPhone) {
720
+ const qr = await this.requestLoginQrcode()
721
+ return {
722
+ canConfirmOnPhone : false,
723
+ mode : 'qrcode',
724
+ qrcodeUrl : qr.qrcodeUrl,
725
+ waitingForPhone : false,
726
+ }
727
+ }
728
+ await this.bridge.pushLoginConfirm()
729
+ // Give webwxpushloginurl a moment to either start waiting on the phone or
730
+ // fall back to showing a QR code if the server refused the auth ticket.
731
+ await new Promise(resolve => setTimeout(resolve, 1500))
732
+ if (this.logonoff()) {
733
+ return {
734
+ canConfirmOnPhone : true,
735
+ mode : 'phone',
736
+ qrcodeUrl : null,
737
+ waitingForPhone : false,
738
+ }
739
+ }
740
+ const after = await this.waitForLoginPage(s => s.waitingForPhone || s.hasQrcode, 4000) || state
741
+ if (this.logonoff() || after.waitingForPhone) {
742
+ return {
743
+ canConfirmOnPhone : true,
744
+ mode : 'phone',
745
+ qrcodeUrl : null,
746
+ waitingForPhone : !this.logonoff(),
747
+ }
748
+ }
749
+ return {
750
+ canConfirmOnPhone : !!after.canConfirmOnPhone,
751
+ mode : 'qrcode',
752
+ qrcodeUrl : after.qrcodeUrl,
753
+ waitingForPhone : false,
754
+ }
755
+ }
756
+
757
+ /**
758
+ * Show a fresh QR code on the login page on demand (dropping the current
759
+ * session first if still logged in).
760
+ */
761
+ public async requestLoginQrcode (): Promise<{ qrcodeUrl: null | string }> {
762
+ if (this.id) {
763
+ await this.forceRelogin(true)
764
+ } else {
765
+ await this.bridge.showLoginQrcode()
766
+ }
767
+ const state = await this.waitForLoginPage(s => s.hasQrcode && !!s.qrcodeUrl)
768
+ return { qrcodeUrl: state ? state.qrcodeUrl : null }
769
+ }
770
+
771
+ /**
772
+ * A failed webwxsync or send answer, as the bridge saw it. Remember it for
773
+ * the logout reason; the minute's check decides what to report.
774
+ */
775
+ private onApiRet (data: ApiAnswer): void {
776
+ log.warn('PuppetWeChat', 'onApiRet() %s answered %s (%s in a row)', data.api, data.ret, data.failures)
777
+ this.lastApiFailure = data
778
+ if (LOGGED_OUT_RETCODES.includes(data.ret)) {
779
+ // don't wait for the minute to pass
780
+ this.checkHealth().catch(e => {
781
+ log.error('PuppetWeChat', 'onApiRet() checkHealth() rejection: %s', e && e.message)
782
+ })
783
+ }
784
+ }
785
+
786
+ private onSyncCheck (data: { retcode: string, selector: string }): void {
787
+ log.warn('PuppetWeChat', 'onSyncCheck() retcode %s selector %s', data.retcode, data.selector)
788
+ this.lastSyncCheckFailure = { ...data, time: Date.now() }
789
+ if (LOGGED_OUT_RETCODES.includes(data.retcode)) {
790
+ // act now rather than at the next minute's check; the web app is
791
+ // already on its way to the login page
792
+ this.sessionEnded(`synccheck retcode ${data.retcode}`, false).catch(e => {
793
+ log.error('PuppetWeChat', 'onSyncCheck() sessionEnded() rejection: %s', e && e.message)
794
+ })
795
+ }
796
+ }
797
+
798
+ /**
799
+ * Mark the bot logged out without telling the page to log out: used when
800
+ * the server has already ended the session.
801
+ */
802
+ private logoutLocally (reason: string): void {
803
+ const user = this.id
804
+ if (!user) {
805
+ return
806
+ }
807
+ this.id = undefined
808
+ this.emit('logout', { contactId: user, data: reason })
809
+ }
810
+
811
+ public async roomTopicList (): Promise<Array<{ id: string, topic: string, memberCount: number }>> {
812
+ const list = await this.bridge.roomTopicList()
813
+ return list.map(r => ({ ...r, topic: plainText(r.topic || '') }))
814
+ }
815
+
301
816
  private async initBridge (): Promise<Bridge> {
302
817
  log.verbose('PuppetWeChat', 'initBridge()')
303
818
 
@@ -317,6 +832,8 @@ export class PuppetWeChat extends Puppet {
317
832
  this.bridge.on('logout', Event.onLogout.bind(this))
318
833
  this.bridge.on('message', Event.onMessage.bind(this))
319
834
  this.bridge.on('scan', Event.onScan.bind(this))
835
+ this.bridge.on('synccheck', this.onSyncCheck.bind(this))
836
+ this.bridge.on('apiret', this.onApiRet.bind(this))
320
837
  this.bridge.on('unload', Event.onUnload.bind(this))
321
838
 
322
839
  try {
@@ -533,8 +1050,8 @@ export class PuppetWeChat extends Puppet {
533
1050
 
534
1051
  try {
535
1052
  const ret = await this.bridge.forward(baseData, patchData)
536
- if (!ret) {
537
- throw new Error('forward failed')
1053
+ if (ret !== true) {
1054
+ throw new Error('forward failed: ' + (ret || 'page error') + this.bridge.lastSendFailure())
538
1055
  }
539
1056
  } catch (e) {
540
1057
  log.error('PuppetWeChat', 'forward() exception: %s', e.message)
@@ -557,14 +1074,19 @@ export class PuppetWeChat extends Puppet {
557
1074
  }
558
1075
 
559
1076
  public async login (userId: string): Promise<void> {
1077
+ // failures of the session before this one say nothing about a later logout
1078
+ this.lastSyncCheckFailure = undefined
1079
+ this.lastApiFailure = undefined
1080
+ this.pageFailures = 0
1081
+ this.bridge.monitor.reset(userId)
560
1082
  return super.login(userId)
561
1083
  }
562
1084
 
563
1085
  /**
564
1086
  * logout from browser, then server will emit `logout` event
565
1087
  */
566
- public async logout (): Promise<void> {
567
- log.verbose('PuppetWeChat', 'logout()')
1088
+ public async logout (reason = 'logout()'): Promise<void> {
1089
+ log.verbose('PuppetWeChat', 'logout(%s)', reason)
568
1090
 
569
1091
  const user = this.selfId()
570
1092
  if (!user) {
@@ -579,7 +1101,7 @@ export class PuppetWeChat extends Puppet {
579
1101
  throw e
580
1102
  } finally {
581
1103
  this.id = undefined
582
- this.emit('logout', { contactId: user, data: 'logout()' })
1104
+ this.emit('logout', { contactId: user, data: reason })
583
1105
  }
584
1106
  }
585
1107
 
@@ -1370,6 +1892,11 @@ export class PuppetWeChat extends Puppet {
1370
1892
  const cookie = await this.bridge.cookies()
1371
1893
  const first = cookie.find(c => c.name === 'webwx_data_ticket')
1372
1894
  const webwxDataTicket = first && first.value
1895
+ if (!webwxDataTicket) {
1896
+ // without it the upload form can't even be built
1897
+ this.healthAlert('ticket', 'webwx_data_ticket missing: files cannot be sent until the next login')
1898
+ throw new Error('webwx_data_ticket missing: log in again to send files')
1899
+ }
1373
1900
  const size = buffer.length
1374
1901
  const fromUserName = this.selfId()
1375
1902
  const id = 'WU_FILE_' + this.fileId
@@ -1603,15 +2130,15 @@ export class PuppetWeChat extends Puppet {
1603
2130
  mediaData.MediaId,
1604
2131
  mediaData.MsgType,
1605
2132
  )
1606
- let ret = false
2133
+ let ret: true | string | false = false
1607
2134
  try {
1608
2135
  ret = await this.bridge.sendMedia(mediaData)
1609
2136
  } catch (e) {
1610
2137
  log.error('PuppetWeChat', 'sendMedia() exception: %s', e.message)
1611
2138
  throw e
1612
2139
  }
1613
- if (!ret) {
1614
- throw new Error('sendMedia fail')
2140
+ if (ret !== true) {
2141
+ throw new Error('sendMedia failed: ' + (ret || 'page error') + this.bridge.lastSendFailure())
1615
2142
  }
1616
2143
  }
1617
2144