puppet-puppeteer.ts 51.0 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
 *       http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16
 *   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 21 22 23 24 25
// import * as http    from 'http'
import * as path    from 'path'
import * as nodeUrl from 'url'

import * as bl      from 'bl'
import * as mime  from 'mime'
import * as request from 'request'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
// import cloneClass   from 'clone-class'
28 29 30
import {
  FileBox,
}                   from 'file-box'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
31 32 33
import {
  ThrottleQueue,
}                   from 'rx-queue'
34 35 36 37 38
import {
  Watchdog,
  WatchdogFood,
}                   from 'watchdog'

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
39 40 41
import {
  Puppet,
  PuppetOptions,
42
  Receiver,
43
}                     from '../puppet/'
44
import {
45
  config,
46 47
  log,
  Raven,
48
}                     from '../config'
49
// import Profile        from '../profile'
50 51
import Misc           from '../misc'

52 53
import {
  Bridge,
54
  Cookie,
55 56
}                       from './bridge'
import Event            from './event'
57 58

import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
59
  WebAppMsgType,
60
  WebContactRawPayload,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61
  WebMessageMediaPayload,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
62
  WebMessageRawPayload,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63
  WebMediaType,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64
  WebMessageType,
65
  // WebRoomRawMember,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66
  WebRoomRawPayload,
67
}                           from './web-schemas'
68

69
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70
  ContactPayload,
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  // ContactQueryFilter,
  ContactType,

  MessagePayload,
  MessageType,

  // RoomMemberQueryFilter,
  RoomPayload,
  // RoomQueryFilter,

  ScanPayload,
}                           from '../puppet/'

import {
  // Contact,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86
}                             from '../contact'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
  // Messageirection,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
}                             from '../message'
90
import {
91
  // Room,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92
}                             from '../room'
M
Mukaiu 已提交
93

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94 95
export type PuppetFoodType = 'scan' | 'ding'
export type ScanFoodType   = 'scan' | 'login' | 'logout'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96

97
export class PuppetPuppeteer extends Puppet {
98
  public bridge       : Bridge
99

100
  public scanPayload? : ScanPayload
101

102
  public scanWatchdog: Watchdog<ScanFoodType>
103

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
104
  private fileId: number
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
105

106 107 108
  constructor(
    public options: PuppetOptions,
  ) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
109
    super(options)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110

111 112 113
    this.fileId = 0
    this.bridge = new Bridge({
      head    : config.head,
114
      profile : this.options.memory,
115
    })
116

117
    const SCAN_TIMEOUT  = 2 * 60 * 1000 // 2 minutes
118
    this.scanWatchdog   = new Watchdog<ScanFoodType>(SCAN_TIMEOUT, 'Scan')
119 120
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
121
  public async start(): Promise<void> {
122
    log.verbose('PuppetPuppeteer', `start() with ${this.options.memory.name}`)
123

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

126
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127
      this.initWatchdog()
128
      this.initWatchdogForScan()
129

130
      this.bridge = await this.initBridge()
131
      log.verbose('PuppetPuppeteer', 'initBridge() done')
132

133 134 135 136
      /**
       *  state must set to `live`
       *  before feed Watchdog
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137
      this.state.on(true)
138

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139 140 141
      /**
       * Feed the dog and start watch
       */
142
      const food: WatchdogFood = {
L
lijiarui 已提交
143 144
        data: 'inited',
        timeout: 2 * 60 * 1000, // 2 mins for first login
145 146
      }
      this.emit('watchdog', food)
147

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148 149 150
      /**
       * Save cookie for every 5 minutes
       */
151
      const throttleQueue = new ThrottleQueue(5 * 60 * 1000)
152
      this.on('watchdog', data => throttleQueue.next(data))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153
      throttleQueue.subscribe(async data => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
154
        log.verbose('Wechaty', 'start() throttleQueue.subscribe() new item: %s', data)
155 156 157
        await this.saveCookie()
      })

158
      log.verbose('PuppetPuppeteer', 'start() done')
159 160

