io.ts 13.3 KB
Newer Older
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5
 *
6 7 8
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
9
 *
10 11 12 13 14 15 16
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
17 18
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19 20
import WebSocket        from 'ws'
import { StateSwitch }  from 'state-switch'
21

22
import {
23
  Message,
24
}                 from './user'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
25 26

import {
27
  PuppetQrcodeScanEvent,
28
}                 from './puppet/'
29

30
import {
31
  config,
L
lijiarui 已提交
32
  log,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33
}                 from './config'
34 35 36
import {
  Wechaty,
}                 from './wechaty'
37

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
38
export interface IoOptions {
L
lijiarui 已提交
39 40 41 42
  wechaty:    Wechaty,
  token:      string,
  apihost?:   string,
  protocol?:  string,
43 44
}

45
export const IO_EVENT_DICT = {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
46 47 48 49 50 51 52 53 54 55 56 57
  botie     : 'tbw',
  error     : 'tbw',
  heartbeat : 'tbw',
  login     : 'tbw',
  logout    : 'tbw',
  message   : 'tbw',
  update    : 'tbw',
  raw       : 'tbw',
  reset     : 'tbw',
  scan      : 'tbw',
  sys       : 'tbw',
  shutdown  : 'tbw',
58 59 60
}

type IoEventName = keyof typeof IO_EVENT_DICT
61

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
62
interface IoEventScan {
63
  name    : 'scan',
64
  payload : PuppetQrcodeScanEvent,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65 66 67
}

interface IoEventAny {
L
lijiarui 已提交
68 69
  name:     IoEventName,
  payload:  any,
70
}
71

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72 73
type IoEvent = IoEventScan | IoEventAny

