@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
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env ts-node
2
+
3
+ import test from 'blue-tape'
4
+
5
+ import {
6
+ ApiAnswer,
7
+ REFUSED_AFTER,
8
+ REFUSED_SEND_FAILURES,
9
+ REFUSED_SYNC_FAILURES,
10
+ SessionHealth,
11
+ SessionMonitor,
12
+ isRefusalCandidate,
13
+ refusedSession,
14
+ } from './session-monitor'
15
+
16
+ function health (lastSync: null | ApiAnswer, lastSend: null | ApiAnswer = null, now = Date.now()): SessionHealth {
17
+ return {
18
+ lastReceived : null,
19
+ lastSend,
20
+ lastSync,
21
+ now,
22
+ sentWithoutSync : null,
23
+ since : now - 3600 * 1000,
24
+ syncCheck : null,
25
+ }
26
+ }
27
+
28
+ function answer (api: string, ret: string, failures: number, failingFor: number, now = Date.now()): ApiAnswer {
29
+ return { api, failingSince: failures ? now - failingFor : null, failures, ret, time: now }
30
+ }
31
+
32
+ test('SessionMonitor remembers when a failing streak started', async t => {
33
+ const monitor = new SessionMonitor()
34
+ const first = monitor.onApiAnswer('webwxsync', '3', Date.now())
35
+ t.equal(first.failures, 1, 'first failure counted')
36
+ t.ok(first.failingSince, 'streak start set')
37
+
38
+ const second = monitor.onApiAnswer('webwxsync', '3', Date.now())
39
+ t.equal(second.failures, 2, 'second failure counted')
40
+ t.equal(second.failingSince, first.failingSince, 'streak start kept')
41
+
42
+ const ok = monitor.onApiAnswer('webwxsync', '0', Date.now())
43
+ t.equal(ok.failingSince, null, 'a success ends the streak')
44
+ const again = monitor.onApiAnswer('webwxsync', '3', Date.now())
45
+ t.ok(again.failingSince && again.failingSince >= ok.time, 'a new streak starts after the success')
46
+ })
47
+
48
+ test('refusedSession() on the 2026-12-06 pattern: webwxsync Ret 3 for minutes', async t => {
49
+ const reason = refusedSession(health(answer('webwxsync', '3', 40000, 4 * 3600 * 1000)))
50
+ t.ok(reason, 'refused')
51
+ t.ok(reason && /webwxsync answered Ret 3/.test(reason), 'reason names the call and Ret: ' + reason)
52
+ })
53
+
54
+ test('refusedSession() waits for both enough failures and enough time', async t => {
55
+ t.notOk(refusedSession(health(answer('webwxsync', '3', REFUSED_SYNC_FAILURES - 1, REFUSED_AFTER * 2))), 'too few failures')
56
+ t.notOk(refusedSession(health(answer('webwxsync', '3', 500, REFUSED_AFTER - 1000))), 'not long enough')
57
+ t.ok(refusedSession(health(answer('webwxsync', '3', REFUSED_SYNC_FAILURES, REFUSED_AFTER))), 'both reached')
58
+ })
59
+
60
+ test('refusedSession() ignores what does not come from the server, and rate limiting', async t => {
61
+ t.notOk(refusedSession(health(answer('webwxsync', 'request failed: net::ERR_ABORTED', 500, REFUSED_AFTER * 2))), 'network failure')
62
+ t.notOk(refusedSession(health(answer('webwxsync', '1205', 500, REFUSED_AFTER * 2))), '1205 is rate limiting')
63
+ t.notOk(refusedSession(health(answer('webwxsync', '0', 0, 0))), 'working session')
64
+ t.notOk(refusedSession(health(null)), 'nothing seen yet')
65
+ })
66
+
67
+ test('refusedSession() on sends alone', async t => {
68
+ const sync = answer('webwxsync', '0', 0, 0)
69
+ t.notOk(refusedSession(health(sync, answer('webwxsendmsg', '3', REFUSED_SEND_FAILURES - 1, REFUSED_AFTER * 2))), 'too few sends')
70
+ t.ok(refusedSession(health(sync, answer('webwxsendmsg', '3', REFUSED_SEND_FAILURES, REFUSED_AFTER))), 'sends refused for long enough')
71
+ })
72
+
73
+ test('isRefusalCandidate() distinguishes server refusals from rate limiting and network errors', async t => {
74
+ t.ok(isRefusalCandidate(answer('webwxsync', '3', 3, 60 * 1000)), 'Ret 3 is a refusal candidate')
75
+ t.ok(isRefusalCandidate(answer('webwxsendappmsg', '-1', 3, 60 * 1000)), 'Ret -1 is a refusal candidate')
76
+ t.notOk(isRefusalCandidate(answer('webwxsendmsg', '1205', 3, 60 * 1000)), '1205 is rate limiting')
77
+ t.notOk(isRefusalCandidate(answer('webwxsync', 'request failed: net::ERR_ABORTED', 3, 60 * 1000)), 'network error is not a refusal')
78
+ t.notOk(isRefusalCandidate(answer('webwxsync', '0', 0, 0)), 'success is not a refusal')
79
+ t.notOk(isRefusalCandidate(null), 'null is not a refusal')
80
+ })
@@ -0,0 +1,219 @@
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
+ // when the first of those failed answers came, null after a success
24
+ failingSince : null | number,
25
+ // BaseResponse.Ret, or what went wrong with the request itself
26
+ ret : string,
27
+ time : number,
28
+ }
29
+
30
+ export interface SessionHealth {
31
+ now : number,
32
+ // when the monitor was last reset: the login it is watching
33
+ since : number,
34
+ syncCheck : null | SyncCheckAnswer,
35
+ lastSync : null | ApiAnswer,
36
+ lastSend : null | ApiAnswer,
37
+ // last time webwxsync brought a message from someone else
38
+ lastReceived : null | number,
39
+ // when the first message since the last webwxsync answer was sent
40
+ sentWithoutSync : null | number,
41
+ }
42
+
43
+ // webwxsync and the calls that send a message, by the last part of their path
44
+ const API_REGEX = /\/(webwxsync|webwxsendmsg|webwxsendappmsg|webwxsendmsgimg|webwxsendvideomsg|webwxsendemoticon)(\?|$)/
45
+ const SYNCCHECK_REGEX = /\/synccheck(\?|$)/
46
+ // window.synccheck={retcode:"0",selector:"2"}
47
+ const SYNCCHECK_BODY_REGEX = /retcode\s*:\s*"?(\d+)"?\s*,\s*selector\s*:\s*"?(\d+)"?/
48
+ // a notice that a chat was opened on the phone, not a message
49
+ const MSGTYPE_STATUSNOTIFY = 51
50
+
51
+ export type WatchedCall = 'synccheck' | string
52
+
53
+ /**
54
+ * The call a request URL makes, when it is one we watch.
55
+ */
56
+ export function watchedCall (url: string): undefined | WatchedCall {
57
+ if (SYNCCHECK_REGEX.test(url)) {
58
+ return 'synccheck'
59
+ }
60
+ const match = API_REGEX.exec(url)
61
+ return match ? match[1] : undefined
62
+ }
63
+
64
+ export function parseSyncCheck (body: string): undefined | { retcode: string, selector: string } {
65
+ const match = SYNCCHECK_BODY_REGEX.exec(body)
66
+ return match ? { retcode: match[1], selector: match[2] } : undefined
67
+ }
68
+
69
+ // A session the server stopped serving keeps answering synccheck as usual,
70
+ // while webwxsync and every send answer an error (seen: BaseResponse.Ret 3,
71
+ // with the session's Sid still recognised: a wrong Sid answers 1101). The
72
+ // web app retries webwxsync a few times a second and never leaves, and a
73
+ // reload brings back the same refused session. Errors that last this long,
74
+ // with nothing succeeding in between, mean the session is gone.
75
+ export const REFUSED_AFTER = 3 * 60 * 1000
76
+ export const REFUSED_SYNC_FAILURES = 10
77
+ export const REFUSED_SEND_FAILURES = 5
78
+ // 1205 is the server asking us to send less; the web app logs out on it by
79
+ // itself.
80
+ const NOT_REFUSAL = ['1205']
81
+
82
+ /**
83
+ * Whether an API failure looks like the server refusing the session (numeric
84
+ * BaseResponse.Ret other than 1205 rate limiting), rather than a transient
85
+ * network error.
86
+ */
87
+ export function isRefusalCandidate (answer: null | ApiAnswer): boolean {
88
+ if (!answer || !answer.failingSince || answer.failures <= 0) {
89
+ return false
90
+ }
91
+ return /^-?\d+$/.test(answer.ret) && !NOT_REFUSAL.includes(answer.ret)
92
+ }
93
+
94
+ /**
95
+ * Why the session counts as refused by the server, or undefined while it
96
+ * does not. Only answers from the server count: a request that failed on the
97
+ * way (`request failed: ...`) says nothing about the session.
98
+ */
99
+ export function refusedSession (health: SessionHealth): undefined | string {
100
+ const checks: Array<[null | ApiAnswer, number]> = [
101
+ [health.lastSync, REFUSED_SYNC_FAILURES],
102
+ [health.lastSend, REFUSED_SEND_FAILURES],
103
+ ]
104
+ for (const [answer, minFailures] of checks) {
105
+ if (!answer || !isRefusalCandidate(answer) || answer.failures < minFailures) {
106
+ continue
107
+ }
108
+ const failingSince = answer.failingSince as number
109
+ const minutes = (health.now - failingSince) / 60000
110
+ if (health.now - failingSince >= REFUSED_AFTER) {
111
+ return `${answer.api} answered Ret ${answer.ret} ${answer.failures} times in a row for ${Math.round(minutes)} minutes`
112
+ }
113
+ }
114
+ return undefined
115
+ }
116
+
117
+ export class SessionMonitor {
118
+
119
+ private since = Date.now()
120
+ private selfId? : string
121
+ private syncCheck : null | SyncCheckAnswer = null
122
+ private lastSync : null | ApiAnswer = null
123
+ private lastSend : null | ApiAnswer = null
124
+ private lastReceived : null | number = null
125
+ private sentWithoutSync : null | number = null
126
+
127
+ /**
128
+ * A new login: what the session before it left behind says nothing about
129
+ * this one.
130
+ */
131
+ public reset (selfId?: string): void {
132
+ this.since = Date.now()
133
+ this.selfId = selfId
134
+ this.syncCheck = null
135
+ this.lastSync = null
136
+ this.lastSend = null
137
+ this.lastReceived = null
138
+ this.sentWithoutSync = null
139
+ }
140
+
141
+ /**
142
+ * The page went to another document: requests in flight are gone, so a
143
+ * send still waiting for its sync would wait for ever.
144
+ */
145
+ public navigated (): void {
146
+ this.sentWithoutSync = null
147
+ }
148
+
149
+ public onSyncCheck (answer: { retcode: string, selector: string }): SyncCheckAnswer {
150
+ this.syncCheck = { ...answer, time: Date.now() }
151
+ return this.syncCheck
152
+ }
153
+
154
+ /**
155
+ * An answer of webwxsync or of a send. `started` is when its request left.
156
+ * `messages` are webwxsync's new messages.
157
+ */
158
+ public onApiAnswer (
159
+ api : string,
160
+ ret : string,
161
+ started : number,
162
+ messages : Array<{ FromUserName?: string, MsgType?: number }> = [],
163
+ ): ApiAnswer {
164
+ const isSync = api === 'webwxsync'
165
+ const previous = isSync ? this.lastSync : this.lastSend
166
+ const now = Date.now()
167
+ const failures = ret === '0' ? 0 : ((previous && previous.failures) || 0) + 1
168
+ const failingSince = ret === '0'
169
+ ? null
170
+ : (previous && previous.failures && previous.failingSince) || now
171
+ const answer = { api, failingSince, failures, ret, time: now }
172
+
173
+ if (isSync) {
174
+ this.lastSync = answer
175
+ } else {
176
+ this.lastSend = answer
177
+ }
178
+ if (ret !== '0') {
179
+ return answer
180
+ }
181
+
182
+ if (!isSync) {
183
+ // Each send makes the server report a change, which the page fetches
184
+ // with webwxsync within a second. That sync can be answered before the
185
+ // send's own answer arrives: one answered since the request left
186
+ // already covers it. Otherwise wait for one, from the first send on.
187
+ const sync = this.lastSync
188
+ const covered = !!sync && sync.ret === '0' && sync.time > started
189
+ if (!covered && !this.sentWithoutSync) {
190
+ this.sentWithoutSync = answer.time
191
+ }
192
+ return answer
193
+ }
194
+
195
+ this.sentWithoutSync = null
196
+ const fromOthers = messages.some(m =>
197
+ m.MsgType !== MSGTYPE_STATUSNOTIFY && !!m.FromUserName && m.FromUserName !== this.selfId,
198
+ )
199
+ if (fromOthers) {
200
+ this.lastReceived = answer.time
201
+ }
202
+ return answer
203
+ }
204
+
205
+ public health (): SessionHealth {
206
+ return {
207
+ lastReceived : this.lastReceived,
208
+ lastSend : this.lastSend,
209
+ lastSync : this.lastSync,
210
+ now : Date.now(),
211
+ sentWithoutSync : this.sentWithoutSync,
212
+ since : this.since,
213
+ syncCheck : this.syncCheck,
214
+ }
215
+ }
216
+
217
+ }
218
+
219
+ export default SessionMonitor
@@ -268,6 +268,57 @@
268
268
  setTimeout(() => checkScan(), 1000)
