message.ts 35.8 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
3
 *
4
 *   @copyright 2016-2017 Huan LI <zixia@zixia.net>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
5
 *
6 7 8 9 10 11 12 13 14 15 16
 *   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
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   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.
L
lijiarui 已提交
17
 *   @ignore
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
18
 */
19 20 21 22 23
import * as fs    from 'fs'
import * as path  from 'path'
import {
  Readable,
}                 from 'stream'
M
Mukaiu 已提交
24

25
import {
26
  config,
27
  Raven,
L
lijiarui 已提交
28 29 30
  RecommendInfo,
  Sayable,
  log,
31
}                 from './config'
32

Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
33 34 35 36 37
import Contact    from './contact'
import Room       from './room'
import UtilLib    from './util-lib'
import PuppetWeb  from './puppet-web/puppet-web'
import Bridge     from './puppet-web/bridge'
38

39
export interface MsgRawObj {
L
lijiarui 已提交
40
  MsgId:            string,
41

L
lijiarui 已提交
42 43 44
  MMActualSender:   string, // getUserContact(message.MMActualSender,message.MMPeerUserName).isContact()
  MMPeerUserName:   string, // message.MsgType == CONF.MSGTYPE_TEXT && message.MMPeerUserName == 'newsapp'
  ToUserName:       string,
45
  FromUserName:     string,
L
lijiarui 已提交
46
  MMActualContent:  string, // Content has @id prefix added by wx
47
  Content:          string,
48

L
lijiarui 已提交
49 50
  MMDigest:         string,
  MMDisplayTime:    number,  // Javascript timestamp of milliseconds
51 52 53 54 55

  /**
   * MsgType == MSGTYPE_APP && message.AppMsgType == CONF.APPMSGTYPE_URL
   * class="cover" mm-src="{{getMsgImg(message.MsgId,'slave')}}"
   */
L
lijiarui 已提交
56 57
  Url:              string,
  MMAppMsgDesc:     string,  // class="desc" ng-bind="message.MMAppMsgDesc"
58 59

  /**
60 61
   * Attachment
   *
62 63
   * MsgType == MSGTYPE_APP && message.AppMsgType == CONF.APPMSGTYPE_ATTACH
   */
L
lijiarui 已提交
64 65 66 67 68 69 70 71 72 73 74
  FileName:         string,  // FileName: '钢甲互联项目BP1108.pdf',
  FileSize:         number,  // FileSize: '2845701',
  MediaId:          string,  // MediaId: '@crypt_b1a45e3f_c21dceb3ac01349...

  MMAppMsgFileExt:      string,  // doc, docx ... 'undefined'?
  MMAppMsgFileSize:     string,  // '2.7MB',
  MMAppMsgDownloadUrl:  string,  // 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetmedia?sender=@4f549c2dafd5ad731afa4d857bf03c10&mediaid=@crypt_b1a45e3f
                                 // <a download ng-if="message.MMFileStatus == CONF.MM_SEND_FILE_STATUS_SUCCESS
                                 // && (massage.MMStatus == CONF.MSG_SEND_STATUS_SUCC || massage.MMStatus === undefined)
                                 // " href="{{message.MMAppMsgDownloadUrl}}">下载</a>
  MMUploadProgress: number,  // < 100
75 76 77 78 79 80 81 82 83 84

  /**
   * 模板消息
   * MSGTYPE_APP && message.AppMsgType == CONF.APPMSGTYPE_READER_TYPE
   *  item.url
   *  item.title
   *  item.pub_time
   *  item.cover
   *  item.digest
   */
L
lijiarui 已提交
85
  MMCategory:       any[],  //  item in message.MMCategory
86 87 88 89 90 91

  /**
   * Type
   *
   * MsgType == CONF.MSGTYPE_VOICE : ng-style="{'width':40 + 7*message.VoiceLength/1000}
   */
L
lijiarui 已提交
92 93 94
  MsgType:          number,
  AppMsgType:       AppMsgType,  // message.MsgType == CONF.MSGTYPE_APP && message.AppMsgType == CONF.APPMSGTYPE_URL
                                 // message.MsgType == CONF.MSGTYPE_TEXT && message.SubMsgType != CONF.MSGTYPE_LOCATION
95

L
lijiarui 已提交
96
  SubMsgType:       MsgType, // "msgType":"{{message.MsgType}}","subType":{{message.SubMsgType||0}},"msgId":"{{message.MsgId}}"
97 98 99 100

  /**
   * Status-es
   */
L
lijiarui 已提交
101 102 103 104 105
  Status:           string,
  MMStatus:         number,  // img ng-show="message.MMStatus == 1" class="ico_loading"
                             // ng-click="resendMsg(message)" ng-show="message.MMStatus == 5" title="重新发送"
  MMFileStatus:     number,  // <p class="loading" ng-show="message.MMStatus == 1 || message.MMFileStatus == CONF.MM_SEND_FILE_STATUS_FAIL">
                             // CONF.MM_SEND_FILE_STATUS_QUEUED, MM_SEND_FILE_STATUS_SENDING
106

107 108 109
  /**
   * Location
   */
L
lijiarui 已提交
110 111 112 113
  MMLocationUrl:    string,  // ng-if="message.MsgType == CONF.MSGTYPE_TEXT && message.SubMsgType == CONF.MSGTYPE_LOCATION"
                             // <a href="{{message.MMLocationUrl}}" target="_blank">
                             // 'http://apis.map.qq.com/uri/v1/geocoder?coord=40.075041,116.338994'
  MMLocationDesc:   string,  // MMLocationDesc: '北京市昌平区回龙观龙腾苑(五区)内(龙腾街南)',
114 115 116 117 118 119 120 121 122 123 124 125