74
export class Io {
75 76
  private readonly cuid     : string
  private readonly protocol : string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77
  private eventBuffer : IoEvent[] = []
78
  private ws          : undefined | WebSocket
79

80
  private readonly state = new StateSwitch('Io', log)
81

82 83
  private reconnectTimer?   : NodeJS.Timer
  private reconnectTimeout? : number
84

85 86
  private lifeTimer? : NodeJS.Timer

87
  private onMessage: undefined | Function
88

89
  private scanPayload?: PuppetQrcodeScanEvent
90

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91 92 93 94
  constructor(
    private options: IoOptions,
  ) {
    options.apihost   = options.apihost   || config.apihost
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95
    options.protocol  = options.protocol  || config.default.DEFAULT_PROTOCOL
96

97
    this.cuid = options.wechaty.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98

99
    this.protocol = options.protocol + '|' + options.wechaty.id
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
100
    log.verbose('Io', 'instantiated with apihost[%s], token[%s], protocol[%s], cuid[%s]',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
101 102 103
                      options.apihost,
                      options.token,
                      options.protocol,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
104
                      this.cuid,
105
              )
106 107
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108 109 110
  public toString() {
    return `Io<${this.options.token}>`
  }
111

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112 113 114
  private connected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN
  }
115

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116 117
  public async start(): Promise<void> {
    log.verbose('Io', 'start()')
118

119 120 121 122
    if (this.lifeTimer) {
      throw new Error('lifeTimer exist')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
123
    this.state.on('pending')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124

125 126
    try {
      await this.initEventHook()
127 128 129

      this.ws = await this.initWebSocket()

130
      this.options.wechaty.on('scan', (qrcode, status) => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131 132
        this.scanPayload = {
          ...this.scanPayload,
133 134
          qrcode,
          status,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135
        }
136
      })
137 138 139 140 141 142 143 144

      this.lifeTimer = setInterval(() => {
        if (this.ws && this.connected()) {
          log.silly('Io', 'start() setInterval() ws.ping()')
          this.ws.ping()
        }
      }, 1000 * 10)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
145
      this.state.on(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147
      return
148
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149
      log.warn('Io', 'start() exception: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151
      throw e
152
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153 154
  }

155
  private initEventHook() {
Huan (李卓桓)'s avatar
log  
Huan (李卓桓) 已提交
156
    log.verbose('Io', 'initEventHook()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
    const wechaty = this.options.wechaty
158

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159
    wechaty.on('error'    , error =>        this.send({ name: 'error',      payload: error }))
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
160
    wechaty.on('heartbeat', data  =>        this.send({ name: 'heartbeat',  payload: { cuid: this.cuid, data } }))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161 162
    wechaty.on('login',     user =>         this.send({ name: 'login',      payload: user }))
    wechaty.on('logout' ,   user =>         this.send({ name: 'logout',     payload: user }))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
163
    wechaty.on('message',   message =>      this.ioMessage(message))
164 165 166 167

    // FIXME: payload schema need to be defined universal
    // wechaty.on('scan',      (url, code) =>  this.send({ name: 'scan',       payload: { url, code } }))
    wechaty.on('scan',      (qrcode, status) =>  this.send({ name: 'scan',  payload: { qrcode, status } } as IoEventScan ))
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

    // const hookEvents: WechatyEventName[] = [
    //   'scan'
    //   , 'login'
    //   , 'logout'
    //   , 'heartbeat'
    //   , 'error'
    // ]
    // hookEvents.map(event => {
    //   wechaty.on(event, (data) => {
    //     const ioEvent: IoEvent = {
    //       name:       event
    //       , payload:  data
    //     }

    //     switch (event) {
    //       case 'login':
    //       case 'logout':
    //         if (data instanceof Contact) {
    //           // ioEvent.payload = data.obj
    //           ioEvent.payload = data
    //         }
    //         break

    //       case 'error':
    //         ioEvent.payload = data.toString()
    //         break

        //   case 'heartbeat':
        //     ioEvent.payload = {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
198
        //       cuid: this.cuid
199 200 201 202 203 204 205 206 207 208 209
        //       , data: data
        //     }
        //     break

        //   default:
        //     break
        // }

    //     this.send(ioEvent)
    //   })
    // })
210

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211 212 213 214
    // wechaty.on('message', m => {
    //   const text = (m.room() ? '[' + m.room().topic() + ']' : '')
    //               + '<' + m.from().name() + '>'
    //               + ':' + m.toStringDigest()
215

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216 217
    //   this.send({ name: 'message', payload:  text })
    // })
218

219
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220 221
  }

222
  private async initWebSocket(): Promise<WebSocket> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
    log.verbose('Io', 'initWebSocket()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
224
    // this.state.current('on', false)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225 226 227 228 229 230 231 232 233 234 235

    // const auth = 'Basic ' + new Buffer(this.setting.token + ':X').toString('base64')
    const auth = 'Token ' + this.options.token
    const headers = { 'Authorization': auth }

    if (!this.options.apihost) {
      throw new Error('no apihost')
    }
    let endpoint = 'wss://' + this.options.apihost + '/v0/websocket'

    // XXX quick and dirty: use no ssl for APIHOST other than official
236 237
    // FIXME: use a configuarable VARIABLE for the domain name at here:
    if (!/api\.chatie\.io/.test(this.options.apihost)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
238 239 240 241 242 243 244
      endpoint = 'ws://' + this.options.apihost + '/v0/websocket'
    }

    const ws = this.ws = new WebSocket(endpoint, this.protocol, { headers })

    ws.on('open',     () => this.wsOnOpen(ws))
    ws.on('message',  data => this.wsOnMessage(data))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
245
    ws.on('error',    e => this.wsOnError(e))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
246
    ws.on('close',    (code, reason) => this.wsOnClose(ws, code, reason))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247

248 249 250 251 252 253
    await new Promise((resolve, reject) => {
      ws.once('open', resolve)
      ws.once('error', reject)
      ws.once('close', reject)
    })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254 255 256
    return ws
  }

ruiruibupt's avatar
ruiruibupt 已提交
257
  private async wsOnOpen(ws: WebSocket): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
258 259 260 261 262 263
    if (this.protocol !== ws.protocol) {
      log.error('Io', 'initWebSocket() require protocol[%s] failed', this.protocol)
      // XXX deal with error?
    }
    log.verbose('Io', 'initWebSocket() connected with protocol [%s]', ws.protocol)
    // this.currentState('connected')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264
    // this.state.current('on')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
265 266 267 268

    // FIXME: how to keep alive???
    // ws._socket.setKeepAlive(true, 100)

269
    this.reconnectTimeout = undefined
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270 271

    const name    = 'sys'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
272
    const payload = 'Wechaty version ' + this.options.wechaty.version() + ` with CUID: ${this.cuid}`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
273 274 275 276 277

    const initEvent: IoEvent = {
      name,
      payload,
    }
ruiruibupt's avatar
ruiruibupt 已提交
278
    await this.send(initEvent)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
279 280
  }

ruiruibupt's avatar
ruiruibupt 已提交
281
  private async wsOnMessage(data: WebSocket.Data) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
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
    log.silly('Io', 'initWebSocket() ws.on(message): %s', data)
    // flags.binary will be set if a binary data is received.
    // flags.masked will be set if the data was masked.

    if (typeof data !== 'string') {
      throw new Error('data should be string...')
    }

    const ioEvent: IoEvent = {
      name    : 'raw',
      payload : data,
    }

    try {
      const obj = JSON.parse(data)
      ioEvent.name    = obj.name
      ioEvent.payload = obj.payload
    } catch (e) {
      log.verbose('Io', 'on(message) recv a non IoEvent data[%s]', data)
    }

    switch (ioEvent.name) {
      case 'botie':
        const payload = ioEvent.payload
        if (payload.onMessage) {
          const script = payload.script
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
308 309 310 311 312 313 314 315 316 317 318
          try {
            /* tslint:disable:no-eval */
            const fn = eval(script)
            if (typeof fn === 'function') {
              this.onMessage = fn
            } else {
              log.warn('Io', 'server pushed function is invalid')
            }
          } catch (e) {
            log.warn('Io', 'server pushed function exception: %s', e)
            this.options.wechaty.emit('error', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
319 320 321 322 323 324
          }
        }
        break

      case 'reset':
        log.verbose('Io', 'on(reset): %s', ioEvent.payload)
ruiruibupt's avatar
ruiruibupt 已提交
325
        await this.options.wechaty.reset(ioEvent.payload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
326 327 328
        break

      case 'shutdown':
329
        log.info('Io', 'on(shutdown): %s', ioEvent.payload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
330 331 332 333
        process.exit(0)
        break

      case 'update':
334 335
        log.verbose('Io', 'on(update): %s', ioEvent.payload)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
336 337 338 339 340 341 342 343
        const wechaty = this.options.wechaty
        if (wechaty.logonoff()) {
          const loginEvent: IoEvent = {
            name    : 'login',
            payload : {
              id   : wechaty.userSelf().id,
              name : wechaty.userSelf().name(),
            },
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344
          }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345
          await this.send(loginEvent)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
346 347
        }

348
        if (this.scanPayload) {
349
          const scanEvent: IoEventScan = {
350
            name:     'scan',
351
            payload:  this.scanPayload,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
352
          }
ruiruibupt's avatar
ruiruibupt 已提交
353
          await this.send(scanEvent)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354 355 356 357 358 359 360 361
        }

        break

      case 'sys':
        // do nothing
        break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
362
      case 'logout':
363
        log.info('Io', 'on(logout): %s', ioEvent.payload)
ruiruibupt's avatar
ruiruibupt 已提交
364
        await this.options.wechaty.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365 366
        break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
367 368 369 370 371 372
      default:
        log.warn('Io', 'UNKNOWN on(%s): %s', ioEvent.name, ioEvent.payload)
        break
    }
  }

373 374 375 376
  // FIXME: it seems the parameter `e` might be `undefined`.
  // @types/ws might has bug for `ws.on('error',    e => this.wsOnError(e))`
  private wsOnError(e?: Error) {
    log.warn('Io', 'initWebSocket() error event[%s]', e && e.message)
377 378 379
    if (!e) {
      return
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393
    this.options.wechaty.emit('error', e)

    // when `error`, there must have already a `close` event
    // we should not call this.reconnect() again
    //
    // this.close()
    // this.reconnect()
  }

  private wsOnClose(
    ws      : WebSocket,
    code    : number,
    message : string,
  ): void {
394 395 396 397 398
    if (this.state.on()) {
      log.warn('Io', 'initWebSocket() close event[%d: %s]', code, message)
      ws.close()
      this.reconnect()
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399 400 401 402 403
  }

  private reconnect() {
    log.verbose('Io', 'reconnect()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
404
    if (this.state.off()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
      log.warn('Io', 'reconnect() canceled because state.target() === offline')
      return
    }

    if (this.connected()) {
      log.warn('Io', 'reconnect() on a already connected io')
      return
    }
    if (this.reconnectTimer) {
      log.warn('Io', 'reconnect() on a already re-connecting io')
      return
    }

    if (!this.reconnectTimeout) {
      this.reconnectTimeout = 1
    } else if (this.reconnectTimeout < 10 * 1000) {
      this.reconnectTimeout *= 3
    }

    log.warn('Io', 'reconnect() will reconnect after %d s', Math.floor(this.reconnectTimeout / 1000))
425
    this.reconnectTimer = setTimeout(async _ => {
426
      this.reconnectTimer = undefined
427
      await this.initWebSocket()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
428 429 430
    }, this.reconnectTimeout)// as any as NodeJS.Timer
  }

431
  private async send(ioEvent?: IoEvent): Promise<void> {
432 433 434 435 436 437
    if (!this.ws) {
      throw new Error('no ws')
    }

    const ws = this.ws

438
    if (ioEvent) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
439
      log.silly('Io', 'send(%s)', JSON.stringify(ioEvent))
440
      this.eventBuffer.push(ioEvent)
441
    } else { log.silly('Io', 'send()') }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
442 443

    if (!this.connected()) {
444
      log.verbose('Io', 'send() without a connected websocket, eventBuffer.length = %d', this.eventBuffer.length)
445
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
446 447
    }

448
    const list: Promise<any>[] = []
449
    while (this.eventBuffer.length) {
450
      const p = new Promise((resolve, reject) => ws.send(
451
        JSON.stringify(
L
lijiarui 已提交
452 453 454
          this.eventBuffer.shift(),
        ),
        (err: Error) => {
455 456
          if (err)  { reject(err) }
          else      { resolve()   }
L
lijiarui 已提交
457
        },
458 459 460 461 462 463 464 465 466
      ))
      list.push(p)
    }

    try {
      await Promise.all(list)
    } catch (e) {
      log.error('Io', 'send() exceptio: %s', e.stack)
      throw e
467
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468
  }
469

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
470 471 472
  public async stop(): Promise<void> {
    log.verbose('Io', 'stop()')

473 474 475 476
    if (!this.ws) {
      throw new Error('no ws')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
477
    this.state.off('pending')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
478

479
    // try to send IoEvents in buffer
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
480
    await this.send()
481
    this.eventBuffer = []
482

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
483 484
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
485
      this.reconnectTimer = undefined
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
486
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
487

488 489 490 491 492
    if (this.lifeTimer) {
      clearInterval(this.lifeTimer)
      this.lifeTimer = undefined
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493
    this.ws.close()
494 495 496 497 498 499 500 501
    await new Promise(r => {
      if (this.ws) {
        this.ws.once('close', r)
      } else {
        r()
      }
    })
    this.ws = undefined
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
502

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503
    this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
504

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
505
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
507 508 509 510 511
  /**
   *
   * Prepare to be overwriten by server setting
   *
   */
512
  private async ioMessage(m: Message): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
513
    log.silly('Io', 'ioMessage() is a nop function before be overwriten from cloud')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
514 515 516
    if (typeof this.onMessage === 'function') {
      await this.onMessage(m)
    }
517
  }
518

519
}
520 521

export default Io