io-client.ts 7.4 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Class IoClient
 * http://www.wechaty.io
 *
 * Licenst: ISC
 * https://github.com/wechaty/wechaty
 *
 */

13
// const co = require('co')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
14 15 16 17 18

/**
 * DO NOT use `require('../')` here!
 * because it will casue a LOOP require ERROR
 */
19 20 21 22
import Wechaty from './wechaty'
import Config  from './config'
import Io      from './io'
import brolog  from './brolog-env'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
23 24 25

class IoClient {
  constructor({
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26
    initToken   = Config.token || Config.DEFAULT_TOKEN
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27 28 29 30 31 32 33
    , log       = brolog
  } = {}) {
    if (!log) {
      const e = new Error('constructor() log(npmlog/brolog) must be set')
      throw e
    }
    this.log = log
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
34
    this.log.verbose('IoClient', 'constructor() with token: %s', initToken)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
35

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36
    if (!initToken) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
37 38 39 40
      const e = new Error('constructor() token must be set')
      this.log.error('IoClient', e.message)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
41
    this.token(initToken)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

    this.targetState('disconnected')
    this.currentState('disconnected')
  }

 // targetState : 'connected' | 'disconnected'
  targetState(newState) {
    if (newState) {
      this.log.verbose('IoClient', 'targetState(%s)', newState)
      this._targetState = newState
    }
    return this._targetState
  }

