message-media.ts 2.0 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 */
9
// const co = require('co')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
10

11 12 13 14 15
import Config   from './config'
import Message  from './message'
import UtilLib  from './util-lib'

import log      from './brolog-env'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
16

17 18
import PuppetWeb from './puppet-web/index'
import PuppetWebBridge from './puppet-web/bridge'
19

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
20
class MediaMessage extends Message {
21
  private bridge: PuppetWebBridge
22

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
23 24
  constructor(rawObj) {
    super(rawObj)
25
    this.bridge = (Config.puppetInstance() as PuppetWeb)
26
                        .bridge
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
  }
28
  public async ready(): Promise<MediaMessage> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
29 30 31
    log.silly('MediaMessage', 'ready()')

    const parentReady = super.ready.bind(this)
32 33 34 35
    // return co.call(this, function* () {
    try {
      await parentReady()
      const url = await this.getMsgImg(this.id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36 37 38
      this.obj.url = url

      return this // IMPORTANT!
39
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
40 41
      log.warn('MediaMessage', 'ready() exception: %s', e.message)
      throw e
42 43 44 45 46 47 48 49 50 51 52 53
    }
    // return co.call(this, function* () {
    //   yield parentReady()
    //   const url = yield this.getMsgImg(this.id)
    //   this.obj.url = url

    //   return this // IMPORTANT!
    // })
    // .catch(e => {
    //   log.warn('MediaMessage', 'ready() exception: %s', e.message)
    //   throw e
    // })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54
  }
55
  private getMsgImg(id: string): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
56 57 58 59 60 61 62
    return this.bridge.getMsgImg(id)
    .catch(e => {
      log.warn('MediaMessage', 'getMsgImg(%d) exception: %s', id, e.message)
      throw e
    })
  }

63
  public readyStream(): Promise<NodeJS.ReadableStream> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64 65
    return this.ready()
    .then(() => {
66
      return (Config.puppetInstance() as PuppetWeb)
67
                    .browser.checkSession()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
68 69 70 71 72 73 74 75 76 77 78
    })
    .then(cookies => {
      return UtilLib.downloadStream(this.obj.url, cookies)
    })
    .catch(e => {
      log.warn('MediaMessage', 'stream() exception: %s', e.message)
      throw e
    })
  }
}

79 80
// module.exports = MediaMessage.default = MediaMessage.MediaMessage = MediaMessage
export default MediaMessage