puppet-web.ts 14.8 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

26
import Contact        from '../contact'
27
// import FriendRequest  from '../friend-request'
28 29 30 31 32 33 34 35 36 37 38
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'
39

40 41 42 43
type PuppetWebSetting = {
  head?:    string
  profile?: string
}
44 45
const DEFAULT_PUPPET_PORT = 18788 // // W(87) X(88), ascii char code ;-]

46
class PuppetWeb extends Puppet {
47

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
48 49
  public browser: Browser
  public bridge:  Bridge
50
  public server: Server
51

52 53
  public scan:    ScanInfo

54 55
  private port: number

56
  constructor(private setting: PuppetWebSetting = {}) {
57
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
58 59

    this.on('watchdog', Watchdog.onFeed.bind(this))
60 61
  }

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

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

67 68 69
    // this.readyState('connecting')
    this.targetState('live')
    this.currentState('birthing')
70

71 72
    // return co.call(this, function* () {
    try {
73

74
      this.port = await UtilLib.getPort(DEFAULT_PUPPET_PORT)
75 76
      log.verbose('PuppetWeb', 'init() getPort %d', this.port)

77 78 79
      // @deprecated 20161004
      // yield this.initAttach(this)
      // log.verbose('PuppetWeb', 'initAttach() done')
80

81
      await this.initServer()
82 83
      log.verbose('PuppetWeb', 'initServer() done')

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

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

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

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

111
  public async quit(): Promise<any> {
112
    log.verbose('PuppetWeb', 'quit()')
113
    this.targetState('dead')
114

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

128 129
    // this.readyState('disconnecting')
    this.currentState('killing')
130

131 132
    // return co.call(this, function* () {
    try {
133 134

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

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

158 159
      // @deprecated 20161004
      // log.verbose('PuppetWeb', 'quit() server.quit() this.initAttach(null)')
160
      // await this.initAttach(null)
161 162

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

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

178
  private async initBrowser(): Promise<Browser> {
179
    log.verbose('PuppetWeb', 'initBrowser()')
180 181 182 183
    const browser = new Browser({
        head:         this.setting.head
      , sessionFile:  this.setting.profile
    })
184 185 186

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

187
    this.browser = browser
188

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

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

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

213 214
    this.bridge = bridge

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

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

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

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

255 256
    this.server = server

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

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

270 271 272 273 274 275 276 277 278
  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')
    }
  }
279

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

291 292 293
  public send(message: Message) {
    const to      = message.to()
    const room    = message.room()
294

295
    let content     = message.content()
296

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

      if (!to) {
306
        message.to(room)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307
      }
308 309
    }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
321 322 323
  public reply(message: Message, replyContent: string) {
    log.warn('PuppetWeb', 'reply() @deprecated, please use Message.say()')

324 325 326
    if (this.self(message)) {
      return Promise.reject(new Error('will not to reply message of myself'))
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327
    return message.say(replyContent)
328 329 330 331 332
  }

  /**
   * logout from browser, then server will emit `logout` event
   */
333
  public logout() {
334
    return this.bridge.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
335 336 337 338
                      .catch(e => {
                        log.error('PuppetWeb', 'logout() exception: %s', e.message)
                        throw e
                      })
339 340
  }

341
  public getContact(id: string): Promise<any> {
342 343 344
    if (!this.bridge) {
      throw new Error('PuppetWeb has no bridge for getContact()')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345

346
    return this.bridge.getContact(id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
347 348 349 350
                      .catch(e => {
                        log.error('PuppetWeb', 'getContact(%d) exception: %s', id, e.message)
                        throw e
                      })
351
  }
352
  public logined() { return !!(this.user) }
353
  public ding(data: any): Promise<any> {
354 355 356 357
    if (!this.bridge) {
      return Promise.reject(new Error('ding fail: no bridge(yet)!'))
    }
    return this.bridge.ding(data)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
358 359 360 361
                      .catch(e => {
                        log.warn('PuppetWeb', 'ding(%s) rejected: %s', data, e.message)
                        throw e
                      })
362
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
364
  public contactFind(filterFunc: string): Promise<Contact[]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365 366 367
    if (!this.bridge) {
      return Promise.reject(new Error('contactFind fail: no bridge(yet)!'))
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
368
    return this.bridge.contactFind(filterFunc)
369
                      .then(idList => idList.map(id => Contact.load(id)))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
370
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
371
                        log.warn('PuppetWeb', 'contactFind(%s) rejected: %s', filterFunc, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372 373 374 375
                        throw e
                      })
  }

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

388
  public roomDel(room: Room, contact: Contact): Promise<number> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
389 390 391
    if (!this.bridge) {
      return Promise.reject(new Error('roomDelMember fail: no bridge(yet)!'))
    }
392 393
    const roomId    = room.id
    const contactId = contact.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
394 395
    return this.bridge.roomDelMember(roomId, contactId)
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
396
                        log.warn('PuppetWeb', 'roomDelMember(%s, %d) rejected: %s', roomId, contactId, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397 398 399 400
                        throw e
                      })
  }

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

414
  public roomTopic(room: Room, topic: string): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415 416
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
417 418
    }
    if (!room || typeof topic === 'undefined') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419
      return Promise.reject(new Error('room or topic not found'))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
421 422

    const roomId = room.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423 424
    return this.bridge.roomModTopic(roomId, topic)
                      .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
425
                        log.warn('PuppetWeb', 'roomTopic(%s) rejected: %s', topic, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
426 427
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
428 429
  }

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

435
    if (!contactList || ! contactList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
436 437 438
      throw new Error('contactList not found')
    }

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

441 442
// console.log('puppet roomCreate: ')
// console.log(contactIdList)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
443
    return this.bridge.roomCreate(contactIdList, topic)
444
                      .then(roomId => Room.load(roomId))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
445
                      .catch(e => {
446
                        log.warn('PuppetWeb', 'roomCreate(%s, %s) rejected: %s', contactIdList.join(','), topic, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
447 448
                        throw e
                      })
449 450 451 452 453
  }

  /**
   * FriendRequest
   */
454
  public friendRequestSend(contact: Contact, hello: string): Promise<any> {
455 456 457 458
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

459 460
    if (!contact) {
      throw new Error('contact not found')
461
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
462

463
    return this.bridge.verifyUserRequest(contact.id, hello)
464
                      .catch(e => {
465
                        log.warn('PuppetWeb', 'bridge.verifyUserRequest(%s, %s) rejected: %s', contact.id, hello, e.message)
466 467
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468 469
  }

470
  public friendRequestAccept(contact: Contact, ticket: string): Promise<any> {
471 472 473 474
    if (!this.bridge) {
      return Promise.reject(new Error('fail: no bridge(yet)!'))
    }

475 476
    if (!contact || !ticket) {
      throw new Error('contact or ticket not found')
477 478
    }

479
    return this.bridge.verifyUserOk(contact.id, ticket)
480
                      .catch(e => {
481
                        log.warn('PuppetWeb', 'bridge.verifyUserOk(%s, %s) rejected: %s', contact.id, ticket, e.message)
482 483 484
                        throw e
                      })
  }
485 486
}

487 488
// module.exports = PuppetWeb.default = PuppetWeb.PuppetWeb = PuppetWeb
export default PuppetWeb