269
269
  }
270
270
 
271
+ /**
272
+ * chatFactory.sendMessage() posts in the background and later sets the
273
+ * message's MMStatus to success or failure. Wait for that, so a message
274
+ * WeChat refused is reported as failed instead of sent.
275
+ */
276
+ // the web app retries a send 3 times, 15s each, before it marks it failed
277
+ const SEND_CONFIRM_TIMEOUT = 75 * 1000
278
+
279
+ function sentResult (m) {
280
+ const confFactory = WechatyBro.glue.confFactory
281
+ const started = Date.now()
282
+ return new Promise(function (resolve) {
283
+ (function check () {
284
+ if (m.MMStatus === confFactory.MSG_SEND_STATUS_SUCC) {
285
+ return resolve(true)
286
+ }
287
+ if (m.MMStatus === confFactory.MSG_SEND_STATUS_FAIL) {
288
+ return resolve('WeChat refused the message')
289
+ }
290
+ if (Date.now() - started > SEND_CONFIRM_TIMEOUT) {
291
+ return resolve('no answer from WeChat in ' + (SEND_CONFIRM_TIMEOUT / 1000) + 's')
292
+ }
293
+ setTimeout(check, 200)
294
+ })()
295
+ })
296
+ }
297
+
298
+ function health () {
299
+ const loginScope = WechatyBro.glue.loginScope
300
+ let roomCount = null
301
+ try {
302
+ roomCount = WechatyBro.glue.contactFactory.getAllChatroomContact().length
303
+ } catch (e) {}
304
+ return {
305
+ loginState : loginState(),
306
+ loginCode : loginScope ? loginScope.code : null,
307
+ now : Date.now(),
308
+ roomCount,
309
+ userName : getUserName(),
310
+ }
311
+ }
312
+
313
+ function roomTopicList () {
314
+ return WechatyBro.glue.contactFactory.getAllChatroomContact()
315
+ .map(r => ({
316
+ id : r.UserName,
317
+ memberCount : (r.MemberList || []).length,
318
+ topic : r.NickName || '',
319
+ }))
320
+ }
321
+
271
322
  function ding (data) {
272
323
  log('recv ding')
273
324
  return data || 'dong'
@@ -431,11 +482,11 @@
431
482
 
432
483
  chatFactory.appendMessage(m)
433
484
  chatFactory.sendMessage(m)
485
+ return sentResult(m)
434
486
  } catch (e) {
435
487
  log('sendMedia() exception: ' + e.message)
436
488
  return false
437
489
  }