  /**
   * MsgType == CONF.MSGTYPE_EMOTICON
   *
   * getMsgImg(message.MsgId,'big',message)
   */

  /**
   * Image
   *
   *  getMsgImg(message.MsgId,'slave')
   */
L
lijiarui 已提交
126 127 128
  MMImgStyle:       string,  // ng-style="message.MMImgStyle"
  MMPreviewSrc:     string,  // message.MMPreviewSrc || message.MMThumbSrc || getMsgImg(message.MsgId,'slave')
  MMThumbSrc:       string,
129 130 131 132 133 134 135

  /**
   * Friend Request & ShareCard ?
   *
   * MsgType == CONF.MSGTYPE_SHARECARD" ng-click="showProfile($event,message.RecommendInfo.UserName)
   * MsgType == CONF.MSGTYPE_VERIFYMSG
   */
L
lijiarui 已提交
136
  RecommendInfo?:   RecommendInfo,
137 138 139 140 141 142 143 144 145 146 147 148

  /**
   * Transpond Message
   */
  MsgIdBeforeTranspond?: string,  // oldMsg.MsgIdBeforeTranspond || oldMsg.MsgId,
  isTranspond?: boolean,
  MMSourceMsgId?: string,
  sendByLocal?: boolean, // If transpond file, it must is false, not need to upload. And, can't to call createMessage(), it set to true
  MMSendContent?: string,

  MMIsChatRoom?: boolean,

149 150
}

151
export interface MsgObj {
L
lijiarui 已提交
152 153 154 155 156 157 158 159 160 161 162
  id:       string,
  type:     MsgType,
  from:     string,
  to?:      string,  // if to is not set, then room must be set
  room?:    string,
  content:  string,
  status:   string,
  digest:   string,
  date:     string,

  url?:     string,  // for MessageMedia class
163 164
}

165 166
// export type MessageTypeName = 'TEXT' | 'IMAGE' | 'VOICE' | 'VERIFYMSG' | 'POSSIBLEFRIEND_MSG'
// | 'SHARECARD' | 'VIDEO' | 'EMOTICON' | 'LOCATION' | 'APP' | 'VOIPMSG' | 'STATUSNOTIFY'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167
// | 'VOIPNOTIFY' | 'VOIPINVITE' | 'MICROVIDEO' | 'SYSNOTICE' | 'SYS' | 'RECALLED'
168 169 170

// export type MessageTypeValue = 1 | 3 | 34 | 37 | 40 | 42 | 43 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 62 | 9999 | 10000 | 10002

171
export interface MsgTypeMap {
L
lijiarui 已提交
172
  [index: string]: string|number,
173 174 175 176
  //   MessageTypeName:  MessageTypeValue
  // , MessageTypeValue: MessageTypeName
}

L
lijiarui 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
/**
 *
 * Enum for AppMsgType values.
 *
 * @enum {number}
 * @property {number} TEXT                    - AppMsgType.TEXT                     (1)     for TEXT
 * @property {number} IMG                     - AppMsgType.IMG                      (2)      for IMG
 * @property {number} AUDIO                   - AppMsgType.AUDIO                    (3)      for AUDIO
 * @property {number} VIDEO                   - AppMsgType.VIDEO                    (4)      for VIDEO
 * @property {number} URL                     - AppMsgType.URL                      (5)      for URL
 * @property {number} ATTACH                  - AppMsgType.ATTACH                   (6)      for ATTACH
 * @property {number} OPEN                    - AppMsgType.OPEN                     (7)      for OPEN
 * @property {number} EMOJI                   - AppMsgType.EMOJI                    (8)      for EMOJI
 * @property {number} VOICE_REMIND            - AppMsgType.VOICE_REMIND             (9)      for VOICE_REMIND
 * @property {number} SCAN_GOOD               - AppMsgType.SCAN_GOOD                (10)     for SCAN_GOOD
 * @property {number} GOOD                    - AppMsgType.GOOD                     (13)     for GOOD
 * @property {number} EMOTION                 - AppMsgType.EMOTION                  (15)     for EMOTION
 * @property {number} CARD_TICKET             - AppMsgType.CARD_TICKET              (16)     for CARD_TICKET
 * @property {number} REALTIME_SHARE_LOCATION - AppMsgType.REALTIME_SHARE_LOCATION  (17)     for REALTIME_SHARE_LOCATION
 * @property {number} TRANSFERS               - AppMsgType.TRANSFERS                (2e3)    for TRANSFERS
 * @property {number} RED_ENVELOPES           - AppMsgType.RED_ENVELOPES            (2001)   for RED_ENVELOPES
 * @property {number} READER_TYPE             - AppMsgType.READER_TYPE              (100001) for READER_TYPE
 */
200
export enum AppMsgType {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  TEXT                     = 1,
  IMG                      = 2,
  AUDIO                    = 3,
  VIDEO                    = 4,
  URL                      = 5,
  ATTACH                   = 6,
  OPEN                     = 7,
  EMOJI                    = 8,
  VOICE_REMIND             = 9,
  SCAN_GOOD                = 10,
  GOOD                     = 13,
  EMOTION                  = 15,
  CARD_TICKET              = 16,
  REALTIME_SHARE_LOCATION  = 17,
  TRANSFERS                = 2e3,
  RED_ENVELOPES            = 2001,
  READER_TYPE              = 100001,
}