      this.emit('start')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
162

163
    } catch (e) {
164
      log.error('PuppetPuppeteer', 'start() exception: %s', e)
165

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
166
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167
      this.emit('error', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
168
      await this.stop()
169

170
      Raven.captureException(e)
171
      throw e
172
    }
173 174
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
  private initWatchdog(): void {
176
    log.verbose('PuppetPuppeteer', 'initWatchdogForPuppet()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177

178 179
    const puppet = this

180
    // clean the dog because this could be re-inited
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
181
    this.watchdog.removeAllListeners()
182

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
183 184 185
    // fix issue #981
    puppet.removeAllListeners('watchdog')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186 187
    puppet.on('watchdog', food => this.watchdog.feed(food))
    this.watchdog.on('feed', food => {
188
      log.silly('PuppetPuppeteer', 'initWatchdogForPuppet() dog.on(feed, food={type=%s, data=%s})', food.type, food.data)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189
      // feed the dog, heartbeat the puppet.
190 191
      // 201805 puppet no need to `heartbeat`?
      // puppet.emit('heartbeat', food.data)
192 193
    })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
194
    this.watchdog.on('reset', async (food, timeout) => {
195
      log.warn('PuppetPuppeteer', 'initWatchdogForPuppet() dog.on(reset) last food:%s, timeout:%s',
196
                            food.data, timeout)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
197
      try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
198 199
        await this.stop()
        await this.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200 201 202
      } catch (e) {
        puppet.emit('error', e)
      }
203 204 205 206 207 208 209 210 211 212
    })
  }

  /**
   * Deal with SCAN events
   *
   * if web browser stay at login qrcode page long time,
   * sometimes the qrcode will not refresh, leave there expired.
   * so we need to refresh the page after a while
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213
  private initWatchdogForScan(): void {
214
    log.verbose('PuppetPuppeteer', 'initWatchdogForScan()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215

216
    const puppet = this
217
    const dog    = this.scanWatchdog
218

219 220 221
    // clean the dog because this could be re-inited
    dog.removeAllListeners()

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    puppet.on('scan', info => dog.feed({
      data: info,
      type: 'scan',
    }))
    puppet.on('login',  user => {
      dog.feed({
        data: user,
        type: 'login',
      })
      // do not monitor `scan` event anymore
      // after user login
      dog.sleep()
    })

    // active monitor again for `scan` event
    puppet.on('logout', user => dog.feed({
      data: user,
      type: 'logout',
    }))

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242
    dog.on('reset', async (food, timePast) => {
243
      log.warn('PuppetPuppeteer', 'initScanWatchdog() on(reset) lastFood: %s, timePast: %s',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
244
                            food.data, timePast)
245 246 247
      try {
        await this.bridge.reload()
      } catch (e) {
248
        log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) exception: %s', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249
        try {
250
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) try to recover by bridge.{quit,init}()', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
251 252
          await this.bridge.quit()
          await this.bridge.init()
253
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) recover successful')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254
        } catch (e) {
255
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) recover FAIL: %s', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256 257
          this.emit('error', e)
        }
258 259 260 261
      }
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
262
  public async stop(): Promise<void> {
263
    log.verbose('PuppetPuppeteer', 'quit()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
265
    if (this.state.off()) {
266
      log.warn('PuppetPuppeteer', 'quit() is called on a OFF puppet. await ready(off) and return.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267 268
      await this.state.ready('off')
      return
269
    }
270
    this.state.off('pending')
271

272
    log.verbose('PuppetPuppeteer', 'quit() make watchdog sleep before do quit')
273 274 275 276

    /**
     * Clean listeners for `watchdog`
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
277
    this.watchdog.sleep()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
278
    this.scanWatchdog.sleep()
279 280 281
    this.watchdog.removeAllListeners()
    this.scanWatchdog.removeAllListeners()
    this.removeAllListeners('watchdog')
282

283
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
284 285 286
      await this.bridge.quit()
      // register the removeListeners micro task at then end of the task queue
      setImmediate(() => this.bridge.removeAllListeners())
287
    } catch (e) {
288
      log.error('PuppetPuppeteer', 'quit() exception: %s', e.message)
289
      Raven.captureException(e)
290
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291
    } finally {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
292
      this.state.off(true)
293
      this.emit('stop')
294
    }
295

296 297
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
298
  private async initBridge(): Promise<Bridge> {
299
    log.verbose('PuppetPuppeteer', 'initBridge()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
301
    if (this.state.off()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
302
      const e = new Error('initBridge() found targetState != live, no init anymore')
303
      log.warn('PuppetPuppeteer', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
304
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
305
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
306

307
    this.bridge.on('ding'     , Event.onDing.bind(this))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
308
    this.bridge.on('error'    , e => this.emit('error', e))
309 310 311 312 313
    this.bridge.on('log'      , Event.onLog.bind(this))
    this.bridge.on('login'    , Event.onLogin.bind(this))
    this.bridge.on('logout'   , Event.onLogout.bind(this))
    this.bridge.on('message'  , Event.onMessage.bind(this))
    this.bridge.on('scan'     , Event.onScan.bind(this))
314
    this.bridge.on('unload'   , Event.onUnload.bind(this))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
315

316
    try {
317
      await this.bridge.init()
318
    } catch (e) {
319
      log.error('PuppetPuppeteer', 'initBridge() exception: %s', e.message)
320
      await this.bridge.quit().catch(console.error)
321 322 323 324
      this.emit('error', e)

      Raven.captureException(e)
      throw e
325
    }
326 327

    return this.bridge
328 329
  }

330 331 332
  public async messageRawPayload(id: string): Promise <WebMessageRawPayload> {
    const rawPayload = await this.bridge.getMessage(id)
    return rawPayload
333
  }
334

335
  public async messageRawPayloadParser(
336
    rawPayload: WebMessageRawPayload,
337
  ): Promise<MessagePayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
338
    log.verbose('PuppetPuppeteer', 'messageRawPayloadParser(%s) @ %s', rawPayload, this)
339

340
    const id                           = rawPayload.MsgId
341 342 343 344
    const fromId                       = rawPayload.MMActualSender               // MMPeerUserName
    const text: string                 = rawPayload.MMActualContent              // Content has @id prefix added by wx
    const timestamp: number            = rawPayload.MMDisplayTime                // Javascript timestamp of milliseconds
    const filename: undefined | string = this.filename(rawPayload) || undefined
345

346 347
    let roomId : undefined | string
    let toId   : undefined | string
348 349 350 351

    // FIXME: has there any better method to know the room ID?
    if (rawPayload.MMIsChatRoom) {
      if (/^@@/.test(rawPayload.FromUserName)) {
352
        roomId = rawPayload.FromUserName // MMPeerUserName always eq FromUserName ?
353
      } else if (/^@@/.test(rawPayload.ToUserName)) {
354
        roomId = rawPayload.ToUserName
355 356 357
      } else {
        throw new Error('parse found a room message, but neither FromUserName nor ToUserName is a room(/^@@/)')
      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
358 359 360 361

      // console.log('rawPayload.FromUserName: ', rawPayload.FromUserName)
      // console.log('rawPayload.ToUserName: ', rawPayload.ToUserName)
      // console.log('rawPayload.MMPeerUserName: ', rawPayload.MMPeerUserName)
M
Mukaiu 已提交
362 363
    }

364 365
    if (rawPayload.ToUserName) {
      if (!/^@@/.test(rawPayload.ToUserName)) { // if a message in room without any specific receiver, then it will set to be `undefined`
366
        toId = rawPayload.ToUserName
367
      }
368 369
    }

370
    const type: MessageType = this.messageTypeFromWeb(rawPayload.MsgType)
371

372
    const payloadBase = {
373
      id,
374
      type,
375
      fromId,
376
      filename,
377
      text,
378
      timestamp,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
379
    }
M
Mukaiu 已提交
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    let payload: MessagePayload

    if (toId) {
      payload = {
        ...payloadBase,
        toId,
        roomId,
      }
    } else if (roomId) {
      payload = {
        ...payloadBase,
        toId,
        roomId,
      }
    } else {
      throw new Error('neither roomId nor toId')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399 400 401
    return payload
  }

402 403 404 405 406 407
  public async messageFile(messageId: string): Promise<FileBox> {
    const rawPayload = await this.messageRawPayload(messageId)
    const fileBox = await this.messageRawPayloadToFile(rawPayload)
    return fileBox
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
408
  private async messageRawPayloadToFile(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    rawPayload: WebMessageRawPayload,
  ): Promise<FileBox> {
    let url = await this.messageRawPayloadToUrl(rawPayload)

    if (!url) {
      throw new Error('no url for type ' + MessageType[rawPayload.MsgType])
    }

    url = url.replace(/^https/i, 'http') // use http instead of https, because https will only success on the very first request!
    const parsedUrl = nodeUrl.parse(url)

    const filename = this.filename(rawPayload)

    if (!filename) {
      throw new Error('no filename')
    }

    const cookies = await this.cookies()

    const headers = {
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',

      // Accept: 'image/webp,image/*,*/*;q=0.8',
      // Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', //  MsgType.IMAGE | VIDEO
      Accept: '*/*',

      Host: parsedUrl.hostname!, // 'wx.qq.com',  // MsgType.VIDEO | IMAGE

      // Referer: protocol + '//wx.qq.com/',
      Referer: url,

      // 'Upgrade-Insecure-Requests': 1, // MsgType.VIDEO | IMAGE

      Range: 'bytes=0-',

      // 'Accept-Encoding': 'gzip, deflate, sdch',
      // 'Accept-Encoding': 'gzip, deflate, sdch, br', // MsgType.IMAGE | VIDEO
      'Accept-Encoding': 'identity;q=1, *;q=0',

      'Accept-Language': 'zh-CN,zh;q=0.8', // MsgType.IMAGE | VIDEO
      // 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.6,en-US;q=0.4,en;q=0.2',

      /**
       * pgv_pvi=6639183872; pgv_si=s8359147520; webwx_data_ticket=gSeBbuhX+0kFdkXbgeQwr6Ck
       */
      Cookie: cookies.map(c => `${c['name']}=${c['value']}`).join('; '),
    }

457
    const fileBox = FileBox.fromRemote(url, filename, headers)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
