puppet-web.ts 14.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Class PuppetWeb
 *
 * use to control wechat in web browser.
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 *
 * Class PuppetWeb
 *
15
 */
16
import {
17 18
    // Config
    ScanInfo
19 20
  , WatchdogFood
}                     from '../config'
21

22
import Contact        from '../contact'
23
// import FriendRequest  from '../friend-request'
24 25 26 27 28 29 30 31 32 33 34
import Message        from '../message'
import Puppet         from '../puppet'
import Room           from '../room'
import UtilLib        from '../util-lib'
import log            from '../brolog-env'

import Bridge         from './bridge'
import Browser        from './browser'
import Event          from './event'
import Server         from './server'
import Watchdog       from './watchdog'
35

36
export type PuppetWebSetting = {
37 38 39
  head?:    string
  profile?: string
}
40 41
const DEFAULT_PUPPET_PORT = 18788 // // W(87) X(88), ascii char code ;-]

42
export class PuppetWeb extends Puppet {
43

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44 45
  public browser: Browser
  public bridge:  Bridge
46
  public server: Server
47

48 49
  public scan:    ScanInfo

50 51
  private port: number

52
  constructor(private setting: PuppetWebSetting = {}) {
53
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54 55

    this.on('watchdog', Watchdog.onFeed.bind(this))
56 57
  }

58
  public toString() { return `Class PuppetWeb({browser:${this.browser},port:${this.port}})` }
59

60
  public async init(): Promise<PuppetWeb> {
61
    log.verbose('PuppetWeb', `init() with head:${this.setting.head}, profile:${this.setting.profile}`)
62

63 64 65
    // this.readyState('connecting')
    this.targetState('live')
    this.currentState('birthing')
66

67 68
    // return co.call(this, function* () {
    try {
69

70
      this.port = await UtilLib.getPort(DEFAULT_PUPPET_PORT)
71 72
      log.verbose('PuppetWeb', 'init() getPort %d', this.port)

73 74 75
      // @deprecated 20161004
      // yield this.initAttach(this)
      // log.verbose('PuppetWeb', 'initAttach() done')
76

77
      await this.initServer()
78 79
      log.verbose('PuppetWeb', 'initServer() done')

80
      await this.initBrowser()
81 82
      log.verbose('PuppetWeb', 'initBrowser() done')

83
      await this.initBridge()
84 85
      log.verbose('PuppetWeb', 'initBridge() done')

86 87 88 89 90
      const food: WatchdogFood = {
        data: 'inited'
        , timeout: 120000 // 2 mins for first login
      }
      this.emit('watchdog', food)
91 92 93 94

      // return this
    // }).catch(e => {   // Reject
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95 96
      log.error('PuppetWeb', 'init() exception: %s', e.stack)
      await this.quit()
97
      throw e
98 99
    }
    // .then(() => {   // Finally
100
      log.verbose('PuppetWeb', 'init() done')
101 102
      // this.readyState('connected')
      this.currentState('live')
103
      return this   // for Chaining
104
    // })
105 106
  }

107
  public async quit(): Promise<any> {
108
    log.verbose('PuppetWeb', 'quit()')
109
    this.targetState('dead')
110

111 112 113 114
    // if (this.readyState() === 'disconnecting') {
    if (this.currentState() === 'killing') {
      // log.warn('PuppetWeb', 'quit() is called but readyState is `disconnecting`?')
      log.warn('PuppetWeb', 'quit() is called but currentState is `killing`?')
115 116 117 118 119 120 121 122 123
      throw new Error('do not call quit again when quiting')
    }

    // POISON must feed before readyState set to "disconnecting"
    this.emit('watchdog', {
      data: 'PuppetWeb.quit()',
      type: 'POISON'
    })

124 125
    // this.readyState('disconnecting')
    this.currentState('killing')
126

127 128
    // return co.call(this, function* () {
    try {
129 130

      if (this.bridge)  {
131
        await this.bridge.quit()
132 133 134 135 136 137 138 139
                        .catch(e => { // fail safe
                          log.warn('PuppetWeb', 'quit() bridge.quit() exception: %s', e.message)
                        })
        log.verbose('PuppetWeb', 'quit() bridge.quit() this.bridge = null')
        this.bridge = null
      } else { log.warn('PuppetWeb', 'quit() without a bridge') }

      if (this.server) {
140
        await this.server.quit()
141 142 143 144 145
        this.server = null
        log.verbose('PuppetWeb', 'quit() server.quit() this.server = null')
      } else { log.verbose('PuppetWeb', 'quit() without a server') }

      if (this.browser) {
146
        await this.browser.quit()
147 148 149 150 151 152 153
                  .catch(e => { // fail safe
                    log.warn('PuppetWeb', 'quit() browser.quit() exception: %s', e.message)
                  })
        log.verbose('PuppetWeb', 'quit() server.quit() this.browser = null')
        this.browser = null
      } else { log.warn('PuppetWeb', 'quit() without a browser') }

154 155
      // @deprecated 20161004
      // log.verbose('PuppetWeb', 'quit() server.quit() this.initAttach(null)')
156
      // await this.initAttach(null)
157 158

      this.currentState('dead')
159 160
    // }).catch(e => { // Reject
    } catch (e) {
161
      log.error('PuppetWeb', 'quit() exception: %s', e.message)
162
      this.currentState('dead')
163
      throw e
164 165 166
    }

    // .then(() => { // Finally, Fail Safe
167
      log.verbose('PuppetWeb', 'quit() done')
168 169
      // this.readyState('disconnected')
      this.currentState('dead')
170
      return this   // for Chaining
171
    // })
172 173
  }

174
  public async initBrowser(): Promise<Browser> {
175
    log.verbose('PuppetWeb', 'initBrowser()')
176 177 178 179
    const browser = new Browser({
        head:         this.setting.head
      , sessionFile:  this.setting.profile
    })
180 181 182

    browser.on('dead', Event.onBrowserDead.bind(this))

183
    this.browser = browser
184

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185 186
    if (this.targetState() !== 'live') {
      log.warn('PuppetWeb', 'initBrowser() found targetState != live, no init anymore')
187 188
      // return Promise.resolve('skipped')
      return Promise.reject('skipped')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189 190
    }

191 192 193 194 195
    // return co.call(this, function* () {
    try {
      await browser.init()
    // }).catch(e => {
    } catch (e) {
196 197
      log.error('PuppetWeb', 'initBrowser() exception: %s', e.message)
      throw e
198
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
199
    return browser // follow func name meaning
200 201
  }

202
  public initBridge(): Promise<Bridge> {
203
    log.verbose('PuppetWeb', 'initBridge()')
204 205 206 207
    const bridge = new Bridge(
        this // use puppet instead of browser, is because browser might change(die) duaring run time
      , this.port
    )
208

209 210
    this.bridge = bridge

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211
    if (this.targetState() !== 'live') {
212 213 214
      const errMsg = 'initBridge() found targetState != live, no init anymore'
      log.warn('PuppetWeb', errMsg)
      return Promise.reject(errMsg)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216

217
    return bridge.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218
                .catch(e => {
219
                  if (!this.browser) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220 221
                    log.warn('PuppetWeb', 'initBridge() without browser?')
                  } else if (this.browser.dead()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222 223 224 225 226 227
                    log.warn('PuppetWeb', 'initBridge() found browser dead, wait it to restore')
                  } else {
                    log.error('PuppetWeb', 'initBridge() exception: %s', e.message)
                    throw e
                  }
                })
228 229
  }

230
  private initServer(): Promise<Server> {
231
    log.verbose('PuppetWeb', 'initServer()')
232
    const server = new Server(this.port)
233 234 235 236 237 238 239 240

    server.on('scan'    , Event.onServerScan.bind(this))
    server.on('login'   , Event.onServerLogin.bind(this))
    server.on('logout'  , Event.onServerLogout.bind(this))
    server.on('message' , Event.onServerMessage.bind(this))

    /**
     * @depreciated 20160825 zixia
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
241
     *
242
     * when `unload` there should always be a `disconnect` event?
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
243
     */
244 245 246 247 248 249 250
    // server.on('unload'  , Event.onServerUnload.bind(this))

    server.on('connection', Event.onServerConnection.bind(this))
    server.on('disconnect', Event.onServerDisconnect.bind(this))
    server.on('log'       , Event.onServerLog.bind(this))
    server.on('ding'      , Event.onServerDing.bind(this))

251 252
    this.server = server

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
253
    if (this.targetState() !== 'live') {
254 255 256
      const errMsg = 'initServer() found targetState != live, no init anymore'
      log.warn('PuppetWeb', errMsg)
      return Promise.reject(errMsg)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257 258
    }

259
    return server.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
260 261 262 263
                .catch(e => {
                  log.error('PuppetWeb', 'initServer() exception: %s', e.message)
                  throw e
                })
264 265
  }

266 267 268 269 270 271 272 273 274
  public reset(reason?: string) {
    log.verbose('PuppetWeb', 'reset(%s)', reason)

    if (this.browser) {
      this.browser.dead('restart required by reset()')
    } else {
      log.warn('PuppetWeb', 'reset() without browser')
    }
  }
275

276
  public self(message?: Message): boolean | Contact {
277 278 279 280
    if (!this.userId) {
      log.verbose('PuppetWeb', 'self() got no this.userId')
      return false
    }
281 282
    if (message && message.from()) {
      return this.userId === message.get('from')
283
    }
284
    return this.user
285
  }
286

287 288 289
  public send(message: Message) {
    const to      = message.to()
    const room    = message.room()
290

291
    let content     = message.content()
292

293
    let destination: Contact|Room = to
294 295
    if (room) {
      destination = room
296
      // TODO use the right @
297 298 299
      // if (to && to!==room) {
      //   content = `@[${to}] ${content}`
      // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300 301

      if (!to) {
302
        message.to(room)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
303
      }
304 305
    }

306 307 308 309 310
    log.silly('PuppetWeb', 'send() destination: %s, content: %s)'
                          , room ? room.topic() : to.name()
                          , content
    )
    return this.bridge.send(destination.id, content)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
311 312 313 314
                      .catch(e => {
                        log.error('PuppetWeb', 'send() exception: %s', e.message)
                        throw e
                      })
315
  }
316

317 318 319 320 321 322 323 324 325 326 327 328 329
  /**
   * Bot say...
   * send to `filehelper` for notice / log
   */
  public say(content: string) {
    const m = new Message()
    m.to('filehelper')
    m.content(content)

    return this.send(m)
  }

  // @deprecated
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
330 331
  public reply(message: Message, replyContent: string) {
    log.warn('PuppetWeb', 'reply() @deprecated, please use Message.say()')
332 333 334
    if (this.self(message)) {
      return Promise.reject(new Error('will not to reply message of myself'))
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
335
    return message.say(replyContent)
336 337 338 339 340
  }

  /**
   * logout from browser, then server will emit `logout` event
   */
341
  public logout() {
342
    return this.bridge.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
343 344 345 346
                      .catch(e => {
                        log.error('PuppetWeb', 'logout() exception: %s', e.message)
                        throw e
                      })
347 348
  }

349
  public getContact(id: string): Promise<any> {
350 351 352
    if (!this.bridge) {
      throw new Error('PuppetWeb has no bridge for getContact()')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
353

354
    return this.bridge.getContact(id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
355 356 357 358
                      .catch(e => {
                        log.error('PuppetWeb', 'getContact(%d) exception: %s', id, e.message)
                        throw e
                      })
359
  }
360
  public logined() { return !!(this.user) }
361
  public ding(data?: any): Promise<any> {
362 363 364 365
    if (!this.bridge) {
      return Promise.reject(new Error('ding fail: no bridge(yet)!'))
    }
    return this.bridge.ding(data)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366 367 368 369
                      .catch(e => {
                        log.warn('PuppetWeb', 'ding(%s) rejected: %s', data, e.message)
                        throw e
                      })
370
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
371

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372
  public contactFind(filterFunc: string): Promise<Contact[]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
373 374 375
    if (!this.bridge) {
      return Promise.reject(new Error('contactFind fail: no bridge(yet)!'))
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
376
    return this.bridge.contactFind(filterFunc)
377
                      .then(idList => idList.map(id => Contact.load(id)))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
379
                        log.warn('PuppetWeb', 'contactFind(%s) rejected: %s', filterFunc, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
380 381 382 383
                        throw e
                      })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
384
  public roomFind(filterFunc: string): Promise<Room[]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
385 386 387
    if (!this.bridge) {
      return Promise.reject(new Error('findRoom fail: no bridge(yet)!'))
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
388
    return this.bridge.roomFind(filterFunc)
389
                      .then(idList => idList.map(id => Room.load(id)))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
390
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
391
                        log.warn('PuppetWeb', 'roomFind(%s) rejected: %s', filterFunc, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
392 393 394 395
                        throw e
                      })
  }

396
  public roomDel(room: Room, contact: Contact): Promise<number> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397 398 399
    if (!this.bridge) {
      return Promise.reject(new Error('roomDelMember fail: no bridge(yet)!'))
    }
400 401
    const roomId    = room.id
    const contactId = contact.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
402 403
    return this.bridge.roomDelMember(roomId, contactId)
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
404
                        log.warn('PuppetWeb', 'roomDelMember(%s, %d) rejected: %s', roomId, contactId, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
405 406 407 408
                        throw e
                      })
  }

409
  public roomAdd(room: Room, contact: Contact): Promise<number> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
410 411 412
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }
413 414
    const roomId    = room.id
    const contactId = contact.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415 416 417 418 419
    return this.bridge.roomAddMember(roomId, contactId)
                      .catch(e => {
                        log.warn('PuppetWeb', 'roomAddMember(%s) rejected: %s', contact, e.message)
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
421

422
  public roomTopic(room: Room, topic: string): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423 424
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
425 426
    }
    if (!room || typeof topic === 'undefined') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
427
      return Promise.reject(new Error('room or topic not found'))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
428
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429 430

    const roomId = room.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
431 432
    return this.bridge.roomModTopic(roomId, topic)
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
433
                        log.warn('PuppetWeb', 'roomTopic(%s) rejected: %s', topic, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
434 435
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
436 437
  }

438
  public roomCreate(contactList: Contact[], topic: string): Promise<Room> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
439 440 441 442
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

443
    if (!contactList || ! contactList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
444 445 446
      throw new Error('contactList not found')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
447
    const contactIdList = contactList.map(c => c.id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
448

449 450
// console.log('puppet roomCreate: ')
// console.log(contactIdList)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
451
    return this.bridge.roomCreate(contactIdList, topic)
452
                      .then(roomId => Room.load(roomId))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453
                      .catch(e => {
454
                        log.warn('PuppetWeb', 'roomCreate(%s, %s) rejected: %s', contactIdList.join(','), topic, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
455 456
                        throw e
                      })
457 458 459 460 461
  }

  /**
   * FriendRequest
   */
462
  public friendRequestSend(contact: Contact, hello: string): Promise<any> {
463 464 465 466
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

467 468
    if (!contact) {
      throw new Error('contact not found')
469
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
470

471
    return this.bridge.verifyUserRequest(contact.id, hello)
472
                      .catch(e => {
473
                        log.warn('PuppetWeb', 'bridge.verifyUserRequest(%s, %s) rejected: %s', contact.id, hello, e.message)
474 475
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
476 477
  }

478
  public friendRequestAccept(contact: Contact, ticket: string): Promise<any> {
479 480 481 482
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

483 484
    if (!contact || !ticket) {
      throw new Error('contact or ticket not found')
485 486
    }

487
    return this.bridge.verifyUserOk(contact.id, ticket)
488
                      .catch(e => {
489
                        log.warn('PuppetWeb', 'bridge.verifyUserOk(%s, %s) rejected: %s', contact.id, ticket, e.message)
490 491 492
                        throw e
                      })
  }
493 494
}

495 496
// module.exports = PuppetWeb.default = PuppetWeb.PuppetWeb = PuppetWeb
export default PuppetWeb