L
lijiarui 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
/**
 *
 * Enum for MsgType values.
 * @enum {number}
 * @property {number} TEXT                - MsgType.TEXT                (1)     for TEXT
 * @property {number} IMAGE               - MsgType.IMAGE               (3)     for IMAGE
 * @property {number} VOICE               - MsgType.VOICE               (34)    for VOICE
 * @property {number} VERIFYMSG           - MsgType.VERIFYMSG           (37)    for VERIFYMSG
 * @property {number} POSSIBLEFRIEND_MSG  - MsgType.POSSIBLEFRIEND_MSG  (40)    for POSSIBLEFRIEND_MSG
 * @property {number} SHARECARD           - MsgType.SHARECARD           (42)    for SHARECARD
 * @property {number} VIDEO               - MsgType.VIDEO               (43)    for VIDEO
 * @property {number} EMOTICON            - MsgType.EMOTICON            (47)    for EMOTICON
 * @property {number} LOCATION            - MsgType.LOCATION            (48)    for LOCATION
 * @property {number} APP                 - MsgType.APP                 (49)    for APP
 * @property {number} VOIPMSG             - MsgType.VOIPMSG             (50)    for VOIPMSG
 * @property {number} STATUSNOTIFY        - MsgType.STATUSNOTIFY        (51)    for STATUSNOTIFY
 * @property {number} VOIPNOTIFY          - MsgType.VOIPNOTIFY          (52)    for VOIPNOTIFY
 * @property {number} VOIPINVITE          - MsgType.VOIPINVITE          (53)    for VOIPINVITE
 * @property {number} MICROVIDEO          - MsgType.MICROVIDEO          (62)    for MICROVIDEO
 * @property {number} SYSNOTICE           - MsgType.SYSNOTICE           (9999)  for SYSNOTICE
 * @property {number} SYS                 - MsgType.SYS                 (10000) for SYS
 * @property {number} RECALLED            - MsgType.RECALLED            (10002) for RECALLED
 */
243
export enum MsgType {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  TEXT                = 1,
  IMAGE               = 3,
  VOICE               = 34,
  VERIFYMSG           = 37,
  POSSIBLEFRIEND_MSG  = 40,
  SHARECARD           = 42,
  VIDEO               = 43,
  EMOTICON            = 47,
  LOCATION            = 48,
  APP                 = 49,
  VOIPMSG             = 50,
  STATUSNOTIFY        = 51,
  VOIPNOTIFY          = 52,
  VOIPINVITE          = 53,
  MICROVIDEO          = 62,
  SYSNOTICE           = 9999,
  SYS                 = 10000,
261
  RECALLED            = 10002,
262 263
}

L
lijiarui 已提交
264 265 266 267 268 269
/**
 * All wechat messages will be encapsulated as a Message.
 *
 * `Message` is `Sayable`,
 * [Example/Ding-Dong-Bot]{@link https://github.com/Chatie/wechaty/blob/master/example/ding-dong-bot.ts}
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270
export class Message implements Sayable {
L
lijiarui 已提交
271 272 273
  /**
   * @private
   */
274
  public static counter = 0
L
lijiarui 已提交
275 276 277 278

  /**
   * @private
   */
279
  public _counter: number
280

281
  // DEPRECATED: TypeScript ENUM did this for us 201705
282 283 284 285 286
  /**
   * a map for:
   *   1. name to id
   *   2. id to name
   */
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  // public static TYPE: MsgTypeMap = {
  //   TEXT:               1,
  //   IMAGE:              3,
  //   VOICE:              34,
  //   VERIFYMSG:          37,
  //   POSSIBLEFRIEND_MSG: 40,
  //   SHARECARD:          42,
  //   VIDEO:              43,
  //   EMOTICON:           47,
  //   LOCATION:           48,
  //   APP:                49,
  //   VOIPMSG:            50,
  //   STATUSNOTIFY:       51,
  //   VOIPNOTIFY:         52,
  //   VOIPINVITE:         53,
  //   MICROVIDEO:         62,
  //   SYSNOTICE:          9999,
  //   SYS:                10000,
  //   RECALLED:           10002,
  // }
307

L
lijiarui 已提交
308 309 310
  /**
   * @private
   */
311 312
  public readonly id: string

L
lijiarui 已提交
313 314 315
  /**
   * @private
   */
316
  public obj = <MsgObj>{}
317

L
lijiarui 已提交
318 319 320
  /**
   * @private
   */
321 322
  public filename(): string {
    throw Error('not a media message')
323 324
  }

