index.js 8.8 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/**
 *
 * 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
 *
 ***************************************/
const util  = require('util')
const fs    = require('fs')
const co    = require('co')

const log = require('../npmlog-env')
const Puppet  = require('../puppet')
const Contact = require('../contact')
const Room    = require('../room')
const Message = require('../message')

const Server  = require('./server')
const Browser = require('./browser')
const Bridge  = require('./bridge')

const Event     = require('./event')
const Watchdog  = require('./watchdog')

36
const UtilLib = require('../util-lib')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
37
const Config  = require('../config')
38

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
39 40
class PuppetWeb extends Puppet {
  constructor({
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
41
    head = Config.DEFAULT_HEAD
42
    , profile = null  // if not set profile, then do not store session.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
43 44 45 46 47 48 49 50 51 52 53 54
  } = {}) {
    super()
    this.head     = head
    this.profile  = profile

    this.userId = null  // user id
    this.user   = null  // <Contact> of user self
  }

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

  init() {
55
    log.verbose('PuppetWeb', `init() with head:${this.head}, profile:${this.profile}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
56

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57 58
    this.readyState('connecting')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
59 60 61 62
    this.on('watchdog', Watchdog.onFeed.bind(this))

    return co.call(this, function* () {

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63
      this.port = yield UtilLib.getPort(Config.DEFAULT_PUPPET_PORT)
64 65
      log.verbose('PuppetWeb', 'init() getPort %d', this.port)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
      yield this.initAttach(this)
      log.verbose('PuppetWeb', 'initAttach() done')

      this.server = yield this.initServer()
      log.verbose('PuppetWeb', 'initServer() done')

      this.browser = yield this.initBrowser()
      log.verbose('PuppetWeb', 'initBrowser() done')

      this.bridge = yield this.initBridge()
      log.verbose('PuppetWeb', 'initBridge() done')

      // this.watchDog('inited') // start watchdog
      this.emit('watchdog', { data: 'inited' })
    })
    .catch(e => {   // Reject
      log.error('PuppetWeb', 'init exception: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
83
      this.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84 85 86 87
      throw e
    })
    .then(() => {   // Finally
      log.verbose('PuppetWeb', 'init() done')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
      this.readyState('connected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89 90 91 92 93 94 95
      return this   // for Chaining
    })
  }

  quit() {
    log.verbose('PuppetWeb', 'quit()')

96 97
    if (this.readyState() === 'disconnecting') {
      log.warn('PuppetWeb', 'quit() is called but readyState is `disconnecting`?')
98 99
      throw new Error('do not call quit again when quiting')
    }
100

101
    // POISON must feed before readyState set to "disconnecting"
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
102 103 104 105 106
    this.emit('watchdog', {
      data: 'PuppetWeb.quit()',
      type: 'POISON'
    })

107 108
    this.readyState('disconnecting')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
109 110 111
    return co.call(this, function* () {

      if (this.bridge)  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112 113 114 115
        yield this.bridge.quit()
                        .catch(e => { // fail safe
                          log.warn('PuppetWeb', 'quit() bridge.quit() exception: %s', e.message)
                        })
116
        log.verbose('PuppetWeb', 'quit() bridge.quit() this.bridge = null')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117 118 119 120 121 122
        this.bridge = null
      } else { log.warn('PuppetWeb', 'quit() without a bridge') }

      if (this.server) {
        yield this.server.quit()
        this.server = null
123
        log.verbose('PuppetWeb', 'quit() server.quit() this.server = null')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124 125 126 127 128 129 130
      } else { log.verbose('PuppetWeb', 'quit() without a server') }

      if (this.browser) {
        yield this.browser.quit()
                  .catch(e => { // fail safe
                    log.warn('PuppetWeb', 'quit() browser.quit() exception: %s', e.message)
                  })
131
        log.verbose('PuppetWeb', 'quit() server.quit() this.browser = null')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
132 133 134
        this.browser = null
      } else { log.warn('PuppetWeb', 'quit() without a browser') }

135
      log.verbose('PuppetWeb', 'quit() server.quit() this.initAttach(null)')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136 137 138 139 140 141 142 143
      yield this.initAttach(null)
    })
    .catch(e => { // Reject
      log.error('PuppetWeb', 'quit() exception: %s', e.message)
      throw e
    })
    .then(() => { // Finally, Fail Safe
      log.verbose('PuppetWeb', 'quit() done')
144
      this.readyState('disconnected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
      return this   // for Chaining
    })
  }

  initAttach(puppet) {
    log.verbose('PuppetWeb', 'initAttach()')
    Contact.attach(puppet)
    Room.attach(puppet)
    Message.attach(puppet)
    return Promise.resolve(!!puppet)
  }

  initBrowser() {
    log.verbose('PuppetWeb', 'initBrowser()')
    const browser = new Browser({
      head: this.head
      , sessionFile: this.profile
    })

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

    // fastUrl is used to open in browser for we can set cookies.
    // backup: 'https://res.wx.qq.com/zh_CN/htmledition/v2/images/icon/ico_loading28a2f7.gif'
    const fastUrl = 'https://wx.qq.com/zh_CN/htmledition/v2/images/webwxgeticon.jpg'

    return co.call(this, function* () {
      yield browser.init()
      yield browser.open(fastUrl)
      yield browser.loadSession()
                  .catch(e => { // fail safe
                   log.verbose('PuppetWeb', 'browser.loadSession(%s) exception: %s', this.profile, e.message || e)
                  })
      yield browser.open()
      return browser // follow func name meaning
    }).catch(e => {
      log.error('PuppetWeb', 'initBrowser() exception: %s', e.message)
      throw e
    })
  }

  initBridge() {
    log.verbose('PuppetWeb', 'initBridge()')
    const bridge = new Bridge({
      puppet:   this // use puppet instead of browser, is because browser might change(die) duaring run time
      , port:   this.port
    })

    return bridge.init()
    .catch(e => {
      if (this.browser.dead()) {
        log.warn('PuppetWeb', 'initBridge() found browser dead, wait it to restore')
      } else {
        log.error('PuppetWeb', 'initBridge() exception: %s', e.message)
        throw e
      }
    })
  }

  initServer() {
    log.verbose('PuppetWeb', 'initServer()')
    const server = new Server({port: this.port})

    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))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211 212 213 214 215 216 217

    /**
     * @depreciated 20160825 zixia
     * 
     * when `unload` there should always be a `disconnect` event?
     */ 
    // server.on('unload'  , Event.onServerUnload.bind(this))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

    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))

    return server.init()
    .catch(e => {
      log.error('PuppetWeb', 'initServer() exception: %s', e.message)
      throw e
    })
  }


  self(message) {
    if (!this.userId) {
      log.verbose('PuppetWeb', 'self() got no this.userId')
      return false
    }
    if (!message || !message.get('from')) {
      log.verbose('PuppetWeb', 'self() got no message')
      return false
    }

    return this.userId == message.get('from')
  }
  send(message) {
    const to      = message.get('to')
    const room    = message.get('room')

    let content     = message.get('content')

    let destination = to
    if (room) {
      destination = room
      // if (to && to!==room) {
      //   content = `@[${to}] ${content}`
      // }
    }

    log.silly('PuppetWeb', `send(${destination}, ${content})`)
    return this.bridge.send(destination, content)
    .catch(e => {
      log.error('PuppetWeb', 'send() exception: %s', e.message)
      throw e
    })
  }
  reply(message, replyContent) {
    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)
    .catch(e => {
      log.error('PuppetWeb', 'reply() exception: %s', e.message)
      throw e
    })
  }

  /**
   * logout from browser, then server will emit `logout` event
   */
  logout() {
    return this.bridge.logout()
    .catch(e => {
      log.error('PuppetWeb', 'logout() exception: %s', e.message)
      throw e
    })
  }

  getContact(id) {
    return this.bridge.getContact(id)
    .catch(e => {
      log.error('PuppetWeb', 'getContact(%d) exception: %s', id, e.message)
      throw e
    })
  }
  logined() { return !!(this.user) }
  ding(data) {
    if (!this.bridge) {
      return Promise.reject(new Error('ding fail: no bridge(yet)!'))
    }
    return this.bridge.ding(data)
    .catch(e => {
      log.warn('PuppetWeb', 'ding(%s) rejected: %s', data, e.message)
      throw e
    })
  }
}

module.exports = PuppetWeb