room.ts 26.3 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 9 10 11 12 13 14 15 16 17
 *
 *   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 已提交
18
 *   @ignore
19
 */
20
// import util from 'util'
21

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

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44 45 46 47 48 49
export const ROOM_EVENT_DICT = {
  join: 'tbw',
  leave: 'tbw',
  topic: 'tbw',
}
export type RoomEventName = keyof typeof ROOM_EVENT_DICT
50

51 52 53 54 55
import {
  RoomMemberQueryFilter,
  RoomPayload,
  RoomQueryFilter,
}                         from './puppet/'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
56

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57
/**
L
lijiarui 已提交
58
 * All wechat rooms(groups) will be encapsulated as a Room.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
59
 *
L
lijiarui 已提交
60
 * `Room` is `Sayable`,
61
 * [Examples/Room-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/room-bot.ts}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
62
 */
63
export class Room extends Accessory implements Sayable {
64

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65
  protected static pool: Map<string, Room>
66

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  /**
   * Create a new room.
   *
   * @static
   * @param {Contact[]} contactList
   * @param {string} [topic]
   * @returns {Promise<Room>}
   * @example <caption>Creat a room with 'lijiarui' and 'juxiaomi', the room topic is 'ding - created'</caption>
   * const helperContactA = await Contact.find({ name: 'lijiarui' })  // change 'lijiarui' to any contact in your wechat
   * const helperContactB = await Contact.find({ name: 'juxiaomi' })  // change 'juxiaomi' to any contact in your wechat
   * const contactList = [helperContactA, helperContactB]
   * console.log('Bot', 'contactList: %s', contactList.join(','))
   * const room = await Room.create(contactList, 'ding')
   * console.log('Bot', 'createDingRoom() new ding room created: %s', room)
   * await room.topic('ding - created')
   * await room.say('ding - created')
   */
  public static async create(contactList: Contact[], topic?: string): Promise<Room> {
    log.verbose('Room', 'create(%s, %s)', contactList.join(','), topic)

    if (!contactList || !Array.isArray(contactList)) {
      throw new Error('contactList not found')
    }

    try {
92 93 94
      const contactIdList = contactList.map(contact => contact.id)
      const roomId = await this.puppet.roomCreate(contactIdList, topic)
      const room = this.load(roomId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      return room
    } catch (e) {
      log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
      Raven.captureException(e)
      throw e
    }
  }

  /**
   * Find room by topic, return all the matched room
   *
   * @static
   * @param {RoomQueryFilter} [query]
   * @returns {Promise<Room[]>}
   * @example
   * const roomList = await Room.findAll()                    // get the room list of the bot
   * const roomList = await Room.findAll({name: 'wechaty'})   // find all of the rooms with name 'wechaty'
   */
113 114 115 116
  public static async findAll<T extends typeof Room>(
    this  : T,
    query : RoomQueryFilter = { topic: /.*/ },
  ): Promise<T['prototype'][]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117
    log.verbose('Room', 'findAll()', JSON.stringify(query))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
118 119 120 121 122 123

    if (!query.topic) {
      throw new Error('topicFilter not found')
    }

    try {
124
      const roomIdList = await this.puppet.roomSearch(query)
125
      const roomList = roomIdList.map(id => this.load(id))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126 127 128 129 130 131
      await Promise.all(roomList.map(room => room.ready()))

      return roomList

    } catch (e) {
      log.verbose('Room', 'findAll() rejected: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
132
      console.error(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
133 134 135 136 137 138 139 140 141 142 143
      Raven.captureException(e)
      return [] as Room[] // fail safe
    }
  }

  /**
   * Try to find a room by filter: {topic: string | RegExp}. If get many, return the first one.
   *
   * @param {RoomQueryFilter} query
   * @returns {Promise<Room | null>} If can find the room, return Room, or return null
   */
144

145 146 147 148
  public static async find<T extends typeof Room>(
    this  : T,
    query : RoomQueryFilter,
  ): Promise<T['prototype'] | null> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149 150 151
    log.verbose('Room', 'find({ topic: %s })', query.topic)

    const roomList = await this.findAll(query)
152
    if (!roomList) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153 154
      return null
    }
155 156 157 158 159 160 161 162 163 164 165
    if (roomList.length < 1) {
      return null
    }

    if (roomList.length > 1) {
      log.warn('Room', 'find() got more than one(%d) result', roomList.length)
    }

    let n = 0
    for (n = 0; n < roomList.length; n++) {
      const room = roomList[n]
166
      // use puppet.roomValidate() to confirm double confirm that this roomId is valid.
167 168
      // https://github.com/lijiarui/wechaty-puppet-padchat/issues/64
      // https://github.com/Chatie/wechaty/issues/1345
169
      const valid = await this.puppet.roomValidate(room.id)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
      if (valid) {
        log.verbose('Room', 'find() confirm room[#%d] with id=%d is vlaid result, return it.',
                            n,
                            room.id,
                  )
        return room
      } else {
        log.verbose('Room', 'find() confirm room[#%d] with id=%d is INVALID result, try next',
                            n,
                            room.id,
                    )
      }
    }
    log.warn('Room', 'find() got %d rooms but no one is valid.', roomList.length)
    return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185 186 187 188
  }