H
hcz 已提交
325 326 327
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
328
  constructor(public rawObj?: MsgRawObj) {
329
    this._counter = Message.counter++
330
    log.silly('Message', 'constructor() SN:%d', this._counter)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
331

332
    if (typeof rawObj === 'string') {
333
      this.rawObj = JSON.parse(rawObj)
334 335
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
336
    this.rawObj = rawObj = rawObj || <MsgRawObj>{}
337
    this.obj = this.parse(rawObj)
338
    this.id = this.obj.id
339
  }
340

L
lijiarui 已提交
341 342 343
  /**
   * @private
   */
344
  // Transform rawObj to local obj
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345 346
  private parse(rawObj): MsgObj {
    const obj: MsgObj = {
347
      id:           rawObj.MsgId,
348 349 350 351 352 353 354
      type:         rawObj.MsgType,
      from:         rawObj.MMActualSender, // MMPeerUserName
      to:           rawObj.ToUserName,
      content:      rawObj.MMActualContent, // Content has @id prefix added by wx
      status:       rawObj.Status,
      digest:       rawObj.MMDigest,
      date:         rawObj.MMDisplayTime,  // Javascript timestamp of milliseconds
L
lijiarui 已提交
355
      url:          rawObj.Url || rawObj.MMAppMsgDownloadUrl || rawObj.MMLocationUrl,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356
    }
357

358
    // FIXME: has there any better method to know the room ID?
359 360 361 362 363 364 365
    if (rawObj.MMIsChatRoom) {
      if (/^@@/.test(rawObj.FromUserName)) {
        obj.room =  rawObj.FromUserName // MMPeerUserName always eq FromUserName ?
      } else if (/^@@/.test(rawObj.ToUserName)) {
        obj.room = rawObj.ToUserName
      } else {
        log.error('Message', 'parse found a room message, but neither FromUserName nor ToUserName is a room(/^@@/)')
366
        // obj.room = undefined // bug compatible
367
      }
368 369 370
      if (obj.to && /^@@/.test(obj.to)) { // if a message in room without any specific receiver, then it will set to be `undefined`
        obj.to = undefined
      }
371
    }
372

373
    return obj
374
  }
L
lijiarui 已提交
375 376 377 378

  /**
   * @private
   */
379
  public toString() {
380
    return UtilLib.plainText(this.obj.content)
381
  }
L
lijiarui 已提交
382 383 384 385

  /**
   * @private
   */
386
  public toStringDigest() {
387
    const text = UtilLib.digestEmoji(this.obj.digest)
388
    return '{' + this.typeEx() + '}' + text
389 390
  }

L
lijiarui 已提交
391 392 393
  /**
   * @private
   */
394
  public toStringEx() {
395
    let s = `${this.constructor.name}#${this._counter}`
396 397 398
    s += '(' + this.getSenderString()
    s += ':' + this.getContentString() + ')'
    return s
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399
  }
L
lijiarui 已提交
400 401 402 403

  /**
   * @private
   */
404
  public getSenderString() {
405 406
    const fromName  = Contact.load(this.obj.from).name()
    const roomTopic = this.obj.room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
407
                  ? (':' + Room.load(this.obj.room).topic())
408
                  : ''
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
409
    return `<${fromName}${roomTopic}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
410
  }
L
lijiarui 已提交
411 412 413 414

  /**
   * @private
   */
415
  public getContentString() {
416
    let content = UtilLib.plainText(this.obj.content)
417
    if (content.length > 20) { content = content.substring(0, 17) + '...' }
418 419
    return '{' + this.type() + '}' + content
  }
420

L
lijiarui 已提交
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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
  public say(text: string, replyTo?: Contact | Contact[]): Promise<any>

  public say(mediaMessage: MediaMessage, replyTo?: Contact | Contact[]): Promise<any>

  /**
   * Reply a Text or Media File message to the sender.
   *
   * @see {@link https://github.com/Chatie/wechaty/blob/master/example/ding-dong-bot.ts|Example/ding-dong-bot}
   * @param {(string | MediaMessage)} textOrMedia
   * @param {(Contact|Contact[])} [replyTo]
   * @returns {Promise<any>}
   *
   * @example
   * const bot = Wechaty.instance()
   * bot
   * .on('message', async m => {
   *   if (/^ding$/i.test(m.content())) {
   *     await m.say('hello world')
   *     console.log('Bot REPLY: hello world')
   *     await m.say(new MediaMessage(__dirname + '/wechaty.png'))
   *     console.log('Bot REPLY: Image')
   *   }
   * })
   */
  public say(textOrMedia: string | MediaMessage, replyTo?: Contact|Contact[]): Promise<any> {
    /* tslint:disable:no-use-before-declare */
    const content = textOrMedia instanceof MediaMessage ? textOrMedia.filename() : textOrMedia
    log.verbose('Message', 'say(%s, %s)', content, replyTo)
    let m
    if (typeof textOrMedia === 'string') {
      m = new Message()
      const room = this.room()
      if (room) {
        m.room(room)
      }

      if (!replyTo) {
        m.to(this.from())
        m.content(textOrMedia)

      } else if (this.room()) {
        let mentionList
        if (Array.isArray(replyTo)) {
          m.to(replyTo[0])
          mentionList = replyTo.map(c => '@' + c.name()).join(' ')
        } else {
          m.to(replyTo)
          mentionList = '@' + replyTo.name()
        }
        m.content(mentionList + ' ' + textOrMedia)
      }
    /* tslint:disable:no-use-before-declare */
    } else if (textOrMedia instanceof MediaMessage) {
      m = textOrMedia
      const room = this.room()
      if (room) {
        m.room(room)
      }

      if (!replyTo) {
        m.to(this.from())
      }
    }

    return config.puppetInstance()
                  .send(m)
  }

H
hcz 已提交
489
  /**
L
lijiarui 已提交
490
   * @private
H
hcz 已提交
491
   */
492
  public from(contact: Contact): void
L
lijiarui 已提交
493 494 495 496

  /**
   * @private
   */
497
  public from(id: string): void
L
lijiarui 已提交
498

499
  public from(): Contact
L
lijiarui 已提交
500 501 502 503 504

  /**
   * Get the sender from a message.
   * @returns {Contact}
   */
505
  public from(contact?: Contact|string): Contact|void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506
    if (contact) {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
507 508
      if (contact instanceof Contact) {
        this.obj.from = contact.id
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
509
      } else if (typeof contact === 'string') {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
510 511 512 513
        this.obj.from = contact
      } else {
        throw new Error('unsupport from param: ' + typeof contact)
      }
514
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
515
    }
516 517 518 519 520 521

    const loadedContact = Contact.load(this.obj.from)
    if (!loadedContact) {
      throw new Error('no from')
    }
    return loadedContact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
522 523
  }

H
hcz 已提交
524
  /**
L
lijiarui 已提交
525
   * @private
H
hcz 已提交
526
   */
527
  public room(room: Room): void
L
lijiarui 已提交
528 529 530 531

  /**
   * @private
   */
532
  public room(id: string): void
L
lijiarui 已提交
533

534
  public room(): Room|null
L
lijiarui 已提交
535 536 537 538 539 540 541

  /**
   * Get the room from the message.
   * If the message is not in a room, then will return `null`
   *
   * @returns {(Room|null)}
   */
542
  public room(room?: Room|string): Room|null|void {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
543 544 545 546 547 548 549 550
    if (room) {
      if (room instanceof Room) {
        this.obj.room = room.id
      } else if (typeof room === 'string') {
        this.obj.room = room
      } else {
        throw new Error('unsupport room param ' + typeof room)
      }
551
      return
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
552
    }
553 554
    if (this.obj.room) {
      return Room.load(this.obj.room)
555
    }
556
    return null
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
557 558
  }

H
hcz 已提交
559
  /**
L
lijiarui 已提交
560 561 562
   * Get the content of the message
   *
   * @returns {string}
H
hcz 已提交
563
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
564
  public content(): string
L
lijiarui 已提交
565 566 567 568

  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
569 570
  public content(content: string): void

L
lijiarui 已提交
571 572 573 574 575
  /**
   * Get the content of the message
   *
   * @returns {string}
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
576
  public content(content?: string): string|void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
577 578
    if (content) {
      this.obj.content = content
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
579
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
580 581 582 583
    }
    return this.obj.content
  }

H
hcz 已提交
584
  /**
L
lijiarui 已提交
585 586
   * Get the type from the message.
   *
587
   * If type is equal to `MsgType.RECALLED`, {@link Message#id} is the msgId of the recalled message.
L
lijiarui 已提交
588 589
   * @see {@link MsgType}
   * @returns {MsgType}
H
hcz 已提交
590
   */
591
  public type(): MsgType {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
592
    return this.obj.type
593 594
  }

H
hcz 已提交
595
  /**
L
lijiarui 已提交
596 597 598 599 600 601
   * Get the typeSub from the message.
   *
   * If message is a location message: `m.type() === MsgType.TEXT && m.typeSub() === MsgType.LOCATION`
   *
   * @see {@link MsgType}
   * @returns {MsgType}
H
hcz 已提交
602
   */
603 604 605 606 607 608 609
  public typeSub(): MsgType {
    if (!this.rawObj) {
      throw new Error('no rawObj')
    }
    return this.rawObj.SubMsgType
  }

H
hcz 已提交
610
  /**
L
lijiarui 已提交
611 612 613 614
   * Get the typeApp from the message.
   *
   * @returns {AppMsgType}
   * @see {@link AppMsgType}
H
hcz 已提交
615
   */
616 617 618 619 620
  public typeApp(): AppMsgType {
    if (!this.rawObj) {
      throw new Error('no rawObj')
    }
    return this.rawObj.AppMsgType
621 622
  }

H
hcz 已提交
623
  /**
L
lijiarui 已提交
624 625 626
   * Get the typeEx from the message.
   *
   * @returns {MsgType}
H
hcz 已提交
627
   */
628
  public typeEx()  { return MsgType[this.obj.type] }
L
lijiarui 已提交
629

H
hcz 已提交
630
  /**
L
lijiarui 已提交
631
   * @private
H
hcz 已提交
632
   */
633
  public count()   { return this._counter }
634

H
hcz 已提交
635
  /**
L
lijiarui 已提交
636 637 638 639 640 641 642
   * Check if a message is sent by self.
   *
   * @returns {boolean} - Return `true` for send from self, `false` for send from others.
   * @example
   * if (message.self()) {
   *  console.log('this message is sent by myself!')
   * }
H
hcz 已提交
643
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
644
  public self(): boolean {
645
    const userId = config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
646 647
                        .userId

648
    const fromId = this.obj.from
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
649 650 651 652 653 654 655
    if (!userId || !fromId) {
      throw new Error('no user or no from')
    }

    return fromId === userId
  }

L
lijiarui 已提交
656 657 658
  /**
   *
   * Get message mentioned contactList.
L
lijiarui 已提交
659 660
   *
   * Message event table as follows
L
lijiarui 已提交
661 662 663 664 665 666 667 668
   *
   * |                                                                            | Web  |  Mac PC Client | iOS Mobile |  android Mobile |
   * | :---                                                                       | :--: |     :----:     |   :---:    |     :---:       |
   * | [You were mentioned] tip ([有人@我]的提示)                                   |  ✘   |        √       |     √      |       √         |
   * | Identify magic code (8197) by copy & paste in mobile                       |  ✘   |        √       |     √      |       ✘         |
   * | Identify magic code (8197) by programming                                  |  ✘   |        ✘       |     ✘      |       ✘         |
   * | Identify two contacts with the same roomAlias by [You were  mentioned] tip |  ✘   |        ✘       |     √      |       √         |
   *
L
lijiarui 已提交
669
   * @returns {Contact[]} - Return message mentioned contactList
L
lijiarui 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
   *
   * @example
   * const contactList = message.mentioned()
   * console.log(contactList)
   */
  public mentioned(): Contact[] {
    let contactList: Contact[] = []
    const room = this.room()
    if (this.type() !== MsgType.TEXT || !room ) {
      return contactList
    }

    // define magic code `8197` to identify @xxx
    const AT_SEPRATOR = String.fromCharCode(8197)

    const atList = this.content().split(AT_SEPRATOR)

    if (atList.length === 0) return contactList

    // Using `filter(e => e.indexOf('@') > -1)` to filter the string without `@`
    const rawMentionedList = atList
      .filter(str => str.includes('@'))
      .map(str => multipleAt(str))
      .filter(str => !!str) // filter blank string

    // convert 'hello@a@b@c' to [ 'c', 'b@c', 'a@b@c' ]
    function multipleAt(str: string) {
      str = str.replace(/^.*?@/, '@')
698 699 700 701 702 703 704 705 706 707
      let name = ''
      const nameList: string[] = []
      str.split('@')
        .filter(mentionName => !!mentionName)
        .reverse()
        .forEach(mentionName => {
          name = mentionName + '@' + name
          nameList.push(name.slice(0, -1)) // get rid of the `@` at beginning
        })
      return nameList
L
lijiarui 已提交
708 709 710 711 712 713 714
    }

    // flatten array, see http://stackoverflow.com/a/10865042/1123955
    const mentionList = [].concat.apply([], rawMentionedList)
    log.verbose('Message', 'mentioned(%s),get mentionList: %s', this.content(), JSON.stringify(mentionList))

    contactList = [].concat.apply([],
Y
Yu Zhan 已提交
715
      mentionList.map(nameStr => room.memberAll(nameStr))
L
lijiarui 已提交
716 717 718 719 720 721 722 723 724
      .filter(contact => !!contact),
    )

    if (contactList.length === 0) {
      log.warn(`Message`, `message.mentioned() can not found member using room.member() from mentionList, metion string: ${JSON.stringify(mentionList)}`)
    }
    return contactList
  }

L
lijiarui 已提交
725 726 727
  /**
   * @private
   */
728
  public async ready(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
729
    log.silly('Message', 'ready()')
730

731
    try {
732
      const from  = Contact.load(this.obj.from)
733
      await from.ready()  // Contact from
734

735 736 737
      if (this.obj.to) {
        const to = Contact.load(this.obj.to)
        await to.ready()
738
      }
739

740 741
      if (this.obj.room) {
        const room  = Room.load(this.obj.room)
742
        await room.ready()  // Room member list
743
      }
744

745
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
746
        log.error('Message', 'ready() exception: %s', e.stack)
747
        Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
748 749 750
        // console.log(e)
        // this.dump()
        // this.dumpRaw()
751
        throw e
752
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
753 754
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
755
  /**
L
lijiarui 已提交
756
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
757
   */
758
  public get(prop: string): string {
759
    log.warn('Message', 'DEPRECATED get() at %s', new Error('stack').stack)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
760

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
761 762
    if (!prop || !(prop in this.obj)) {
      const s = '[' + Object.keys(this.obj).join(',') + ']'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
763 764
      throw new Error(`Message.get(${prop}) must be in: ${s}`)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
765
    return this.obj[prop]
766 767
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
768
  /**
L
lijiarui 已提交
769
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
770
   */
771
  public set(prop: string, value: string): this {
772
    log.warn('Message', 'DEPRECATED set() at %s', new Error('stack').stack)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
773

774 775 776
    if (typeof value !== 'string') {
      throw new Error('value must be string, we got: ' + typeof value)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
777
    this.obj[prop] = value
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
778
    return this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
779
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
780

L
lijiarui 已提交
781 782 783
  /**
   * @private
   */
784
  public dump() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
785 786
    console.error('======= dump message =======')
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
787
  }
L
lijiarui 已提交
788 789 790 791

  /**
   * @private
   */
792
  public dumpRaw() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
793
    console.error('======= dump raw message =======')
794 795 796
    if (!this.rawObj) {
      throw new Error('no this.obj')
    }
797
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj && this.rawObj[k]}`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
798 799
  }

L
lijiarui 已提交
800 801 802
  /**
   * @todo add function
   */
803
  public static async find(query) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
804
    return Promise.resolve(new Message(<MsgRawObj>{MsgId: '-1'}))
805 806
  }

