puppet-web.ts 15.2 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 17
 */
// const util  = require('util')
// const fs    = require('fs')
18 19
// const co    = require('co')

20
import {
21 22
    Config
  , ScanInfo
23 24
  , WatchdogFood
}                     from '../config'
25
import Contact        from '../contact'
26
// import FriendRequest  from '../friend-request'
27 28 29 30 31 32 33 34 35 36 37
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'
38

39 40
const DEFAULT_PUPPET_PORT = 18788 // // W(87) X(88), ascii char code ;-]

41
class PuppetWeb extends Puppet {
42

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

47 48
  public scan:    ScanInfo

49 50 51 52 53 54
  private port: number

  constructor(
      private head: string    = Config.head
    , private profile: string = null  // if not set profile, then do not store session.
  ) {
55
    super()
56 57
    // this.head     = head
    // this.profile  = profile
58

59 60
    // this.userId = null  // user id
    // this.user   = null  // <Contact> of user self
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61 62

    this.on('watchdog', Watchdog.onFeed.bind(this))
63 64
  }

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

67
  public async init(): Promise<PuppetWeb> {
68 69
    log.verbose('PuppetWeb', `init() with head:${this.head}, profile:${this.profile}`)

70 71 72
    // this.readyState('connecting')
    this.targetState('live')
    this.currentState('birthing')
73

74 75
    // return co.call(this, function* () {
    try {
76

77
      this.port = await UtilLib.getPort(DEFAULT_PUPPET_PORT)
78 79
      log.verbose('PuppetWeb', 'init() getPort %d', this.port)

80 81 82
      // @deprecated 20161004
      // yield this.initAttach(this)
      // log.verbose('PuppetWeb', 'initAttach() done')
83

84
      await this.initServer()
85 86
      log.verbose('PuppetWeb', 'initServer() done')

87
      await this.initBrowser()
88 89
      log.verbose('PuppetWeb', 'initBrowser() done')

90
      await this.initBridge()
91 92
      log.verbose('PuppetWeb', 'initBridge() done')

93 94 95 96 97
      const food: WatchdogFood = {
        data: 'inited'
        , timeout: 120000 // 2 mins for first login
      }
      this.emit('watchdog', food)
98 99 100 101

      // return this
    // }).catch(e => {   // Reject
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
102 103
      log.error('PuppetWeb', 'init() exception: %s', e.stack)
      await this.quit()
104
      throw e
105 106
    }
    // .then(() => {   // Finally
107
      log.verbose('PuppetWeb', 'init() done')
108 109
      // this.readyState('connected')
      this.currentState('live')
110
      return this   // for Chaining
111
    // })
112 113
  }

114
  public async quit(): Promise<any> {
115
    log.verbose('PuppetWeb', 'quit()')
116
    this.targetState('dead')
117

118 119 120 121
    // 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`?')
122 123 124 125 126 127 128 129 130
      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'
    })

131 132
    // this.readyState('disconnecting')
    this.currentState('killing')
133

134 135
    // return co.call(this, function* () {
    try {
136 137

      if (this.bridge)  {
138
        await this.bridge.quit()
139 140 141 142 143 144 145 146
                        .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) {
147
        await this.server.quit()
148 149 150 151 152
        this.server = null
        log.verbose('PuppetWeb', 'quit() server.quit() this.server = null')
      } else { log.verbose('PuppetWeb', 'quit() without a server') }

      if (this.browser) {
153
        await this.browser.quit()
154 155 156 157 158 159 160
                  .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') }

161 162
      // @deprecated 20161004
      // log.verbose('PuppetWeb', 'quit() server.quit() this.initAttach(null)')
163
      // await this.initAttach(null)
164 165

      this.currentState('dead')
166 167
    // }).catch(e => { // Reject
    } catch (e) {
168
      log.error('PuppetWeb', 'quit() exception: %s', e.message)
169
      this.currentState('dead')
170
      throw e
171 172 173
    }

    // .then(() => { // Finally, Fail Safe
174
      log.verbose('PuppetWeb', 'quit() done')
175 176
      // this.readyState('disconnected')
      this.currentState('dead')
177
      return this   // for Chaining
178
    // })
179 180
  }

