wechaty.ts 29.2 KB
Newer Older
1
/**
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5
 *
6 7 8
 *   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
9
 *
10
 *       http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16
 *   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.
L
lijiarui 已提交
17 18
 *
 *  @ignore
19
 */
20 21 22
import cuid    from 'cuid'
import os      from 'os'
import semver  from 'semver'
23

24
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
25
  // Constructor,
26
  cloneClass,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
  // instanceToClass,
28
}                   from 'clone-class'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
29 30 31
import {
  FileBox,
}                   from 'file-box'
32 33 34
import {
  callerResolve,
  hotImport,
35
}                   from 'hot-import'
36 37 38 39 40 41
import {
  StateSwitch,
}                   from 'state-switch'
import {
  MemoryCard,
}                   from 'memory-card'
42

43 44 45
import {
  Accessory,
}                       from './accessory'
46
import {
47
  VERSION,
48
  config,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
49
  log,
50
  Raven,
51
  Sayable,
52
}                       from './config'
53

M
Mukaiu 已提交
54
import {
55 56 57
  PUPPET_DICT,
  PuppetName,
}                       from './puppet-config'
58
import {
59 60
  Puppet,
  PuppetOptions,
61
}                       from './puppet/'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
62

63
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
64
  Contact,
65
  ContactSelf,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66 67
}                       from './contact'
import {
68
  Friendship,
69
}                       from './friendship'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
71
  Message,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72 73
}                       from './message'
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
74
  Room,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
75
}                       from './room'
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
import {
  CHAT_EVENT_DICT,
  PUPPET_EVENT_DICT,
  PuppetEventName,
  // ChatEventName,
}                       from './puppet/schemas/puppet'

// export const WECHAT_EVENT_DICT = {
//   friend      : 'tbw',
//   login       : 'tbw',
//   logout      : 'tbw',
//   message     : 'tbw',
//   'room-join' : 'tbw',
//   'room-leave': 'tbw',
//   'room-topic': 'tbw',
//   scan        : 'tbw',
// }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
94

95
export const WECHATY_EVENT_DICT = {
96
  ...CHAT_EVENT_DICT,
97 98 99 100
  error     : 'tbw',
  heartbeat : 'tbw',
  start     : 'tbw',
  stop      : 'tbw',
101 102 103
}

export type WechatyEventName  = keyof typeof WECHATY_EVENT_DICT
104 105