  /**
   * @private
189
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
190
   */
191
  public static load<T extends typeof Room>(
192 193
    this : T,
    id   : string,
194
  ): T['prototype'] {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195 196 197 198
    if (!this.pool) {
      this.pool = new Map<string, Room>()
    }

199 200 201
    const existingRoom = this.pool.get(id)
    if (existingRoom) {
      return existingRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202
    }
203

204 205
    const newRoom = new (this as any)(id) as Room
    // newRoom.payload = this.puppet.cacheRoomPayload.get(id)
206

207 208
    this.pool.set(id, newRoom)
    return newRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
209 210
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211 212 213 214 215 216 217
  /**
   *
   *
   * Instance Properties
   *
   *
   */
218
  protected get payload(): undefined | RoomPayload {
219 220 221 222
    if (!this.id) {
      return undefined
    }

223 224 225
    const readyPayload = this.puppet.roomPayloadCache(this.id)
    return readyPayload
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226

H
hcz 已提交
227 228 229
  /**
   * @private
   */
230
  constructor(
231
    public readonly id: string,
232
  ) {
233
    super()
234
    log.silly('Room', `constructor(${id})`)
235 236 237 238 239 240 241 242 243 244 245 246

    // tslint:disable-next-line:variable-name
    const MyClass = instanceToClass(this, Room)

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

    if (!this.puppet) {
      throw new Error('Room class can not be instanciated without a puppet!')
    }

247
  }
248

H
hcz 已提交
249 250 251
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252
  public toString() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
253
    if (this.payload && this.payload.topic) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254
      return `Room<${this.payload.topic}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
255
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256
    return `Room<${this.id || ''}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257
  }
L
lijiarui 已提交
258

259 260
  public async *[Symbol.asyncIterator](): AsyncIterableIterator<Contact> {
    const memberList = await this.memberList()
261 262 263 264 265
    for (const contact of memberList) {
      yield contact
    }
  }

L
lijiarui 已提交
266 267 268
  /**
   * @private
   */
269
  public async ready(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270
    dirty = false,
271
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
272
    log.verbose('Room', 'ready()')
273

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
274
    if (!dirty && this.isReady()) {
275 276 277
      return
    }

278 279 280 281
    if (dirty) {
      await this.puppet.roomPayloadDirty(this.id)
    }
    await this.puppet.roomPayload(this.id)
282 283 284

    const memberIdList = await this.puppet.roomMemberList(this.id)

285
    await Promise.all(
286 287 288
      memberIdList
        .map(id => this.wechaty.Contact.load(id))
        .map(contact => contact.ready()),
289 290 291 292 293 294 295
    )
  }

  /**
   * @private
   */
  public isReady(): boolean {
296
    return !!(this.payload)
297 298 299 300 301
  }

  public say(text: string)                     : Promise<void>
  public say(text: string, mention: Contact)   : Promise<void>
  public say(text: string, mention: Contact[]) : Promise<void>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
302
  public say(file: FileBox)                    : Promise<void>
303
  public say(text: never, ...args: never[])    : never
L
lijiarui 已提交
304 305 306 307

  /**
   * Send message inside Room, if set [replyTo], wechaty will mention the contact as well.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
308
   * @param {(string | MediaMessage)} textOrContactOrFile - Send `text` or `media file` inside Room.
L
lijiarui 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
   * @param {(Contact | Contact[])} [replyTo] - Optional parameter, send content inside Room, and mention @replyTo contact or contactList.
   * @returns {Promise<boolean>}
   * If bot send message successfully, it will return true. If the bot failed to send for blocking or any other reason, it will return false
   *
   * @example <caption>Send text inside Room</caption>
   * const room = await Room.find({name: 'wechaty'})        // change 'wechaty' to any of your room in wechat
   * await room.say('Hello world!')
   *
   * @example <caption>Send media file inside Room</caption>
   * const room = await Room.find({name: 'wechaty'})        // change 'wechaty' to any of your room in wechat
   * await room.say(new MediaMessage('/test.jpg'))          // put the filePath you want to send here
   *
   * @example <caption>Send text inside Room, and mention @replyTo contact</caption>
   * const contact = await Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of the room member
   * const room = await Room.find({name: 'wechaty'})        // change 'wechaty' to any of your room in wechat
   * await room.say('Hello world!', contact)
   */
326
  public async say(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327 328
    textOrContactOrFile : string | Contact | FileBox,
    mention?            : Contact | Contact[],
329 330
  ): Promise<void> {
    log.verbose('Room', 'say(%s, %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
331
                                  textOrContactOrFile,
332 333 334 335
                                  Array.isArray(mention)
                                  ? mention.map(c => c.name()).join(', ')
                                  : mention ? mention.name() : '',
                )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
336
    let text: string
337

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
338 339
    const replyToList: Contact[] = [].concat(mention as any || [])

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
340
    if (typeof textOrContactOrFile === 'string') {
341 342 343 344

      if (replyToList.length > 0) {
        const AT_SEPRATOR = String.fromCharCode(8197)
        const mentionList = replyToList.map(c => '@' + c.name()).join(AT_SEPRATOR)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345
        text = mentionList + ' ' + textOrContactOrFile
346
      } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
347
        text = textOrContactOrFile
348
      }
349
      await this.puppet.messageSendText({
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
350 351
        roomId    : this.id,
        contactId : replyToList.length && replyToList[0].id || undefined,
352
      }, text)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
353
    } else if (textOrContactOrFile instanceof FileBox) {
354 355
      await this.puppet.messageSendFile({
        roomId: this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356 357 358 359 360
      }, textOrContactOrFile)
    } else if (textOrContactOrFile instanceof Contact) {
      await this.puppet.messageSendContact({
        roomId: this.id,
      }, textOrContactOrFile.id)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
361 362
    } else {
      throw new Error('arg unsupported')
363 364
    }
  }
L
lijiarui 已提交
365

366
  public emit(event: 'leave', leaverList:   Contact[],  remover?: Contact)                    : boolean
367 368 369 370 371 372
  public emit(event: 'join' , inviteeList:  Contact[] , inviter:  Contact)                    : boolean
  public emit(event: 'topic', topic:        string,     oldTopic: string,   changer: Contact) : boolean
  public emit(event: never, ...args: never[]): never

