message-media.ts 1.9 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 10 11 12 13
import Config   from './config'
import Message  from './message'
import UtilLib  from './util-lib'

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

15 16
import PuppetWeb        from './puppet-web/puppet-web'
import PuppetWebBridge  from './puppet-web/bridge'
17

18
export class MediaMessage extends Message {
19
  private bridge: PuppetWebBridge
20

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

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

      return this // IMPORTANT!
37
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
38 39
      log.warn('MediaMessage', 'ready() exception: %s', e.message)
      throw e
40 41 42 43 44 45 46 47 48 49 50 51
    }
    // 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 (李卓桓) 已提交
52
  }
53
  private getMsgImg(id: string): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54 55 56 57 58 59 60
    return this.bridge.getMsgImg(id)
    .catch(e => {
      log.warn('MediaMessage', 'getMsgImg(%d) exception: %s', id, e.message)
      throw e
    })
  }

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

77
export default MediaMessage