puppet-puppeteer.ts 49.8 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
 */
19 20
// import * as request from 'request'
// import * as bl      from 'bl'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
22
// import cloneClass   from 'clone-class'
23 24 25
import {
  FileBox,
}                   from 'file-box'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26 27 28
import {
  ThrottleQueue,
}                   from 'rx-queue'
29 30 31 32 33
import {
  Watchdog,
  WatchdogFood,
}                   from 'watchdog'

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
34 35 36 37
import {
  Puppet,
  PuppetOptions,
  ScanData,
38
}                     from '../puppet/'
39
import {
40
  config,
41 42
  log,
  Raven,
43 44 45 46
}                     from '../config'
import Profile        from '../profile'
import Misc           from '../misc'

47 48
import {
  Bridge,
49
  Cookie,
50 51
}                       from './bridge'
import Event            from './event'
52 53

import {
54
  WebContactRawPayload,
55
  // WebMessageMediaPayload,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
56
  WebMessageRawPayload,
57
  // WebMediaType,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
58 59 60
  WebMessageType,
  WebRoomRawMember,
  WebRoomRawPayload,
61
}                           from './web-schemas'
62

63
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64 65 66 67
  Contact,
  ContactPayload,
  ContactQueryFilter,
  Gender,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
68
}                             from '../contact'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
69 70
import {
  Message,
71
  MessageDirection,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72
  MessagePayload,
73
  MessageType,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
74
}                             from '../message'
75
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
76 77 78 79
  Room,
  RoomMemberQueryFilter,
  RoomPayload,
  RoomQueryFilter,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80
}                             from '../room'
81 82 83
// import {
//   FriendRequest,
// }                             from '../puppet/friend-request'
M
Mukaiu 已提交
84

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85 86
export type PuppetFoodType = 'scan' | 'ding'
export type ScanFoodType   = 'scan' | 'login' | 'logout'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87

88
export class PuppetPuppeteer extends Puppet {
89
  public bridge   : Bridge
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90
  public scanInfo?: ScanData
91

92
  public scanWatchdog: Watchdog<ScanFoodType>
93

94
  // private fileId: number
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
95

96 97 98
  constructor(
    public options: PuppetOptions,
  ) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
99
    super(options)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100

101
    // this.fileId = 0
102

103
    const SCAN_TIMEOUT  = 2 * 60 * 1000 // 2 minutes
104
    this.scanWatchdog   = new Watchdog<ScanFoodType>(SCAN_TIMEOUT, 'Scan')
105 106
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
107
  public async start(): Promise<void> {
108
    log.verbose('PuppetPuppeteer', `start() with ${this.options.profile}`)
109

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

112
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113
      this.initWatchdog()
114
      this.initWatchdogForScan()
115 116

      this.bridge = await this.initBridge(this.options.profile)
117
      log.verbose('PuppetPuppeteer', 'initBridge() done')
118

119 120 121 122
      /**
       *  state must set to `live`
       *  before feed Watchdog
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
123
      this.state.on(true)
124

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125 126 127
      /**
       * Feed the dog and start watch
       */
128
      const food: WatchdogFood = {
L
lijiarui 已提交
129 130
        data: 'inited',
        timeout: 2 * 60 * 1000, // 2 mins for first login
131 132
      }
      this.emit('watchdog', food)
133

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
134 135 136
      /**
       * Save cookie for every 5 minutes
       */
137 138
      const throttleQueue = new ThrottleQueue(5 * 60 * 1000)
      this.on('heartbeat', data => throttleQueue.next(data))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139
      throttleQueue.subscribe(async data => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
140
        log.verbose('Wechaty', 'start() throttleQueue.subscribe() new item: %s', data)
141 142 143
        await this.saveCookie()
      })

144
      log.verbose('PuppetPuppeteer', 'start() done')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
145
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146

147
    } catch (e) {
148
      log.error('PuppetPuppeteer', 'start() exception: %s', e)
149

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151
      this.emit('error', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152
      await this.stop()
153

154
      Raven.captureException(e)
155
      throw e
156
    }
157 158
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159
  public initWatchdog(): void {
160
    log.verbose('PuppetPuppeteer', 'initWatchdogForPuppet()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161

162 163
    const puppet = this

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167 168 169
    // fix issue #981
    puppet.removeAllListeners('watchdog')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
170 171
    puppet.on('watchdog', food => this.watchdog.feed(food))
    this.watchdog.on('feed', food => {
172
      log.silly('PuppetPuppeteer', 'initWatchdogForPuppet() dog.on(feed, food={type=%s, data=%s})', food.type, food.data)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
173
      // feed the dog, heartbeat the puppet.
174 175 176
      puppet.emit('heartbeat', food.data)
    })

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177
    this.watchdog.on('reset', async (food, timeout) => {
178
      log.warn('PuppetPuppeteer', 'initWatchdogForPuppet() dog.on(reset) last food:%s, timeout:%s',
179
                            food.data, timeout)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180
      try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
181 182
        await this.stop()
        await this.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
183 184 185
      } catch (e) {
        puppet.emit('error', e)
      }
186 187 188 189 190 191 192 193 194 195 196
    })
  }

  /**
   * 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
   */
  public initWatchdogForScan(): void {
197
    log.verbose('PuppetPuppeteer', 'initWatchdogForScan()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
198

199
    const puppet = this
200
    const dog    = this.scanWatchdog
201

202 203 204
    // clean the dog because this could be re-inited
    dog.removeAllListeners()

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    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 (李卓桓) 已提交
225
    dog.on('reset', async (food, timePast) => {
226
      log.warn('PuppetPuppeteer', 'initScanWatchdog() on(reset) lastFood: %s, timePast: %s',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227
                            food.data, timePast)
228 229 230
      try {
        await this.bridge.reload()
      } catch (e) {
231
        log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) exception: %s', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
232
        try {
233
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) try to recover by bridge.{quit,init}()', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
234 235
          await this.bridge.quit()
          await this.bridge.init()
236
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) recover successful')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
237
        } catch (e) {
238
          log.error('PuppetPuppeteer', 'initScanWatchdog() on(reset) recover FAIL: %s', e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
239 240
          this.emit('error', e)
        }
241 242 243 244
      }
    })
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
248
    if (this.state.off()) {
249
      log.warn('PuppetPuppeteer', 'quit() is called on a OFF puppet. await ready(off) and return.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
250 251
      await this.state.ready('off')
      return
252
    }
253
    this.state.off('pending')
254

255
    log.verbose('PuppetPuppeteer', 'quit() make watchdog sleep before do quit')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256
    this.watchdog.sleep()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257
    this.scanWatchdog.sleep()
258

259
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
260 261 262
      await this.bridge.quit()
      // register the removeListeners micro task at then end of the task queue
      setImmediate(() => this.bridge.removeAllListeners())
263
    } catch (e) {
264
      log.error('PuppetPuppeteer', 'quit() exception: %s', e.message)
265
      Raven.captureException(e)
266
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267
    } finally {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268
      this.state.off(true)
269
    }
270 271
  }