458 459 460 461

    return fileBox
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
462
  private messageTypeFromWeb(webMsgType: WebMessageType): MessageType {
463
    switch (webMsgType) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
464
      case WebMessageType.TEXT:
465 466
        return MessageType.Text

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
467 468
      case WebMessageType.EMOTICON:
      case WebMessageType.IMAGE:
469 470
        return MessageType.Image

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
471
      case WebMessageType.VOICE:
472
        return MessageType.Audio
473

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
474 475
      case WebMessageType.MICROVIDEO:
      case WebMessageType.VIDEO:
476
        return MessageType.Video
477

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
478
      case WebMessageType.TEXT:
479 480
        return MessageType.Text

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
481 482 483 484 485 486
      /**
       * Treat those Types as TEXT
       *
       * FriendRequest is a SYS message
       * FIXME: should we use better message type at here???
       */
487
      case WebMessageType.SYS:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
488
      case WebMessageType.APP:
489
        return MessageType.Text
490 491 492 493 494 495 496 497 498 499 500 501

      // VERIFYMSG           = 37,
      // POSSIBLEFRIEND_MSG  = 40,
      // SHARECARD           = 42,
      // LOCATION            = 48,
      // VOIPMSG             = 50,
      // STATUSNOTIFY        = 51,
      // VOIPNOTIFY          = 52,
      // VOIPINVITE          = 53,
      // SYSNOTICE           = 9999,
      // RECALLED            = 10002,
      default:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
502 503
        log.warn('PuppetPuppeteer', 'messageTypeFromWeb(%d) un-supported WebMsgType, treat as TEXT', webMsgType)
        return MessageType.Text
504
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
505 506
  }

507
  /**
508
   * TODO: Test this function if it could work...
509 510
   */
  // public async forward(baseData: MsgRawObj, patchData: MsgRawObj): Promise<boolean> {
511
  public async messageForward(
512 513
    receiver  : Receiver,
    messageId : string,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
514
  ): Promise<void> {
515

516 517 518 519
    log.silly('PuppetPuppeteer', 'forward(receiver=%s, messageId=%s)',
                                  receiver,
                                  messageId,
              )
520

521
    let rawPayload = await this.messageRawPayload(messageId)
522 523

    // rawPayload = Object.assign({}, rawPayload)
524

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
525
    const newMsg = <WebMessageRawPayload>{}
526 527 528 529 530 531 532 533 534 535 536 537 538
    const largeFileSize = 25 * 1024 * 1024
    // let ret = false
    // if you know roomId or userId, you can use `Room.load(roomId)` or `Contact.load(userId)`
    // let sendToList: Contact[] = [].concat(sendTo as any || [])
    // sendToList = sendToList.filter(s => {
    //   if ((s instanceof Room || s instanceof Contact) && s.id) {
    //     return true
    //   }
    //   return false
    // }) as Contact[]
    // if (sendToList.length < 1) {
    //   throw new Error('param must be Room or Contact and array')
    // }
539
    if (rawPayload.FileSize >= largeFileSize && !rawPayload.Signature) {
540 541
      // if has RawObj.Signature, can forward the 25Mb+ file
      log.warn('MediaMessage', 'forward() Due to webWx restrictions, more than 25MB of files can not be downloaded and can not be forwarded.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
542
      throw new Error('forward() Due to webWx restrictions, more than 25MB of files can not be downloaded and can not be forwarded.')
543 544
    }

545
    newMsg.FromUserName         = this.id || ''
546
    newMsg.isTranspond          = true
547 548
    newMsg.MsgIdBeforeTranspond = rawPayload.MsgIdBeforeTranspond || rawPayload.MsgId
    newMsg.MMSourceMsgId        = rawPayload.MsgId
549
    // In room msg, the content prefix sender:, need to be removed, otherwise the forwarded sender will display the source message sender, causing self () to determine the error
550
    newMsg.Content      = Misc.unescapeHtml(rawPayload.Content.replace(/^@\w+:<br\/>/, '')).replace(/^[\w\-]+:<br\/>/, '')
551
    newMsg.MMIsChatRoom = receiver.roomId ? true : false
552 553 554

    // The following parameters need to be overridden after calling createMessage()

555
    rawPayload = Object.assign(rawPayload, newMsg)
556 557 558 559 560
    // for (let i = 0; i < sendToList.length; i++) {
      // newMsg.ToUserName = sendToList[i].id
      // // all call success return true
      // ret = (i === 0 ? true : ret) && await config.puppetInstance().forward(m, newMsg)
    // }
561
    newMsg.ToUserName = receiver.contactId || receiver.roomId as string
562 563
    // ret = await config.puppetInstance().forward(m, newMsg)
    // return ret
564
    const baseData  = rawPayload
565 566
    const patchData = newMsg

567
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
568 569 570 571
      const ret = await this.bridge.forward(baseData, patchData)
      if (!ret) {
        throw new Error('forward failed')
      }
572
    } catch (e) {
573
      log.error('PuppetPuppeteer', 'forward() exception: %s', e.message)
574 575 576 577 578
      Raven.captureException(e)
      throw e
    }
  }