181
  private async initBrowser(): Promise<Browser> {
182
    log.verbose('PuppetWeb', 'initBrowser()')
183 184 185 186
    const browser = new Browser(
        this.head
      , this.profile
    )
187 188 189

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

190
    this.browser = browser
191

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
192 193
    if (this.targetState() !== 'live') {
      log.warn('PuppetWeb', 'initBrowser() found targetState != live, no init anymore')
194 195
      // return Promise.resolve('skipped')
      return Promise.reject('skipped')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
196 197
    }

198 199 200 201 202
    // return co.call(this, function* () {
    try {
      await browser.init()
    // }).catch(e => {
    } catch (e) {
203 204
      log.error('PuppetWeb', 'initBrowser() exception: %s', e.message)
      throw e
205
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
    return browser // follow func name meaning
207 208
  }

209
  private initBridge(): Promise<Bridge> {
210
    log.verbose('PuppetWeb', 'initBridge()')
211 212 213 214
    const bridge = new Bridge(
        this // use puppet instead of browser, is because browser might change(die) duaring run time
      , this.port
    )
215

216 217
    this.bridge = bridge

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218
    if (this.targetState() !== 'live') {
219 220 221
      const errMsg = 'initBridge() found targetState != live, no init anymore'
      log.warn('PuppetWeb', errMsg)
      return Promise.reject(errMsg)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223

224
    return bridge.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
                .catch(e => {
226
                  if (!this.browser) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228
                    log.warn('PuppetWeb', 'initBridge() without browser?')
                  } else if (this.browser.dead()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
229 230 231 232 233 234
                    log.warn('PuppetWeb', 'initBridge() found browser dead, wait it to restore')
                  } else {
                    log.error('PuppetWeb', 'initBridge() exception: %s', e.message)
                    throw e
                  }
                })
235 236
  }

237
  private initServer(): Promise<Server> {
238
    log.verbose('PuppetWeb', 'initServer()')
239
    const server = new Server(this.port)
240 241 242 243 244 245 246 247

    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 (李卓桓) 已提交
248
     *
249
     * when `unload` there should always be a `disconnect` event?
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
250
     */
251 252 253 254 255 256 257
    // 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))

258 259
    this.server = server

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
260
    if (this.targetState() !== 'live') {
261 262 263
      const errMsg = 'initServer() found targetState != live, no init anymore'
      log.warn('PuppetWeb', errMsg)
      return Promise.reject(errMsg)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264 265
    }

266
    return server.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267 268 269 270
                .catch(e => {
                  log.error('PuppetWeb', 'initServer() exception: %s', e.message)
                  throw e
                })
271 272
  }

273 274 275 276 277 278 279 280 281
  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')
    }
  }
282

283
  public self(message?: Message): boolean | Contact {
284 285 286 287
    if (!this.userId) {
      log.verbose('PuppetWeb', 'self() got no this.userId')
      return false
    }
288 289
    if (message && message.from()) {
      return this.userId === message.get('from')
290
    }
291
    return this.user
292
  }
293

294 295 296
  public send(message: Message) {
    const to      = message.to()
    const room    = message.room()
297

298
    let content     = message.content()
299

300
    let destination: Contact|Room = to
301 302
    if (room) {
      destination = room
303
      // TODO use the right @
304 305 306
      // if (to && to!==room) {
      //   content = `@[${to}] ${content}`
      // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307 308

      if (!to) {
309
        message.to(room)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
310
      }
311 312
    }

313 314 315 316 317
    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 (李卓桓) 已提交
318 319 320 321
                      .catch(e => {
                        log.error('PuppetWeb', 'send() exception: %s', e.message)
                        throw e
                      })
322
  }
323

324
  public reply(message, replyContent) {
325 326 327 328 329 330 331 332 333 334 335 336 337
    if (this.self(message)) {
      return Promise.reject(new Error('will not to reply message of myself'))
    }

    const m = new Message()
    .set('content'  , replyContent)

    .set('from'     , message.obj.to)
    .set('to'       , message.obj.from)
    .set('room'     , message.obj.room)

    // log.verbose('PuppetWeb', 'reply() by message: %s', util.inspect(m))
    return this.send(m)
338 339 340 341
                .catch(e => {
                  log.error('PuppetWeb', 'reply() exception: %s', e.message)
                  throw e
                })
342 343 344 345 346
  }

  /**
   * logout from browser, then server will emit `logout` event
   */
347
  public logout() {
348
    return this.bridge.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349 350 351 352
                      .catch(e => {
                        log.error('PuppetWeb', 'logout() exception: %s', e.message)
                        throw e
                      })
353 354
  }

355
  public getContact(id: string): Promise<any> {
356 357 358
    if (!this.bridge) {
      throw new Error('PuppetWeb has no bridge for getContact()')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
359

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

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

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

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

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

428
  public roomTopic(room: Room, topic: string): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429 430
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
431 432
    }
    if (!room || typeof topic === 'undefined') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
433
      return Promise.reject(new Error('room or topic not found'))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
434
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
435 436

    const roomId = room.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
437 438
    return this.bridge.roomModTopic(roomId, topic)
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
439
                        log.warn('PuppetWeb', 'roomTopic(%s) rejected: %s', topic, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440 441
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
442 443
  }

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

449
    if (!contactList || ! contactList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
450 451 452
      throw new Error('contactList not found')
    }

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

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

  /**
   * FriendRequest
   */
468
  public friendRequestSend(contact: Contact, hello: string): Promise<any> {
469 470 471 472
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

473 474
    if (!contact) {
      throw new Error('contact not found')
475
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
476

477
    return this.bridge.verifyUserRequest(contact.id, hello)
478
                      .catch(e => {
479
                        log.warn('PuppetWeb', 'bridge.verifyUserRequest(%s, %s) rejected: %s', contact.id, hello, e.message)
480 481
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
482 483
  }

484
  public friendRequestAccept(contact: Contact, ticket: string): Promise<any> {
485 486 487 488
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

489 490
    if (!contact || !ticket) {
      throw new Error('contact or ticket not found')
491 492
    }

493
    return this.bridge.verifyUserOk(contact.id, ticket)
494
                      .catch(e => {
495
                        log.warn('PuppetWeb', 'bridge.verifyUserOk(%s, %s) rejected: %s', contact.id, ticket, e.message)
496 497 498
                        throw e
                      })
  }
499 500
}

501 502
// module.exports = PuppetWeb.default = PuppetWeb.PuppetWeb = PuppetWeb
export default PuppetWeb