L
lijiarui 已提交
807 808 809
  /**
   * @todo add function
   */
810 811
  public static async findAll(query) {
    return Promise.resolve([
L
lijiarui 已提交
812 813
      new Message   (<MsgRawObj>{MsgId: '-2'}),
      new Message (<MsgRawObj>{MsgId: '-3'}),
814
    ])
815 816
  }

L
lijiarui 已提交
817 818 819
  // public to(room: Room): void
  // public to(): Contact|Room
  // public to(contact?: Contact|Room|string): Contact|Room|void {
L
lijiarui 已提交
820

L
lijiarui 已提交
821 822 823 824
  /**
   * @private
   */
  public to(contact: Contact): void
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
825

L
lijiarui 已提交
826
  /**
L
lijiarui 已提交
827
   * @private
L
lijiarui 已提交
828
   */
L
lijiarui 已提交
829
  public to(id: string): void
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
830

L
lijiarui 已提交
831
  public to(): Contact|null // if to is not set, then room must had set
M
Mukaiu 已提交
832

L
lijiarui 已提交
833 834 835 836 837 838 839 840 841 842 843 844 845
  /**
   * Get the destination of the message
   * Message.to() will return null if a message is in a room, use Message.room() to get the room.
   * @returns {(Contact|null)}
   */
  public to(contact?: Contact|string): Contact|Room|null|void {
    if (contact) {
      if (contact instanceof Contact) {
        this.obj.to = contact.id
      } else if (typeof contact === 'string') {
        this.obj.to = contact
      } else {
        throw new Error('unsupport to param ' + typeof contact)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
846
      }
L
lijiarui 已提交
847 848
      return
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
849

L
lijiarui 已提交
850 851 852 853
    // no parameter

    if (!this.obj.to) {
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
854
    }
L
lijiarui 已提交
855 856
    return Contact.load(this.obj.to)
  }
M
Mukaiu 已提交
857

L
lijiarui 已提交
858 859 860 861 862 863 864 865 866 867
  /**
   * Please notice that when we are running Wechaty,
   * if you use the browser that controlled by Wechaty to send attachment files,
   * you will get a zero sized file, because it is not an attachment from the network,
   * but a local data, which is not supported by Wechaty yet.
   *
   * @returns {Promise<Readable>}
   */
  public readyStream(): Promise<Readable> {
    throw Error('abstract method')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
868 869
  }

L
lijiarui 已提交
870 871 872 873 874 875 876 877
  // DEPRECATED: TypeScript ENUM did this for us 201705
  // public static initType() {
  //   Object.keys(Message.TYPE).forEach(k => {
  //     const v = Message.TYPE[k]
  //     Message.TYPE[v] = k // Message.Type[1] = 'TEXT'
  //   })
  // }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
878
}
879