579 580 581 582
  public async messageSendText(
    receiver : Receiver,
    text     : string,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
583
    log.verbose('PuppetPuppeteer', 'messageSendText(receiver=%s, text=%s)', JSON.stringify(receiver), text)
M
Mukaiu 已提交
584 585 586

    let destinationId

587 588 589 590
    if (receiver.roomId) {
      destinationId = receiver.roomId
    } else if (receiver.contactId) {
      destinationId = receiver.contactId
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
591
    } else {
592
      throw new Error('PuppetPuppeteer.messageSendText(): message with neither room nor to?')
M
Mukaiu 已提交
593 594
    }

595 596 597 598
    log.silly('PuppetPuppeteer', 'messageSendText() destination: %s, text: %s)',
                                  destinationId,
                                  text,
              )
M
Mukaiu 已提交
599

600 601 602 603 604 605 606 607
    try {
      await this.bridge.send(destinationId, text)
    } catch (e) {
      log.error('PuppetPuppeteer', 'messageSendText() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
  }
M
Mukaiu 已提交
608

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
609
  public async login(userId: string): Promise<void> {
610
    return super.login(userId)
611 612
  }

613 614 615
  /**
   * logout from browser, then server will emit `logout` event
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
616
  public async logout(): Promise<void> {
617
    log.verbose('PuppetPuppeteer', 'logout()')
618

619
    const user = this.selfId()
620 621 622 623
    if (!user) {
      log.warn('PuppetPuppeteer', 'logout() without self()')
      return
    }
624

625 626 627
    try {
      await this.bridge.logout()
    } catch (e) {
628
      log.error('PuppetPuppeteer', 'logout() exception: %s', e.message)
629
      Raven.captureException(e)
630
      throw e
631
    } finally {
632
      this.id = undefined
633
      this.emit('logout', user)
634
    }
635 636
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
637 638 639 640 641
  /**
   *
   * Contact
   *
   */
642
  public async contactRawPayload(id: string): Promise<WebContactRawPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
643
    log.silly('PuppetPuppeteer', 'contactRawPayload(%s) @ %s', id, this)
644 645 646 647
    try {
      const rawPayload = await this.bridge.getContact(id) as WebContactRawPayload
      return rawPayload
    } catch (e) {
648
      log.error('PuppetPuppeteer', 'contactRawPayload(%s) exception: %s', id, e.message)
649 650 651 652 653 654 655
      Raven.captureException(e)
      throw e
    }

  }

  public async contactRawPayloadParser(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
656
    rawPayload: WebContactRawPayload,
657
  ): Promise<ContactPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
658
    log.silly('PuppetPuppeteer', 'contactParseRawPayload(Object.keys(payload).length=%d)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
659 660 661
                                    Object.keys(rawPayload).length,
                )
    if (!Object.keys(rawPayload).length) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
662 663 664
      log.error('PuppetPuppeteer', 'contactParseRawPayload(Object.keys(payload).length=%d)',
                                    Object.keys(rawPayload).length,
                )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
665
      log.error('PuppetPuppeteer', 'contactParseRawPayload() got empty rawPayload!')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
666 667 668 669 670
      throw new Error('empty raw payload')
      // return {
      //   gender: Gender.Unknown,
      //   type:   Contact.Type.Unknown,
      // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
671 672 673 674 675 676
    }

    // this.id = rawPayload.UserName   // MMActualSender??? MMPeerUserName??? `getUserContact(message.MMActualSender,message.MMPeerUserName).HeadImgUrl`
    // uin:        rawPayload.Uin,    // stable id: 4763975 || getCookie("wxuin")

    return {
677
      id:         rawPayload.UserName,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
678
      weixin:     rawPayload.Alias,  // Wechat ID
679
      name:       Misc.plainText(rawPayload.NickName || ''),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
680
      alias:      rawPayload.RemarkName,
681
      gender:     rawPayload.Sex,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
      province:   rawPayload.Province,
      city:       rawPayload.City,
      signature:  rawPayload.Signature,

      address:    rawPayload.Alias, // XXX: need a stable address for user

      star:       !!rawPayload.StarFriend,
      friend:     rawPayload.stranger === undefined
                    ? undefined
                    : !rawPayload.stranger, // assign by injectio.js
      avatar:     rawPayload.HeadImgUrl,
      /**
       * @see 1. https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3243
       * @see 2. https://github.com/Urinx/WeixinBot/blob/master/README.md
       * @ignore
       */
      // tslint:disable-next-line
      type:      (!!rawPayload.UserName && !rawPayload.UserName.startsWith('@@') && !!(rawPayload.VerifyFlag & 8))
700 701
                    ? ContactType.Official
                    : ContactType.Personal,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
702 703 704 705 706 707 708 709
      /**
       * @see 1. https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L3246
       * @ignore
       */
      // special:       specialContactList.indexOf(rawPayload.UserName) > -1 || /@qqim$/.test(rawPayload.UserName),
    }
  }

710 711 712 713
  public async ding(data?: any): Promise<string> {
    try {
      return await this.bridge.ding(data)
    } catch (e) {
714
      log.warn('PuppetPuppeteer', 'ding(%s) rejected: %s', data, e.message)
715
      Raven.captureException(e)
716
      throw e
717 718
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
719

720
  public async contactAvatar(contactId: string): Promise<FileBox> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
721
    log.verbose('PuppetPuppeteer', 'contactAvatar(%s)', contactId)
722
    const payload = await this.contactPayload(contactId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
723 724 725 726 727 728 729
    if (!payload.avatar) {
      throw new Error('Can not get avatar: no payload.avatar!')
    }

    try {
      const hostname = await this.hostname()
      const avatarUrl = `http://${hostname}${payload.avatar}&type=big` // add '&type=big' to get big image
730
      const cookieList = await this.cookies()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
731 732
      log.silly('PuppeteerContact', 'avatar() url: %s', avatarUrl)

733
      /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
734
       * FileBox headers (will be used in NodeJS.http.get param options)
735 736 737 738 739 740
       */
      const headers = {
        cookie: cookieList.map(c => `${c['name']}=${c['value']}`).join('; '),
      }
      // return Misc.urlStream(avatarUrl, cookies)

741 742
      // const contact = this.Contact.load(contactId)
      // await contact.ready()
743

744
      const fileName = (payload.name || 'unknown') + '-avatar.jpg'
745
      return FileBox.fromRemote(
746
        avatarUrl,
747
        fileName,
748 749 750
        headers,
      )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
751 752 753 754 755 756 757
    } catch (err) {
      log.warn('PuppeteerContact', 'avatar() exception: %s', err.stack)
      Raven.captureException(err)
      throw err
    }
  }

758 759
  public contactAlias(contactId: string)                      : Promise<string>
  public contactAlias(contactId: string, alias: string | null): Promise<void>
760 761

  public async contactAlias(
762 763
    contactId : string,
    alias?    : string | null,
764 765 766 767 768
  ): Promise<string | void> {
    if (typeof alias === 'undefined') {
      throw new Error('to be implement')
    }

769
    try {
770
      const ret = await this.bridge.contactAlias(contactId, alias)
771
      if (!ret) {
772
        log.warn('PuppetPuppeteer', 'contactRemark(%s, %s) bridge.contactAlias() return false',
773
                              contactId, alias,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
774 775
                            )
        throw new Error('bridge.contactAlias fail')
776 777
      }
    } catch (e) {
778
      log.warn('PuppetPuppeteer', 'contactRemark(%s, %s) rejected: %s', contactId, alias, e.message)
779
      Raven.captureException(e)
780 781 782 783
      throw e
    }
  }

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  // private contactQueryFilterToFunctionString(
  //   query: ContactQueryFilter,
  // ): string {
  //   log.verbose('PuppetPuppeteer', 'contactQueryFilterToFunctionString({ %s })',
  //                           Object.keys(query)
  //                                 .map(k => `${k}: ${query[k as keyof ContactQueryFilter]}`)
  //                                 .join(', '),
  //             )

  //   if (Object.keys(query).length !== 1) {
  //     throw new Error('query only support one key. multi key support is not availble now.')
  //   }

  //   const filterKey = Object.keys(query)[0] as keyof ContactQueryFilter

  //   let filterValue: string | RegExp | undefined  = query[filterKey]
  //   if (!filterValue) {
  //     throw new Error('filterValue not found')
  //   }

  //   const protocolKeyMap = {
  //     name:   'NickName',
  //     alias:  'RemarkName',
  //   }

  //   const protocolFilterKey = protocolKeyMap[filterKey]
  //   if (!protocolFilterKey) {
  //     throw new Error('unsupport protocol filter key')
  //   }

  //   /**
  //    * must be string because we need inject variable value
  //    * into code as variable namespecialContactList
  //    */
  //   let filterFunction: string

  //   if (filterValue instanceof RegExp) {
  //     filterFunction = `(function (c) { return ${filterValue.toString()}.test(c.${protocolFilterKey}) })`
  //   } else if (typeof filterValue === 'string') {
  //     filterValue = filterValue.replace(/'/g, '\\\'')
  //     filterFunction = `(function (c) { return c.${protocolFilterKey} === '${filterValue}' })`
  //   } else {
  //     throw new Error('unsupport name type')
  //   }

  //   return filterFunction
  // }

  public async contactList(): Promise<string[]> {
    const idList = await this.bridge.contactList()
    return idList
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
835 836
  }

837 838 839
  // public async contactFindAll(
  //   query: ContactQueryFilter = { name: /.*/ },
  // ): Promise<string[]> {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
840

841
  //   const filterFunc = this.contactQueryFilterToFunctionString(query)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
842

843 844 845 846 847 848 849 850 851
  //   try {
  //     const idList = await this.bridge.contactFind(filterFunc)
  //     return idList
  //   } catch (e) {
  //     log.warn('PuppetPuppeteer', 'contactFind(%s) rejected: %s', filterFunc, e.message)
  //     Raven.captureException(e)
  //     throw e
  //   }
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
852

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
853 854 855 856 857 858
  /**
   *
   * Room
   *
   */
  public async roomRawPayload(id: string): Promise<WebRoomRawPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
859
    log.verbose('PuppetPuppeteer', 'roomRawPayload(%s)', id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
860 861

    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
862
      let rawPayload: WebRoomRawPayload | undefined  // = await this.bridge.getContact(room.id) as PuppeteerRoomRawPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
863 864 865 866

      // let currNum = rawPayload.MemberList && rawPayload.MemberList.length || 0
      // let prevNum = room.memberList().length  // rawPayload && rawPayload.MemberList && this.rawObj.MemberList.length || 0

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
867
      let prevLength = 0
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
868

869 870 871
      /**
       * @todo use Misc.retry() to replace the following loop
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
872 873
      let ttl = 7
      while (ttl--/* && currNum !== prevNum */) {
874 875 876
        rawPayload = await this.bridge.getContact(id) as undefined | WebRoomRawPayload

        if (rawPayload) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
877
          const currLength = rawPayload.MemberList && rawPayload.MemberList.length || -1
878

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
879
          log.silly('PuppetPuppeteer', `roomPayload() this.bridge.getContact(%s) MemberList.length:(prev:%d, curr:%d) at ttl:%d`,
880
            id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
881
            prevLength,
882 883 884 885 886
            currLength,
            ttl,
          )

          if (prevLength === currLength) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
887
            log.silly('PuppetPuppeteer', `roomPayload() puppet.getContact(%s) done at ttl:%d with length:%d`, this.id, ttl, currLength)
888 889
            return rawPayload
          }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
890 891 892 893 894 895 896 897
          if (currLength >= prevLength) {
            prevLength = currLength
          } else {
            log.warn('PuppetPuppeteer', 'roomRawPayload() currLength(%d) <= prevLength(%d) ???',
                                        currLength,
                                        prevLength,
                    )
          }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
898 899
        }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
900
        log.silly('PuppetPuppeteer', `roomPayload() puppet.getContact(${id}) retry at ttl:%d`, ttl)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
901 902 903
        await new Promise(r => setTimeout(r, 1000)) // wait for 1 second
      }

