1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | import cuid from 'cuid'
|
21 | import os from 'os'
|
22 |
|
23 | import { Brolog } from 'brolog'
|
24 | import { instanceToClass } from 'clone-class'
|
25 |
|
26 | import {
|
27 | Puppet,
|
28 |
|
29 | MemoryCard,
|
30 | StateSwitch,
|
31 |
|
32 | PUPPET_EVENT_DICT,
|
33 | PuppetEventName,
|
34 | PuppetOptions,
|
35 | PayloadType,
|
36 | } from 'wechaty-puppet'
|
37 |
|
38 | import {
|
39 | FileBox,
|
40 | Raven,
|
41 |
|
42 | config,
|
43 | log,
|
44 | } from './config'
|
45 |
|
46 | import {
|
47 | VERSION,
|
48 | GIT_COMMIT_HASH,
|
49 | } from './version'
|
50 |
|
51 | import {
|
52 | Sayable,
|
53 | } from './types'
|
54 |
|
55 | import {
|
56 | Io,
|
57 | } from './io'
|
58 | import {
|
59 | PuppetModuleName,
|
60 | } from './puppet-config'
|
61 | import {
|
62 | PuppetManager,
|
63 | } from './puppet-manager'
|
64 |
|
65 | import {
|
66 | Contact,
|
67 | ContactSelf,
|
68 | Friendship,
|
69 | Image,
|
70 | Message,
|
71 | MiniProgram,
|
72 | Room,
|
73 | RoomInvitation,
|
74 | Tag,
|
75 | UrlLink,
|
76 |
|
77 | wechatifyContact,
|
78 | wechatifyContactSelf,
|
79 | wechatifyFriendship,
|
80 | wechatifyImage,
|
81 | wechatifyMessage,
|
82 | wechatifyMiniProgram,
|
83 | wechatifyRoom,
|
84 | wechatifyRoomInvitation,
|
85 | wechatifyTag,
|
86 | wechatifyUrlLink,
|
87 | } from './user/mod'
|
88 |
|
89 | import { timestampToDate } from './helper-functions/pure/timestamp-to-date'
|
90 |
|
91 | import {
|
92 | WechatyEventEmitter,
|
93 | WechatyEventName,
|
94 | } from './events/wechaty-events'
|
95 |
|
96 | import {
|
97 | WechatyPlugin,
|
98 | WechatyPluginUninstaller,
|
99 | isWechatyPluginUninstaller,
|
100 | } from './plugin'
|
101 |
|
102 | export interface WechatyOptions {
|
103 | memory? : MemoryCard,
|
104 | name? : string,
|
105 |
|
106 | puppet? : PuppetModuleName | Puppet,
|
107 | puppetOptions? : PuppetOptions,
|
108 | ioToken? : string,
|
109 | }
|
110 |
|
111 | const PUPPET_MEMORY_NAME = 'puppet'
|
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 | class Wechaty extends WechatyEventEmitter implements Sayable {
|
137 |
|
138 | static readonly VERSION = VERSION
|
139 | static readonly log: Brolog = log
|
140 | readonly log: Brolog = log
|
141 |
|
142 | public readonly state : StateSwitch
|
143 | private readonly readyState : StateSwitch
|
144 | public readonly wechaty : Wechaty
|
145 |
|
146 | |
147 |
|
148 |
|
149 |
|
150 | private static globalInstance: Wechaty
|
151 |
|
152 | private static globalPluginList: WechatyPlugin[] = []
|
153 |
|
154 | private pluginUninstallerList: WechatyPluginUninstaller[]
|
155 |
|
156 | private memory?: MemoryCard
|
157 |
|
158 | private lifeTimer? : NodeJS.Timer
|
159 | private io? : Io
|
160 |
|
161 | public puppet!: Puppet
|
162 |
|
163 | |
164 |
|
165 |
|
166 |
|
167 | public readonly id : string
|
168 |
|
169 | protected wechatifiedContact? : typeof Contact
|
170 | protected wechatifiedContactSelf? : typeof ContactSelf
|
171 | protected wechatifiedFriendship? : typeof Friendship
|
172 | protected wechatifiedImage? : typeof Image
|
173 | protected wechatifiedMessage? : typeof Message
|
174 | protected wechatifiedMiniProgram? : typeof MiniProgram
|
175 | protected wechatifiedRoom? : typeof Room
|
176 | protected wechatifiedRoomInvitation? : typeof RoomInvitation
|
177 | protected wechatifiedTag? : typeof Tag
|
178 | protected wechatifiedUrlLink? : typeof UrlLink
|
179 |
|
180 | get Contact () : typeof Contact { return guardWechatify(this.wechatifiedContact) }
|
181 | get ContactSelf () : typeof ContactSelf { return guardWechatify(this.wechatifiedContactSelf) }
|
182 | get Friendship () : typeof Friendship { return guardWechatify(this.wechatifiedFriendship) }
|
183 | get Image () : typeof Image { return guardWechatify(this.wechatifiedImage) }
|
184 | get Message () : typeof Message { return guardWechatify(this.wechatifiedMessage) }
|
185 | get MiniProgram () : typeof MiniProgram { return guardWechatify(this.wechatifiedMiniProgram) }
|
186 | get Room () : typeof Room { return guardWechatify(this.wechatifiedRoom) }
|
187 | get RoomInvitation () : typeof RoomInvitation { return guardWechatify(this.wechatifiedRoomInvitation) }
|
188 | get Tag () : typeof Tag { return guardWechatify(this.wechatifiedTag) }
|
189 | get UrlLink () : typeof UrlLink { return guardWechatify(this.wechatifiedUrlLink) }
|
190 |
|
191 | |
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 | public static instance (
|
206 | options?: WechatyOptions,
|
207 | ) {
|
208 | if (options && this.globalInstance) {
|
209 | throw new Error('instance can be only initialized once by options!')
|
210 | }
|
211 | if (!this.globalInstance) {
|
212 | this.globalInstance = new Wechaty(options)
|
213 | }
|
214 | return this.globalInstance
|
215 | }
|
216 |
|
217 | |
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 |
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 | public static use (
|
237 | ...plugins: (WechatyPlugin | WechatyPlugin[])[]
|
238 | ) {
|
239 | const pluginList = plugins.flat()
|
240 | this.globalPluginList = this.globalPluginList.concat(pluginList)
|
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 | constructor (
|
286 | private options: WechatyOptions = {},
|
287 | ) {
|
288 | super()
|
289 | log.verbose('Wechaty', 'constructor()')
|
290 |
|
291 | this.memory = this.options.memory
|
292 |
|
293 | this.id = cuid()
|
294 |
|
295 | this.state = new StateSwitch('Wechaty', { log })
|
296 | this.readyState = new StateSwitch('WechatyReady', { log })
|
297 |
|
298 | this.wechaty = this
|
299 |
|
300 | |
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 | super.setMaxListeners(1024)
|
310 |
|
311 | this.pluginUninstallerList = []
|
312 | this.installGlobalPlugin()
|
313 | }
|
314 |
|
315 | |
316 |
|
317 |
|
318 | public override toString () {
|
319 | if (!this.options) {
|
320 | return this.constructor.name
|
321 | }
|
322 |
|
323 | return [
|
324 | 'Wechaty#',
|
325 | this.id,
|
326 | `<${(this.options && this.options.puppet) || ''}>`,
|
327 | `(${(this.memory && this.memory.name) || ''})`,
|
328 | ].join('')
|
329 | }
|
330 |
|
331 | |
332 |
|
333 |
|
334 |
|
335 | public name () {
|
336 | return this.options.name || 'wechaty'
|
337 | }
|
338 |
|
339 | public override on (event: WechatyEventName, listener: (...args: any[]) => any): this {
|
340 | log.verbose('Wechaty', 'on(%s, listener) registering... listenerCount: %s',
|
341 | event,
|
342 | this.listenerCount(event),
|
343 | )
|
344 |
|
345 | return super.on(event, listener)
|
346 | }
|
347 |
|
348 | |
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 | public use (...plugins: (WechatyPlugin | WechatyPlugin[])[]) {
|
361 | const pluginList = plugins.flat() as WechatyPlugin[]
|
362 | const uninstallerList = pluginList
|
363 | .map(plugin => plugin(this))
|
364 | .filter(isWechatyPluginUninstaller)
|
365 |
|
366 | this.pluginUninstallerList.push(
|
367 | ...uninstallerList,
|
368 | )
|
369 | return this
|
370 | }
|
371 |
|
372 | private installGlobalPlugin () {
|
373 |
|
374 | const uninstallerList = instanceToClass(this, Wechaty)
|
375 | .globalPluginList
|
376 | .map(plugin => plugin(this))
|
377 | .filter(isWechatyPluginUninstaller)
|
378 |
|
379 | this.pluginUninstallerList.push(
|
380 | ...uninstallerList,
|
381 | )
|
382 | }
|
383 |
|
384 | private async initPuppet (): Promise<void> {
|
385 | log.verbose('Wechaty', 'initPuppet() %s', this.options.puppet || '')
|
386 |
|
387 | const initialized = !!this.puppet
|
388 |
|
389 | if (initialized) {
|
390 | log.verbose('Wechaty', 'initPuppet(%s) had already been initialized, no need to init twice', this.options.puppet)
|
391 | return
|
392 | }
|
393 |
|
394 | if (!this.memory) {
|
395 | throw new Error('no memory')
|
396 | }
|
397 |
|
398 | const puppet = this.options.puppet || config.systemPuppetName()
|
399 | const puppetMemory = this.memory.multiplex(PUPPET_MEMORY_NAME)
|
400 |
|
401 | const puppetInstance = await PuppetManager.resolve({
|
402 | puppet,
|
403 | puppetOptions : this.options.puppetOptions,
|
404 |
|
405 | })
|
406 |
|
407 | |
408 |
|
409 |
|
410 | puppetInstance.setMemory(puppetMemory)
|
411 |
|
412 | this.initPuppetEventBridge(puppetInstance)
|
413 | this.wechatifyUserModules(puppetInstance)
|
414 |
|
415 | |
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 | ;(this.emit as any)('puppet', puppetInstance)
|
422 | }
|
423 |
|
424 | protected initPuppetEventBridge (puppet: Puppet) {
|
425 | log.verbose('Wechaty', 'initPuppetEventBridge(%s)', puppet)
|
426 |
|
427 | const eventNameList: PuppetEventName[] = Object.keys(PUPPET_EVENT_DICT) as PuppetEventName[]
|
428 | for (const eventName of eventNameList) {
|
429 | log.verbose('Wechaty',
|
430 | 'initPuppetEventBridge() puppet.on(%s) (listenerCount:%s) registering...',
|
431 | eventName,
|
432 | puppet.listenerCount(eventName),
|
433 | )
|
434 |
|
435 | switch (eventName) {
|
436 | case 'dong':
|
437 | puppet.on('dong', payload => {
|
438 | this.emit('dong', payload.data)
|
439 | })
|
440 | break
|
441 |
|
442 | case 'error':
|
443 | puppet.on('error', payload => {
|
444 | this.emit('error', new Error(payload.data))
|
445 | })
|
446 | break
|
447 |
|
448 | case 'heartbeat':
|
449 | puppet.on('heartbeat', payload => {
|
450 | |
451 |
|
452 |
|
453 |
|
454 | this.emit('heartbeat', payload.data)
|
455 | })
|
456 | break
|
457 |
|
458 | case 'friendship':
|
459 | puppet.on('friendship', async payload => {
|
460 | const friendship = this.Friendship.load(payload.friendshipId)
|
461 | try {
|
462 | await friendship.ready()
|
463 | this.emit('friendship', friendship)
|
464 | friendship.contact().emit('friendship', friendship)
|
465 | } catch (e) {
|
466 | this.emit('error', e)
|
467 | }
|
468 | })
|
469 | break
|
470 |
|
471 | case 'login':
|
472 | puppet.on('login', async payload => {
|
473 | const contact = this.ContactSelf.load(payload.contactId)
|
474 | try {
|
475 | await contact.ready()
|
476 | this.emit('login', contact)
|
477 | } catch (e) {
|
478 | this.emit('error', e)
|
479 | }
|
480 | })
|
481 | break
|
482 |
|
483 | case 'logout':
|
484 | puppet.on('logout', async payload => {
|
485 | const contact = this.ContactSelf.load(payload.contactId)
|
486 | try {
|
487 | await contact.ready()
|
488 | this.emit('logout', contact, payload.data)
|
489 | } catch (e) {
|
490 | this.emit('error', e)
|
491 | }
|
492 | })
|
493 | break
|
494 |
|
495 | case 'message':
|
496 | puppet.on('message', async payload => {
|
497 | const msg = this.Message.load(payload.messageId)
|
498 | try {
|
499 | await msg.ready()
|
500 | this.emit('message', msg)
|
501 |
|
502 | const room = msg.room()
|
503 | if (room) {
|
504 | room.emit('message', msg)
|
505 | } else {
|
506 | msg.talker().emit('message', msg)
|
507 | }
|
508 | } catch (e) {
|
509 | this.emit('error', e)
|
510 | }
|
511 | })
|
512 | break
|
513 |
|
514 | case 'ready':
|
515 | puppet.on('ready', () => {
|
516 | log.silly('Wechaty', 'initPuppetEventBridge() puppet.on(ready)')
|
517 |
|
518 | this.emit('ready')
|
519 | this.readyState.on(true)
|
520 | })
|
521 | break
|
522 |
|
523 | case 'room-invite':
|
524 | puppet.on('room-invite', async payload => {
|
525 | const roomInvitation = this.RoomInvitation.load(payload.roomInvitationId)
|
526 | this.emit('room-invite', roomInvitation)
|
527 | })
|
528 | break
|
529 |
|
530 | case 'room-join':
|
531 | puppet.on('room-join', async payload => {
|
532 | const room = this.Room.load(payload.roomId)
|
533 | try {
|
534 | await room.sync()
|
535 |
|
536 | const inviteeList = payload.inviteeIdList.map(id => this.Contact.load(id))
|
537 | await Promise.all(inviteeList.map(c => c.ready()))
|
538 |
|
539 | const inviter = this.Contact.load(payload.inviterId)
|
540 | await inviter.ready()
|
541 | const date = timestampToDate(payload.timestamp)
|
542 |
|
543 | this.emit('room-join', room, inviteeList, inviter, date)
|
544 | room.emit('join', inviteeList, inviter, date)
|
545 | } catch (e) {
|
546 | this.emit('error', e)
|
547 | }
|
548 | })
|
549 | break
|
550 |
|
551 | case 'room-leave':
|
552 | puppet.on('room-leave', async payload => {
|
553 | try {
|
554 | const room = this.Room.load(payload.roomId)
|
555 |
|
556 | |
557 |
|
558 |
|
559 | await room.sync()
|
560 |
|
561 | const leaverList = payload.removeeIdList.map(id => this.Contact.load(id))
|
562 | await Promise.all(leaverList.map(c => c.ready()))
|
563 |
|
564 | const remover = this.Contact.load(payload.removerId)
|
565 | await remover.ready()
|
566 | const date = timestampToDate(payload.timestamp)
|
567 |
|
568 | this.emit('room-leave', room, leaverList, remover, date)
|
569 | room.emit('leave', leaverList, remover, date)
|
570 |
|
571 |
|
572 | const selfId = this.puppet.selfId()
|
573 | if (selfId && payload.removeeIdList.includes(selfId)) {
|
574 | await this.puppet.dirtyPayload(PayloadType.Room, payload.roomId)
|
575 | await this.puppet.dirtyPayload(PayloadType.RoomMember, payload.roomId)
|
576 | }
|
577 | } catch (e) {
|
578 | this.emit('error', e)
|
579 | }
|
580 | })
|
581 | break
|
582 |
|
583 | case 'room-topic':
|
584 | puppet.on('room-topic', async payload => {
|
585 | try {
|
586 | const room = this.Room.load(payload.roomId)
|
587 | await room.sync()
|
588 |
|
589 | const changer = this.Contact.load(payload.changerId)
|
590 | await changer.ready()
|
591 | const date = timestampToDate(payload.timestamp)
|
592 |
|
593 | this.emit('room-topic', room, payload.newTopic, payload.oldTopic, changer, date)
|
594 | room.emit('topic', payload.newTopic, payload.oldTopic, changer, date)
|
595 | } catch (e) {
|
596 | this.emit('error', e)
|
597 | }
|
598 | })
|
599 | break
|
600 |
|
601 | case 'scan':
|
602 | puppet.on('scan', async payload => {
|
603 | this.emit('scan', payload.qrcode || '', payload.status, payload.data)
|
604 | })
|
605 | break
|
606 |
|
607 | case 'reset':
|
608 |
|
609 | break
|
610 |
|
611 | case 'dirty':
|
612 | |
613 |
|
614 |
|
615 | puppet.on('dirty', async ({ payloadType, payloadId }) => {
|
616 | try {
|
617 | switch (payloadType) {
|
618 | case PayloadType.RoomMember:
|
619 | case PayloadType.Contact:
|
620 | await this.Contact.load(payloadId).sync()
|
621 | break
|
622 | case PayloadType.Room:
|
623 | await this.Room.load(payloadId).sync()
|
624 | break
|
625 |
|
626 | |
627 |
|
628 |
|
629 | case PayloadType.Friendship:
|
630 |
|
631 | break
|
632 | case PayloadType.Message:
|
633 |
|
634 | break
|
635 |
|
636 | case PayloadType.Unknown:
|
637 | default:
|
638 | throw new Error('unknown payload type: ' + payloadType)
|
639 | }
|
640 | } catch (e) {
|
641 | this.emit('error', e)
|
642 | }
|
643 | })
|
644 | break
|
645 |
|
646 | default:
|
647 | |
648 |
|
649 |
|
650 | throw new Error('eventName ' + eventName + ' unsupported!')
|
651 |
|
652 | }
|
653 | }
|
654 | }
|
655 |
|
656 | protected wechatifyUserModules (puppet: Puppet) {
|
657 | log.verbose('Wechaty', 'wechatifyUserModules(%s)', puppet)
|
658 |
|
659 | if (this.wechatifiedContactSelf) {
|
660 | throw new Error('can not be initialized twice!')
|
661 | }
|
662 |
|
663 | |
664 |
|
665 |
|
666 | this.wechatifiedContact = wechatifyContact(this)
|
667 | this.wechatifiedContactSelf = wechatifyContactSelf(this)
|
668 | this.wechatifiedFriendship = wechatifyFriendship(this)
|
669 | this.wechatifiedImage = wechatifyImage(this)
|
670 | this.wechatifiedMessage = wechatifyMessage(this)
|
671 | this.wechatifiedMiniProgram = wechatifyMiniProgram(this)
|
672 | this.wechatifiedRoom = wechatifyRoom(this)
|
673 | this.wechatifiedRoomInvitation = wechatifyRoomInvitation(this)
|
674 | this.wechatifiedTag = wechatifyTag(this)
|
675 | this.wechatifiedUrlLink = wechatifyUrlLink(this)
|
676 |
|
677 | this.puppet = puppet
|
678 | }
|
679 |
|
680 | |
681 |
|
682 |
|
683 |
|
684 |
|
685 |
|
686 |
|
687 |
|
688 |
|
689 |
|
690 |
|
691 | public async start (): Promise<void> {
|
692 | log.verbose('Wechaty', '<%s>(%s) start() v%s is starting...',
|
693 | this.options.puppet || config.systemPuppetName(),
|
694 | this.options.name || '',
|
695 | this.version(),
|
696 | )
|
697 | log.verbose('Wechaty', 'id: %s', this.id)
|
698 |
|
699 | if (this.state.on()) {
|
700 | log.silly('Wechaty', 'start() on a starting/started instance')
|
701 | await this.state.ready('on')
|
702 | log.silly('Wechaty', 'start() state.ready() resolved')
|
703 | return
|
704 | }
|
705 |
|
706 | this.readyState.off(true)
|
707 |
|
708 | if (this.lifeTimer) {
|
709 | throw new Error('start() lifeTimer exist')
|
710 | }
|
711 |
|
712 | this.state.on('pending')
|
713 |
|
714 | try {
|
715 | if (!this.memory) {
|
716 | this.memory = new MemoryCard(this.options.name)
|
717 | }
|
718 |
|
719 | try {
|
720 | await this.memory.load()
|
721 | } catch (e) {
|
722 | log.silly('Wechaty', 'start() memory.load() had already loaded')
|
723 | }
|
724 |
|
725 | await this.initPuppet()
|
726 | await this.puppet.start()
|
727 |
|
728 | if (this.options.ioToken) {
|
729 | this.io = new Io({
|
730 | token : this.options.ioToken,
|
731 | wechaty : this,
|
732 | })
|
733 | await this.io.start()
|
734 | }
|
735 |
|
736 | } catch (e) {
|
737 | console.error(e)
|
738 | log.error('Wechaty', 'start() exception: %s', e && e.message)
|
739 | Raven.captureException(e)
|
740 | this.emit('error', e)
|
741 |
|
742 | try {
|
743 | await this.stop()
|
744 | } catch (e) {
|
745 | log.error('Wechaty', 'start() stop() exception: %s', e && e.message)
|
746 | Raven.captureException(e)
|
747 | this.emit('error', e)
|
748 | }
|
749 | return
|
750 | }
|
751 |
|
752 | this.on('heartbeat', () => this.memoryCheck())
|
753 |
|
754 | this.lifeTimer = setInterval(() => {
|
755 | log.silly('Wechaty', 'start() setInterval() this timer is to keep Wechaty running...')
|
756 | }, 1000 * 60 * 60)
|
757 |
|
758 | this.state.on(true)
|
759 | this.emit('start')
|
760 | }
|
761 |
|
762 | |
763 |
|
764 |
|
765 |
|
766 |
|
767 |
|
768 |
|
769 | public async stop (): Promise<void> {
|
770 | log.verbose('Wechaty', '<%s> stop() v%s is stopping ...',
|
771 | this.options.puppet || config.systemPuppetName(),
|
772 | this.version(),
|
773 | )
|
774 |
|
775 | |
776 |
|
777 |
|
778 |
|
779 | while (this.pluginUninstallerList.length > 0) {
|
780 | const uninstaller = this.pluginUninstallerList.pop()
|
781 | if (uninstaller) uninstaller()
|
782 | }
|
783 |
|
784 | if (this.state.off()) {
|
785 | log.silly('Wechaty', 'stop() on an stopping/stopped instance')
|
786 | await this.state.ready('off')
|
787 | log.silly('Wechaty', 'stop() state.ready(off) resolved')
|
788 | return
|
789 | }
|
790 |
|
791 | this.readyState.off(true)
|
792 |
|
793 | this.state.off('pending')
|
794 |
|
795 | if (this.lifeTimer) {
|
796 | clearInterval(this.lifeTimer)
|
797 | this.lifeTimer = undefined
|
798 | }
|
799 |
|
800 | try {
|
801 | await this.puppet.stop()
|
802 | } catch (e) {
|
803 | log.warn('Wechaty', 'stop() puppet.stop() exception: %s', e.message)
|
804 | }
|
805 |
|
806 | try {
|
807 | if (this.io) {
|
808 | await this.io.stop()
|
809 | this.io = undefined
|
810 | }
|
811 |
|
812 | } catch (e) {
|
813 | log.error('Wechaty', 'stop() exception: %s', e.message)
|
814 | Raven.captureException(e)
|
815 | this.emit('error', e)
|
816 | }
|
817 |
|
818 | this.state.off(true)
|
819 | this.emit('stop')
|
820 | }
|
821 |
|
822 | public async ready (): Promise<void> {
|
823 | log.verbose('Wechaty', 'ready()')
|
824 | return this.readyState.ready('on').then(() => {
|
825 | return log.silly('Wechaty', 'ready() this.readyState.ready(on) resolved')
|
826 | })
|
827 | }
|
828 |
|
829 | |
830 |
|
831 |
|
832 |
|
833 |
|
834 |
|
835 |
|
836 | public async logout (): Promise<void> {
|
837 | log.verbose('Wechaty', 'logout()')
|
838 |
|
839 | try {
|
840 | await this.puppet.logout()
|
841 | } catch (e) {
|
842 | log.error('Wechaty', 'logout() exception: %s', e.message)
|
843 | Raven.captureException(e)
|
844 | throw e
|
845 | }
|
846 | }
|
847 |
|
848 | |
849 |
|
850 |
|
851 |
|
852 |
|
853 |
|
854 |
|
855 |
|
856 |
|
857 |
|
858 |
|
859 | public logonoff (): boolean {
|
860 | try {
|
861 | return this.puppet.logonoff()
|
862 | } catch (e) {
|
863 |
|
864 | return false
|
865 | }
|
866 | }
|
867 |
|
868 | |
869 |
|
870 |
|
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 | public userSelf (): ContactSelf {
|
877 | const userId = this.puppet.selfId()
|
878 | const user = this.ContactSelf.load(userId)
|
879 | return user
|
880 | }
|
881 |
|
882 | public async say (text: string) : Promise<void>
|
883 | public async say (contact: Contact) : Promise<void>
|
884 | public async say (file: FileBox) : Promise<void>
|
885 | public async say (mini: MiniProgram) : Promise<void>
|
886 | public async say (url: UrlLink) : Promise<void>
|
887 |
|
888 | public async say (...args: never[]): Promise<never>
|
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 | public async say (
|
945 | something: string
|
946 | | Contact
|
947 | | FileBox
|
948 | | MiniProgram
|
949 | | UrlLink
|
950 | ): Promise<void> {
|
951 | log.verbose('Wechaty', 'say(%s)', something)
|
952 |
|
953 | await this.userSelf().say(something as any)
|
954 | }
|
955 |
|
956 | |
957 |
|
958 |
|
959 | public static version (gitHash = false): string {
|
960 | if (gitHash && GIT_COMMIT_HASH) {
|
961 | return `#git[${GIT_COMMIT_HASH}]`
|
962 | }
|
963 | return VERSION
|
964 | }
|
965 |
|
966 | |
967 |
|
968 |
|
969 |
|
970 |
|
971 |
|
972 |
|
973 |
|
974 |
|
975 |
|
976 |
|
977 | public version (forceNpm = false): string {
|
978 | return Wechaty.version(forceNpm)
|
979 | }
|
980 |
|
981 | |
982 |
|
983 |
|
984 | public static async sleep (millisecond: number): Promise<void> {
|
985 | await new Promise(resolve => {
|
986 | setTimeout(resolve, millisecond)
|
987 | })
|
988 | }
|
989 |
|
990 | |
991 |
|
992 |
|
993 | public async sleep (millisecond: number): Promise<void> {
|
994 | return Wechaty.sleep(millisecond)
|
995 | }
|
996 |
|
997 | |
998 |
|
999 |
|
1000 | public ding (data?: string): void {
|
1001 | log.silly('Wechaty', 'ding(%s)', data || '')
|
1002 |
|
1003 | try {
|
1004 | this.puppet.ding(data)
|
1005 | } catch (e) {
|
1006 | log.error('Wechaty', 'ding() exception: %s', e.message)
|
1007 | Raven.captureException(e)
|
1008 | throw e
|
1009 | }
|
1010 | }
|
1011 |
|
1012 | |
1013 |
|
1014 |
|
1015 | private memoryCheck (minMegabyte = 4): void {
|
1016 | const freeMegabyte = Math.floor(os.freemem() / 1024 / 1024)
|
1017 | log.silly('Wechaty', 'memoryCheck() free: %d MB, require: %d MB',
|
1018 | freeMegabyte, minMegabyte,
|
1019 | )
|
1020 |
|
1021 | if (freeMegabyte < minMegabyte) {
|
1022 | const e = new Error(`memory not enough: free ${freeMegabyte} < require ${minMegabyte} MB`)
|
1023 | log.warn('Wechaty', 'memoryCheck() %s', e.message)
|
1024 | this.emit('error', e)
|
1025 | }
|
1026 | }
|
1027 |
|
1028 | |
1029 |
|
1030 |
|
1031 | public async reset (reason?: string): Promise<void> {
|
1032 | log.verbose('Wechaty', 'reset() with reason: %s, call stack: %s',
|
1033 | reason || 'no reason',
|
1034 |
|
1035 | new Error().stack,
|
1036 | )
|
1037 | await this.puppet.stop()
|
1038 | await this.puppet.start()
|
1039 | }
|
1040 |
|
1041 | public unref (): void {
|
1042 | log.verbose('Wechaty', 'unref()')
|
1043 |
|
1044 | if (this.lifeTimer) {
|
1045 | this.lifeTimer.unref()
|
1046 | }
|
1047 |
|
1048 | this.puppet.unref()
|
1049 | }
|
1050 |
|
1051 | }
|
1052 |
|
1053 |
|
1054 |
|
1055 |
|
1056 | function guardWechatify<T extends Function> (userModule?: T): T {
|
1057 | if (!userModule) {
|
1058 | throw new Error('Wechaty user module (for example, wechaty.Room) can not be used before wechaty.start()!')
|
1059 | }
|
1060 | return userModule
|
1061 | }
|
1062 |
|
1063 | export {
|
1064 | Wechaty,
|
1065 | }
|