export interface WechatyOptions {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106 107
  puppet?  : PuppetName | Puppet,
  profile? : null | string,
108
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
109

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110
/**
L
lijiarui 已提交
111
 * Main bot class.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112
 *
L
lijiarui 已提交
113
 * [The World's Shortest ChatBot Code: 6 lines of JavaScript]{@link #wechatyinstance}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
114
 *
L
lijiarui 已提交
115 116 117
 * [Wechaty Starter Project]{@link https://github.com/lijiarui/wechaty-getting-started}
 * @example
 * import { Wechaty } from 'wechaty'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
118
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
 */
120
export class Wechaty extends Accessory implements Sayable {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
121
  /**
122
   * singleton globalInstance
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
123
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124
   */
125
  private static globalInstance: Wechaty
126

127 128
  private readonly memory : MemoryCard
  private readonly state  : StateSwitch
129

130
  private lifeTimer?: NodeJS.Timer
131

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
132
  /**
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
133
   * the cuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
134
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135
   */
136
  public readonly id : string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137

138
  // tslint:disable-next-line:variable-name
139
  public readonly Contact       : typeof Contact
140
  // tslint:disable-next-line:variable-name
141 142
  public readonly ContactSelf   : typeof ContactSelf
  // tslint:disable-next-line:variable-name
143
  public readonly Friendship    : typeof Friendship
144
  // tslint:disable-next-line:variable-name
145
  public readonly Message       : typeof Message
146
  // tslint:disable-next-line:variable-name
147
  public readonly Room          : typeof Room
148

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
150
   * get the singleton instance of Wechaty
L
lijiarui 已提交
151 152 153 154 155 156 157 158 159
   *
   * @example <caption>The World's Shortest ChatBot Code: 6 lines of JavaScript</caption>
   * const { Wechaty } = require('wechaty')
   *
   * Wechaty.instance() // Singleton
   * .on('scan', (url, code) => console.log(`Scan QR Code to login: ${code}\n${url}`))
   * .on('login',       user => console.log(`User ${user} logined`))
   * .on('message',  message => console.log(`Message: ${message}`))
   * .init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161 162 163
  public static instance(
    options?: WechatyOptions,
  ) {
164
    if (options && this.globalInstance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
165
      throw new Error('instance can be only inited once by options!')
166
    }
167 168
    if (!this.globalInstance) {
      this.globalInstance = new Wechaty(options)
169
    }
170
    return this.globalInstance
171 172
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
173
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
174
   * @public
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
176
  constructor(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177
    private options: WechatyOptions = {},
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178
  ) {
179
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180 181
    log.verbose('Wechaty', 'contructor()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
182
    options.profile = options.profile === null
183
                      ? null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
184
                      : (options.profile || config.default.DEFAULT_PROFILE)
185

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186
    this.memory = new MemoryCard(options.profile || undefined)
187 188
    this.state  = new StateSwitch('Wechaty', log)
    this.id     = cuid()
189 190 191 192 193 194 195 196 197 198

    /**
     * Clone Classes for this bot and attach the `puppet` to the Class
     *
     *   https://stackoverflow.com/questions/36886082/abstract-constructor-type-in-typescript
     *   https://github.com/Microsoft/TypeScript/issues/5843#issuecomment-290972055
     *   https://github.com/Microsoft/TypeScript/issues/19197
     */
    // TODO: make Message & Room constructor private???
    this.Contact        = cloneClass(Contact)
199
    this.ContactSelf    = cloneClass(ContactSelf)
200
    this.Friendship  = cloneClass(Friendship)
201 202
    this.Message        = cloneClass(Message)
    this.Room           = cloneClass(Room)
203 204
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
205
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
206
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
207
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
208 209 210 211 212 213
  public toString() {
    if (!this.options) {
      return this.constructor.name
    }

    return [
214 215
      'Wechaty#',
      this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216
      `<${this.options && this.options.puppet || ''}>`,
217
      `(${this.memory  && this.memory.name    || ''})`,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218 219
    ].join('')
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
   */
224
  public static version(forceNpm = false): string {
225
    if (!forceNpm) {
226
      const revision = config.gitRevision()
227
      if (revision) {
228
        return `#git[${revision}]`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
229
      }
230
    }
231
    return VERSION
232
  }
233

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
234
 /**
Huan (李卓桓)'s avatar
linting  
Huan (李卓桓) 已提交
235 236 237 238 239 240 241 242 243
  * Return version of Wechaty
  *
  * @param {boolean} [forceNpm=false]  - if set to true, will only return the version in package.json.
  *                                      otherwise will return git commit hash if .git exists.
  * @returns {string}                  - the version number
  * @example
  * console.log(Wechaty.instance().version())       // return '#git[af39df]'
  * console.log(Wechaty.instance().version(true))   // return '0.7.9'
  */
244
  public version(forceNpm = false): string {
245
    return Wechaty.version(forceNpm)
246
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
248
  public emit(event: 'error'      , error: Error)                                                     : boolean
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249
  public emit(event: 'friendship' , friendship: Friendship)                                           : boolean
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
250 251 252 253 254 255 256 257 258 259
  public emit(event: 'heartbeat'  , data: any)                                                        : boolean
  public emit(event: 'logout'     , user: ContactSelf)                                                : boolean
  public emit(event: 'login'      , user: ContactSelf)                                                : boolean
  public emit(event: 'message'    , message: Message)                                                 : boolean
  public emit(event: 'room-join'  , room: Room, inviteeList : Contact[], inviter  : Contact)          : boolean
  public emit(event: 'room-leave' , room: Room, leaverList  : Contact[], remover? : Contact)          : boolean
  public emit(event: 'room-topic' , room: Room, newTopic: string, oldTopic: string, changer: Contact) : boolean
  public emit(event: 'scan'       , qrcode: string, status: number, data?: string)                    : boolean
  public emit(event: 'start')                                                                         : boolean
  public emit(event: 'stop')                                                                          : boolean
260 261 262 263 264 265 266 267 268 269 270

  // guard for the above event: make sure it includes all the possible values
  public emit(event: never, listener: never): never

  public emit(
    event:   WechatyEventName,
    ...args: any[]
  ): boolean {
    return super.emit(event, ...args)
  }

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
271
  public on(event: 'error'      , listener: string | ((this: Wechaty, error: Error) => void))                                                     : this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
272
  public on(event: 'friendship' , listener: string | ((this: Wechaty, friendship: Friendship) => void))                                           : this
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
273 274 275 276 277 278 279 280 281 282
  public on(event: 'heartbeat'  , listener: string | ((this: Wechaty, data: any) => void))                                                        : this
  public on(event: 'logout'     , listener: string | ((this: Wechaty, user: ContactSelf) => void))                                                : this
  public on(event: 'login'      , listener: string | ((this: Wechaty, user: ContactSelf) => void))                                                : this
  public on(event: 'message'    , listener: string | ((this: Wechaty, message: Message) => void))                                                 : this
  public on(event: 'room-join'  , listener: string | ((this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void))            : this
  public on(event: 'room-leave' , listener: string | ((this: Wechaty, room: Room, leaverList: Contact[], remover?: Contact) => void))             : this
  public on(event: 'room-topic' , listener: string | ((this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void)) : this
  public on(event: 'scan'       , listener: string | ((this: Wechaty, qrcode: string, status: number, data?: string) => void))                    : this
  public on(event: 'start'      , listener: string | ((this: Wechaty) => void))                                                                   : this
  public on(event: 'stop'       , listener: string | ((this: Wechaty) => void))                                                                   : this
283

284
  // guard for the above event: make sure it includes all the possible values
285
  public on(event: never, listener: never): never
L
lijiarui 已提交
286

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
287
  /**
L
lijiarui 已提交
288 289 290 291 292 293 294 295 296 297 298 299
   * @desc       Wechaty Class Event Type
   * @typedef    WechatyEventName
   * @property   {string}  error      - When the bot get error, there will be a Wechaty error event fired.
   * @property   {string}  login      - After the bot login full successful, the event login will be emitted, with a Contact of current logined user.
   * @property   {string}  logout     - Logout will be emitted when bot detected log out, with a Contact of the current login user.
   * @property   {string}  heartbeat  - Get bot's heartbeat.
   * @property   {string}  friend     - When someone sends you a friend request, there will be a Wechaty friend event fired.
   * @property   {string}  message    - Emit when there's a new message.
   * @property   {string}  room-join  - Emit when anyone join any room.
   * @property   {string}  room-topic - Get topic event, emitted when someone change room topic.
   * @property   {string}  room-leave - Emit when anyone leave the room.<br>
   *                                    If someone leaves the room by themselves, wechat will not notice other people in the room, so the bot will never get the "leave" event.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
L
lijiarui 已提交
301 302 303 304 305 306
   */

  /**
   * @desc       Wechaty Class Event Function
   * @typedef    WechatyEventFunction
   * @property   {Function} error           -(this: Wechaty, error: Error) => void callback function
307 308
   * @property   {Function} login           -(this: Wechaty, user: ContactSelf)=> void
   * @property   {Function} logout          -(this: Wechaty, user: ContactSelf) => void
L
lijiarui 已提交
309 310 311 312 313 314 315 316 317 318 319 320
   * @property   {Function} scan            -(this: Wechaty, url: string, code: number) => void <br>
   * <ol>
   * <li>URL: {String} the QR code image URL</li>
   * <li>code: {Number} the scan status code. some known status of the code list here is:</li>
   * </ol>
   * <ul>
   * <li>0 initial_</li>
   * <li>200 login confirmed</li>
   * <li>201 scaned, wait for confirm</li>
   * <li>408 waits for scan</li>
   * </ul>
   * @property   {Function} heartbeat       -(this: Wechaty, data: any) => void
321
   * @property   {Function} friend          -(this: Wechaty, request?: Friendship) => void
L
lijiarui 已提交
322 323
   * @property   {Function} message         -(this: Wechaty, message: Message) => void
   * @property   {Function} room-join       -(this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
324
   * @property   {Function} room-topic      -(this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void
L
lijiarui 已提交
325 326 327 328 329
   * @property   {Function} room-leave      -(this: Wechaty, room: Room, leaverList: Contact[]) => void
   */

  /**
   * @listens Wechaty
330
   * @param   {WechatyEventName}      event      - Emit WechatyEvent
L
lijiarui 已提交
331 332 333
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {Wechaty}                          - this for chain
   *
334
   * More Example Gist: [Examples/Friend-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/friend-bot.ts}
L
lijiarui 已提交
335 336 337 338 339 340 341
   *
   * @example <caption>Event:scan </caption>
   * wechaty.on('scan', (url: string, code: number) => {
   *   console.log(`[${code}] Scan ${url} to login.` )
   * })
   *
   * @example <caption>Event:login </caption>
342
   * bot.on('login', (user: ContactSelf) => {
L
lijiarui 已提交
343 344 345 346
   *   console.log(`user ${user} login`)
   * })
   *
   * @example <caption>Event:logout </caption>
347
   * bot.on('logout', (user: ContactSelf) => {
L
lijiarui 已提交
348 349 350 351 352 353 354 355 356
   *   console.log(`user ${user} logout`)
   * })
   *
   * @example <caption>Event:message </caption>
   * wechaty.on('message', (message: Message) => {
   *   console.log(`message ${message} received`)
   * })
   *
   * @example <caption>Event:friend </caption>
357 358
   * bot.on('friend', (request: Friendship) => {
   *   if(request.type === Friendship.Type.RECEIVE){ // 1. receive new friend request from new contact
359
   *     const contact = request.contact()
L
lijiarui 已提交
360 361 362 363 364 365
   *     let result = await request.accept()
   *       if(result){
   *         console.log(`Request from ${contact.name()} is accept succesfully!`)
   *       } else{
   *         console.log(`Request from ${contact.name()} failed to accept!`)
   *       }
366
   * 	  } else if (request.type === Friendship.Type.CONFIRM) { // 2. confirm friend ship
L
lijiarui 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
   *       console.log(`new friendship confirmed with ${contact.name()}`)
   *    }
   *  })
   *
   * @example <caption>Event:room-join </caption>
   * bot.on('room-join', (room: Room, inviteeList: Contact[], inviter: Contact) => {
   *   const nameList = inviteeList.map(c => c.name()).join(',')
   *   console.log(`Room ${room.topic()} got new member ${nameList}, invited by ${inviter}`)
   * })
   *
   * @example <caption>Event:room-leave </caption>
   * bot.on('room-leave', (room: Room, leaverList: Contact[]) => {
   *   const nameList = leaverList.map(c => c.name()).join(',')
   *   console.log(`Room ${room.topic()} lost member ${nameList}`)
   * })
   *
   * @example <caption>Event:room-topic </caption>
   * bot.on('room-topic', (room: Room, topic: string, oldTopic: string, changer: Contact) => {
   *   console.log(`Room ${room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
   * })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
387
   */
388
  public on(event: WechatyEventName, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
389
    log.verbose('Wechaty', 'on(%s, %s) registered',
390 391 392 393 394 395
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

396
    if (typeof listener === 'function') {
397
      this.addListenerFunction(event, listener)
398
    } else {
399
      this.addListenerModuleFile(event, listener)
400
    }
401
    return this
402 403
  }

404
  private addListenerModuleFile(event: WechatyEventName, modulePath: string): void {
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    const absoluteFilename = callerResolve(modulePath, __filename)
    log.verbose('Wechaty', 'onModulePath() hotImpor(%s)', absoluteFilename)
    hotImport(absoluteFilename)
      .then((func: Function) => super.on(event, (...args: any[]) => {
        try {
          func.apply(this, args)
        } catch (e) {
          log.error('Wechaty', 'onModulePath(%s, %s) listener exception: %s',
                                event, modulePath, e)
          this.emit('error', e)
        }
      }))
      .catch(e => {
        log.error('Wechaty', 'onModulePath(%s, %s) hotImport() exception: %s',
                              event, modulePath, e)
        this.emit('error', e)
      })
  }

424
  private addListenerFunction(event: WechatyEventName, listener: Function): void {
425 426 427 428 429 430 431 432 433 434 435 436
    log.verbose('Wechaty', 'onFunction(%s)', event)

    super.on(event, (...args: any[]) => {
      try {
        listener.apply(this, args)
      } catch (e) {
        log.error('Wechaty', 'onFunction(%s) listener exception: %s', event, e)
        this.emit('error', e)
      }
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
437 438 439 440 441 442 443 444 445
  private initPuppet(): void {
    log.verbose('Wechaty', 'initPuppet(%s)', this.options.puppet)

    const puppet = this.initPuppetResolver(this.options.puppet)

    this.initPuppetVersionSatisfy(puppet)
    this.initPuppetEventBridge(puppet)
    this.initPuppetAccessory(puppet)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
446

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
447
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
448
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
449
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
450 451
  private initPuppetVersionSatisfy(puppet: Puppet): void {
    log.verbose('Wechaty', 'initPuppetVersionSatisfy(%s)', puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
452

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453
    if (this.initPuppetSemverSatisfy(
454 455
      puppet.wechatyVersionRange(),
    )) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
456
      return
457 458
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
459 460 461 462
    throw new Error(`The Puppet Plugin(${puppet.constructor.name}) `
      + `requires a version range(${puppet.wechatyVersionRange()}) `
      + `that is not satisfying the Wechaty version: ${this.version()}.`,
    )
463 464 465 466 467
  }

  /**
   * Init the Puppet
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468
  private initPuppetResolver(puppet?: PuppetName | Puppet): Puppet {
469 470
    log.verbose('Wechaty', 'initPuppetResolver(%s)', puppet)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
471
    if (!puppet) {
472
      log.info('Wechaty', 'initPuppet() using puppet: %s', config.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473 474 475
      puppet  = config.puppet
    }

476
    if (typeof puppet === 'string') {
477
      // tslint:disable-next-line:variable-name
478 479 480 481 482
      const MyPuppet = PUPPET_DICT[puppet]
      if (!MyPuppet) {
        throw new Error('no such puppet: ' + puppet)
      }

483
      const options: PuppetOptions = {
484
        memory : this.memory,
485 486
      }

487
      return new MyPuppet(options)
488

489 490
    } else if (puppet instanceof Puppet) {
      return puppet
491 492
    } else {
      throw new Error('unsupported options.puppet!')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493
    }
494
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
495

496 497 498 499
  /**
   * Plugin Version Range Check
   */
  private initPuppetSemverSatisfy(versionRange: string) {
500
    log.verbose('Wechaty', 'initPuppetSemverSatisfy(%s)', versionRange)
501
    return semver.satisfies(
502
      this.version(true),
503 504 505
      versionRange,
    )
  }
506

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
507
  protected initPuppetEventBridge(puppet: Puppet) {
508
    const eventNameList: PuppetEventName[] = Object.keys(PUPPET_EVENT_DICT) as any
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    for (const eventName of eventNameList) {
      log.verbose('Wechaty', 'initPuppetEventBridge() puppet.on(%s) registered', eventName)
      // /// e as any ??? Maybe this is a bug of TypeScript v2.5.3
      // puppet.on(event as any, (...args: any[]) => {
      //   this.emit(event, ...args)
      // })

      switch (eventName) {
        case 'error':
          puppet.removeAllListeners('error')
          puppet.on('error', error => {
            this.emit('error', new Error(error))
          })
          break

524
        case 'watchdog':
525
          puppet.removeAllListeners('heartbeat')
526 527 528 529
          puppet.on('watchdog', data => {
            /**
             * Use `watchdog` event from Puppet to `heartbeat` Wechaty.
             */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
530
            // TODO: use a throttle queue to prevent beat too fast.
531 532 533 534 535 536
            this.emit('heartbeat', data)
          })
          break

        case 'start':
        case 'stop':
537 538 539
          // do not emit 'start'/'stop' again for wechaty:
          // because both puppet & wechaty should have their own
          // `start`/`stop` event seprately
540 541
          break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555
        // case 'start':
        //   puppet.removeAllListeners('start')
        //   puppet.on('start', () => {
        //     this.emit('start')
        //   } )
        //   break

        // case 'stop':
        //   puppet.removeAllListeners('stop')
        //   puppet.on('stop', () => {
        //     this.emit('stop')
        //   } )
        //   break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
556 557 558 559 560 561 562 563 564 565 566
        case 'friendship':
          puppet.removeAllListeners('friendship')
          puppet.on('friendship', async friendshipId => {
            const friendship = this.Friendship.load(friendshipId)
            await friendship.ready()
            this.emit('friendship', friendship)
            friendship.contact().emit('friendship', friendship)

            // support deprecated event name: friend.
            // Huan LI 201806
            this.emit('friend' as any, friendship as any)
567 568 569 570 571 572
          })
          break

        case 'login':
          puppet.removeAllListeners('login')
          puppet.on('login', async contactId => {
573
            const contact = this.ContactSelf.load(contactId)
574 575 576 577 578 579 580 581
            await contact.ready()
            this.emit('login', contact)
          })
          break

        case 'logout':
          puppet.removeAllListeners('logout')
          puppet.on('logout', async contactId => {
582
            const contact = this.ContactSelf.load(contactId)
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
            await contact.ready()
            this.emit('logout', contact)
          })
          break

        case 'message':
          puppet.removeAllListeners('message')
          puppet.on('message', async messageId => {
            const msg = this.Message.create(messageId)
            await msg.ready()
            this.emit('message', msg)
          })
          break

        case 'room-join':
          puppet.removeAllListeners('room-join')
          puppet.on('room-join', async (roomId, inviteeIdList, inviterId) => {
            const room = this.Room.load(roomId)
            await room.ready()

            const inviteeList = inviteeIdList.map(id => this.Contact.load(id))
            await Promise.all(inviteeList.map(c => c.ready()))

            const inviter = this.Contact.load(inviterId)
            await inviter.ready()

            this.emit('room-join', room, inviteeList, inviter)
610
            room.emit('join', inviteeList, inviter)
611 612 613 614 615
          })
          break

        case 'room-leave':
          puppet.removeAllListeners('room-leave')
616
          puppet.on('room-leave', async (roomId, leaverIdList, removerId) => {
617 618 619 620 621 622
            const room = this.Room.load(roomId)
            await room.ready()

            const leaverList = leaverIdList.map(id => this.Contact.load(id))
            await Promise.all(leaverList.map(c => c.ready()))

623 624 625 626 627 628 629
            let remover: undefined | Contact = undefined
            if (removerId) {
              remover = this.Contact.load(removerId)
              await remover.ready()
            }

            this.emit('room-leave', room, leaverList, remover)
630
            room.emit('leave', leaverList, remover)
631 632 633 634 635
          })
          break

        case 'room-topic':
          puppet.removeAllListeners('room-topic')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
636
          puppet.on('room-topic', async (roomId, newTopic, oldTopic, changerId) => {
637 638 639 640 641 642
            const room = this.Room.load(roomId)
            await room.ready()

            const changer = this.Contact.load(changerId)
            await changer.ready()

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
643 644
            this.emit('room-topic', room, newTopic, oldTopic, changer)
            room.emit('topic', newTopic, oldTopic, changer)
645 646 647 648 649
          })
          break

        case 'scan':
          puppet.removeAllListeners('scan')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
650 651
          puppet.on('scan', async (qrcode, status, data) => {
            this.emit('scan', qrcode, status, data)
652 653 654
          })
          break

655 656 657
        case 'watchdog':
          break

658 659 660 661
        default:
          throw new Error('eventName ' + eventName + 'unsupported!')

      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
662
    }
663
  }
664

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
665
  protected initPuppetAccessory(puppet: Puppet) {
666
    log.verbose('Wechaty', 'initAccessory(%s)', puppet)
667

668
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
669
     * 1. Set Wechaty
670
     */
671
    this.Contact.wechaty       = this
672
    this.ContactSelf.wechaty   = this
673
    this.Friendship.wechaty = this
674 675 676
    this.Message.wechaty       = this
    this.Room.wechaty          = this

677
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
678
     * 2. Set Puppet
679
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
680
    this.Contact.puppet       = puppet
681
    this.ContactSelf.puppet   = puppet
682
    this.Friendship.puppet = puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
683 684 685 686
    this.Message.puppet       = puppet
    this.Room.puppet          = puppet

    this.puppet               = puppet
687 688
  }

689 690 691 692 693 694 695 696 697 698 699 700
  /**
   * Start the bot, return Promise.
   *
   * @returns {Promise<void>}
   * @example
   * await bot.start()
   * // do other stuff with bot here
   */
  public async start(): Promise<void> {
    log.info('Wechaty', 'v%s starting...' , this.version())
    log.verbose('Wechaty', 'puppet: %s'   , this.options.puppet)
    log.verbose('Wechaty', 'profile: %s'  , this.options.profile)
701
    log.verbose('Wechaty', 'id: %s'       , this.id)
702 703 704

    if (this.state.on()) {
      log.silly('Wechaty', 'start() on a starting/started instance')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
705
      await this.state.ready('on')
706 707 708 709
      log.silly('Wechaty', 'start() state.ready() resolved')
      return
    }

710 711 712 713
    if (this.lifeTimer) {
      throw new Error('start() lifeTimer exist')
    }

714 715 716
    this.state.on('pending')

    try {
717
      await this.memory.load()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
718 719

      this.initPuppet()
720 721 722 723

      await this.puppet.start()

    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
724
      console.error(e)
725 726 727 728 729 730 731
      log.error('Wechaty', 'start() exception: %s', e && e.message)
      Raven.captureException(e)
      throw e
    }

    this.on('heartbeat', () => this.memoryCheck())

732 733 734 735
    this.lifeTimer = setInterval(() => {
      log.silly('Wechaty', 'start() setInterval() this timer is to keep Wechaty running...')
    }, 1000 * 60 * 60)

736 737 738 739 740 741
    this.state.on(true)
    this.emit('start')

    return
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
742 743 744 745 746 747 748 749
  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
750
    log.verbose('Wechaty', 'stop()')
751

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
752
    if (this.state.off()) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
753 754 755
      log.silly('Wechaty', 'stop() on an stopping/stopped instance')
      await this.state.ready('off')
      log.silly('Wechaty', 'stop() state.ready(off) resolved')
756
      return
757
    }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
758

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
759
    this.state.off('pending')
760
    await this.memory.save()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
761

762 763 764 765 766
    if (this.lifeTimer) {
      clearInterval(this.lifeTimer)
      this.lifeTimer = undefined
    }

767
    try {
768
      await this.puppet.stop()
769
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
770
      log.error('Wechaty', 'stop() exception: %s', e.message)
771
      Raven.captureException(e)
772
      this.emit('error', e)
773
    }
774 775 776 777 778 779 780 781 782 783

    this.state.off(true)
    this.emit('stop')

    /**
     * MUST use setImmediate at here(the end of this function),
     * because we need to run the micro task registered by the `emit` method
     */
    setImmediate(() => this.puppet.removeAllListeners())

784
    return
785
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
786

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
787
  /**
L
lijiarui 已提交
788 789 790 791 792
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
793
   */
794
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
795 796
    log.verbose('Wechaty', 'logout()')

797 798 799 800 801 802 803
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
804
    return
805
  }
806

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
807 808 809 810 811
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
812
   * if (bot.logonoff()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
813 814 815 816 817
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
818
  public logonoff(): Boolean {
819
    return this.puppet.logonoff()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
820 821
  }

822 823 824 825
  /**
   * @deprecated
   */
  public self(): Contact {
826
    log.warn('Wechaty', 'self() DEPRECATED. use userSelf() instead.')
827 828 829
    return this.userSelf()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
830
  /**
L
lijiarui 已提交
831 832 833 834
   * Get current user
   *
   * @returns {Contact}
   * @example
835
   * const contact = bot.userSelf()
L
lijiarui 已提交
836
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
837
   */
838
  public userSelf(): Contact {
839
    const userId = this.puppet.selfId()
840
    const user = this.ContactSelf.load(userId)
841
    return user
842
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
843

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
844
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
845
   * Send message to userSelf
L
lijiarui 已提交
846
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
847
   * @param {string} textOrContactOrFile
L
lijiarui 已提交
848
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
849
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862
  public async say(textOrContactOrFile: string | Contact | FileBox): Promise<void> {
    log.verbose('Wechaty', 'say(%s)', textOrContactOrFile)

    // Make Typescript Happy:
    if (typeof textOrContactOrFile === 'string') {
      await this.userSelf().say(textOrContactOrFile)
    } else if (textOrContactOrFile instanceof Contact) {
      await this.userSelf().say(textOrContactOrFile)
    } else if (textOrContactOrFile instanceof FileBox) {
      await this.userSelf().say(textOrContactOrFile)
    } else {
      throw new Error('unsupported')
    }
863 864
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
865
  /**
L
lijiarui 已提交
866
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
867
   */
868
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
869
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
870 871 872 873
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
874
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
875
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
876
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
877
  public async ding(): Promise<false | 'dong'> {
878 879 880 881 882
    try {
      return await this.puppet.ding() // should return 'dong'
    } catch (e) {
      log.error('Wechaty', 'ding() exception: %s', e.message)
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
883
      return false
884
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
885
  }
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900

  /**
   * @private
   */
  private memoryCheck(minMegabyte = 4): void {
    const freeMegabyte = Math.floor(os.freemem() / 1024 / 1024)
    log.silly('Wechaty', 'memoryCheck() free: %d MB, require: %d MB',
                          freeMegabyte, minMegabyte)

    if (freeMegabyte < minMegabyte) {
      const e = new Error(`memory not enough: free ${freeMegabyte} < require ${minMegabyte} MB`)
      log.warn('Wechaty', 'memoryCheck() %s', e.message)
      this.emit('error', e)
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
901 902 903 904 905

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
906
    log.verbose('Wechaty', 'reset() because %s', reason || 'no reason')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
907 908
    await this.puppet.stop()
    await this.puppet.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
909 910 911
    return
  }

912 913 914
  public unref(): void {
    log.warn('Wechaty', 'unref() To Be Implemented. See: https://github.com/Chatie/wechaty/issues/1197')
  }
915
}
916 917

export default Wechaty