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 10 11
import { Config, log }  from './config'
import { Message }      from './message'
import { UtilLib }      from './util-lib'
12

13 14
import { PuppetWeb }    from './puppet-web/puppet-web'
import { Bridge as PuppetWebBridge }       from './puppet-web/bridge'
15

16
export class MediaMessage extends Message {
17
  private bridge: PuppetWebBridge
18

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

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

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

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