880
// Message.initType()
881

L
lijiarui 已提交
882 883 884 885
/**
 * Meidia Type Message
 *
 */
M
Mukaiu 已提交
886
export class MediaMessage extends Message {
L
lijiarui 已提交
887 888 889
  /**
   * @private
   */
M
Mukaiu 已提交
890
  private bridge: Bridge
L
lijiarui 已提交
891 892 893 894

  /**
   * @private
   */
M
Mukaiu 已提交
895
  private filePath: string
L
lijiarui 已提交
896 897 898 899

  /**
   * @private
   */
M
Mukaiu 已提交
900
  private fileName: string // 'music'
L
lijiarui 已提交
901 902 903 904

  /**
   * @private
   */
M
Mukaiu 已提交
905 906
  private fileExt: string // 'mp3'

L
lijiarui 已提交
907 908 909
  /**
   * @private
   */
910
  constructor(rawObj: Object)
L
lijiarui 已提交
911 912 913 914

  /**
   * @private
   */
M
Mukaiu 已提交
915 916
  constructor(filePath: string)

917
  constructor(rawObjOrFilePath: Object | string) {
M
Mukaiu 已提交
918 919
    if (typeof rawObjOrFilePath === 'string') {
      super()
M
Mukaiu 已提交
920
      this.filePath = rawObjOrFilePath
M
Mukaiu 已提交
921 922 923 924 925 926 927 928 929 930 931

      const pathInfo = path.parse(rawObjOrFilePath)
      this.fileName = pathInfo.name
      this.fileExt = pathInfo.ext.replace(/^\./, '')
    } else if (rawObjOrFilePath instanceof Object) {
      super(rawObjOrFilePath as any)
    } else {
      throw new Error('not supported construct param')
    }

    // FIXME: decoupling needed
932
    this.bridge = (config.puppetInstance() as PuppetWeb)
933
                    .bridge
M
Mukaiu 已提交
934 935
  }

L
lijiarui 已提交
936 937 938
  /**
   * @private
   */
M
Mukaiu 已提交
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 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
  public async ready(): Promise<void> {
    log.silly('MediaMessage', 'ready()')

    try {
      await super.ready()

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

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

            case AppMsgType.URL:
            case AppMsgType.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('MediaMessage', e.message)
              this.dumpRaw()
              throw e
          }
          break

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

        default:
          throw new Error('not support message type for MediaMessage')
      }