904
      throw new Error('no payload')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
905 906

    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
907
      log.error('PuppetPuppeteer', 'roomRawPayload(%s) exception: %s', id, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
908 909 910 911 912
      Raven.captureException(e)
      throw e
    }
  }

913
  public async roomRawPayloadParser(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
914
    rawPayload: WebRoomRawPayload,
915 916
  ): Promise<RoomPayload> {
    log.verbose('PuppetPuppeteer', 'roomRawPayloadParser(%s)', rawPayload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
917

918 919
    // const payload = await this.roomPayload(rawPayload.UserName)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
920
    // console.log(rawPayload)
921 922 923 924
    // const memberList = (rawPayload.MemberList || [])
    //                     .map(m => this.Contact.load(m.UserName))
    // await Promise.all(memberList.map(c => c.ready()))

925
    const id            = rawPayload.UserName
926 927
    const rawMemberList = rawPayload.MemberList || []
    const memberIdList  = rawMemberList.map(rawMember => rawMember.UserName)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
928

929 930 931 932
    // const nameMap         = await this.roomParseMap('name'        , rawPayload.MemberList)
    // const roomAliasMap    = await this.roomParseMap('roomAlias'   , rawPayload.MemberList)
    // const contactAliasMap = await this.roomParseMap('contactAlias', rawPayload.MemberList)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
933
    const aliasDict = {} as { [id: string]: string | undefined }
934 935

    if (Array.isArray(rawPayload.MemberList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
936 937 938 939 940 941 942 943 944 945 946
      rawPayload.MemberList.forEach(rawMember => {
        aliasDict[rawMember.UserName] = rawMember.DisplayName
      })
      // const memberListPayload = await Promise.all(
      //   rawPayload.MemberList
      //     .map(rawMember => rawMember.UserName)
      //     .map(contactId => this.contactPayload(contactId)),
      // )
      // console.log(memberListPayload)
      // memberListPayload.forEach(payload => aliasDict[payload.id] = payload.alias)
      // console.log(aliasDict)
947
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
948

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
949
    const roomPayload: RoomPayload = {
950
      id,
951
      topic:      Misc.plainText(rawPayload.NickName || ''),
952
      memberIdList,
953 954 955 956
      aliasDict,
      // nameMap,
      // roomAliasMap,
      // contactAliasMap,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
957
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
958 959
    // console.log(roomPayload)
    return roomPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
960 961
  }

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
  // private async roomParseMap(
  //   parseSection   : keyof RoomMemberQueryFilter,
  //   rawMemberList? : WebRoomRawMember[],
  // ): Promise<{ string, string }> {
  //   log.verbose('PuppetPuppeteer', 'roomParseMap(%s, rawMemberList.length=%d)',
  //                                   parseSection,
  //                                   rawMemberList && rawMemberList.length,
  //               )

  //   const dict: Map<string, string> = new Map<string, string>()

  //   const updateMember = async (member: WebRoomRawMember) => {
  //     let tmpName: string
  //     // console.log(member)
  //     const payload = await this.contactPayload(member.UserName)
  //     // contact.ready().then(() => console.log('###############', contact.name()))
  //     // console.log(contact)
  //     // log.silly('PuppetPuppeteer', 'roomParseMap() memberList.forEach(contact=%s)', contact)

  //     switch (parseSection) {
  //       case 'name':
  //         tmpName = payload.name || ''
  //         break
  //       case 'roomAlias':
  //         tmpName = member.DisplayName
  //         break
  //       case 'contactAlias':
  //         tmpName = payload.alias || ''
  //         break
  //       default:
  //         throw new Error('parseMap failed, member not found')
  //     }
  //     /**
  //      * ISSUE #64 emoji need to be striped
  //      * ISSUE #104 never use remark name because sys group message will never use that
  //      * @rui: Wrong for 'never use remark name because sys group message will never use that', see more in the latest comment in #104
  //      * @rui: webwx's NickName here return contactAlias, if not set contactAlias, return name
  //      * @rui: 2017-7-2 webwx's NickName just ruturn name, no contactAlias
  //      */
  //     dict.set(member.UserName, Misc.stripEmoji(tmpName))
  //   }
  //   if (Array.isArray(rawMemberList)) {
  //     await Promise.all(rawMemberList.map(updateMember))
  //   }
  //   return dict
  // }

  public async roomList(): Promise<string[]> {
    log.verbose('PuppetPupppeteer', 'roomList()')

    const idList = await this.bridge.roomList()
    return idList
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1014 1015
  }

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  // public async roomFindAll(
  //   query: RoomQueryFilter = { topic: /.*/ },
  // ): Promise<string[]> {

  //   let topicFilter = query.topic

  //   if (!topicFilter) {
  //     throw new Error('topicFilter not found')
  //   }

  //   let filterFunction: string

  //   if (topicFilter instanceof RegExp) {
  //     filterFunction = `(function (c) { return ${topicFilter.toString()}.test(c) })`
  //   } else if (typeof topicFilter === 'string') {
  //     topicFilter = topicFilter.replace(/'/g, '\\\'')
  //     filterFunction = `(function (c) { return c === '${topicFilter}' })`
  //   } else {
  //     throw new Error('unsupport topic type')
  //   }

  //   try {
  //     const idList = await this.bridge.roomFind(filterFunction)
  //     return idList
  //   } catch (e) {
  //     log.warn('PuppetPuppeteer', 'roomFind(%s) rejected: %s', filterFunction, e.message)
  //     Raven.captureException(e)
  //     throw e
  //   }
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1046

1047 1048 1049 1050
  public async roomDel(
    roomId    : string,
    contactId : string,
  ): Promise<void> {
1051
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1052
      await this.bridge.roomDelMember(roomId, contactId)
1053
    } catch (e) {
1054
      log.warn('PuppetPuppeteer', 'roomDelMember(%s, %d) rejected: %s', roomId, contactId, e.message)
1055 1056 1057
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1058 1059
  }

1060 1061 1062 1063
  public async roomAdd(
    roomId    : string,
    contactId : string,
  ): Promise<void> {
1064
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1065
      await this.bridge.roomAddMember(roomId, contactId)
1066
    } catch (e) {
1067
      log.warn('PuppetPuppeteer', 'roomAddMember(%s) rejected: %s', contactId, e.message)
1068 1069 1070
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1071
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1072

1073 1074 1075 1076
  public async roomTopic(
    roomId : string,
    topic  : string,
  ): Promise<string> {
1077 1078 1079
    try {
      return await this.bridge.roomModTopic(roomId, topic)
    } catch (e) {
1080
      log.warn('PuppetPuppeteer', 'roomTopic(%s) rejected: %s', topic, e.message)
1081 1082 1083
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1084 1085
  }

1086 1087 1088 1089
  public async roomCreate(
    contactIdList : string[],
    topic         : string,
  ): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1090 1091
    try {
      const roomId = await this.bridge.roomCreate(contactIdList, topic)
1092
      if (!roomId) {
1093
        throw new Error('PuppetPuppeteer.roomCreate() roomId "' + roomId + '" not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1094
      }
1095
      return roomId
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1096 1097

    } catch (e) {
1098
      log.warn('PuppetPuppeteer', 'roomCreate(%s, %s) rejected: %s', contactIdList.join(','), topic, e.message)
1099
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1100 1101
      throw e
    }
1102 1103
  }

1104 1105
  public async roomQuit(roomId: string): Promise<void> {
    log.warn('PuppetPuppeteer', 'roomQuit(%s) not supported by Web API', roomId)
1106 1107
  }

1108
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1109
   *
1110
   * FriendRequest
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1111
   *
1112
   */
1113 1114 1115 1116
  public async friendRequestSend(
    contactId : string,
    hello     : string,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1117
    try {
1118
      await this.bridge.verifyUserRequest(contactId, hello)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1119
    } catch (e) {
1120
      log.warn('PuppetPuppeteer', 'bridge.verifyUserRequest(%s, %s) rejected: %s', contactId, hello, e.message)
1121
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1122 1123
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1124 1125
  }

1126 1127 1128 1129
  public async friendRequestAccept(
    contactId : string,
    ticket    : string,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1130
    try {
1131
      await this.bridge.verifyUserOk(contactId, ticket)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1132
    } catch (e) {
1133
      log.warn('PuppetPuppeteer', 'bridge.verifyUserOk(%s, %s) rejected: %s', contactId, ticket, e.message)
1134
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1135 1136
      throw e
    }
1137
  }
1138 1139 1140 1141 1142

  /**
   * @private
   * For issue #668
   */
1143
  public async waitStable(): Promise<void> {
1144
    log.verbose('PuppetPuppeteer', 'readyStable()')
1145

1146 1147 1148
    let   prevLength = -1
    let   ttl        = 60
    const sleepTime  = 60 * 1000 / ttl
1149

1150
    while (ttl-- > 0) {
1151
      const contactIdList = await this.contactList()
1152 1153 1154
      if (prevLength === contactIdList.length) {
        log.verbose('PuppetPuppeteer', 'readyStable() stable() READY length=%d', prevLength)
        return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1155
      }
1156
      prevLength = contactIdList.length
1157

1158 1159
      await new Promise(r => setTimeout(r, sleepTime))
    }
1160

1161
    log.warn('PuppetPuppeteer', 'readyStable() TTL expired. Final length=%d', prevLength)
1162
  }
1163

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1164 1165 1166 1167 1168 1169
  /**
   * https://www.chatie.io:8080/api
   * location.hostname = www.chatie.io
   * location.host = www.chatie.io:8080
   * See: https://stackoverflow.com/a/11379802/1123955
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1170
  private async hostname(): Promise<string> {
1171 1172 1173 1174 1175 1176 1177
    try {
      const name = await this.bridge.hostname()
      if (!name) {
        throw new Error('no hostname found')
      }
      return name
    } catch (e) {
1178
      log.error('PuppetPuppeteer', 'hostname() exception:%s', e)
1179 1180 1181 1182 1183
      this.emit('error', e)
      throw e
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1184
  private async cookies(): Promise<Cookie[]> {
1185 1186 1187 1188 1189
    return await this.bridge.cookies()
  }

  public async saveCookie(): Promise<void> {
    const cookieList = await this.bridge.cookies()
1190 1191
    this.options.memory.set('cookies', cookieList)
    this.options.memory.save()
1192
  }
1193

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1194
  private extToType(ext: string): WebMessageType {
1195
    switch (ext) {
1196 1197 1198 1199
      case '.bmp':
      case '.jpeg':
      case '.jpg':
      case '.png':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1200
        return WebMessageType.IMAGE
1201
      case '.gif':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1202
        return WebMessageType.EMOTICON
1203
      case '.mp4':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1204
        return WebMessageType.VIDEO
1205
      default:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1206
        return WebMessageType.APP
1207 1208 1209
    }
  }

1210
  // public async readyMedia(): Promise<this> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1211 1212 1213 1214
  private async messageRawPayloadToUrl(
    rawPayload: WebMessageRawPayload,
  ): Promise<null | string> {
    log.silly('PuppetPuppeteer', 'readyMedia()')
1215

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1216 1217
    // let type = MessageType.Unknown
    let url: undefined | string
1218

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1219
    try {
1220

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
      switch (rawPayload.MsgType) {
        case WebMessageType.EMOTICON:
          // type = MessageType.Emoticon
          url = await this.bridge.getMsgEmoticon(rawPayload.MsgId)
          break
        case WebMessageType.IMAGE:
          // type = MessageType.Image
          url = await this.bridge.getMsgImg(rawPayload.MsgId)
          break
        case WebMessageType.VIDEO:
        case WebMessageType.MICROVIDEO:
          // type = MessageType.Video
          url = await this.bridge.getMsgVideo(rawPayload.MsgId)
          break
        case WebMessageType.VOICE:
          // type = MessageType.Audio
          url = await this.bridge.getMsgVoice(rawPayload.MsgId)
          break
1239

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        case WebMessageType.APP:
          switch (rawPayload.AppMsgType) {
            case WebAppMsgType.ATTACH:
              if (!rawPayload.MMAppMsgDownloadUrl) {
                throw new Error('no MMAppMsgDownloadUrl')
              }
              // had set in Message
              // type = MessageType.Attachment
              url = rawPayload.MMAppMsgDownloadUrl
              break

            case WebAppMsgType.URL:
            case WebAppMsgType.READER_TYPE:
              if (!rawPayload.Url) {
                throw new Error('no Url')
              }
              // had set in Message
              // type = MessageType.Attachment
              url = rawPayload.Url
              break

            default:
              const e = new Error('ready() unsupported typeApp(): ' + rawPayload.AppMsgType)
              log.warn('PuppeteerMessage', e.message)
              throw e
          }
          break
1267

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1268 1269 1270 1271 1272 1273
        case WebMessageType.TEXT:
          if (rawPayload.SubMsgType === WebMessageType.LOCATION) {
            // type = MessageType.Image
            url = await this.bridge.getMsgPublicLinkImg(rawPayload.MsgId)
          }
          break
1274

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        default:
          /**
           * not a support media message, do nothing.
           */
          return null
          // return this
      }

      if (!url) {
        // if (!this.payload.url) {
        //   /**
        //    * not a support media message, do nothing.
        //    */
        //   return this
        // }
        // url = this.payload.url
        // return {
        //   type: MessageType.Unknown,
        // }
        return null
      }

    } catch (e) {
      log.warn('PuppetPuppeteer', 'ready() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }

    return url

  }
1306

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1307 1308 1309 1310 1311 1312
  private filename(
    rawPayload: WebMessageRawPayload,
  ): null | string {
    log.verbose('PuppetPuppeteer', 'filename()')

    let filename = rawPayload.FileName || rawPayload.MediaId || rawPayload.MsgId
1313

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1314 1315
    const re = /\.[a-z0-9]{1,7}$/i
    if (!re.test(filename)) {
1316 1317 1318 1319 1320
      if (rawPayload.MMAppMsgFileExt) {
        filename += '.' + rawPayload.MMAppMsgFileExt
      } else {
        filename += this.extname(rawPayload)
      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1321
    }
1322

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1323 1324 1325
    log.silly('PuppetPuppeteer', 'filename()=%s, build from rawPayload', filename)
    return filename
  }
1326

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1327 1328 1329 1330
  private extname(
    rawPayload: WebMessageRawPayload,
  ): string {
    let ext: string
1331

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1332
    // const type = this.type()
1333

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    switch (rawPayload.MsgType) {
      case WebMessageType.EMOTICON:
        ext = '.gif'
        break

      case WebMessageType.IMAGE:
        ext = '.jpg'
        break

      case WebMessageType.VIDEO:
      case WebMessageType.MICROVIDEO:
        ext = '.mp4'
        break

      case WebMessageType.VOICE:
        ext = '.mp3'
        break

      case WebMessageType.APP:
        switch (rawPayload.AppMsgType) {
          case WebAppMsgType.URL:
            ext = '.url' // XXX
            break
          default:
            ext = '.' + rawPayload.MsgType
            break
        }
        break

      case WebMessageType.TEXT:
        if (rawPayload.SubMsgType === WebMessageType.LOCATION) {
          ext = '.jpg'
        }
        ext = '.' + rawPayload.MsgType

        break

      default:
        log.silly('PuppeteerMessage', `ext() got unknown type: ${rawPayload.MsgType}`)
        ext = '.' + rawPayload.MsgType
    }

    return ext

  }
1379

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
  private async uploadMedia(
    file       : FileBox,
    toUserName : string,
  ): Promise<WebMessageMediaPayload> {
    const filename = file.name
    const ext      = path.extname(filename) //  message.ext()

    // const contentType = Misc.mime(ext)
    const contentType = mime.getType(ext)
    // const contentType = message.mimeType()
    if (!contentType) {
      throw new Error('no MIME Type found on mediaMessage: ' + file.name)
    }
    let mediatype: WebMediaType
1394

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
    switch (ext) {
      case '.bmp':
      case '.jpeg':
      case '.jpg':
      case '.png':
      case '.gif':
        mediatype = WebMediaType.Image
        break
      case '.mp4':
        mediatype = WebMediaType.Video
        break
      default:
        mediatype = WebMediaType.Attachment
    }
1409

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1410
    const buffer = await new Promise<Buffer>((resolve, reject) => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1411 1412 1413 1414 1415
      file.pipe(bl((err: Error, data: Buffer) => {
        if (err) reject(err)
        else resolve(data)
      }))
    })
1416

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1417 1418 1419 1420 1421
    // Sending video files is not allowed to exceed 20MB
    // https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L1115
    const MAX_FILE_SIZE   = 100 * 1024 * 1024
    const LARGE_FILE_SIZE = 25 * 1024 * 1024
    const MAX_VIDEO_SIZE  = 20 * 1024 * 1024
1422

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1423 1424 1425 1426 1427
    if (mediatype === WebMediaType.Video && buffer.length > MAX_VIDEO_SIZE)
      throw new Error(`Sending video files is not allowed to exceed ${MAX_VIDEO_SIZE / 1024 / 1024}MB`)
    if (buffer.length > MAX_FILE_SIZE) {
      throw new Error(`Sending files is not allowed to exceed ${MAX_FILE_SIZE / 1024 / 1024}MB`)
    }
1428

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    const md5 = Misc.md5(buffer)

    const baseRequest     = await this.getBaseRequest()
    const passTicket      = await this.bridge.getPassticket()
    const uploadMediaUrl  = await this.bridge.getUploadMediaUrl()
    const checkUploadUrl  = await this.bridge.getCheckUploadUrl()
    const cookie          = await this.bridge.cookies()
    const first           = cookie.find(c => c.name === 'webwx_data_ticket')
    const webwxDataTicket = first && first.value
    const size            = buffer.length
1439
    const fromUserName    = this.selfId()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448
    const id              = 'WU_FILE_' + this.fileId
    this.fileId++

    const hostname = await this.bridge.hostname()
    const headers = {
      Referer: `https://${hostname}`,
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
      Cookie: cookie.map(c => c.name + '=' + c.value).join('; '),
    }
1449

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    log.silly('PuppetPuppeteer', 'uploadMedia() headers:%s', JSON.stringify(headers))

    const uploadMediaRequest = {
      BaseRequest:   baseRequest,
      FileMd5:       md5,
      FromUserName:  fromUserName,
      ToUserName:    toUserName,
      UploadType:    2,
      ClientMediaId: +new Date,
      MediaType:     WebMediaType.Attachment,
      StartPos:      0,
      DataLen:       size,
      TotalLen:      size,
      Signature:     '',
      AESKey:        '',
    }
1466

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475
    const checkData = {
      BaseRequest:  baseRequest,
      FromUserName: fromUserName,
      ToUserName:   toUserName,
      FileName:     filename,
      FileSize:     size,
      FileMd5:      md5,
      FileType:     7,              // If do not have this parameter, the api will fail
    }
1476

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    const mediaData = {
      ToUserName: toUserName,
      MediaId:    '',
      FileName:   filename,
      FileSize:   size,
      FileMd5:    md5,
      MMFileExt:  ext,
    } as WebMessageMediaPayload

    // If file size > 25M, must first call checkUpload to get Signature and AESKey, otherwise it will fail to upload
    // https://github.com/Chatie/webwx-app-tracker/blob/7c59d35c6ea0cff38426a4c5c912a086c4c512b2/formatted/webwxApp.js#L1132 #1182
    if (size > LARGE_FILE_SIZE) {
      let ret
      try {
        ret = <any> await new Promise((resolve, reject) => {
          const r = {
            url: `https://${hostname}${checkUploadUrl}`,
            headers,
            json: checkData,
          }
          request.post(r, (err, _ /* res */, body) => {
            try {
              if (err) {
                reject(err)
              } else {
                let obj = body
                if (typeof body !== 'object') {
                  log.silly('PuppetPuppeteer', 'updateMedia() typeof body = %s', typeof body)
                  try {
                    obj = JSON.parse(body)
                  } catch (e) {
                    log.error('PuppetPuppeteer', 'updateMedia() body = %s', body)
                    log.error('PuppetPuppeteer', 'updateMedia() exception: %s', e)
                    this.emit('error', e)
                  }
                }
                if (typeof obj !== 'object' || obj.BaseResponse.Ret !== 0) {
                  const errMsg = obj.BaseResponse || 'api return err'
                  log.silly('PuppetPuppeteer', 'uploadMedia() checkUpload err:%s \nreq:%s\nret:%s', JSON.stringify(errMsg), JSON.stringify(r), body)
                  reject(new Error('chackUpload err:' + JSON.stringify(errMsg)))
                }
                resolve({
                  Signature : obj.Signature,
                  AESKey    : obj.AESKey,
                })
              }
            } catch (e) {
              reject(e)
            }
          })
        })
      } catch (e) {
        log.error('PuppetPuppeteer', 'uploadMedia() checkUpload exception: %s', e.message)
        throw e
      }
      if (!ret.Signature) {
        log.error('PuppetPuppeteer', 'uploadMedia(): chackUpload failed to get Signature')
        throw new Error('chackUpload failed to get Signature')
      }
      uploadMediaRequest.Signature = ret.Signature
      uploadMediaRequest.AESKey    = ret.AESKey
      mediaData.Signature          = ret.Signature
    } else {
      delete uploadMediaRequest.Signature
      delete uploadMediaRequest.AESKey
    }

    log.verbose('PuppetPuppeteer', 'uploadMedia() webwx_data_ticket: %s', webwxDataTicket)
    log.verbose('PuppetPuppeteer', 'uploadMedia() pass_ticket: %s', passTicket)

    const formData = {
      id,
      name: filename,
      type: contentType,
      lastModifiedDate: Date().toString(),
      size,
      mediatype,
      uploadmediarequest: JSON.stringify(uploadMediaRequest),
      webwx_data_ticket: webwxDataTicket,
      pass_ticket: passTicket || '',
      filename: {
        value: buffer,
        options: {
          filename,
          contentType,
          size,
        },
      },
    }
    let mediaId: string
    try {
      mediaId = <string>await new Promise((resolve, reject) => {
        try {
          request.post({
            url: uploadMediaUrl + '?f=json',
            headers,
            formData,
          }, function (err, _, body) {
            if (err) { reject(err) }
            else {
              let obj = body
              if (typeof body !== 'object') {
                obj = JSON.parse(body)
              }
              resolve(obj.MediaId || '')
            }
          })
        } catch (e) {
          reject(e)
        }
      })
    } catch (e) {
      log.error('PuppetPuppeteer', 'uploadMedia() uploadMedia exception: %s', e.message)
      throw new Error('uploadMedia err: ' + e.message)
    }
    if (!mediaId) {
      log.error('PuppetPuppeteer', 'uploadMedia(): upload fail')
      throw new Error('PuppetPuppeteer.uploadMedia(): upload fail')
    }
    return Object.assign(mediaData, { MediaId: mediaId })
  }
1598

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1599 1600 1601 1602 1603
  public async messageSendFile(
    receiver : Receiver,
    file     : FileBox,
  ): Promise<void> {
    log.verbose('PuppetPuppeteer', 'messageSendFile(receiver=%s, file=%s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1604
                                    JSON.stringify(receiver),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1605 1606
                                    file.toString(),
                )
1607

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1608
    let destinationId
1609

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1610 1611 1612 1613 1614 1615 1616
    if (receiver.roomId) {
      destinationId = receiver.roomId
    } else if (receiver.contactId) {
      destinationId = receiver.contactId
    } else {
      throw new Error('PuppetPuppeteer.messageSendFile(): message with neither room nor to?')
    }
1617

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1618 1619
    let mediaData: WebMessageMediaPayload
    let rawPayload = {} as WebMessageRawPayload
1620

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    if (!rawPayload || !rawPayload.MediaId) {
      try {
        mediaData = await this.uploadMedia(file, destinationId)
        rawPayload = Object.assign(rawPayload, mediaData)
        log.silly('PuppetPuppeteer', 'Upload completed, new rawObj:%s', JSON.stringify(rawPayload))
      } catch (e) {
        log.error('PuppetPuppeteer', 'sendMedia() exception: %s', e.message)
        throw e
      }
    } else {
      // To support forward file
      log.silly('PuppetPuppeteer', 'skip upload file, rawObj:%s', JSON.stringify(rawPayload))
      mediaData = {
        ToUserName : destinationId,
        MediaId    : rawPayload.MediaId,
        MsgType    : rawPayload.MsgType,
        FileName   : rawPayload.FileName,
        FileSize   : rawPayload.FileSize,
        MMFileExt  : rawPayload.MMFileExt,
      }
      if (rawPayload.Signature) {
        mediaData.Signature = rawPayload.Signature
      }
    }
    // console.log('mediaData.MsgType', mediaData.MsgType)
    // console.log('rawObj.MsgType', message.rawObj && message.rawObj.MsgType)

    mediaData.MsgType = this.extToType(path.extname(file.name))
    log.silly('PuppetPuppeteer', 'sendMedia() destination: %s, mediaId: %s, MsgType; %s)',
      destinationId,
      mediaData.MediaId,
      mediaData.MsgType,
    )
    let ret = false
    try {
      ret = await this.bridge.sendMedia(mediaData)
    } catch (e) {
      log.error('PuppetPuppeteer', 'sendMedia() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
    if (!ret) {
      throw new Error('sendMedia fail')
    }
  }

  private async getBaseRequest(): Promise<any> {
    try {
      const json = await this.bridge.getBaseRequest()
      const obj = JSON.parse(json)
      return obj.BaseRequest
    } catch (e) {
      log.error('PuppetPuppeteer', 'send() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
  }
1678

1679
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
1680

1681
export default PuppetPuppeteer