272
  public async initBridge(profile: Profile): Promise<Bridge> {
273
    log.verbose('PuppetPuppeteer', 'initBridge()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
274

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275
    if (this.state.off()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
276
      const e = new Error('initBridge() found targetState != live, no init anymore')
277
      log.warn('PuppetPuppeteer', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
278
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
279
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
280

281
    const head = config.head
282 283 284 285 286 287
    // we have to set this.bridge right now,
    // because the Event.onXXX might arrive while we are initializing.
    this.bridge = new Bridge({
      head,
      profile,
    })
288

289
    this.bridge.on('ding'     , Event.onDing.bind(this))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
290
    this.bridge.on('error'    , e => this.emit('error', e))
291 292 293 294 295
    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))
296
    this.bridge.on('unload'   , Event.onUnload.bind(this))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
297

298
    try {
299
      await this.bridge.init()
300
    } catch (e) {
301
      log.error('PuppetPuppeteer', 'initBridge() exception: %s', e.message)
302
      await this.bridge.quit().catch(console.error)
303 304 305 306
      this.emit('error', e)

      Raven.captureException(e)
      throw e
307
    }
308 309

    return this.bridge
310 311
  }

312 313 314
  public async messageRawPayload(id: string): Promise <WebMessageRawPayload> {
    const rawPayload = await this.bridge.getMessage(id)
    return rawPayload
315
  }
316

317
  public async messageRawPayloadParser(
318
    rawPayload: WebMessageRawPayload,
319
  ): Promise<MessagePayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
320
    log.verbose('PuppetPuppeteer', 'messageRawPayloadParser(%s) @ %s', rawPayload, this)
321

322
    const from: Contact     = this.Contact.load(rawPayload.MMActualSender)  // MMPeerUserName
323 324
    const text: string      = rawPayload.MMActualContent                    // Content has @id prefix added by wx
    const date: Date        = new Date(rawPayload.MMDisplayTime)            // Javascript timestamp of milliseconds
325 326 327 328 329 330 331

    let room : undefined | Room
    let to   : undefined | Contact

    // FIXME: has there any better method to know the room ID?
    if (rawPayload.MMIsChatRoom) {
      if (/^@@/.test(rawPayload.FromUserName)) {
332
        room = this.Room.load(rawPayload.FromUserName) // MMPeerUserName always eq FromUserName ?
333
      } else if (/^@@/.test(rawPayload.ToUserName)) {
334
        room = this.Room.load(rawPayload.ToUserName)
335 336 337 338
      } else {
        throw new Error('parse found a room message, but neither FromUserName nor ToUserName is a room(/^@@/)')
      }
      room = room
M
Mukaiu 已提交
339 340
    }

341 342
    if (rawPayload.ToUserName) {
      if (!/^@@/.test(rawPayload.ToUserName)) { // if a message in room without any specific receiver, then it will set to be `undefined`
343
        to = this.Contact.load(rawPayload.ToUserName)
344
      }
345 346
    }

347
    const file: FileBox | undefined = undefined
M
Mukaiu 已提交
348

349
    const type: MessageType = this.messageTypeFromWeb(rawPayload.MsgType)
350

351 352 353 354 355 356 357 358 359 360 361 362
    const payload: MessagePayload = {
      direction: MessageDirection.MT,
      type,
      from,
      to,
      room,
      text,
      // status:       rawPayload.Status,
      // digest:       rawPayload.MMDigest,
      date,
      file,
      // url:          rawPayload.Url || rawObj.MMAppMsgDownloadUrl || rawObj.MMLocationUrl,
363 364
    }

365
    // TODO: parse the url to FileBox
M
Mukaiu 已提交
366

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
367 368 369
    return payload
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
370
  private messageTypeFromWeb(webMsgType: WebMessageType): MessageType {
371
    switch (webMsgType) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372
      case WebMessageType.TEXT:
373 374
        return MessageType.Text

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
375 376
      case WebMessageType.EMOTICON:
      case WebMessageType.IMAGE:
377 378
        return MessageType.Image

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
379
      case WebMessageType.VOICE:
380
        return MessageType.Audio
381

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
382 383
      case WebMessageType.MICROVIDEO:
      case WebMessageType.VIDEO:
384
        return MessageType.Video
385

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
386
      case WebMessageType.TEXT:
387 388 389
        return MessageType.Text

      case WebMessageType.SYS:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
390
        // FriendRequest is a SYS message
391 392
        // FIXME: should we use better message type at here???
        return MessageType.Text
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

      // VERIFYMSG           = 37,
      // POSSIBLEFRIEND_MSG  = 40,
      // SHARECARD           = 42,
      // LOCATION            = 48,
      // APP                 = 49,
      // VOIPMSG             = 50,
      // STATUSNOTIFY        = 51,
      // VOIPNOTIFY          = 52,
      // VOIPINVITE          = 53,
      // SYSNOTICE           = 9999,
      // RECALLED            = 10002,
      default:
        throw new Error('un-supported WebMsgType: ' + webMsgType)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
408 409
  }

410
  /**
411
   * TODO: Test this function if it could work...
412 413
   */
  // public async forward(baseData: MsgRawObj, patchData: MsgRawObj): Promise<boolean> {
414
  public async messageForward(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415
    message : Message,
416
    to      : Contact | Room,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
417
  ): Promise<void> {
418

419 420 421
    log.silly('PuppetPuppeteer', 'forward(%s, %s)',
                                  message,
                                  to,
422
    )
423

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
424
    let rawPayload = await this.messageRawPayload(message.id)
425 426

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
428
    const newMsg = <WebMessageRawPayload>{}
429 430 431 432 433 434 435 436 437 438 439 440 441
    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')
    // }
442
    if (rawPayload.FileSize >= largeFileSize && !rawPayload.Signature) {
443 444
      // 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 (李卓桓) 已提交
445
      throw new Error('forward() Due to webWx restrictions, more than 25MB of files can not be downloaded and can not be forwarded.')
446 447
    }

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
448
    newMsg.FromUserName         = this.user && this.user.id || ''
449
    newMsg.isTranspond          = true
450 451
    newMsg.MsgIdBeforeTranspond = rawPayload.MsgIdBeforeTranspond || rawPayload.MsgId
    newMsg.MMSourceMsgId        = rawPayload.MsgId
452
    // 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
453 454
    newMsg.Content      = Misc.unescapeHtml(rawPayload.Content.replace(/^@\w+:<br\/>/, '')).replace(/^[\w\-]+:<br\/>/, '')
    newMsg.MMIsChatRoom = to instanceof Room ? true : false
455 456 457

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

458
    rawPayload = Object.assign(rawPayload, newMsg)
459 460 461 462 463
    // 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)
    // }
464
    newMsg.ToUserName = to.id
465 466
    // ret = await config.puppetInstance().forward(m, newMsg)
    // return ret
467
    const baseData  = rawPayload
468 469
    const patchData = newMsg

470
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
471 472 473 474
      const ret = await this.bridge.forward(baseData, patchData)
      if (!ret) {
        throw new Error('forward failed')
      }
475
    } catch (e) {
476
      log.error('PuppetPuppeteer', 'forward() exception: %s', e.message)
477 478 479 480 481
      Raven.captureException(e)
      throw e
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
482
   public async messageSend(message: Message): Promise<void> {
483
    log.verbose('PuppetPuppeteer', 'send(%s)', message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
484

M
Mukaiu 已提交
485 486 487 488 489 490 491
    const to   = message.to()
    const room = message.room()

    let destinationId

    if (room) {
      destinationId = room.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
492
    } else if (to) {
M
Mukaiu 已提交
493
      destinationId = to.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
494
    } else {
495
      throw new Error('PuppetPuppeteer.send(): message with neither room nor to?')
M
Mukaiu 已提交
496 497
    }

498
    if (message.type() === MessageType.Text) {
499
      log.silly('PuppetPuppeteer', 'send() TEXT message.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
500
      const text = message.text()
M
Mukaiu 已提交
501

502
      log.silly('PuppetPuppeteer', 'send() destination: %s, text: %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503 504
                                    destinationId,
                                    text,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
505
                )
M
Mukaiu 已提交
506 507

      try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
508
        await this.bridge.send(destinationId, text)
M
Mukaiu 已提交
509
      } catch (e) {
510
        log.error('PuppetPuppeteer', 'send() exception: %s', e.message)
511
        Raven.captureException(e)
M
Mukaiu 已提交
512 513
        throw e
      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
514
    } else {
515
      log.silly('PuppetPuppeteer', 'send() non-TEXT message.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
516

517 518 519 520 521 522
      log.error('PuppetPuppeteer', 'messageSend() sendMedia un-implement yet!!!')
      // TODO: implement this!
      // const ret = await this.sendMedia(message)
      // if (!ret) {
      //   throw new Error('sendMedia fail')
      // }
M
Mukaiu 已提交
523 524
    }
  }
525

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
526
  public async login(user: Contact): Promise<void> {
527 528 529 530 531 532 533 534 535
    log.warn('PuppetPuppeteer', 'login(%s)', user)
    this.user = user
    this.emit('login', user)
  }

  public logonoff(): boolean {
    return !!(this.user)
  }

536 537 538
  /**
   * logout from browser, then server will emit `logout` event
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
539
  public async logout(): Promise<void> {
540
    log.verbose('PuppetPuppeteer', 'logout()')
541

542 543 544 545 546
    const user = this.userSelf()
    if (!user) {
      log.warn('PuppetPuppeteer', 'logout() without self()')
      return
    }
547

548 549 550
    try {
      await this.bridge.logout()
    } catch (e) {
551
      log.error('PuppetPuppeteer', 'logout() exception: %s', e.message)
552
      Raven.captureException(e)
553
      throw e
554 555 556
    } finally {
      this.user = undefined
      this.emit('logout', user)
557
    }
558 559
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
560 561 562 563 564
  /**
   *
   * Contact
   *
   */
565
  public async contactRawPayload(id: string): Promise<WebContactRawPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
566
    log.verbose('PuppetPuppeteer', 'contactRawPayload(%s) @ %s', id, this)
567 568 569 570
    try {
      const rawPayload = await this.bridge.getContact(id) as WebContactRawPayload
      return rawPayload
    } catch (e) {
571
      log.error('PuppetPuppeteer', 'contactRawPayload(%s) exception: %s', id, e.message)
572 573 574 575 576 577 578
      Raven.captureException(e)
      throw e
    }

  }

  public async contactRawPayloadParser(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
579
    rawPayload: WebContactRawPayload,
580
  ): Promise<ContactPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
581 582 583 584 585 586
    log.verbose('PuppetPuppeteer', 'contactParseRawPayload(Object.keys(payload).length=%d)',
                                    Object.keys(rawPayload).length,
                )
    if (!Object.keys(rawPayload).length) {
      log.error('PuppetPuppeteer', 'contactParseRawPayload() got empty rawPayload!')
      return {
587
        gender: Gender.Unknown,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
588
        type:   Contact.Type.Unknown,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
589
      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
590 591 592 593 594 595 596
    }

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

    return {
      weixin:     rawPayload.Alias,  // Wechat ID
597
      name:       Misc.plainText(rawPayload.NickName || ''),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
598
      alias:      rawPayload.RemarkName,
599
      gender:     rawPayload.Sex,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
      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))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
618 619
                    ? Contact.Type.Official
                    : Contact.Type.Personal,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
620 621 622 623 624 625 626 627
      /**
       * @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),
    }
  }

628 629 630 631
  public async ding(data?: any): Promise<string> {
    try {
      return await this.bridge.ding(data)
    } catch (e) {
632
      log.warn('PuppetPuppeteer', 'ding(%s) rejected: %s', data, e.message)
633
      Raven.captureException(e)
634
      throw e
635 636
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
637

638
  public async contactAvatar(contact: Contact): Promise<FileBox> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
639
    const payload = await this.contactPayload(contact.id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
640 641 642 643 644 645 646
    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
647
      const cookieList = await this.cookies()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
648 649
      log.silly('PuppeteerContact', 'avatar() url: %s', avatarUrl)

650 651 652 653 654 655 656 657 658 659 660 661 662 663
      /**
       * FileBox headers
       */
      const headers = {
        cookie: cookieList.map(c => `${c['name']}=${c['value']}`).join('; '),
      }
      // return Misc.urlStream(avatarUrl, cookies)

      return FileBox.fromRemote(
        avatarUrl,
        contact.name() || 'unknown' + '-avatar.jpg',
        headers,
      )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
664 665 666 667 668 669 670
    } catch (err) {
      log.warn('PuppeteerContact', 'avatar() exception: %s', err.stack)
      Raven.captureException(err)
      throw err
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
671 672
  public contactAlias(contact: Contact)                      : Promise<string>
  public contactAlias(contact: Contact, alias: string | null): Promise<void>
673 674

  public async contactAlias(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
675
    contact: Contact,
676 677 678 679 680 681
    alias?: string | null,
  ): Promise<string | void> {
    if (typeof alias === 'undefined') {
      throw new Error('to be implement')
    }

682
    try {
683
      const ret = await this.bridge.contactAlias(contact.id, alias)
684
      if (!ret) {
685
        log.warn('PuppetPuppeteer', 'contactRemark(%s, %s) bridge.contactAlias() return false',
686
                              contact.id, alias,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
687 688
                            )
        throw new Error('bridge.contactAlias fail')
689 690
      }
    } catch (e) {
691
      log.warn('PuppetPuppeteer', 'contactRemark(%s, %s) rejected: %s', contact.id, alias, e.message)
692
      Raven.captureException(e)
693 694 695 696
      throw e
    }
  }

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
697 698 699
  private contactQueryFilterToFunctionString(
    query: ContactQueryFilter,
  ): string {
700
    log.verbose('PuppetPuppeteer', 'contactQueryFilterToFunctionString({ %s })',
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
701
                            Object.keys(query)
702
                                  .map((k: keyof ContactQueryFilter) => `${k}: ${query[k]}`)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
703 704 705 706 707 708 709
                                  .join(', '),
              )

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

710
    const filterKey = Object.keys(query)[0] as keyof ContactQueryFilter
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
711

712 713 714
    let filterValue: string | RegExp | undefined  = query[filterKey]
    if (!filterValue) {
      throw new Error('filterValue not found')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
715 716
    }

717 718 719
    const protocolKeyMap = {
      name:   'NickName',
      alias:  'RemarkName',
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
720 721
    }

722 723 724
    const protocolFilterKey = protocolKeyMap[filterKey]
    if (!protocolFilterKey) {
      throw new Error('unsupport protocol filter key')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
725 726 727 728 729 730 731 732 733
    }

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

    if (filterValue instanceof RegExp) {
734
      filterFunction = `(function (c) { return ${filterValue.toString()}.test(c.${protocolFilterKey}) })`
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
735 736
    } else if (typeof filterValue === 'string') {
      filterValue = filterValue.replace(/'/g, '\\\'')
737
      filterFunction = `(function (c) { return c.${protocolFilterKey} === '${filterValue}' })`
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
738 739 740 741 742 743 744
    } else {
      throw new Error('unsupport name type')
    }

    return filterFunction
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
745
  public async contactFindAll(query: ContactQueryFilter): Promise<Contact[]> {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
746 747 748

    const filterFunc = this.contactQueryFilterToFunctionString(query)

749 750
    try {
      const idList = await this.bridge.contactFind(filterFunc)
751
      return idList.map(id => {
752
        const c = this.Contact.load(id)
753 754
        return c
      })
755
    } catch (e) {
756
      log.warn('PuppetPuppeteer', 'contactFind(%s) rejected: %s', filterFunc, e.message)
757 758 759
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
760 761
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
762 763 764 765 766 767
  /**
   *
   * Room
   *
   */
  public async roomRawPayload(id: string): Promise<WebRoomRawPayload> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
768
    log.verbose('PuppetPuppeteer', 'roomRawPayload(%s)', id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
769 770

    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
771
      let rawPayload: WebRoomRawPayload | undefined  // = await this.bridge.getContact(room.id) as PuppeteerRoomRawPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
772 773 774 775

      // 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 (李卓桓) 已提交
776 777
      let prevNum = 0

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
778 779
      let ttl = 7
      while (ttl--/* && currNum !== prevNum */) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
780
        rawPayload = await this.bridge.getContact(id) as WebRoomRawPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
781 782 783 784

        const currNum = rawPayload.MemberList && rawPayload.MemberList.length || 0

        log.silly('PuppetPuppeteer', `roomPayload() this.bridge.getContact(%s) MemberList.length:%d at ttl:%d`,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
785
          id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
786 787 788 789
          currNum,
          ttl,
        )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
790 791 792
        if (currNum > 0 && prevNum === currNum) {
          log.silly('PuppetPuppeteer', `roomPayload() puppet.getContact(${id}) done at ttl:%d`, ttl)
          break
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
793
        }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
794
        prevNum = currNum
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
795

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
796
        log.silly('PuppetPuppeteer', `roomPayload() puppet.getContact(${id}) retry at ttl:%d`, ttl)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
797 798 799 800 801 802 803 804
        await new Promise(r => setTimeout(r, 1000)) // wait for 1 second
      }

      // await this.readyAllMembers(rawPayload && rawPayload.MemberList || [])
      if (!rawPayload) {
        throw new Error('no payload')
      }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
805
      return rawPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
806
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
807
      log.error('PuppetPuppeteer', 'roomRawPayload(%s) exception: %s', id, e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
808 809 810 811 812
      Raven.captureException(e)
      throw e
    }
  }

813
  public async roomRawPayloadParser(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
814
    rawPayload: WebRoomRawPayload,
815 816
  ): Promise<RoomPayload> {
    log.verbose('PuppetPuppeteer', 'roomRawPayloadParser(%s)', rawPayload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
817

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
818
    // console.log(rawPayload)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
819
    const memberList = (rawPayload.MemberList || [])
820
                        .map(m => this.Contact.load(m.UserName))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
821
    await Promise.all(memberList.map(c => c.ready()))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
822 823 824 825 826

    const nameMap         = this.roomParseMap('name'        , rawPayload.MemberList)
    const roomAliasMap    = this.roomParseMap('roomAlias'   , rawPayload.MemberList)
    const contactAliasMap = this.roomParseMap('contactAlias', rawPayload.MemberList)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
827
    const roomPayload: RoomPayload = {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
828 829
      // id:         rawPayload.UserName,
      // encryId:    rawPayload.EncryChatRoomId, // ???
830
      topic:      Misc.plainText(rawPayload.NickName || ''),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
831 832 833 834 835 836 837
      // ownerUin:   rawPayload.OwnerUin,
      memberList,

      nameMap,
      roomAliasMap,
      contactAliasMap,
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
838 839
    // console.log(roomPayload)
    return roomPayload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
840 841 842 843
  }

  private roomParseMap(
    parseSection: keyof RoomMemberQueryFilter,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
844
    memberList?:  WebRoomRawMember[],
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
845
  ): Map<string, string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
846 847 848 849 850 851
    log.verbose('PuppetPuppeteer', 'roomParseMap(%s, memberList.length=%d)',
                                    parseSection,
                                    memberList && memberList.length,
                )

    const dict: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
852 853 854
    if (memberList && memberList.map) {
      memberList.forEach(member => {
        let tmpName: string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
855
        // console.log(member)
856
        const contact = this.Contact.load(member.UserName)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
857 858 859
        // contact.ready().then(() => console.log('###############', contact.name()))
        // console.log(contact)
        // log.silly('PuppetPuppeteer', 'roomParseMap() memberList.forEach(contact=%s)', contact)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

        switch (parseSection) {
          case 'name':
            tmpName = contact.name()
            break
          case 'roomAlias':
            tmpName = member.DisplayName
            break
          case 'contactAlias':
            tmpName = contact.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
         */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
881
        dict.set(member.UserName, Misc.stripEmoji(tmpName))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
882 883
      })
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
884
    return dict
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
885 886
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
887 888
  public async roomFindAll(
    query: RoomQueryFilter = { topic: /.*/ },
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
889
  ): Promise<Room[]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

    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')
    }

908
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
909
      const idList = await this.bridge.roomFind(filterFunction)
910
      return idList.map(id => {
911
        const r = this.Room.load(id) as Room
912 913
        return r
      })
914
    } catch (e) {
915
      log.warn('PuppetPuppeteer', 'roomFind(%s) rejected: %s', filterFunction, e.message)
916 917 918
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
919 920
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
921
  public async roomDel(room: Room, contact: Contact): Promise<void> {
922 923
    const roomId    = room.id
    const contactId = contact.id
924
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
925
      await this.bridge.roomDelMember(roomId, contactId)
926
    } catch (e) {
927
      log.warn('PuppetPuppeteer', 'roomDelMember(%s, %d) rejected: %s', roomId, contactId, e.message)
928 929 930
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
931 932
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
933
  public async roomAdd(room: Room, contact: Contact): Promise<void> {
934 935
    const roomId    = room.id
    const contactId = contact.id
936
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
937
      await this.bridge.roomAddMember(roomId, contactId)
938
    } catch (e) {
939
      log.warn('PuppetPuppeteer', 'roomAddMember(%s) rejected: %s', contact, e.message)
940 941 942
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
943
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
944

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
945
  public async roomTopic(room: Room, topic: string): Promise<string> {
946
    if (!room || typeof topic === 'undefined') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
947
      return Promise.reject(new Error('room or topic not found'))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
948
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
949 950

    const roomId = room.id
951 952 953
    try {
      return await this.bridge.roomModTopic(roomId, topic)
    } catch (e) {
954
      log.warn('PuppetPuppeteer', 'roomTopic(%s) rejected: %s', topic, e.message)
955 956 957
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
958 959
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
960
  public async roomCreate(contactList: Contact[], topic: string): Promise<Room> {
961
    if (!contactList || ! contactList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
962 963 964
      throw new Error('contactList not found')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
965
    const contactIdList = contactList.map(c => c.id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
966

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
967 968
    try {
      const roomId = await this.bridge.roomCreate(contactIdList, topic)
969
      if (!roomId) {
970
        throw new Error('PuppetPuppeteer.roomCreate() roomId "' + roomId + '" not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
971
      }
972
      const r = this.Room.load(roomId) as Room
973
      return r
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
974 975

    } catch (e) {
976
      log.warn('PuppetPuppeteer', 'roomCreate(%s, %s) rejected: %s', contactIdList.join(','), topic, e.message)
977
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
978 979
      throw e
    }
980 981
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
982
  public async roomQuit(room: Room): Promise<void> {
983 984 985
    log.warn('PuppetPuppeteer', 'roomQuit(%s) not supported by Web API', room)
  }

986
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
987
   *
988
   * FriendRequest
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
989
   *
990
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
991
  public async friendRequestSend(contact: Contact, hello: string): Promise<void> {
992 993
    if (!contact) {
      throw new Error('contact not found')
994
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
995

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
996
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
997
      await this.bridge.verifyUserRequest(contact.id, hello)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
998
    } catch (e) {
999
      log.warn('PuppetPuppeteer', 'bridge.verifyUserRequest(%s, %s) rejected: %s', contact.id, hello, e.message)
1000
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1001 1002
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1003 1004
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1005
  public async friendRequestAccept(contact: Contact, ticket: string): Promise<void> {
1006 1007
    if (!contact || !ticket) {
      throw new Error('contact or ticket not found')
1008 1009
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1010
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1011
      await this.bridge.verifyUserOk(contact.id, ticket)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1012
    } catch (e) {
1013
      log.warn('PuppetPuppeteer', 'bridge.verifyUserOk(%s, %s) rejected: %s', contact.id, ticket, e.message)
1014
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1015 1016
      throw e
    }
1017
  }
1018 1019 1020 1021 1022 1023

  /**
   * @private
   * For issue #668
   */
  public async readyStable(): Promise<void> {
1024
    log.verbose('PuppetPuppeteer', 'readyStable()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1025
    let counter = -1
1026

1027
    const stable = async (done: Function): Promise<void> => {
1028
      log.silly('PuppetPuppeteer', 'readyStable() stable() counter=%d', counter)
1029

1030
      const contactList = await this.Contact.findAll()
1031
      if (counter === contactList.length) {
1032
        log.verbose('PuppetPuppeteer', 'readyStable() stable() READY counter=%d', counter)
1033
        return done()
1034 1035
      }
      counter = contactList.length
1036
      setTimeout(() => stable(done), 1000)
1037 1038 1039 1040
        .unref()
    }

    return new Promise<void>((resolve, reject) => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1041
      const timer = setTimeout(() => {
1042
        log.warn('PuppetPuppeteer', 'readyStable() stable() reject at counter=%d', counter)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1043 1044 1045 1046
        return reject(new Error('timeout after 60 seconds'))
      }, 60 * 1000)
      timer.unref()

1047
      const done = () => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1048
        clearTimeout(timer)
1049
        return resolve()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1050
      }
1051

1052
      return stable(done)
1053 1054 1055
    })

  }
1056

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1057 1058 1059 1060 1061 1062
  /**
   * https://www.chatie.io:8080/api
   * location.hostname = www.chatie.io
   * location.host = www.chatie.io:8080
   * See: https://stackoverflow.com/a/11379802/1123955
   */
1063 1064 1065 1066 1067 1068 1069 1070
  public async hostname(): Promise<string> {
    try {
      const name = await this.bridge.hostname()
      if (!name) {
        throw new Error('no hostname found')
      }
      return name
    } catch (e) {
1071
      log.error('PuppetPuppeteer', 'hostname() exception:%s', e)
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
      this.emit('error', e)
      throw e
    }
  }

  public async cookies(): Promise<Cookie[]> {
    return await this.bridge.cookies()
  }

  public async saveCookie(): Promise<void> {
    const cookieList = await this.bridge.cookies()
    this.options.profile.set('cookies', cookieList)
    this.options.profile.save()
  }
1086

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1087
  public extToType(ext: string): WebMessageType {
1088
    switch (ext) {
1089 1090 1091 1092
      case '.bmp':
      case '.jpeg':
      case '.jpg':
      case '.png':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1093
        return WebMessageType.IMAGE
1094
      case '.gif':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1095
        return WebMessageType.EMOTICON
1096
      case '.mp4':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1097
        return WebMessageType.VIDEO
1098
      default:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1099
        return WebMessageType.APP
1100 1101 1102
    }
  }

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 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 1267 1268 1269 1270 1271 1272 1273 1274 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 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 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 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 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 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
  /**
   *
   *
   *
   *
   *
   *  THE FOLLOWING COMMENT OUTED CODE
   *
   *  IS: TO BE MERGE
   *
   *
   *
   *
   *
   *
   *
   */

  // public async readyMedia(): Promise<this> {
  //   log.silly('PuppetPuppeteer', 'readyMedia()')

  //   try {

  //     let url: string | undefined
  //     switch (this.type()) {
  //       case WebMsgType.EMOTICON:
  //         url = await puppet.bridge.getMsgEmoticon(this.id)
  //         break
  //       case WebMsgType.IMAGE:
  //         url = await puppet.bridge.getMsgImg(this.id)
  //         break
  //       case WebMsgType.VIDEO:
  //       case WebMsgType.MICROVIDEO:
  //         url = await puppet.bridge.getMsgVideo(this.id)
  //         break
  //       case WebMsgType.VOICE:
  //         url = await puppet.bridge.getMsgVoice(this.id)
  //         break

  //       case WebMsgType.APP:
  //         if (!this.rawObj) {
  //           throw new Error('no rawObj')
  //         }
  //         switch (this.typeApp()) {
  //           case WebAppMsgType.ATTACH:
  //             if (!this.rawObj.MMAppMsgDownloadUrl) {
  //               throw new Error('no MMAppMsgDownloadUrl')
  //             }
  //             // had set in Message
  //             // url = this.rawObj.MMAppMsgDownloadUrl
  //             break

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

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

  //       case WebMsgType.TEXT:
  //         if (this.typeSub() === WebMsgType.LOCATION) {
  //           url = await puppet.bridge.getMsgPublicLinkImg(this.id)
  //         }
  //         break

  //       default:
  //         /**
  //          * not a support media message, do nothing.
  //          */
  //         return this
  //     }

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

  //     this.payload.url = url

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

  //   return this
  // }

  // public async readyStream(): Promise<Readable> {
  //   log.verbose('PuppetPuppeteer', 'readyStream()')

  //   /**
  //    * 1. local file
  //    */
  //   try {
  //     const filename = this.filename()
  //     if (filename) {
  //       return fs.createReadStream(filename)
  //     }
  //   } catch (e) {
  //     // no filename
  //   }

  //   /**
  //    * 2. remote url
  //    */
  //   try {
  //     await this.ready()
  //     // FIXME: decoupling needed
  //     const cookies = await (this.puppet as any as PuppetPuppeteer).cookies()
  //     if (!this.payload.url) {
  //       throw new Error('no url')
  //     }
  //     log.verbose('PuppetPuppeteer', 'readyStream() url: %s', this.payload.url)
  //     return Misc.urlStream(this.payload.url, cookies)
  //   } catch (e) {
  //     log.warn('PuppetPuppeteer', 'readyStream() exception: %s', e.stack)
  //     Raven.captureException(e)
  //     throw e
  //   }
  // }

  // public filename(): string | null {
  //   log.verbose('PuppetPuppeteer', 'filename()')

  //   if (this.parsedPath) {
  //     // https://nodejs.org/api/path.html#path_path_parse_path
  //     const filename = path.join(
  //       this.parsedPath!.dir  || '',
  //       this.parsedPath!.base || '',
  //     )
  //     log.silly('PuppetPuppeteer', 'filename()=%s, build from parsedPath', filename)
  //     return filename
  //   }

  //   if (this.rawObj) {
  //     let filename = this.rawObj.FileName || this.rawObj.MediaId || this.rawObj.MsgId

  //     const re = /\.[a-z0-9]{1,7}$/i
  //     if (!re.test(filename)) {
  //       const ext = this.rawObj.MMAppMsgFileExt || this.ext()
  //       filename += '.' + ext
  //     }

  //     log.silly('PuppetPuppeteer', 'filename()=%s, build from rawObj', filename)
  //     return filename
  //   }

  //   return null

  // }

  // public ext(): string {
  //   const fileExt = this.extFromFile()
  //   if (fileExt) {
  //     return fileExt
  //   }

  //   const typeExt = this.extFromType()
  //   if (typeExt) {
  //     return typeExt
  //   }

  //   throw new Error('unknown ext()')
  // }

  // private extFromFile(): string | null {
  //   if (this.parsedPath && this.parsedPath.ext) {
  //     return this.parsedPath.ext
  //   }
  //   return null
  // }

  // private extFromType(): string {
  //   let ext: string

  //   const type = this.type()

  //   switch (type) {
  //     case WebMsgType.EMOTICON:
  //       ext = '.gif'
  //       break

  //     case WebMsgType.IMAGE:
  //       ext = '.jpg'
  //       break

  //     case WebMsgType.VIDEO:
  //     case WebMsgType.MICROVIDEO:
  //       ext = '.mp4'
  //       break

  //     case WebMsgType.VOICE:
  //       ext = '.mp3'
  //       break

  //     case WebMsgType.APP:
  //       switch (this.typeApp()) {
  //         case WebAppMsgType.URL:
  //           ext = '.url' // XXX
  //           break
  //         default:
  //           ext = '.' + this.type()
  //           break
  //       }
  //       break

  //     case WebMsgType.TEXT:
  //       if (this.typeSub() === WebMsgType.LOCATION) {
  //         ext = '.jpg'
  //       }
  //       ext = '.' + this.type()

  //       break

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

  //   return ext

  // }

  // /**
  //  * return the MIME Type of this MediaMessage
  //  *
  //  */
  // public mimeType(): string | null {
  //   // getType support both 'js' & '.js' as arg
  //   return mime.getType(this.ext())
  // }

  // private async uploadMedia(message: PuppeteerMessage, toUserName: string): Promise<WebMessageMediaPayload> {
  //   if (message.type() === PuppeteerMessage.Type.Text) {
  //     throw new Error('require a Media Message')
  //   }

  //   const filename = message.filename()
  //   const ext      = 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: ' + message.filename())
  //   }
  //   let mediatype: WebMediaType

  //   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
  //   }

  //   const readStream = await message.readyStream()
  //   const buffer = <Buffer>await new Promise((resolve, reject) => {
  //     readStream.pipe(bl((err: Error, data: Buffer) => {
  //       if (err) reject(err)
  //       else resolve(data)
  //     }))
  //   })

  //   // 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

  //   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`)
  //   }

  //   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
  //   const fromUserName    = this.userSelf()!.id
  //   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('; '),
  //   }

  //   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:        '',
  //   }

  //   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
  //   }

  //   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, res, 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 })
  // }

  // public async sendMedia(message: PuppeteerMessage): Promise<boolean> {
  //   const to   = message.to()
  //   const room = message.room()

  //   let destinationId

  //   if (room) {
  //     destinationId = room.id
  //   } else {
  //     if (!to) {
  //       throw new Error('PuppetPuppeteer.sendMedia(): message with neither room nor to?')
  //     }
  //     destinationId = to.id
  //   }

  //   let mediaData: WebMessageMediaPayload
  //   const rawObj = message.rawObj || {} as WebMessageRawPayload

  //   if (!rawObj || !rawObj.MediaId) {
  //     try {
  //       mediaData = await this.uploadMedia(message, destinationId)
  //       message.rawObj = Object.assign(rawObj, mediaData)
  //       log.silly('PuppetPuppeteer', 'Upload completed, new rawObj:%s', JSON.stringify(message.rawObj))
  //     } catch (e) {
  //       log.error('PuppetPuppeteer', 'sendMedia() exception: %s', e.message)
  //       return false
  //     }
  //   } else {
  //     // To support forward file
  //     log.silly('PuppetPuppeteer', 'skip upload file, rawObj:%s', JSON.stringify(rawObj))
  //     mediaData = {
  //       ToUserName : destinationId,
  //       MediaId    : rawObj.MediaId,
  //       MsgType    : rawObj.MsgType,
  //       FileName   : rawObj.FileName,
  //       FileSize   : rawObj.FileSize,
  //       MMFileExt  : rawObj.MMFileExt,
  //     }
  //     if (rawObj.Signature) {
  //       mediaData.Signature = rawObj.Signature
  //     }
  //   }
  //   // console.log('mediaData.MsgType', mediaData.MsgType)
  //   // console.log('rawObj.MsgType', message.rawObj && message.rawObj.MsgType)

  //   mediaData.MsgType = this.extToType(message.ext())
  //   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)
  //     return false
  //   }
  //   return ret
  // }

  // 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
  //   }
  // }

1645
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
1646

1647
export {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1648
  WebRoomRawPayload,
1649
}
1650
export default PuppetPuppeteer