      if (!url) {
        if (!this.obj.url) {
          throw new Error('no obj.url')
        }
        url = this.obj.url
      }

      this.obj.url = url

    } catch (e) {
      log.warn('MediaMessage', 'ready() exception: %s', e.message)
1012
      Raven.captureException(e)
M
Mukaiu 已提交
1013 1014 1015 1016
      throw e
    }
  }

H
hcz 已提交
1017
  /**
L
lijiarui 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026
   * Get the MediaMessage file extension, etc: `jpg`, `gif`, `pdf`, `word` ..
   *
   * @returns {string}
   * @example
   * bot.on('message', async function (m) {
   *   if (m instanceof MediaMessage) {
   *     console.log('media message file name extention is: ' + m.ext())
   *   }
   * })
H
hcz 已提交
1027
   */
M
Mukaiu 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  public ext(): string {
    if (this.fileExt)
      return this.fileExt

    switch (this.type()) {
      case MsgType.EMOTICON:
        return 'gif'

      case MsgType.IMAGE:
        return 'jpg'

      case MsgType.VIDEO:
      case MsgType.MICROVIDEO:
        return 'mp4'

      case MsgType.VOICE:
        return 'mp3'

      case MsgType.APP:
        switch (this.typeApp()) {
          case AppMsgType.URL:
            return 'url' // XXX
        }
        break

      case MsgType.TEXT:
        if (this.typeSub() === MsgType.LOCATION) {
          return 'jpg'
        }
        break
    }
    throw new Error('not support type: ' + this.type())
  }

H
hcz 已提交
1062
  /**
L
lijiarui 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071
   * Get the MediaMessage filename, etc: `how to build a chatbot.pdf`..
   *
   * @returns {string}
   * @example
   * bot.on('message', async function (m) {
   *   if (m instanceof MediaMessage) {
   *     console.log('media message file name is: ' + m.filename())
   *   }
   * })
H
hcz 已提交
1072
   */