438
- return true
439
490
  }
440
491
 
441
492
  function forward (baseData, patchData) {
@@ -455,11 +506,11 @@
455
506
 
456
507
  chatFactory.appendMessage(m)
457
508
  chatFactory.sendMessage(m)
509
+ return sentResult(m)
458
510
  } catch (e) {
459
511
  log('forward() exception: ' + e.message)
460
512
  return false
461
513
  }
462
- return true
463
514
  }
464
515
 
465
516
  function send (ToUserName, Content) {
@@ -478,11 +529,11 @@
478
529
  })
479
530
  chatFactory.appendMessage(m)
480
531
  chatFactory.sendMessage(m)
532
+ return sentResult(m)
481
533
  } catch (e) {
482
534
  log('send() exception: ' + e.message)
483
535
  return false
484
536
  }
485
- return true
486
537
  }
487
538
 
488
539
  function getMessage (id) {
@@ -811,6 +862,7 @@
811
862
 
812
863
  scanCode : null,
813
864
  heartBeatTimmer : null,
865
+
814
866
  },
815
867
 
816
868
  // funcs
@@ -846,6 +898,9 @@
846
898
  roomList,
847
899
  roomDelMember,
848
900
  roomModTopic,
901
+ roomTopicList,
902
+
903
+ health,
849
904
 
850
905
  // for Friend Request
851
906
  verifyUserRequest,