message.ts 19.7 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 *   Wechaty - https://github.com/chatie/wechaty
 *
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
 *
 *   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.
 *   @ignore
 */
19 20
// import path from 'path'
// import cuid from 'cuid'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
22
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
23
  FileBox,
24 25 26 27
}                     from 'file-box'
import {
  instanceToClass,
}                     from 'clone-class'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
28

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
29
import {
30
  log,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
31
  Sayable,
32 33 34 35
}                 from './config'
import {
  Accessory,
}                 from './accessory'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36

37 38 39 40 41 42
import {
  Contact,
}                 from './contact'
import {
  Room,
}                 from './room'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
43

44 45 46 47
import {
  MessagePayload,
  MessageType,
}                 from './puppet/'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
48 49 50 51 52 53
/**
 * All wechat messages will be encapsulated as a Message.
 *
 * `Message` is `Sayable`,
 * [Examples/Ding-Dong-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/ding-dong-bot.ts}
 */
54
export class Message extends Accessory implements Sayable {
55 56 57 58 59 60 61

  /**
   *
   * Static Properties
   *
   */

62
  // tslint:disable-next-line:variable-name
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63
  public static readonly Type = MessageType
64

65 66 67 68 69
  /**
   * @todo add function
   */
  public static async find<T extends typeof Message>(
    this: T,
70
    query: any,
71
  ): Promise<T['prototype'] | null> {
72
    return (await this.findAll(query))[0]
73 74 75 76 77 78 79
  }