  public emit(
    event:   RoomEventName,
373
    ...args: any[]
374 375 376 377
  ): boolean {
    return super.emit(event, ...args)
  }

378 379 380 381
  public on(event: 'leave', listener: (this: Room, leaverList:  Contact[], remover?: Contact) => void)                  : this
  public on(event: 'join' , listener: (this: Room, inviteeList: Contact[], inviter:  Contact) => void)                  : this
  public on(event: 'topic', listener: (this: Room, topic:       string,    oldTopic: string, changer: Contact) => void) : this
  public on(event: never,   ...args: never[])                                                                           : never
L
lijiarui 已提交
382 383 384 385 386 387 388 389 390 391

   /**
    * @desc       Room Class Event Type
    * @typedef    RoomEventName
    * @property   {string}  join  - Emit when anyone join any room.
    * @property   {string}  topic - Get topic event, emitted when someone change room topic.
    * @property   {string}  leave - Emit when anyone leave the room.<br>
    *                               If someone leaves the room by themselves, wechat will not notice other people in the room, so the bot will never get the "leave" event.
    */

H
hcz 已提交
392
  /**
L
lijiarui 已提交
393 394 395 396 397
   * @desc       Room Class Event Function
   * @typedef    RoomEventFunction
   * @property   {Function} room-join       - (this: Room, inviteeList: Contact[] , inviter: Contact)  => void
   * @property   {Function} room-topic      - (this: Room, topic: string, oldTopic: string, changer: Contact) => void
   * @property   {Function} room-leave      - (this: Room, leaver: Contact) => void
H
hcz 已提交
398
   */
L
lijiarui 已提交
399

H
hcz 已提交
400
  /**
L
lijiarui 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
   * @listens Room
   * @param   {RoomEventName}      event      - Emit WechatyEvent
   * @param   {RoomEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {this}                          - this for chain
   *
   * @example <caption>Event:join </caption>
   * const room = await Room.find({topic: 'event-room'}) // change `event-room` to any room topic in your wechat
   * if (room) {
   *   room.on('join', (room: Room, inviteeList: Contact[], inviter: Contact) => {
   *     const nameList = inviteeList.map(c => c.name()).join(',')
   *     console.log(`Room ${room.topic()} got new member ${nameList}, invited by ${inviter}`)
   *   })
   * }
   *
   * @example <caption>Event:leave </caption>
   * const room = await Room.find({topic: 'event-room'}) // change `event-room` to any room topic in your wechat
   * if (room) {
   *   room.on('leave', (room: Room, leaverList: Contact[]) => {
   *     const nameList = leaverList.map(c => c.name()).join(',')
   *     console.log(`Room ${room.topic()} lost member ${nameList}`)
   *   })
   * }
   *
   * @example <caption>Event:topic </caption>
   * const room = await Room.find({topic: 'event-room'}) // change `event-room` to any room topic in your wechat
   * if (room) {
   *   room.on('topic', (room: Room, topic: string, oldTopic: string, changer: Contact) => {
   *     console.log(`Room ${room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
   *   })
   * }
   *
H
hcz 已提交
432
   */
433
  public on(event: RoomEventName, listener: (...args: any[]) => any): this {
434
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
435

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
436
    super.on(event, listener) // Room is `Sayable`
437
    return this
438 439
  }

H
hcz 已提交
440
  /**
L
lijiarui 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
   * Add contact in a room
   *
   * @param {Contact} contact
   * @returns {Promise<number>}
   * @example
   * const contact = await Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any contact in your wechat
   * const room = await Room.find({topic: 'wechat'})        // change 'wechat' to any room topic in your wechat
   * if (room) {
   *   const result = await room.add(contact)
   *   if (result) {
   *     console.log(`add ${contact.name()} to ${room.topic()} successfully! `)
   *   } else{
   *     console.log(`failed to add ${contact.name()} to ${room.topic()}! `)
   *   }
   * }
H
hcz 已提交
456
   */
457 458
  public async add(contact: Contact): Promise<void> {
    log.verbose('Room', 'add(%s)', contact)
459
    await this.puppet.roomAdd(this.id, contact.id)
460
  }
461

H
hcz 已提交
462
  /**
L
lijiarui 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
   * Delete a contact from the room
   * It works only when the bot is the owner of the room
   * @param {Contact} contact
   * @returns {Promise<number>}
   * @example
   * const room = await Room.find({topic: 'wechat'})          // change 'wechat' to any room topic in your wechat
   * const contact = await Contact.find({name: 'lijiarui'})   // change 'lijiarui' to any room member in the room you just set
   * if (room) {
   *   const result = await room.del(contact)
   *   if (result) {
   *     console.log(`remove ${contact.name()} from ${room.topic()} successfully! `)
   *   } else{
   *     console.log(`failed to remove ${contact.name()} from ${room.topic()}! `)
   *   }
   * }
H
hcz 已提交
478
   */
479 480
  public async del(contact: Contact): Promise<void> {
    log.verbose('Room', 'del(%s)', contact)
481
    await this.puppet.roomDel(this.id, contact.id)
482
    // this.delLocal(contact)
483 484
  }

485 486
  // private delLocal(contact: Contact): void {
  //   log.verbose('Room', 'delLocal(%s)', contact)
487

488 489 490 491 492 493 494 495 496 497
  //   const memberIdList = this.payload && this.payload.memberIdList
  //   if (memberIdList && memberIdList.length > 0) {
  //     for (let i = 0; i < memberIdList.length; i++) {
  //       if (memberIdList[i] === contact.id) {
  //         memberIdList.splice(i, 1)
  //         break
  //       }
  //     }
  //   }
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
498

H
hcz 已提交
499
  /**
L
lijiarui 已提交
500
   * @private
H
hcz 已提交
501
   */
502 503
  public async quit(): Promise<void> {
    log.verbose('Room', 'quit() %s', this)
504
    await this.puppet.roomQuit(this.id)
505
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506

507 508
  public async topic()                : Promise<string>
  public async topic(newTopic: string): Promise<void>
509

L
lijiarui 已提交
510 511 512 513
  /**
   * SET/GET topic from the room
   *
   * @param {string} [newTopic] If set this para, it will change room topic.
514
   * @returns {Promise<string | void>}
L
lijiarui 已提交
515 516 517 518 519 520 521
   *
   * @example <caption>When you say anything in a room, it will get room topic. </caption>
   * const bot = Wechaty.instance()
   * bot
   * .on('message', async m => {
   *   const room = m.room()
   *   if (room) {
522
   *     const topic = await room.topic()
L
lijiarui 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
   *     console.log(`room topic is : ${topic}`)
   *   }
   * })
   *
   * @example <caption>When you say anything in a room, it will change room topic. </caption>
   * const bot = Wechaty.instance()
   * bot
   * .on('message', async m => {
   *   const room = m.room()
   *   if (room) {
   *     const oldTopic = room.topic()
   *     room.topic('change topic to wechaty!')
   *     console.log(`room topic change from ${oldTopic} to ${room.topic()}`)
   *   }
   * })
   */
539
  public async topic(newTopic?: string): Promise<void | string> {
540 541 542
    log.verbose('Room', 'topic(%s)', newTopic ? newTopic : '')
    if (!this.isReady()) {
      log.warn('Room', 'topic() room not ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
543
      throw new Error('not ready')
544 545 546
    }

    if (typeof newTopic === 'undefined') {
547 548 549 550 551 552 553 554 555 556 557 558 559 560
      if (this.payload && this.payload.topic) {
        return this.payload.topic
      } else {
        const memberIdList = await this.puppet.roomMemberList(this.id)
        const memberList = memberIdList
                            .filter(id => id !== this.puppet.selfId())
                            .map(id => this.wechaty.Contact.load(id))

        let defaultTopic = memberList[0].name()
        for (let i = 1; i < 3 && memberList[i]; i++) {
          defaultTopic += ',' + memberList[i].name()
        }
        return defaultTopic
      }
561 562 563
    }

    const future = this.puppet
564
        .roomTopic(this.id, newTopic)
565 566 567 568 569 570 571 572 573
        .catch(e => {
          log.warn('Room', 'topic(newTopic=%s) exception: %s',
                            newTopic, e && e.message || e,
                  )
          Raven.captureException(e)
        })

    return future
  }
574

575 576 577 578 579 580 581 582 583 584 585 586 587
  public async announce()             : Promise<string>
  public async announce(text: string) : Promise<void>

  public async announce(text?: string): Promise<void | string> {
    log.verbose('Room', 'announce(%s)', text ? text : '')

    if (text) {
      await this.puppet.roomAnnounce(this.id, text)
    } else {
      return await this.puppet.roomAnnounce(this.id)
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
588 589 590
  /**
   * Room QR Code
   */
591 592
  public async qrcode(): Promise<string> {
    log.verbose('Room', 'qrcode()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
593 594
    const qrcode = await this.puppet.roomQrcode(this.id)
    return qrcode
595 596
  }

L
lijiarui 已提交
597
  /**
L
lijiarui 已提交
598
   * Return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
599
   * @param {Contact} contact
L
lijiarui 已提交
600 601 602 603 604 605 606 607 608 609 610 611
   * @returns {string | null} - If a contact has an alias in room, return string, otherwise return null
   * @example
   * const bot = Wechaty.instance()
   * bot
   * .on('message', async m => {
   *   const room = m.room()
   *   const contact = m.from()
   *   if (room) {
   *     const alias = room.alias(contact)
   *     console.log(`${contact.name()} alias is ${alias}`)
   *   }
   * })
L
lijiarui 已提交
612
   */
613
  public async alias(contact: Contact): Promise<null | string> {
614 615
    return this.roomAlias(contact)
  }
616

H
hcz 已提交
617
  /**
L
lijiarui 已提交
618 619 620
   * Same as function alias
   * @param {Contact} contact
   * @returns {(string | null)}
H
hcz 已提交
621
   */
622
  public async roomAlias(contact: Contact): Promise<null | string> {
623

624
    const memberPayload = await this.puppet.roomMemberPayload(this.id, contact.id)
625 626 627

    if (memberPayload && memberPayload.roomAlias) {
      return memberPayload.roomAlias
628
    }
629 630

    return null
631
  }
632

H
hcz 已提交
633
  /**
634
   * Check if the room has member `contact`, the return is a Promise and must be `await`-ed
L
lijiarui 已提交
635 636 637 638 639 640 641
   *
   * @param {Contact} contact
   * @returns {boolean} Return `true` if has contact, else return `false`.
   * @example <caption>Check whether 'lijiarui' is in the room 'wechaty'</caption>
   * const contact = await Contact.find({name: 'lijiarui'})   // change 'lijiarui' to any of contact in your wechat
   * const room = await Room.find({topic: 'wechaty'})         // change 'wechaty' to any of the room in your wechat
   * if (contact && room) {
642
   *   if (await room.has(contact)) {
L
lijiarui 已提交
643 644 645 646 647
   *     console.log(`${contact.name()} is in the room ${room.topic()}!`)
   *   } else {
   *     console.log(`${contact.name()} is not in the room ${room.topic()} !`)
   *   }
   * }
H
hcz 已提交
648
   */
649 650 651 652
  public async has(contact: Contact): Promise<boolean> {
    const memberIdList = await this.puppet.roomMemberList(this.id)

    if (!memberIdList) {
653 654
      return false
    }
655 656 657 658

    return memberIdList
            .filter(id => id === contact.id)
            .length > 0
659
  }
L
lijiarui 已提交
660

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
661 662
  public async memberAll(name: string)                  : Promise<Contact[]>
  public async memberAll(filter: RoomMemberQueryFilter) : Promise<Contact[]>
663

L
lijiarui 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
  /**
   * The way to search member by Room.member()
   *
   * @typedef    MemberQueryFilter
   * @property   {string} name            -Find the contact by wechat name in a room, equal to `Contact.name()`.
   * @property   {string} roomAlias       -Find the contact by alias set by the bot for others in a room.
   * @property   {string} contactAlias    -Find the contact by alias set by the contact out of a room, equal to `Contact.alias()`.
   * [More Detail]{@link https://github.com/Chatie/wechaty/issues/365}
   */

  /**
   * Find all contacts in a room
   *
   * #### definition
   * - `name`                 the name-string set by user-self, should be called name, equal to `Contact.name()`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
679
   * - `roomAlias`            the name-string set by user-self in the room, should be called roomAlias
L
lijiarui 已提交
680
   * - `contactAlias`         the name-string set by bot for others, should be called alias, equal to `Contact.alias()`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
681
   * @param {(RoomMemberQueryFilter | string)} query -When use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
682 683 684
   * @returns {Contact[]}
   * @memberof Room
   */
685
  public async memberAll(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
686
    query: string | RoomMemberQueryFilter,
687 688
  ): Promise<Contact[]> {
    log.silly('Room', 'memberAll(%s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
689
                      JSON.stringify(query),
690 691
              )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
692 693 694 695
    const contactIdList = await this.puppet.roomMemberSearch(this.id, query)
    const contactList   = contactIdList.map(id => this.wechaty.Contact.load(id))

    return contactList
696
  }
697

698 699
  public async member(name  : string)               : Promise<null | Contact>
  public async member(filter: RoomMemberQueryFilter): Promise<null | Contact>
700

L
lijiarui 已提交
701 702 703
  /**
   * Find all contacts in a room, if get many, return the first one.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
704
   * @param {(RoomMemberQueryFilter | string)} queryArg -When use member(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
   * @returns {(Contact | null)}
   *
   * @example <caption>Find member by name</caption>
   * const room = await Room.find({topic: 'wechaty'})           // change 'wechaty' to any room name in your wechat
   * if (room) {
   *   const member = room.member('lijiarui')                   // change 'lijiarui' to any room member in your wechat
   *   if (member) {
   *     console.log(`${room.topic()} got the member: ${member.name()}`)
   *   } else {
   *     console.log(`cannot get member in room: ${room.topic()}`)
   *   }
   * }
   *
   * @example <caption>Find member by MemberQueryFilter</caption>
   * const room = await Room.find({topic: 'wechaty'})          // change 'wechaty' to any room name in your wechat
   * if (room) {
   *   const member = room.member({name: 'lijiarui'})          // change 'lijiarui' to any room member in your wechat
   *   if (member) {
   *     console.log(`${room.topic()} got the member: ${member.name()}`)
   *   } else {
   *     console.log(`cannot get member in room: ${room.topic()}`)
   *   }
   * }
   */
729
  public async member(
730
    queryArg: string | RoomMemberQueryFilter,
731
  ): Promise<null | Contact> {
732 733 734 735 736 737
    log.verbose('Room', 'member(%s)', JSON.stringify(queryArg))

    let memberList: Contact[]
    // ISSUE #622
    // error TS2345: Argument of type 'string | MemberQueryFilter' is not assignable to parameter of type 'MemberQueryFilter' #622
    if (typeof queryArg === 'string') {
738
      memberList =  await this.memberAll(queryArg)
739
    } else {
740
      memberList =  await this.memberAll(queryArg)
741 742 743 744 745 746 747 748 749 750 751
    }

    if (!memberList || !memberList.length) {
      return null
    }

    if (memberList.length > 1) {
      log.warn('Room', 'member(%s) get %d contacts, use the first one by default', JSON.stringify(queryArg), memberList.length)
    }
    return memberList[0]
  }
752

H
hcz 已提交
753
  /**
L
lijiarui 已提交
754 755 756
   * Get all room member from the room
   *
   * @returns {Contact[]}
H
hcz 已提交
757
   */
758 759 760 761
  public async memberList(): Promise<Contact[]> {
    log.verbose('Room', 'memberList()')

    const memberIdList = await this.puppet.roomMemberList(this.id)
762

763
    if (!memberIdList) {
764 765 766
      log.warn('Room', 'memberList() not ready')
      return []
    }
767 768 769 770

    const contactList = memberIdList.map(
      id => this.wechaty.Contact.load(id),
    )
771
    return contactList
772
  }
773

L
lijiarui 已提交
774 775
  /**
   * Force reload data for Room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
776
   * @deprecated use sync() instead
L
lijiarui 已提交
777 778
   * @returns {Promise<void>}
   */
779 780 781
  public async refresh(): Promise<void> {
    return this.sync()
  }
L
lijiarui 已提交
782

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
783 784 785 786 787
  /**
   * Sync data for Room
   *
   * @returns {Promise<void>}
   */
788
  public async sync(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
789
    await this.ready(true)
790
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
791

L
lijiarui 已提交
792 793 794 795 796 797
  /**
   * @private
   * Get room's owner from the room.
   * Not recommend, because cannot always get the owner
   * @returns {(Contact | null)}
   */
798 799 800
  public owner(): Contact | null {
    log.info('Room', 'owner()')

801 802 803 804 805
    const ownerId = this.payload && this.payload.ownerId
    if (!ownerId) {
      return null
    }

806
    const owner = this.wechaty.Contact.load(ownerId)
807
    return owner
808
  }
L
lijiarui 已提交
809

810 811 812 813 814 815
  public async avatar(): Promise<FileBox> {
    log.verbose('Room', 'avatar()')

    return this.puppet.roomAvatar(this.id)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
816
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
817 818

export default Room