-
Notifications
You must be signed in to change notification settings - Fork 71
/
bridge.ts
1083 lines (920 loc) · 33 KB
/
bridge.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Wechaty - https://github.com/chatie/wechaty
*
* @copyright 2016-2018 Huan LI <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// tslint:disable:arrow-parens
import { EventEmitter } from 'events'
import fs from 'fs'
import path from 'path'
import {
Browser,
ChromeArgOptions,
Dialog,
launch,
LaunchOptions,
Page,
Protocol,
} from 'puppeteer'
import puppeteerExtra from 'puppeteer-extra'
import stealthPlugin from 'puppeteer-extra-plugin-stealth'
import { StateSwitch } from 'state-switch'
import { parseString } from 'xml2js'
import {
MemoryCard,
} from 'memory-card'
/* tslint:disable:no-var-requires */
// const retryPromise = require('retry-promise').default
import {
log,
MEMORY_SLOT,
retry,
} from './config'
import {
WebContactRawPayload,
WebMessageMediaPayload,
WebMessageRawPayload,
WebRoomRawPayload,
} from './web-schemas'
import {
unescapeHtml,
} from './pure-function-helpers/mod'
export interface InjectResult {
code: number,
message: string,
}
export interface BridgeOptions {
endpoint? : string,
head? : boolean,
launchOptions? : LaunchOptions,
memory : MemoryCard,
stealthless? : boolean,
}
export class Bridge extends EventEmitter {
private browser : undefined | Browser
private page : undefined | Page
private state : StateSwitch
constructor (
public options: BridgeOptions,
) {
super()
log.verbose('PuppetWeChatBridge', 'constructor()')
this.state = new StateSwitch('PuppetWeChatBridge', log)
}
public async start (): Promise<void> {
log.verbose('PuppetWeChatBridge', 'start()')
this.state.on('pending')
try {
this.browser = await this.initBrowser()
log.verbose('PuppetWeChatBridge', 'start() initBrowser() done')
this.on('load', this.onLoad.bind(this))
const ready = new Promise(resolve => this.once('ready', resolve))
this.page = await this.initPage(this.browser)
await ready
this.state.on(true)
log.verbose('PuppetWeChatBridge', 'start() initPage() done')
} catch (e) {
log.error('PuppetWeChatBridge', 'start() exception: %s', e)
this.state.off(true)
try {
if (this.page) {
await this.page.close()
}
if (this.browser) {
await this.browser.close()
}
} catch (e2) {
log.error('PuppetWeChatBridge', 'start() exception %s, close page/browser exception %s', e, e2)
}
this.emit('error', e)
throw e
}
}
public async initBrowser (): Promise<Browser> {
log.verbose('PuppetWeChatBridge', 'initBrowser()')
const launchOptions = { ...this.options.launchOptions } as LaunchOptions & ChromeArgOptions
const headless = !(this.options.head)
const launchOptionsArgs = launchOptions.args || []
if (this.options.endpoint) {
launchOptions.executablePath = this.options.endpoint
}
const options = {
...launchOptions,
args: [
'--audio-output-channels=0',
'--disable-default-apps',
'--disable-extensions',
'--disable-translate',
'--disable-gpu',
'--disable-setuid-sandbox',
'--disable-sync',
'--hide-scrollbars',
'--mute-audio',
'--no-sandbox',
...launchOptionsArgs,
],
headless,
}
log.verbose('PuppetWeChatBridge', 'initBrowser() with options=%s', JSON.stringify(options))
let browser
if (!this.options.stealthless) {
/**
* Puppeteer 4.0
* https://github.com/berstend/puppeteer-extra/issues/211#issuecomment-636283110
*/
const plugin = stealthPlugin()
plugin.onBrowser = () => {}
puppeteerExtra.use(plugin)
browser = await puppeteerExtra.launch(options)
} else {
browser = await launch(options)
}
const version = await browser.version()
log.verbose('PuppetWeChatBridge', 'initBrowser() version: %s', version)
return browser
}
public async onDialog (dialog: Dialog) {
log.warn('PuppetWeChatBridge', 'onDialog() page.on(dialog) type:%s message:%s',
dialog.type, dialog.message())
try {
// XXX: Which ONE is better?
await dialog.accept()
// await dialog.dismiss()
} catch (e) {
log.error('PuppetWeChatBridge', 'onDialog() dialog.dismiss() reject: %s', e)
}
this.emit('error', new Error(`${dialog.type}(${dialog.message()})`))
}
public async onLoad (page: Page): Promise<void> {
log.verbose('PuppetWeChatBridge', 'onLoad() page.url=%s', page.url())
if (this.state.off()) {
log.verbose('PuppetWeChatBridge', 'onLoad() OFF state detected. NOP')
return // reject(new Error('onLoad() OFF state detected'))
}
try {
const emitExist = await page.evaluate(() => {
return typeof window.wechatyPuppetBridgeEmit === 'function'
})
if (!emitExist) {
/**
* expose window.wechatyPuppetBridgeEmit at here.
* enable wechaty-bro.js to emit message to bridge
*/
await page.exposeFunction('wechatyPuppetBridgeEmit', this.emit.bind(this))
}
await this.readyAngular(page)
await this.inject(page)
await this.clickSwitchAccount(page)
this.emit('ready')
} catch (e) {
log.error('PuppetWeChatBridge', 'onLoad() exception: %s', e)
await page.close()
this.emit('error', e)
}
}
public async initPage (browser: Browser): Promise<Page> {
log.verbose('PuppetWeChatBridge', 'initPage()')
// set this in time because the following callbacks
// might be called before initPage() return.
const page = this.page = await browser.newPage()
/**
* Can we support UOS with puppeteer? #127
* https://github.com/wechaty/wechaty-puppet-wechat/issues/127
*
* Credit: @luvletter2333 https://github.com/luvletter2333
*/
const UOS_PATCH_CLIENT_VERSION = '2.0.0'
const UOS_PATCH_EXTSPAM = 'Gp8ICJkIEpkICggwMDAwMDAwMRAGGoAI1GiJSIpeO1RZTq9QBKsRbPJdi84ropi16EYI10WB6g74sGmRwSNXjPQnYUKYotKkvLGpshucCaeWZMOylnc6o2AgDX9grhQQx7fm2DJRTyuNhUlwmEoWhjoG3F0ySAWUsEbH3bJMsEBwoB//0qmFJob74ffdaslqL+IrSy7LJ76/G5TkvNC+J0VQkpH1u3iJJs0uUYyLDzdBIQ6Ogd8LDQ3VKnJLm4g/uDLe+G7zzzkOPzCjXL+70naaQ9medzqmh+/SmaQ6uFWLDQLcRln++wBwoEibNpG4uOJvqXy+ql50DjlNchSuqLmeadFoo9/mDT0q3G7o/80P15ostktjb7h9bfNc+nZVSnUEJXbCjTeqS5UYuxn+HTS5nZsPVxJA2O5GdKCYK4x8lTTKShRstqPfbQpplfllx2fwXcSljuYi3YipPyS3GCAqf5A7aYYwJ7AvGqUiR2SsVQ9Nbp8MGHET1GxhifC692APj6SJxZD3i1drSYZPMMsS9rKAJTGz2FEupohtpf2tgXm6c16nDk/cw+C7K7me5j5PLHv55DFCS84b06AytZPdkFZLj7FHOkcFGJXitHkX5cgww7vuf6F3p0yM/W73SoXTx6GX4G6Hg2rYx3O/9VU2Uq8lvURB4qIbD9XQpzmyiFMaytMnqxcZJcoXCtfkTJ6pI7a92JpRUvdSitg967VUDUAQnCXCM/m0snRkR9LtoXAO1FUGpwlp1EfIdCZFPKNnXMeqev0j9W9ZrkEs9ZWcUEexSj5z+dKYQBhIICviYUQHVqBTZSNy22PlUIeDeIs11j7q4t8rD8LPvzAKWVqXE+5lS1JPZkjg4y5hfX1Dod3t96clFfwsvDP6xBSe1NBcoKbkyGxYK0UvPGtKQEE0Se2zAymYDv41klYE9s+rxp8e94/H8XhrL9oGm8KWb2RmYnAE7ry9gd6e8ZuBRIsISlJAE/e8y8xFmP031S6Lnaet6YXPsFpuFsdQs535IjcFd75hh6DNMBYhSfjv456cvhsb99+fRw/KVZLC3yzNSCbLSyo9d9BI45Plma6V8akURQA/qsaAzU0VyTIqZJkPDTzhuCl92vD2AD/QOhx6iwRSVPAxcRFZcWjgc2wCKh+uCYkTVbNQpB9B90YlNmI3fWTuUOUjwOzQRxJZj11NsimjOJ50qQwTTFj6qQvQ1a/I+MkTx5UO+yNHl718JWcR3AXGmv/aa9rD1eNP8ioTGlOZwPgmr2sor2iBpKTOrB83QgZXP+xRYkb4zVC+LoAXEoIa1+zArywlgREer7DLePukkU6wHTkuSaF+ge5Of1bXuU4i938WJHj0t3D8uQxkJvoFi/EYN/7u2P1zGRLV4dHVUsZMGCCtnO6BBigFMAA='
const extraHeaders = {
'client-version' : UOS_PATCH_CLIENT_VERSION,
extspam : UOS_PATCH_EXTSPAM,
referer : 'https://wx.qq.com/?&lang=zh_CN&target=t',
}
await page.setExtraHTTPHeaders(extraHeaders)
page.on('error', e => this.emit('error', e))
page.on('dialog', this.onDialog.bind(this))
const cookieList = (await this.options.memory.get(MEMORY_SLOT)) as Protocol.Network.Cookie[]
const url = this.entryUrl(cookieList)
log.verbose('PuppetWeChatBridge', 'initPage() before page.goto(url)')
// Does this related to(?) the CI Error: exception: Navigation Timeout Exceeded: 30000ms exceeded
await page.goto(url)
log.verbose('PuppetWeChatBridge', 'initPage() after page.goto(url)')
if (cookieList && cookieList.length) {
await page.setCookie(...cookieList)
log.silly('PuppetWeChatBridge', 'initPage() page.setCookie() %s cookies set back', cookieList.length)
}
page.on('load', () => this.emit('load', page))
await page.reload() // reload page to make effect of the new cookie.
return page
}
public async readyAngular (page: Page): Promise<void> {
log.verbose('PuppetWeChatBridge', 'readyAngular()')
try {
await page.waitForFunction("typeof window.angular !== 'undefined'")
} catch (e) {
log.verbose('PuppetWeChatBridge', 'readyAngular() exception: %s', e)
const blockedMessage = await this.testBlockedMessage()
if (blockedMessage) { // Wechat Account Blocked
// TODO: advertise for puppet-padchat
log.info('PuppetWeChatBridge', `
Please see: Account Login Issue <https://github.com/wechaty/wechaty/issues/872>
`)
throw new Error(blockedMessage)
} else {
throw e
}
}
}
public async inject (page: Page): Promise<void> {
log.verbose('PuppetWeChatBridge', 'inject()')
const WECHATY_BRO_JS_FILE = path.join(
__dirname,
'wechaty-bro.js',
)
try {
const sourceCode = fs.readFileSync(WECHATY_BRO_JS_FILE)
.toString()
let retObj = await page.evaluate(sourceCode) as InjectResult
if (retObj && /^(2|3)/.test(retObj.code.toString())) {
// HTTP Code 2XX & 3XX
log.silly('PuppetWeChatBridge', 'inject() eval(Wechaty) return code[%d] message[%s]',
retObj.code, retObj.message)
} else { // HTTP Code 4XX & 5XX
throw new Error('execute injectio error: ' + retObj.code + ', ' + retObj.message)
}
retObj = await this.proxyWechaty('init')
if (retObj && /^(2|3)/.test(retObj.code.toString())) {
// HTTP Code 2XX & 3XX
log.silly('PuppetWeChatBridge', 'inject() Wechaty.init() return code[%d] message[%s]',
retObj.code, retObj.message)
} else { // HTTP Code 4XX & 5XX
throw new Error('execute proxyWechaty(init) error: ' + retObj.code + ', ' + retObj.message)
}
const SUCCESS_CIPHER = 'ding() OK!'
const future = new Promise(resolve => this.once('dong', resolve))
this.ding(SUCCESS_CIPHER)
const r = await future
if (r !== SUCCESS_CIPHER) {
throw new Error('fail to get right return from call ding()')
}
log.silly('PuppetWeChatBridge', 'inject() ding success')
} catch (e) {
log.verbose('PuppetWeChatBridge', 'inject() exception: %s. stack: %s', e.message, e.stack)
throw e
}
}
public async logout (): Promise<any> {
log.verbose('PuppetWeChatBridge', 'logout()')
try {
return await this.proxyWechaty('logout')
} catch (e) {
log.error('PuppetWeChatBridge', 'logout() exception: %s', e.message)
throw e
}
}
public async stop (): Promise<void> {
log.verbose('PuppetWeChatBridge', 'stop()')
if (!this.page) {
throw new Error('no page')
}
if (!this.browser) {
throw new Error('no browser')
}
this.state.off('pending')
try {
await this.page.close()
log.silly('PuppetWeChatBridge', 'stop() page.close()-ed')
} catch (e) {
log.warn('PuppetWeChatBridge', 'stop() page.close() exception: %s', e)
}
try {
await this.browser.close()
log.silly('PuppetWeChatBridge', 'stop() browser.close()-ed')
} catch (e) {
log.warn('PuppetWeChatBridge', 'stop() browser.close() exception: %s', e)
}
this.state.off(true)
}
public async getUserName (): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getUserName()')
try {
const userName = await this.proxyWechaty('getUserName')
return userName
} catch (e) {
log.error('PuppetWeChatBridge', 'getUserName() exception: %s', e.message)
throw e
}
}
public async contactAlias (contactId: string, alias: null | string): Promise<boolean> {
try {
return await this.proxyWechaty('contactRemark', contactId, alias)
} catch (e) {
log.verbose('PuppetWeChatBridge', 'contactRemark() exception: %s', e.message)
// Issue #509 return false instead of throw when contact is not a friend.
// throw e
log.warn('PuppetWeChatBridge', 'contactRemark() does not work on contact is not a friend')
return false
}
}
public async contactList (): Promise<string[]> {
try {
return await this.proxyWechaty('contactList')
} catch (e) {
log.error('PuppetWeChatBridge', 'contactList() exception: %s', e.message)
throw e
}
}
public async roomList (): Promise<string[]> {
try {
return await this.proxyWechaty('roomList')
} catch (e) {
log.error('PuppetWeChatBridge', 'roomList() exception: %s', e.message)
throw e
}
}
public async roomDelMember (
roomId: string,
contactId: string,
): Promise<number> {
if (!roomId || !contactId) {
throw new Error('no roomId or contactId')
}
try {
return await this.proxyWechaty('roomDelMember', roomId, contactId)
} catch (e) {
log.error('PuppetWeChatBridge', 'roomDelMember(%s, %s) exception: %s', roomId, contactId, e.message)
throw e
}
}
public async roomAddMember (
roomId: string,
contactId: string,
): Promise<number> {
log.verbose('PuppetWeChatBridge', 'roomAddMember(%s, %s)', roomId, contactId)
if (!roomId || !contactId) {
throw new Error('no roomId or contactId')
}
try {
return await this.proxyWechaty('roomAddMember', roomId, contactId)
} catch (e) {
log.error('PuppetWeChatBridge', 'roomAddMember(%s, %s) exception: %s', roomId, contactId, e.message)
throw e
}
}
public async roomModTopic (
roomId: string,
topic: string,
): Promise<string> {
if (!roomId) {
throw new Error('no roomId')
}
try {
await this.proxyWechaty('roomModTopic', roomId, topic)
return topic
} catch (e) {
log.error('PuppetWeChatBridge', 'roomModTopic(%s, %s) exception: %s', roomId, topic, e.message)
throw e
}
}
public async roomCreate (contactIdList: string[], topic?: string): Promise<string> {
if (!contactIdList || !Array.isArray(contactIdList)) {
throw new Error('no valid contactIdList')
}
try {
const roomId = await this.proxyWechaty('roomCreate', contactIdList, topic)
if (typeof roomId === 'object') {
// It is a Error Object send back by callback in browser(WechatyBro)
throw roomId
}
return roomId
} catch (e) {
log.error('PuppetWeChatBridge', 'roomCreate(%s) exception: %s', contactIdList, e.message)
throw e
}
}
public async verifyUserRequest (
contactId: string,
hello: string,
): Promise<boolean> {
log.verbose('PuppetWeChatBridge', 'verifyUserRequest(%s, %s)', contactId, hello)
if (!contactId) {
throw new Error('no valid contactId')
}
try {
return await this.proxyWechaty('verifyUserRequest', contactId, hello)
} catch (e) {
log.error('PuppetWeChatBridge', 'verifyUserRequest(%s, %s) exception: %s', contactId, hello, e.message)
throw e
}
}
public async verifyUserOk (
contactId: string,
ticket: string,
): Promise<boolean> {
log.verbose('PuppetWeChatBridge', 'verifyUserOk(%s, %s)', contactId, ticket)
if (!contactId || !ticket) {
throw new Error('no valid contactId or ticket')
}
try {
return await this.proxyWechaty('verifyUserOk', contactId, ticket)
} catch (e) {
log.error('PuppetWeChatBridge', 'verifyUserOk(%s, %s) exception: %s', contactId, ticket, e.message)
throw e
}
}
public async send (
toUserName: string,
text: string,
): Promise<void> {
log.verbose('PuppetWeChatBridge', 'send(%s, %s)', toUserName, text)
if (!toUserName) {
throw new Error('UserName not found')
}
if (!text) {
throw new Error('cannot say nothing')
}
try {
const ret = await this.proxyWechaty('send', toUserName, text)
if (!ret) {
throw new Error('send fail')
}
} catch (e) {
log.error('PuppetWeChatBridge', 'send() exception: %s', e.message)
throw e
}
}
public async getMsgImg (id: string): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getMsgImg(%s)', id)
try {
return await this.proxyWechaty('getMsgImg', id)
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getMsgImg, %d) exception: %s', id, e.message)
throw e
}
}
public async getMsgEmoticon (id: string): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getMsgEmoticon(%s)', id)
try {
return await this.proxyWechaty('getMsgEmoticon', id)
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getMsgEmoticon, %d) exception: %s', id, e.message)
throw e
}
}
public async getMsgVideo (id: string): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getMsgVideo(%s)', id)
try {
return await this.proxyWechaty('getMsgVideo', id)
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getMsgVideo, %d) exception: %s', id, e.message)
throw e
}
}
public async getMsgVoice (id: string): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getMsgVoice(%s)', id)
try {
return await this.proxyWechaty('getMsgVoice', id)
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getMsgVoice, %d) exception: %s', id, e.message)
throw e
}
}
public async getMsgPublicLinkImg (id: string): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getMsgPublicLinkImg(%s)', id)
try {
return await this.proxyWechaty('getMsgPublicLinkImg', id)
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getMsgPublicLinkImg, %d) exception: %s', id, e.message)
throw e
}
}
public async getMessage (id: string): Promise<WebMessageRawPayload> {
try {
return await retry(async (retryException, attempt) => {
log.silly('PuppetWeChatBridge', 'getMessage(%s) retry attempt %d',
id,
attempt,
)
try {
const rawPayload = await this.proxyWechaty('getMessage', id)
if (rawPayload && Object.keys(rawPayload).length > 0) {
return rawPayload
}
throw new Error('got empty return value at attempt: ' + attempt)
} catch (e) {
log.verbose('PuppetWeChatBridge', 'getMessage() proxyWechaty(getMessage, %s) exception: %s', id, e.message)
retryException(e)
}
})
} catch (e) {
log.error('PuppetWeChatBridge', 'promiseRetry() getContact() finally FAIL: %s', e.message)
throw e
}
}
public async getContact (id: string): Promise<WebContactRawPayload | WebRoomRawPayload> {
try {
return await retry(async (retryException, attempt) => {
log.silly('PuppetWeChatBridge', 'getContact(%s) retry attempt %d',
id,
attempt,
)
try {
const rawPayload = await this.proxyWechaty('getContact', id)
if (rawPayload && Object.keys(rawPayload).length > 0) {
return rawPayload
}
throw new Error('got empty return value at attempt: ' + attempt)
} catch (e) {
log.verbose('PuppetWeChatBridge', 'getContact() proxyWechaty(getContact, %s) exception: %s', id, e.message)
retryException(e)
}
})
} catch (e) {
log.error('PuppetWeChatBridge', 'promiseRetry() getContact() finally FAIL: %s', e.message)
throw e
}
}
public async getBaseRequest (): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getBaseRequest()')
try {
return await this.proxyWechaty('getBaseRequest')
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getBaseRequest) exception: %s', e.message)
throw e
}
}
public async getPassticket (): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getPassticket()')
try {
return await this.proxyWechaty('getPassticket')
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getPassticket) exception: %s', e.message)
throw e
}
}
public async getCheckUploadUrl (): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getCheckUploadUrl()')
try {
return await this.proxyWechaty('getCheckUploadUrl')
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getCheckUploadUrl) exception: %s', e.message)
throw e
}
}
public async getUploadMediaUrl (): Promise<string> {
log.verbose('PuppetWeChatBridge', 'getUploadMediaUrl()')
try {
return await this.proxyWechaty('getUploadMediaUrl')
} catch (e) {
log.silly('PuppetWeChatBridge', 'proxyWechaty(getUploadMediaUrl) exception: %s', e.message)
throw e
}
}
public async sendMedia (mediaData: WebMessageMediaPayload): Promise<boolean> {
log.verbose('PuppetWeChatBridge', 'sendMedia(mediaData)')
if (!mediaData.ToUserName) {
throw new Error('UserName not found')
}
if (!mediaData.MediaId) {
throw new Error('cannot say nothing')
}
try {
return await this.proxyWechaty('sendMedia', mediaData)
} catch (e) {
log.error('PuppetWeChatBridge', 'sendMedia() exception: %s', e.message)
throw e
}
}
public async forward (baseData: WebMessageRawPayload, patchData: WebMessageRawPayload): Promise<boolean> {
log.verbose('PuppetWeChatBridge', 'forward()')
if (!baseData.ToUserName) {
throw new Error('UserName not found')
}
if (!patchData.MMActualContent && !patchData.MMSendContent && !patchData.Content) {
throw new Error('cannot say nothing')
}
try {
return await this.proxyWechaty('forward', baseData, patchData)
} catch (e) {
log.error('PuppetWeChatBridge', 'forward() exception: %s', e.message)
throw e
}
}
/**
* Proxy Call to Wechaty in Bridge
*/
public async proxyWechaty (
wechatyFunc : string,
...args : any[]
): Promise<any> {
log.silly('PuppetWeChatBridge', 'proxyWechaty(%s%s)',
wechatyFunc,
args.length === 0
? ''
: ', ' + args.join(', '),
)
if (!this.page) {
throw new Error('no page')
}
try {
const noWechaty = await this.page.evaluate(() => {
return typeof WechatyBro === 'undefined'
})
if (noWechaty) {
const e = new Error('there is no WechatyBro in browser(yet)')
throw e
}
} catch (e) {
log.warn('PuppetWeChatBridge', 'proxyWechaty() noWechaty exception: %s', e)
throw e
}
const argsEncoded = Buffer.from(
encodeURIComponent(
JSON.stringify(args),
),
).toString('base64')
// see: http://blog.sqrtthree.com/2015/08/29/utf8-to-b64/
const argsDecoded = `JSON.parse(decodeURIComponent(window.atob('${argsEncoded}')))`
const wechatyScript = `
WechatyBro
.${wechatyFunc}
.apply(
undefined,
${argsDecoded},
)
`.replace(/[\n\s]+/, ' ')
// log.silly('PuppetWeChatBridge', 'proxyWechaty(%s, ...args) %s', wechatyFunc, wechatyScript)
// console.log('proxyWechaty wechatyFunc args[0]: ')
// console.log(args[0])
try {
const ret = await this.page.evaluate(wechatyScript)
return ret
} catch (e) {
log.verbose('PuppetWeChatBridge', 'proxyWechaty(%s, %s) ', wechatyFunc, args.join(', '))
log.warn('PuppetWeChatBridge', 'proxyWechaty() exception: %s', e.message)
throw e
}
}
public ding (data: any): void {
log.verbose('PuppetWeChatBridge', 'ding(%s)', data || '')
this.proxyWechaty('ding', data)
.then(dongData => {
return this.emit('dong', dongData)
})
.catch(e => {
log.error('PuppetWeChatBridge', 'ding(%s) exception: %s', data, e.message)
this.emit('error', e)
})
}
public preHtmlToXml (text: string): string {
log.verbose('PuppetWeChatBridge', 'preHtmlToXml()')
const preRegex = /^<pre[^>]*>([^<]+)<\/pre>$/i
const matches = text.match(preRegex)
if (!matches) {
return text
}
return unescapeHtml(matches[1])
}
public async innerHTML (): Promise<string> {
const html = await this.evaluate(() => {
return window.document.body.innerHTML
})
return html
}
/**
* Throw if there's a blocked message
*/
public async testBlockedMessage (text?: string): Promise<string | false> {
if (!text) {
text = await this.innerHTML()
}
if (!text) {
throw new Error('testBlockedMessage() no text found!')
}
const textSnip = text.substr(0, 50).replace(/\n/, '')
log.verbose('PuppetWeChatBridge', 'testBlockedMessage(%s)',
textSnip)
interface BlockedMessage {
error?: {
ret : number,
message : string,
}
}
let obj: BlockedMessage
try {
// see unit test for detail
const tryXmlText = this.preHtmlToXml(text)
// obj = JSON.parse(toJson(tryXmlText))
obj = await new Promise((resolve, reject) => {
parseString(tryXmlText, { explicitArray: false }, (err, result) => {
if (err) {
return reject(err)
}
return resolve(result)
})
})
} catch (e) {
log.warn('PuppetWeChatBridge', 'testBlockedMessage() toJson() exception: %s', e)
return false
}
if (!obj) {
// FIXME: when will this happen?
log.warn('PuppetWeChatBridge', 'testBlockedMessage() toJson(%s) return empty obj', textSnip)
return false
}
if (!obj.error) {
return false
}
const ret = +obj.error.ret
const message = obj.error.message
log.warn('PuppetWeChatBridge', 'testBlockedMessage() error.ret=%s', ret)
if (ret === 1203) {
// <error>
// <ret>1203</ret>
// <message>当前登录环境异常。为了你的帐号安全,暂时不能登录web微信。你可以通过手机客户端或者windows微信登录。</message>
// </error>
return message
}
return message // other error message
// return new Promise<string | false>(resolve => {
// parseString(tryXmlText, { explicitArray: false }, (err, obj: BlockedMessage) => {
// if (err) { // HTML can not be parsed to JSON
// return resolve(false)
// }
// if (!obj) {
// // FIXME: when will this happen?
// log.warn('PuppetWeChatBridge', 'testBlockedMessage() parseString(%s) return empty obj', textSnip)
// return resolve(false)
// }
// if (!obj.error) {
// return resolve(false)
// }
// const ret = +obj.error.ret
// const message = obj.error.message
// log.warn('PuppetWeChatBridge', 'testBlockedMessage() error.ret=%s', ret)
// if (ret === 1203) {
// // <error>
// // <ret>1203</ret>
// // <message>当前登录环境异常。为了你的帐号安全,暂时不能登录web微信。你可以通过手机客户端或者windows微信登录。</message>
// // </error>
// return resolve(message)
// }
// return resolve(message) // other error message
// })
// })
}
public async clickSwitchAccount (page: Page): Promise<boolean> {
log.verbose('PuppetWeChatBridge', 'clickSwitchAccount()')
// https://github.com/GoogleChrome/puppeteer/issues/537#issuecomment-334918553
// async function listXpath(thePage: Page, xpath: string): Promise<ElementHandle[]> {
// log.verbose('PuppetWeChatBridge', 'clickSwitchAccount() listXpath()')
// try {
// const nodeHandleList = await (thePage as any).evaluateHandle(xpathInner => {
// const nodeList: Node[] = []
// const query = document.evaluate(xpathInner, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
// for (let i = 0, length = query.snapshotLength; i < length; ++i) {
// nodeList.push(query.snapshotItem(i))
// }
// return nodeList
// }, xpath)
// const properties = await nodeHandleList.getProperties()
// const elementHandleList: ElementHandle[] = []
// const releasePromises: Promise<void>[] = []
// for (const property of properties.values()) {
// const element = property.asElement()
// if (element)
// elementHandleList.push(element)
// else
// releasePromises.push(property.dispose())
// }
// await Promise.all(releasePromises)
// return elementHandleList
// } catch (e) {
// log.verbose('PuppetWeChatBridge', 'clickSwitchAccount() listXpath() exception: %s', e)
// return []
// }
// }
// TODO: use page.$x() (with puppeteer v1.1 or above) to replace DIY version of listXpath() instead.
// See: https://github.com/GoogleChrome/puppeteer/blob/v1.1.0/docs/api.md#pagexexpression
const XPATH_SELECTOR
= "//div[contains(@class,'association') and contains(@class,'show')]/a[@ng-click='qrcodeLogin()']"
try {
// const [button] = await listXpath(page, XPATH_SELECTOR)
const [button] = await page.$x(XPATH_SELECTOR)
if (button) {
await button.click()
log.silly('PuppetWeChatBridge', 'clickSwitchAccount() clicked!')
return true
} else {
log.silly('PuppetWeChatBridge', 'clickSwitchAccount() button not found')
return false
}
} catch (e) {
log.silly('PuppetWeChatBridge', 'clickSwitchAccount() exception: %s', e)
throw e
}
}
public async hostname (): Promise<string | null> {
log.verbose('PuppetWeChatBridge', 'hostname()')
if (!this.page) {
throw new Error('no page')
}
try {
const hostname = await this.page.evaluate(() => window.location.hostname)
log.silly('PuppetWeChatBridge', 'hostname() got %s', hostname)
return hostname
} catch (e) {
log.error('PuppetWeChatBridge', 'hostname() exception: %s', e)
this.emit('error', e)
return null
}
}
public async cookies (cookieList: Cookie[]): Promise<void>
public async cookies (): Promise<Cookie[]>
public async cookies (cookieList?: Protocol.Network.Cookie[]): Promise<void | Protocol.Network.Cookie[]> {
if (!this.page) {
throw new Error('no page')
}
if (cookieList) {
try {