  /**
   * @todo add function
   */
  public static async findAll<T extends typeof Message>(
    this: T,
80
    query: any,
81
  ): Promise<T['prototype'][]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
82
    log.verbose('Message', 'findAll(%s)', query)
83
    return [
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84 85
      new (this as any)({ MsgId: 'id1' }),
      new (this as any)({ MsdId: 'id2' }),
86
    ]
87 88
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
 /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90 91
  * Create a Mobile Terminated Message
  *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92 93 94
  * "mobile originated" or "mobile terminated"
  * https://www.tatango.com/resources/video-lessons/video-mo-mt-sms-messaging/
  */
95
  // TODO: rename create to load ??? Huan 201806
96 97 98
  public static create(id: string): Message {
    log.verbose('Message', 'static create(%s)', id)

99 100 101 102 103 104 105
    /**
     * Must NOT use `Message` at here
     * MUST use `this` at here
     *
     * because the class will be `cloneClass`-ed
     */
    const msg = new this(id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106

107
    // msg.payload = this.puppet.cacheMessagePayload.get(id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108

109
    return msg
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110 111
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112 113 114 115 116
  /**
   *
   * Instance Properties
   *
   */
117
  private get payload(): undefined | MessagePayload {
118 119 120 121
    if (!this.id) {
      return undefined
    }

122 123
    return this.puppet.messagePayloadCache(this.id)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125 126 127
  /**
   * @private
   */
128 129
  constructor(
    public readonly id: string,
130 131
  ) {
    super()
132
    log.verbose('Message', 'constructor(%s) for class %s',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
133
                          id || '',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
134 135
                          this.constructor.name,
              )
136

137 138 139 140 141 142 143 144 145 146
    // tslint:disable-next-line:variable-name
    const MyClass = instanceToClass(this, Message)

    if (MyClass === Message) {
      throw new Error('Message class can not be instanciated directly! See: https://github.com/Chatie/wechaty/issues/1217')
    }

    if (!this.puppet) {
      throw new Error('Message class can not be instanciated without a puppet!')
    }
147
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148 149 150 151 152

  /**
   * @private
   */
  public toString() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153 154 155 156
    if (!this.isReady()) {
      return this.constructor.name
    }

157 158 159
    const msgStrList = [
      'Message',
      `#${MessageType[this.type()]}`,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160
      '(',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161
        this.room() ? (this.room() + '') : '',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
162
        this.from() || '',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
163
        '',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
164
        this.to() || '',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
165
      ')',
166
    ]
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167 168 169
    if (   this.type() === Message.Type.Text
        || this.type() === Message.Type.Unknown
    ) {
170
      msgStrList.push(`<${this.text().substr(0, 70)}>`)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
171
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
172
      log.silly('Message', 'toString() for message type: %s(%s)', Message.Type[this.type()], this.type())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
173

174 175 176
      if (!this.payload) {
        throw new Error('no payload')
      }
177
      const filename = this.payload.filename
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178 179 180 181 182 183 184 185
      // if (!filename) {
      //   throw new Error(
      //     'no file for message id: ' + this.id
      //     + ' with type: ' + Message.Type[this.payload.type]
      //     + '(' + this.payload.type + ')',
      //   )
      // }
      msgStrList.push(`<${filename || 'unknown file name'}>`)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
186
    }
187 188

    return msgStrList.join('')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189
  }
190 191 192 193
  /**
   * Get the sender from a message.
   * @returns {Contact}
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
194
  public from(): null | Contact {
195 196 197
    if (!this.payload) {
      throw new Error('no payload')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
198

199 200 201 202
    // if (contact) {
    //   this.payload.from = contact
    //   return
    // }
203

204 205
    const fromId = this.payload.fromId
    if (!fromId) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
      return null
207
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
208

209
    const from = this.wechaty.Contact.load(fromId)
210
    return from
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
211 212
  }

213 214 215 216 217
  /**
   * 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)}
   */
218 219 220 221 222
  public to(): null | Contact {
    if (!this.payload) {
      throw new Error('no payload')
    }

223 224 225 226 227
    const toId = this.payload.toId
    if (!toId) {
      return null
    }

228
    const to = this.wechaty.Contact.load(toId)
229
    return to
230 231
  }

232 233 234 235 236 237
  /**
   * Get the room from the message.
   * If the message is not in a room, then will return `null`
   *
   * @returns {(Room | null)}
   */
238 239 240 241
  public room(): null | Room {
    if (!this.payload) {
      throw new Error('no payload')
    }
242 243 244 245
    const roomId = this.payload.roomId
    if (!roomId) {
      return null
    }
246

247
    const room = this.wechaty.Room.load(roomId)
248
    return room
249 250
  }

251 252 253 254 255
  /**
   * Get the text content of the message
   *
   * @returns {string}
   */
256 257 258 259 260
  public text(): string {
    if (!this.payload) {
      throw new Error('no payload')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
261
    return this.payload.text || ''
262 263 264 265
  }

  public async say(text: string, mention?: Contact | Contact[]): Promise<void>
  public async say(file: FileBox): Promise<void>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
266

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
267 268 269 270
  /**
   * Reply a Text or Media File message to the sender.
   *
   * @see {@link https://github.com/Chatie/wechaty/blob/master/examples/ding-dong-bot.ts|Examples/ding-dong-bot}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
271
   * @param {(string | FileBox)} textOrContactOrFile
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
272
   * @param {(Contact|Contact[])} [mention]
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
273 274 275 276 277 278
   * @returns {Promise<void>}
   *
   * @example
   * const bot = new Wechaty()
   * bot
   * .on('message', async m => {
279
   *   if (/^ding$/i.test(m.text())) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
280 281
   *     await m.say('hello world')
   *     console.log('Bot REPLY: hello world')
282
   *     await m.say(new bot.Message(__dirname + '/wechaty.png'))
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
283 284 285 286
   *     console.log('Bot REPLY: Image')
   *   }
   * })
   */
287
  public async say(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
288
    textOrContactOrFile : string | Contact | FileBox,
289 290
    mention?   : Contact | Contact[],
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291
    log.verbose('Message', 'say(%s, %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
292
                            textOrContactOrFile.toString(),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
293 294
                            mention,
                )
295 296 297 298 299 300 301 302 303 304 305 306

    // const user = this.puppet.userSelf()
    const from = this.from()
    // const to   = this.to()
    const room = this.room()

    const mentionList = mention
                          ? Array.isArray(mention)
                            ? mention
                            : [mention]
                          : []

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    if (typeof textOrContactOrFile === 'string') {
      await this.sayText(
        textOrContactOrFile,
        from || undefined,
        room || undefined,
        mentionList,
      )
    } else if (textOrContactOrFile instanceof Contact) {
      /**
       * Contact Card
       */
      await this.puppet.messageSendContact({
        roomId    : room && room.id || undefined,
        contactId : from && from.id || undefined,
      }, textOrContactOrFile.id)
322 323 324 325
    } else {
      /**
       * File Message
       */
326 327
      await this.puppet.messageSendFile({
        roomId    : room && room.id || undefined,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
328 329
        contactId : from && from.id || undefined,
      }, textOrContactOrFile)
330 331 332 333
    }
  }

  private async sayText(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
334 335 336 337
    text         : string,
    to?          : Contact,
    room?        : Room,
    mentionList? : Contact[],
338
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
339
    if (room && mentionList && mentionList.length > 0) {
340
      /**
341
       * 1 had mentioned someone
342
       */
343 344 345 346 347 348
      const mentionContact = mentionList[0]
      const textMentionList = mentionList.map(c => '@' + c.name()).join(' ')
      await this.puppet.messageSendText({
        contactId: mentionContact.id,
        roomId: room.id,
      }, textMentionList + ' ' + text)
349 350
    } else {
      /**
351
       * 2 did not mention anyone
352
       */
353
      await this.puppet.messageSendText({
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354 355
        contactId : to && to.id,
        roomId    : room && room.id,
356
      }, text)
357 358 359
    }
  }

360 361 362
  public async file(): Promise<FileBox> {
    if (this.type() === Message.Type.Text) {
      throw new Error('text message no file')
363
    }
364 365
    const fileBox = await this.puppet.messageFile(this.id)
    return fileBox
366
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
367 368 369 370 371 372

  /**
   * Get the type from the message.
   *
   * If type is equal to `MsgType.RECALLED`, {@link Message#id} is the msgId of the recalled message.
   * @see {@link MsgType}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
373
   * @returns {WebMsgType}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
374
   */
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  public type(): MessageType {
    if (!this.payload) {
      throw new Error('no payload')
    }
    return this.payload.type || MessageType.Unknown
  }

  // public typeBak(): MessageType {
  //   log.silly('Message', 'type() = %s', WebMsgType[this.payload.type])

  //   /**
  //    * 1. A message created with rawObj
  //    */
  //   if (this.payload.type) {
  //     return this.payload.type
  //   }

  //   /**
  //    * 2. A message created with TEXT
  //    */
  //   const ext = this.extFromFile()
  //   if (!ext) {
  //     return WebMsgType.TEXT
  //   }

  //   /**
  //    * 3. A message created with local file
  //    */
  //   switch (ext.toLowerCase()) {
  //     case '.bmp':
  //     case '.jpg':
  //     case '.jpeg':
  //     case '.png':
  //       return WebMsgType.IMAGE

  //     case '.gif':
  //       return  WebMsgType.EMOTICON

  //     case '.mp4':
  //       return WebMsgType.VIDEO

  //     case '.mp3':
  //       return WebMsgType.VOICE
  //   }

  //   throw new Error('unknown type: ' + ext)
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
422

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423 424 425 426 427 428 429 430 431
  // /**
  //  * Get the typeSub from the message.
  //  *
  //  * If message is a location message: `m.type() === MsgType.TEXT && m.typeSub() === MsgType.LOCATION`
  //  *
  //  * @see {@link MsgType}
  //  * @returns {WebMsgType}
  //  */
  // public abstract typeSub(): WebMsgType
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
432

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
433 434 435 436 437 438 439
  // /**
  //  * Get the typeApp from the message.
  //  *
  //  * @returns {WebAppMsgType}
  //  * @see {@link AppMsgType}
  //  */
  // public abstract typeApp(): WebAppMsgType
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440 441 442 443 444 445 446 447 448 449

  /**
   * 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!')
   * }
   */
450
  public self(): boolean {
451
    const userId = this.puppet.selfId()
452 453
    const from = this.from()

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
454
    return !!from && from.id === userId
455
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

  /**
   *
   * Get message mentioned contactList.
   *
   * Message event table as follows
   *
   * |                                                                            | 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 |  ✘   |        ✘       |     √      |       √         |
   *
   * @returns {Contact[]} - Return message mentioned contactList
   *
   * @example
   * const contactList = message.mentioned()
   * console.log(contactList)
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
476
  public async mentioned(): Promise<Contact[]> {
477
    log.verbose('Message', 'mentioned()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
478

479 480
    const room = this.room()
    if (this.type() !== MessageType.Text || !room ) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
481
      return []
482 483 484 485 486 487
    }

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

    const atList = this.text().split(AT_SEPRATOR)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
488 489
    // console.log('atList: ', atList)
    if (atList.length === 0) return []
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

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

    // convert 'hello@a@b@c' to [ 'c', 'b@c', 'a@b@c' ]
    function multipleAt(str: string) {
      str = str.replace(/^.*?@/, '@')
      let name = ''
      const nameList: string[] = []
      str.split('@')
        .filter(mentionName => !!mentionName)
        .reverse()
        .forEach(mentionName => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
505
          // console.log('mentionName: ', mentionName)
506 507 508 509 510 511
          name = mentionName + '@' + name
          nameList.push(name.slice(0, -1)) // get rid of the `@` at beginning
        })
      return nameList
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
512 513 514 515 516 517 518 519 520 521 522
    let mentionNameList: string[] = []
    // Flatten Array
    // see http://stackoverflow.com/a/10865042/1123955
    mentionNameList = mentionNameList.concat.apply([], rawMentionedList)
    // filter blank string
    mentionNameList = mentionNameList.filter(s => !!s)

    log.verbose('Message', 'mentioned() text = "%s", mentionNameList = "%s"',
                            this.text(),
                            JSON.stringify(mentionNameList),
                )
523

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
524 525 526 527
    const contactListNested = await Promise.all(
      mentionNameList.map(
        name => room.memberAll(name),
      ),
528 529
    )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
530 531 532
    let contactList: Contact[] = []
    contactList = contactList.concat.apply([], contactListNested)

533
    if (contactList.length === 0) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
534
      log.warn('Message', `message.mentioned() can not found member using room.member() from mentionList, metion string: ${JSON.stringify(mentionNameList)}`)
535 536 537 538 539 540 541 542 543
    }
    return contactList
  }

  /**
   * @private
   */
  public isReady(): boolean {
    return !!this.payload
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
544
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
545 546 547 548

  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
549 550 551 552 553 554 555
  public async ready(): Promise<void> {
    log.verbose('Message', 'ready()')

    if (this.isReady()) {
      return
    }

556 557 558 559 560
    await this.puppet.messagePayload(this.id)

    if (!this.payload) {
      throw new Error('no payload')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
561

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
562 563 564 565 566
    const fromId = this.payload.fromId
    const roomId = this.payload.roomId
    const toId   = this.payload.toId

    if (fromId) {
567
      await this.wechaty.Contact.load(fromId).ready()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
568 569
    }
    if (roomId) {
570
      await this.wechaty.Room.load(roomId).ready()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
571 572
    }
    if (toId) {
573
      await this.wechaty.Contact.load(toId).ready()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
574
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
575
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
576

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
  // public async readyMedia(): Promise<this> {
  //   log.silly('PuppeteerMessage', 'readyMedia()')

  //   const puppet = this.puppet

  //   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('PuppeteerMessage', 'ready() exception: %s', e.message)
  //     Raven.captureException(e)
  //     throw e
  //   }

  //   return this
  // }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
662 663 664 665

  /**
   * Get the read stream for attachment file
   */
666
  // public abstract async readyStream(): Promise<Readable>
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
667

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
668 669 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 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
  /**
   * 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:
   * ```
   * 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:
   * ```
   * AppMsgType {
   *   TEXT                     = 1,
   *   IMG                      = 2,
   *   VIDEO                    = 4,
   *   ATTACH                   = 6,
   *   EMOJI                    = 8,
   * }
   * ```
   * 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 shields the web wx to download more than 25Mb files with a file size of 0.
   *
   * But if the file is uploaded by you using wechaty, you can forward it.
   * You need to detect the following conditions in the message event, which can be forwarded if it is met.
   *
   * ```javasrcipt
   * .on('message', async m => {
   *   if (m.self() && m.rawObj && m.rawObj.Signature) {
   *     // Filter the contacts you have forwarded
   *     const msg = <MediaMessage> m
   *     await msg.forward()
   *   }
   * })
   * ```
   *
   * @param {(Sayable | Sayable[])} to Room or Contact
   * The recipient of the message, the room, or the contact
   * @returns {Promise<boolean>}
   * @memberof MediaMessage
   */
717 718
  public async forward(to: Room | Contact): Promise<void> {
    log.verbose('Message', 'forward(%s)', to)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
719

720 721 722 723 724 725 726 727
    let roomId, contactId

    if (to instanceof Room) {
      roomId = to.id
    }
    if (to instanceof Contact) {
      contactId = to.id
    }
728
    try {
729 730 731 732 733 734 735
      await this.puppet.messageForward(
        {
          contactId,
          roomId,
        },
        this.id,
      )
736 737 738 739 740
    } catch (e) {
      log.error('Message', 'forward(%s) exception: %s', to, e)
      throw e
    }
  }
741 742 743 744 745 746 747 748 749 750

  public date(): Date {
    if (!this.payload) {
      throw new Error('no payload')
    }

    // convert the unit timestamp to milliseconds
    // (from seconds to milliseconds)
    return new Date(1000 * this.payload.timestamp)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
751 752 753
}

export default Message