@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
@@ -1 +1 @@
1
- {"version":3,"file":"demo.js","sourceRoot":"","sources":["../../examples/demo.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAEH,4BAA4B;AAE5B,oCAAyC;AAUzC;;;;GAIG;AACH,MAAM,MAAM,GAAG,IAAI,kBAAY,EAAE,CAAA;AAEjC;;;;GAIG;AACH,MAAM;KACH,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;KACtB,EAAE,CAAC,OAAO,EAAG,OAAO,CAAC;KACrB,EAAE,CAAC,MAAM,EAAI,MAAM,CAAC;KACpB,EAAE,CAAC,OAAO,EAAG,OAAO,CAAC;KACrB,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAE3B;;;;GAIG;AACH,MAAM,CAAC,KAAK,EAAE;KACX,KAAK,CAAC,KAAK,EAAC,CAAC,EAAC,EAAE;IACf,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAA;IACrC,MAAM,MAAM,CAAC,IAAI,EAAE,CAAA;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;AAClB,CAAC,CAAC,CAAA;AAEJ;;;;GAIG;AAEH;;;;;GAKG;AACH,SAAS,MAAM,CAAE,OAAyB;IACxC,IAAI,OAAO,CAAC,MAAM,EAAE;QAClB,gCAAgC;QAChC,yCAAyC;QACzC,MAAM,cAAc,GAAG;YACrB,gCAAgC;YAChC,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC;SACnC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QAEV,OAAO,CAAC,IAAI,C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,IAAI,CAAC,GAAG,OAAO,CAAC,SAAS,WAAW,CAAC,CAAA;AAC/C,CAAC;AAED,SAAS,OAAO,CAAE,OAA0B;IAC1C,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC;;;;MAIE;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,SAAS,CAAE,OAA4B;IACpD,MAAM,cAAc,GAAG,MAAM,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IACrE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAA;AAC9C,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,GAAG;kBACE,MAAM,CAAC,OAAO,EAAE;;;;CAIjC,CAAA;AACD,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA"}
@@ -26,11 +26,11 @@ async function main() {
26
26
  return 1; // fail finally :(
27
27
  }
28
28
  async function unitTest() {
29
- const child = child_process_1.spawn('npm', [
29
+ const child = (0, child_process_1.spawn)('npm', [
30
30
  'run',
31
31
  'test:unit',
32
32
  ], {
33
- shell: true,
33
+ shell: true, // https://stackoverflow.com/a/39682805/1123955
34
34
  stdio: 'inherit',
35
35
  });
36
36
  return new Promise((resolve, reject) => {
@@ -1 +1 @@
1
- {"version":3,"file":"retry-unit-tests.js","sourceRoot":"","sources":["../../scripts/retry-unit-tests.ts"],"names":[],"mappings":";;AACA;;;;;;GAMG;;AAEH,4BAA4B;AAE5B,iDAAqC;AAErC,MAAM,aAAa,GAAG,CAAC,CAAA;AAEvB,KAAK,UAAU,IAAI;IACjB,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAA;IAEtC,IAAI,KAAK,GAAG,CAAC,CAAA;IACb,IAAI,IAAI,GAAG,KAAK,CAAA;IAChB,GAAG;QACD,OAAO,CAAC,IAAI,CAAC,iCAAiC,KAAK,EAAE,CAAC,CAAA;QACt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
  * limitations under the License.
17
17
  *
18
18
  */
19
- /// <reference types="node" />
20
19
  import { EventEmitter } from 'events';
21
20
  import { Browser, Dialog, LaunchOptions, Page, Protocol } from 'puppeteer';
21
+ import { SessionMonitor } from './session-monitor';
22
22
  import { MemoryCard } from 'memory-card';
23
23
  import { WebContactRawPayload, WebMessageMediaPayload, WebMessageRawPayload, WebRoomRawPayload } from './web-schemas';
24
24
  export interface InjectResult {
@@ -38,11 +38,20 @@ export declare class Bridge extends EventEmitter {
38
38
  private browser;
39
39
  private page;
40
40
  private state;
41
+ readonly monitor: SessionMonitor;
41
42
  constructor(options: BridgeOptions);
42
43
  start(): Promise<void>;
43
44
  initBrowser(): Promise<Browser>;
44
45
  onDialog(dialog: Dialog): Promise<void>;
45
46
  onLoad(page: Page): Promise<void>;
47
+ /**
48
+ * Feed the session monitor with the answers of the web app's own
49
+ * synccheck, webwxsync and send requests, as the browser reports them.
50
+ * This only listens: the page is not touched, and nothing here may throw
51
+ * into puppeteer's event handling.
52
+ */
53
+ private watchSession;
54
+ private onWatchedResponse;
46
55
  initPage(browser: Browser): Promise<Page>;
47
56
  private uosPatch;
48
57
  readyAngular(page: Page): Promise<void>;
@@ -71,8 +80,8 @@ export declare class Bridge extends EventEmitter {
71
80
  getPassticket(): Promise<string>;
72
81
  getCheckUploadUrl(): Promise<string>;
73
82
  getUploadMediaUrl(): Promise<string>;
74
- sendMedia(mediaData: WebMessageMediaPayload): Promise<boolean>;
75
- forward(baseData: WebMessageRawPayload, patchData: WebMessageRawPayload): Promise<boolean>;
83
+ sendMedia(mediaData: WebMessageMediaPayload): Promise<true | string | false>;
84
+ forward(baseData: WebMessageRawPayload, patchData: WebMessageRawPayload): Promise<true | string | false>;
76
85
  /**
77
86
  * Proxy Call to Wechaty in Bridge
78
87
  */
@@ -93,8 +102,77 @@ export declare class Bridge extends EventEmitter {
93
102
  */
94
103
  entryUrl(cookieList?: Protocol.Network.Cookie[]): string;
95
104
  reload(): Promise<void>;
105
+ /**
106
+ * Leave a session the server refuses for the login page. Reloading alone
107
+ * brings the refused session back: the server still renders the page as
108
+ * logged in for as long as its session cookies are there. So those go,
109
+ * while `webwx_auth_ticket` (valid for years) and `wxuin` stay: with them
110
+ * the login page can ask the phone to confirm instead of showing a QR code.
111
+ * When `preferQrcode` is true, `login_frequency` and `last_wxuin` are also
112
+ * dropped so the page lands directly on a fresh QR code while still keeping
113
+ * `webwx_auth_ticket` and `wxuin` for later phone confirmations.
114
+ */
115
+ dropSession(preferQrcode?: boolean): Promise<void>;
116
+ /**
117
+ * Make the login page offer confirming the login on the phone. False when
118
+ * the cookies needed for it are missing (no `webwx_auth_ticket` or
119
+ * `wxuin`): then only a QR code can log in.
120
+ */
121
+ offerConfirmOnPhone(list?: Cookie[]): Promise<boolean>;
122
+ /**
123
+ * What the web app's login page is doing, or null when it is not showing
124
+ * (logged in, or still loading).
125
+ */
126
+ loginPageState(): Promise<null | LoginPageState>;
127
+ /**
128
+ * Ask the phone to confirm the login, as the login page's "Log in" button
129
+ * does. The web app then waits for the confirmation and logs in by itself;
130
+ * when the server refuses to ask the phone, it shows a QR code instead.
131
+ */
132
+ pushLoginConfirm(): Promise<void>;
133
+ /**
134
+ * Stop waiting for the phone and show a fresh QR code. If the page is
135
+ * already on the QR code view (which may have expired), reload straight
136
+ * into a new QR code instead.
137
+ */
138
+ showLoginQrcode(): Promise<void>;
139
+ /**
140
+ * For the error of a send that just failed: what WeChat answered, when a
141
+ * failed answer came in during the last few seconds.
142
+ */
143
+ lastSendFailure(): string;
144
+ /**
145
+ * The page itself, for tools that need to look at it (screenshots,
146
+ * remote control). Undefined before start() and after stop().
147
+ */
148
+ currentPage(): undefined | Page;
149
+ /**
150
+ * State of the web app as the page sees it. Unlike evaluate(), errors are
151
+ * thrown: a closed page or a crashed browser must not look like a page that
152
+ * is merely still loading.
153
+ */
154
+ health(): Promise<null | BrowserHealth>;
155
+ roomTopicList(): Promise<Array<{
156
+ id: string;
157
+ topic: string;
158
+ memberCount: number;
159
+ }>>;
96
160
  evaluate(fn: () => any, ...args: any[]): Promise<any>;
97
161
  }
98
- export declare type Cookie = Protocol.Network.Cookie;
162
+ export interface BrowserHealth {
163
+ loginState: boolean;
164
+ loginCode: null | number | string;
165
+ now: number;
166
+ roomCount: null | number;
167
+ userName: null | string;
168
+ }
169
+ export interface LoginPageState {
170
+ canConfirmOnPhone: boolean;
171
+ code: null | number | string;
172
+ hasQrcode: boolean;
173
+ qrcodeUrl: null | string;
174
+ waitingForPhone: boolean;
175
+ }
176
+ export type Cookie = Protocol.Network.Cookie;
99
177
  export default Bridge;
100
178
  //# sourceMappingURL=bridge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../../src/bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;;AAGH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AAGrC,OAAO,EACL,OAAO,EAEP,MAAM,EAEN,aAAa,EACb,IAAI,EACJ,QAAQ,EACT,MAA4B,WAAW,CAAA;AAMxC,OAAO,EACL,UAAU,EACX,MAA4B,aAAa,CAAA;AAW1C,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EAClB,MAA6B,eAAe,CAAA;AAM7C,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAK,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAS,MAAM,CAAC;IACzB,IAAI,CAAC,EAAa,OAAO,CAAC;IAC1B,aAAa,CAAC,EAAI,aAAa,CAAC;IAChC,MAAM,EAAY,UAAU,CAAC;IAC7B,WAAW,CAAC,EAAM,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAU,MAAM,CAAA;CACzB;AAED,qBAAa,MAAO,SAAQ,YAAY;IAO7B,OAAO,EAAE,aAAa;IAL/B,OAAO,CAAC,OAAO,CAAsB;I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AAO,CAAC;CAC7B;AAKD,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAA;AAC5C,eAAe,MAAM,CAAA"}
@@ -31,6 +31,7 @@ const puppeteer_extra_1 = __importDefault(require("puppeteer-extra"));
31
31
  const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
32
32
  const state_switch_1 = require("state-switch");
33
33
  const xml2js_1 = require("xml2js");
34
+ const session_monitor_1 = require("./session-monitor");
34
35
  /* tslint:disable:no-var-requires */
35
36
  // const retryPromise = require('retry-promise').default
36
37
  const config_1 = require("./config");
@@ -39,6 +40,7 @@ class Bridge extends events_1.EventEmitter {
39
40
  constructor(options) {
40
41
  super();
41
42
  this.options = options;
43
+ this.monitor = new session_monitor_1.SessionMonitor();
42
44
  config_1.log.verbose('PuppetWeChatBridge', 'constructor()');
43
45
  this.state = new state_switch_1.StateSwitch('PuppetWeChatBridge', config_1.log);
44
46
  }
@@ -104,13 +106,13 @@ class Bridge extends events_1.EventEmitter {
104
106
  * Puppeteer 4.0
105
107
  * https://github.com/berstend/puppeteer-extra/issues/211#issuecomment-636283110
106
108
  */
107
- const plugin = puppeteer_extra_plugin_stealth_1.default();
109
+ const plugin = (0, puppeteer_extra_plugin_stealth_1.default)();
108
110
  plugin.onBrowser = () => { };
109
111
  puppeteer_extra_1.default.use(plugin);
110
112
  browser = await puppeteer_extra_1.default.launch(options);
111
113
  }
112
114
  else {
113
- browser = await puppeteer_1.launch(options);
115
+ browser = await (0, puppeteer_1.launch)(options);
114
116
  }
115
117
  const version = await browser.version();
116
118
  config_1.log.verbose('PuppetWeChatBridge', 'initBrowser() version: %s', version);
@@ -156,6 +158,94 @@ class Bridge extends events_1.EventEmitter {
156
158
  this.emit('error', e);
157
159
  }
158
160
  }
161
+ /**
162
+ * Feed the session monitor with the answers of the web app's own
163
+ * synccheck, webwxsync and send requests, as the browser reports them.
164
+ * This only listens: the page is not touched, and nothing here may throw
165
+ * into puppeteer's event handling.
166
+ */
167
+ watchSession(page) {
168
+ const started = new WeakMap();
169
+ page.on('request', request => {
170
+ try {
171
+ if ((0, session_monitor_1.watchedCall)(request.url())) {
172
+ started.set(request, Date.now());
173
+ }
174
+ }
175
+ catch (e) {
176
+ config_1.log.verbose('PuppetWeChatBridge', 'watchSession() request: %s', e && e.message);
177
+ }
178
+ });
179
+ page.on('response', response => {
180
+ this.onWatchedResponse(response, started).catch(e => {
181
+ config_1.log.verbose('PuppetWeChatBridge', 'watchSession() response: %s', e && e.message);
182
+ });
183
+ });
184
+ page.on('requestfailed', request => {
185
+ try {
186
+ const call = (0, session_monitor_1.watchedCall)(request.url());
187
+ // a synccheck that fails is simply asked again; its silence is
188
+ // what the stall check looks at
189
+ if (!call || call === 'synccheck') {
190
+ return;
191
+ }
192
+ const failure = request.failure();
193
+ const answer = this.monitor.onApiAnswer(call, 'request failed: ' + ((failure && failure.errorText) || 'unknown'), started.get(request) || Date.now());
194
+ this.emit('apiret', answer);
195
+ }
196
+ catch (e) {
197
+ config_1.log.verbose('PuppetWeChatBridge', 'watchSession() requestfailed: %s', e && e.message);
198
+ }
199
+ });
200
+ // a new document only: the web app also changes its URL inside one
201
+ // document, which leaves its requests alone
202
+ page.on('domcontentloaded', () => this.monitor.navigated());
203
+ }
204
+ async onWatchedResponse(response, started) {
205
+ const request = response.request();
206
+ const call = (0, session_monitor_1.watchedCall)(request.url());
207
+ if (!call) {
208
+ return;
209
+ }
210
+ let body;
211
+ try {
212
+ body = await response.text();
213
+ }
214
+ catch (e) {
215
+ // the page went elsewhere before the body could be read: no information
216
+ return;
217
+ }
218
+ if (call === 'synccheck') {
219
+ const parsed = response.status() === 200 && (0, session_monitor_1.parseSyncCheck)(body);
220
+ if (!parsed) {
221
+ return;
222
+ }
223
+ const answer = this.monitor.onSyncCheck(parsed);
224
+ if (answer.retcode !== '0') {
225
+ this.emit('synccheck', answer);
226
+ }
227
+ return;
228
+ }
229
+ let ret;
230
+ let messages;
231
+ if (response.status() !== 200) {
232
+ ret = 'http ' + response.status();
233
+ }
234
+ else {
235
+ try {
236
+ const json = JSON.parse(body);
237
+ ret = String(json.BaseResponse.Ret);
238
+ messages = json.AddMsgList;
239
+ }
240
+ catch (e) {
241
+ ret = 'unreadable answer';
242
+ }
243
+ }
244
+ const answer = this.monitor.onApiAnswer(call, ret, started.get(request) || Date.now(), messages);
245
+ if (ret !== '0') {
246
+ this.emit('apiret', answer);
247
+ }
248
+ }
159
249
  async initPage(browser) {
160
250
  config_1.log.verbose('PuppetWeChatBridge', 'initPage()');
161
251
  // set this in time because the following callbacks
@@ -168,6 +258,7 @@ class Bridge extends events_1.EventEmitter {
168
258
  await this.uosPatch(page);
169
259
  page.on('error', e => this.emit('error', e));
170
260
  page.on('dialog', this.onDialog.bind(this));
261
+ this.watchSession(page);
171
262
  const cookieList = (await this.options.memory.get(config_1.MEMORY_SLOT));
172
263
  const url = this.entryUrl(cookieList);
173
264
  config_1.log.verbose('PuppetWeChatBridge', 'initPage() before page.goto(url)');
@@ -452,9 +543,10 @@ class Bridge extends events_1.EventEmitter {
452
543
  throw new Error('cannot say nothing');
453
544
  }
454
545
  try {
546
+ // true once WeChat accepted the message, else why it was not sent
455
547
  const ret = await this.proxyWechaty('send', toUserName, text);
456
- if (!ret) {
457
- throw new Error('send fail');
548
+ if (ret !== true) {
549
+ throw new Error('send failed: ' + (ret || 'page error') + this.lastSendFailure());
458
550
  }
459
551
  }
460
552
  catch (e) {
@@ -514,7 +606,7 @@ class Bridge extends events_1.EventEmitter {
514
606
  }
515
607
  async getMessage(id) {
516
608
  try {
517
- return await config_1.retry(async (retryException, attempt) => {
609
+ return await (0, config_1.retry)(async (retryException, attempt) => {
518
610
  config_1.log.silly('PuppetWeChatBridge', 'getMessage(%s) retry attempt %d', id, attempt);
519
611
  try {
520
612
  const rawPayload = await this.proxyWechaty('getMessage', id);
@@ -536,7 +628,7 @@ class Bridge extends events_1.EventEmitter {
536
628
  }
537
629
  async getContact(id) {
538
630
  try {
539
- return await config_1.retry(async (retryException, attempt) => {
631
+ return await (0, config_1.retry)(async (retryException, attempt) => {
540
632
  config_1.log.silly('PuppetWeChatBridge', 'getContact(%s) retry attempt %d', id, attempt);
541
633
  try {
542
634
  const rawPayload = await this.proxyWechaty('getContact', id);
@@ -693,7 +785,7 @@ class Bridge extends events_1.EventEmitter {
693
785
  if (!matches) {
694
786
  return text;
695
787
  }
696
- return mod_1.unescapeHtml(matches[1]);
788
+ return (0, mod_1.unescapeHtml)(matches[1]);
697
789
  }
698
790
  async innerHTML() {
699
791
  const html = await this.evaluate(() => {
@@ -719,7 +811,7 @@ class Bridge extends events_1.EventEmitter {
719
811
  const tryXmlText = this.preHtmlToXml(text);
720
812
  // obj = JSON.parse(toJson(tryXmlText))
721
813
  obj = await new Promise((resolve, reject) => {
722
- xml2js_1.parseString(tryXmlText, { explicitArray: false }, (err, result) => {
814
+ (0, xml2js_1.parseString)(tryXmlText, { explicitArray: false }, (err, result) => {
723
815
  if (err) {
724
816
  return reject(err);
725
817
  }
@@ -909,6 +1001,186 @@ class Bridge extends events_1.EventEmitter {
909
1001
  }
910
1002
  await this.page.reload();
911
1003
  }
1004
+ /**
1005
+ * Leave a session the server refuses for the login page. Reloading alone
1006
+ * brings the refused session back: the server still renders the page as
1007
+ * logged in for as long as its session cookies are there. So those go,
1008
+ * while `webwx_auth_ticket` (valid for years) and `wxuin` stay: with them
1009
+ * the login page can ask the phone to confirm instead of showing a QR code.
1010
+ * When `preferQrcode` is true, `login_frequency` and `last_wxuin` are also
1011
+ * dropped so the page lands directly on a fresh QR code while still keeping
1012
+ * `webwx_auth_ticket` and `wxuin` for later phone confirmations.
1013
+ */
1014
+ async dropSession(preferQrcode = false) {
1015
+ config_1.log.verbose('PuppetWeChatBridge', 'dropSession(preferQrcode=%s)', preferQrcode);
1016
+ if (!this.page) {
1017
+ throw new Error('no page');
1018
+ }
1019
+ const page = this.page;
1020
+ const url = page.url();
1021
+ const list = await page.cookies();
1022
+ const toRemove = preferQrcode
1023
+ ? [...SESSION_COOKIES, 'login_frequency', 'last_wxuin']
1024
+ : SESSION_COOKIES;
1025
+ if (!preferQrcode) {
1026
+ await this.offerConfirmOnPhone(list);
1027
+ }
1028
+ const drop = list.filter(c => toRemove.includes(c.name));
1029
+ if (drop.length) {
1030
+ await page.deleteCookie(...drop.map(c => ({ domain: c.domain, name: c.name, path: c.path, url })));
1031
+ }
1032
+ config_1.log.info('PuppetWeChatBridge', 'dropSession() removed %s, reloading', drop.map(c => c.name).join(', ') || 'no cookies');
1033
+ await page.reload();
1034
+ }
1035
+ /**
1036
+ * Make the login page offer confirming the login on the phone. False when
1037
+ * the cookies needed for it are missing (no `webwx_auth_ticket` or
1038
+ * `wxuin`): then only a QR code can log in.
1039
+ */
1040
+ async offerConfirmOnPhone(list) {
1041
+ if (!this.page) {
1042
+ throw new Error('no page');
1043
+ }
1044
+ const page = this.page;
1045
+ list = list || await page.cookies();
1046
+ const uin = list.find(c => c.name === 'wxuin' && !!c.value);
1047
+ const ticket = list.find(c => c.name === 'webwx_auth_ticket' && !!c.value);
1048
+ if (!uin || !ticket) {
1049
+ return false;
1050
+ }
1051
+ const host = new URL(page.url()).hostname;
1052
+ // the web app sets these for two days
1053
+ const expires = Math.floor(Date.now() / 1000) + 2 * 24 * 3600;
1054
+ await page.setCookie({ domain: host, expires, name: 'login_frequency', path: '/', value: '2' }, { domain: host, expires, name: 'last_wxuin', path: '/', value: uin.value });
1055
+ return true;
1056
+ }
1057
+ /**
1058
+ * What the web app's login page is doing, or null when it is not showing
1059
+ * (logged in, or still loading).
1060
+ */
1061
+ async loginPageState() {
1062
+ if (!this.page) {
1063
+ throw new Error('no page');
1064
+ }
1065
+ return this.page.evaluate(() => {
1066
+ const w = window;
1067
+ if (w.MMCgi && w.MMCgi.isLogin) {
1068
+ return null;
1069
+ }
1070
+ const scope = w.angular && w.angular.element('[ng-controller="loginController"]').scope();
1071
+ if (!scope) {
1072
+ return null;
1073
+ }
1074
+ return {
1075
+ canConfirmOnPhone: !!scope.isAssociationLogin,
1076
+ code: scope.code === undefined ? null : scope.code,
1077
+ hasQrcode: !!scope.qrcodeUrl,
1078
+ // scope.qrcodeUrl is the image URL (/qrcode/<uuid>); convert it to the
1079
+ // scannable QR payload (/l/<uuid>), matching Event.onScan.
1080
+ qrcodeUrl: scope.qrcodeUrl ? String(scope.qrcodeUrl).replace(/\/qrcode\//, '/l/') : null,
1081
+ waitingForPhone: !!scope.isWaitingAsConfirm,
1082
+ };
1083
+ });
1084
+ }
1085
+ /**
1086
+ * Ask the phone to confirm the login, as the login page's "Log in" button
1087
+ * does. The web app then waits for the confirmation and logs in by itself;
1088
+ * when the server refuses to ask the phone, it shows a QR code instead.
1089
+ */
1090
+ async pushLoginConfirm() {
1091
+ if (!this.page) {
1092
+ throw new Error('no page');
1093
+ }
1094
+ await this.page.evaluate(() => {
1095
+ const w = window;
1096
+ const scope = w.angular && w.angular.element('[ng-controller="loginController"]').scope();
1097
+ if (!scope) {
1098
+ throw new Error('Login page is not loaded yet');
1099
+ }
1100
+ // a confirmation asked before is still being waited for
1101
+ if (w.checkLoginPromise) {
1102
+ w.checkLoginPromise.abort();
1103
+ w.checkLoginPromise = null;
1104
+ }
1105
+ scope.$apply(() => scope.associationLogin());
1106
+ });
1107
+ }
1108
+ /**
1109
+ * Stop waiting for the phone and show a fresh QR code. If the page is
1110
+ * already on the QR code view (which may have expired), reload straight
1111
+ * into a new QR code instead.
1112
+ */
1113
+ async showLoginQrcode() {
1114
+ if (!this.page) {
1115
+ throw new Error('no page');
1116
+ }
1117
+ const switched = await this.page.evaluate(() => {
1118
+ const w = window;
1119
+ const scope = w.angular && w.angular.element('[ng-controller="loginController"]').scope();
1120
+ if (!scope) {
1121
+ return false;
1122
+ }
1123
+ if (w.checkLoginPromise) {
1124
+ w.checkLoginPromise.abort();
1125
+ w.checkLoginPromise = null;
1126
+ }
1127
+ if (scope.isAssociationLogin || scope.isWaitingAsConfirm) {
1128
+ scope.$apply(() => scope.qrcodeLogin());
1129
+ return true;
1130
+ }
1131
+ return false;
1132
+ });
1133
+ if (!switched) {
1134
+ await this.dropSession(true);
1135
+ }
1136
+ }
1137
+ /**
1138
+ * For the error of a send that just failed: what WeChat answered, when a
1139
+ * failed answer came in during the last few seconds.
1140
+ */
1141
+ lastSendFailure() {
1142
+ const last = this.monitor.health().lastSend;
1143
+ return last && last.ret !== '0' && Date.now() - last.time < 5000
1144
+ ? ` (${last.api} answered ${last.ret})`
1145
+ : '';
1146
+ }
1147
+ /**
1148
+ * The page itself, for tools that need to look at it (screenshots,
1149
+ * remote control). Undefined before start() and after stop().
1150
+ */
1151
+ currentPage() {
1152
+ return this.page;
1153
+ }
1154
+ /**
1155
+ * State of the web app as the page sees it. Unlike evaluate(), errors are
1156
+ * thrown: a closed page or a crashed browser must not look like a page that
1157
+ * is merely still loading.
1158
+ */
1159
+ async health() {
1160
+ if (!this.page) {
1161
+ throw new Error('no page');
1162
+ }
1163
+ if (this.page.isClosed()) {
1164
+ throw new Error('page closed');
1165
+ }
1166
+ return this.page.evaluate(() => {
1167
+ // eslint-disable-next-line no-undef
1168
+ if (typeof WechatyBro === 'undefined' || typeof WechatyBro.health !== 'function') {
1169
+ return null;
1170
+ }
1171
+ // eslint-disable-next-line no-undef
1172
+ return WechatyBro.health();
1173
+ });
1174
+ }
1175
+ async roomTopicList() {
1176
+ try {
1177
+ return await this.proxyWechaty('roomTopicList');
1178
+ }
1179
+ catch (e) {
1180
+ config_1.log.error('PuppetWeChatBridge', 'roomTopicList() exception: %s', e.message);
1181
+ throw e;
1182
+ }
1183
+ }
912
1184
  async evaluate(fn, ...args) {
913
1185
  config_1.log.silly('PuppetWeChatBridge', 'evaluate()');
914
1186
  if (!this.page) {
@@ -925,5 +1197,7 @@ class Bridge extends events_1.EventEmitter {
925
1197
  }
926
1198
  }
927
1199
  exports.Bridge = Bridge;
1200
+ // what makes the server render the page as logged in
1201
+ const SESSION_COOKIES = ['wxsid', 'webwx_data_ticket', 'wxpluginkey'];
928
1202
  exports.default = Bridge;
929
1203
  //# sourceMappingURL=bridge.js.map