  // currentState : 'connecting' | 'connected' | 'disconnecting' | 'disconnected'
  currentState(newState) {
    if (newState) {
      this.log.verbose('IoClient', 'currentState(%s)', newState)
      this._currentState = newState
    }
    return this._currentState
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63 64
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66 67 68
  init() {
    this.log.verbose('IoClient', 'init()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
69 70 71 72 73 74 75 76
    if (/connecting|disconnecting/.test(this.currentState())) {
      this.log.warn('IoClient', 'init() with currentState() with connecting, skip init')
      return Promise.reject('pending')
    }

    this.targetState('connected')
    this.currentState('connecting')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77 78 79
    const wechaty = this.wechaty  = new Wechaty({
      profile: Config.DEFAULT_PROFILE
    })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
81
    return co.call(this, function* () {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
82 83 84
      this.io       = yield this.initIo()
      this.wechaty  = yield this.initWechaty()
      this.currentState('connected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85 86 87
      return this
    }).catch(e => {
      this.log.error('IoClient', 'init() exception: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
      this.currentState('disconnected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89 90 91 92
      throw e
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
93
  initWechaty() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94 95
    this.log.verbose('IoClient', 'initWechaty()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96 97 98 99 100 101 102
    if (this.targetState() !== 'connected') {
      this.log.warn('IoClient', 'initWechaty() targetState is not `connected`, skipped')
      return Promise.resolve(wechaty)
    }

    const wechaty = this.wechaty

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115
    wechaty
    .on('login'	       , user => this.log.info('IoClient', `${user.name()} logined`))
    .on('logout'	     , user => this.log.info('IoClient', `${user.name()} logouted`))
    .on('scan', ({url, code}) => this.log.info('IoClient', `[${code}] ${url}`))
    .on('message'   , message => {
      message.ready()
            .then(this.onMessage.bind(this))
            .catch(e => this.log.error('IoClient', 'message.ready() %s' , e))
    })

    return wechaty.init()
                  .then(_ => {
                    this.log.verbose('IoClient', 'wechaty.init() succ')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116
                    return wechaty
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117 118 119 120 121 122 123 124
                  })
                  .catch(e => {
                    this.log.error('IoClient', 'init() init fail: %s', e)
                    wechaty.quit()
                    throw e
                  })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125
  initIo() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126
    this.log.verbose('IoClient', 'initIo() with token %s', this.token())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
128 129 130 131 132 133
    if (this.targetState() !== 'connected') {
      this.log.warn('IoClient', 'initIo() targetState is not `connected`, skipped')
      return Promise.resolve()
    }

    if (!this.wechaty) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
134
      throw new Error('initIo() need a wechaty instance')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136 137

    const wechaty = this.wechaty
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
138

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139
    const io = new Io({
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
140
      wechaty
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
141
      , token: this.token()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
142 143 144 145
    })

    return io.init()
            .catch(e => {
146
              this.log.verbose('IoClient', 'initIo() init fail: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
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
              throw e
            })
  }

  initWeb(port = Config.httpPort) {
//    if (process.env.DYNO) {
//    }
    const app = require('express')()

    app.get('/', function (req, res) {
      res.send('Wechaty IO Bot Alive!')
    })

    return new Promise((resolve, reject) => {
      app.listen(port, () => {
        this.log.verbose('IoClient', 'initWeb() Wechaty IO Bot listening on port ' + port + '!')

        return resolve(this)

      })
    })
  }

  onMessage(m) {
    const from = m.from()
    const to = m.to()
    const content = m.toString()
    const room = m.room()

176
    // this.log.info('Bot', '%s<%s>:%s'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177
    //               , (room ? '['+room.topic()+']' : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178 179 180 181 182 183
    //               , from.name()
    //               , m.toStringDigest()
    //         )

    if (/^wechaty|botie/i.test(m.get('content')) && !bot.self(m)) {
      bot.reply(m, 'https://www.wechaty.io')
184
        .then(_ => this.log.info('Bot', 'REPLIED to magic word "wechaty"'))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185 186
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
187 188 189 190

  start() {
    this.log.verbose('IoClient', 'start()')

191 192 193
    if (!this.wechaty) {
      return this.init()
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
194 195 196 197 198

    if (/connecting|disconnecting/.test(this.currentState())) {
      this.log.warn('IoClient', 'start() with a pending state, not the time')
      return Promise.reject('pending')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
199

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200 201
    this.targetState('connected')
    this.currentState('connecting')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
203
    return this.initIo(this.wechaty)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204 205 206 207 208 209 210 211 212
              .then(io => {
                this.io = io
                this.currentState('connected')
              })
              .catch(e => {
                this.log.error('IoClient', 'start() exception: %s', e.message)
                this.currentState('disconnected')
                throw e
              })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213 214 215 216
  }

  stop() {
    this.log.verbose('IoClient', 'stop()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
217 218 219
    this.targetState('disconnected')
    this.currentState('disconnecting')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220 221
    if (!this.io) {
      this.log.warn('IoClient', 'stop() without this.io')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
      this.currentState('connected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223 224 225 226
      return Promise.resolve()
    }

    const p = this.io.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227
                    .then(_ => this.currentState('disconnected'))
228
    // this.io = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
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
    return p
  }

  restart() {
    this.log.verbose('IoClient', 'restart()')

    return co.call(this, function* () {
      yield this.stop()
      yield this.start()
      return this
    }).catch(e => {
      this.log.error('IoClient', 'restart() exception %s', e.message)
      throw e
    })
  }

  token(newToken) {
    if (newToken) {
      this.log.verbose('IoClient', 'token(%s)', newToken)
      this._token = newToken
    }
    return this._token
  }

  quit() {
    this.log.verbose('IoClient', 'quit()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
255

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256 257 258 259 260 261 262
    if (this.currentState() === 'disconnecting') {
      this.log.warn('IoClient', 'quit() with currentState() = `disconnecting`, skipped')
      return Promise.reject('quit() with currentState = `disconnecting`')
    }

    this.targetState('disconnected')
    this.currentState('disconnecting')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
263 264 265 266 267

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

      if (this.wechaty) {
        yield this.wechaty.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268
        this.wechaty = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
269 270 271 272
      } else { this.log.warn('IoClient', 'quit() no this.wechaty') }

      if (this.io) {
        yield this.io.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
273
        this.io = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
274 275
      } else { this.log.warn('IoClient', 'quit() no this.io') }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
276
      this.currentState('disconnected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
277 278
    }).catch(e => {
      this.log.error('IoClient', 'exception: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
279

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
280 281 282
      // XXX fail safe?
      this.currentState('disconnected')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
283 284 285
      throw e
    })
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
286 287
}

288 289
// module.exports = IoClient.default = IoClient.IoClient = IoClient
export default IoClient