M
Mukaiu 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081
  public filename(): string {
    if (this.fileName && this.fileExt) {
      return this.fileName + '.' + this.fileExt
    }

    if (!this.rawObj) {
      throw new Error('no rawObj')
    }

1082
    let filename = this.rawObj.FileName || this.rawObj.MediaId || this.rawObj.MsgId
M
Mukaiu 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099

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

  // private getMsgImg(id: string): Promise<string> {
  //   return this.bridge.getMsgImg(id)
  //   .catch(e => {
  //     log.warn('MediaMessage', 'getMsgImg(%d) exception: %s', id, e.message)
  //     throw e
  //   })
  // }

L
lijiarui 已提交
1100
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1101
   * Get the read stream for attachment file
L
lijiarui 已提交
1102
   */
1103
  public async readyStream(): Promise<Readable> {
M
Mukaiu 已提交
1104 1105
    if (this.filePath)
      return fs.createReadStream(this.filePath)
M
Mukaiu 已提交
1106 1107 1108 1109

    try {
      await this.ready()
      // FIXME: decoupling needed
1110
      const cookies = await (config.puppetInstance() as PuppetWeb).browser.readCookie()
M
Mukaiu 已提交
1111 1112 1113
      if (!this.obj.url) {
        throw new Error('no url')
      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1114
      log.verbose('MediaMessage', 'stream() url: %s', this.obj.url)
M
Mukaiu 已提交
1115 1116 1117
      return UtilLib.urlStream(this.obj.url, cookies)
    } catch (e) {
      log.warn('MediaMessage', 'stream() exception: %s', e.stack)
1118
      Raven.captureException(e)
M
Mukaiu 已提交
1119 1120 1121
      throw e
    }
  }
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

  public forward(room: Room): Promise<boolean>
  public forward(contact: Contact): Promise<boolean>
  /**
   * Forward the received message.
   *
   * The types of messages that can be forwarded are as follows:
   *
   * The return value of {@link Message#type} matches one of the following types:
   * ```json
   * MsgType {
   *   TEXT                = 1,
   *   IMAGE               = 3,
   *   VIDEO               = 43,
   *   EMOTICON            = 47,
   *   LOCATION            = 48,
   *   APP                 = 49,
   *   MICROVIDEO          = 62,
   * }
   * ```
   *
   * When the return value of {@link Message#type} is `MsgType.APP`, the return value of {@link Message#typeApp} matches one of the following types:
   * ```json
   * AppMsgType {
   *   TEXT                     = 1,
   *   IMG                      = 2,
   *   VIDEO                    = 4,
   *   ATTACH                   = 6,
   *   EMOJI                    = 8,
   * }
   * ```
   * But, it should be noted that when forwarding ATTACH type message, if the file size is greater than 25Mb, the forwarding will fail.
   * The reason is that the server limits the forwarding of files above 25Mb. You need to download the file and use `new MediaMessage (file)` to send the file.
   *
   * @param {(Room | Contact)} sendTo
   * The recipient of the message, the room, or the contact
   * @returns {Promise<boolean>}
   * @memberof MediaMessage
   */
  public forward(sendTo: Room|Contact): Promise<boolean> {
    if (!this.rawObj) {
      throw new Error('no rawObj!')
    }
    let m = Object.assign({}, this.rawObj)
    const newMsg = <MsgRawObj>{}
    const fileSizeLimit = 25 * 1024 * 1024
    let id = ''
    // if you know roomId or userId, you can use `Room.load(roomId)` or `Contact.load(userId)`
    if (sendTo instanceof Room || sendTo instanceof Contact) {
      id = sendTo.id
    } else {
      throw new Error('param must be Room or Contact!')
    }

    newMsg.ToUserName = id
    newMsg.FromUserName = config.puppetInstance().userId || ''
    newMsg.isTranspond = true
    newMsg.MsgIdBeforeTranspond = m.MsgIdBeforeTranspond || m.MsgId
    newMsg.MMSourceMsgId = m.MsgId
    // 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
    newMsg.Content = UtilLib.unescapeHtml(m.Content.replace(/^@\w+:<br\/>/, '')).replace(/^[\w\-]+:<br\/>/, '')
    newMsg.MMIsChatRoom = sendTo instanceof Room ? true : false

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

    // If you want to forward the file, would like to skip the duplicate upload, sendByLocal must be false.
    // But need to pay attention to file.size> 25Mb, due to the server policy restrictions, need to re-upload
    if (m.FileSize >= fileSizeLimit) {
      log.warn('Message', 'forward() file size >= 25Mb,the message may fail to be forwarded due to server policy restrictions.')
    }
    newMsg.sendByLocal = false
    newMsg.MMActualSender = config.puppetInstance().userId || ''
    if (m.MMSendContent) {
      newMsg.MMSendContent = m.MMSendContent.replace(/^@\w+:\s/, '')
    }
    if (m.MMDigest) {
      newMsg.MMDigest = m.MMDigest.replace(/^@\w+:/, '')
    }
    if (m.MMActualContent) {
      newMsg.MMActualContent = UtilLib.stripHtml(m.MMActualContent.replace(/^@\w+:<br\/>/, '')).replace(/^[\w\-]+:<br\/>/, '')
    }
    m = Object.assign(m, newMsg)

    return config.puppetInstance()
      .forward(m, newMsg)
  }
M
Mukaiu 已提交
1208
}
1209

Huan (李卓桓)'s avatar
doc  
Huan (李卓桓) 已提交
1210
/*
1211 1212 1213 1214 1215
 * join room in mac client: https://support.weixin.qq.com/cgi-bin/
 * mmsupport-bin/addchatroombyinvite
 * ?ticket=AUbv%2B4GQA1Oo65ozlIqRNw%3D%3D&exportkey=AS9GWEg4L82fl3Y8e2OeDbA%3D
 * &lang=en&pass_ticket=T6dAZXE27Y6R29%2FFppQPqaBlNwZzw9DAN5RJzzzqeBA%3D
 * &wechat_real_lang=en
Huan (李卓桓)'s avatar
doc  
Huan (李卓桓) 已提交
1216
 */
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
1217 1218

export default Message