room.ts 26.4 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 21 22 23 24 25
import {
  FileBox,
}                   from 'file-box'
import {
  instanceToClass,
}                   from 'clone-class'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26

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

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

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

49 50 51 52
import {
  RoomMemberQueryFilter,
  RoomPayload,
  RoomQueryFilter,
53
}                         from 'wechaty-puppet'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  /**
   * 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 {
90 91 92
      const contactIdList = contactList.map(contact => contact.id)
      const roomId = await this.puppet.roomCreate(contactIdList, topic)
      const room = this.load(roomId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
      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'
   */
111 112 113 114
  public static async findAll<T extends typeof Room>(
    this  : T,
    query : RoomQueryFilter = { topic: /.*/ },
  ): Promise<T['prototype'][]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
115
    log.verbose('Room', 'findAll()', JSON.stringify(query))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116 117 118 119 120 121

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

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

      return roomList

    } catch (e) {
      log.verbose('Room', 'findAll() rejected: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130
      console.error(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131 132 133 134 135 136 137 138 139 140 141
      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
   */
142

143 144
  public static async find<T extends typeof Room>(
    this  : T,
145
    query : string | RoomQueryFilter,
146
  ): Promise<T['prototype'] | null> {
147 148 149 150 151
    log.verbose('Room', 'find(%s)', JSON.stringify(query))

    if (typeof query === 'string') {
      query = { topic: query }
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152 153

    const roomList = await this.findAll(query)
154
    if (!roomList) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
155 156
      return null
    }
157 158 159 160 161 162 163 164 165 166 167
    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]
168
      // use puppet.roomValidate() to confirm double confirm that this roomId is valid.
169 170
      // https://github.com/lijiarui/wechaty-puppet-padchat/issues/64
      // https://github.com/Chatie/wechaty/issues/1345
171
      const valid = await this.puppet.roomValidate(room.id)
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      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 (李卓桓) 已提交
187 188 189 190
  }

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

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

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

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

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

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

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

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

249
  }
250

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

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

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

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

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

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

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

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

  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 (李卓桓) 已提交
304
  public say(file: FileBox)                    : Promise<void>
305
  public say(text: never, ...args: never[])    : never
L
lijiarui 已提交
306 307 308 309

  /**
   * Send message inside Room, if set [replyTo], wechaty will mention the contact as well.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
310
   * @param {(string | MediaMessage)} textOrContactOrFile - Send `text` or `media file` inside Room.
L
lijiarui 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
   * @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)
   */
328
  public async say(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
329 330
    textOrContactOrFile : string | Contact | FileBox,
    mention?            : Contact | Contact[],
331 332
  ): Promise<void> {
    log.verbose('Room', 'say(%s, %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
333
                                  textOrContactOrFile,
334 335 336 337
                                  Array.isArray(mention)
                                  ? mention.map(c => c.name()).join(', ')
                                  : mention ? mention.name() : '',
                )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
338
    let text: string
339

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

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

      if (replyToList.length > 0) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345 346 347
        // const AT_SEPRATOR = String.fromCharCode(8197)
        const AT_SEPRATOR = FOUR_PER_EM_SPACE

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

370
  public emit(event: 'leave', leaverList:   Contact[],  remover?: Contact)                    : boolean
371 372 373 374 375 376
  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,
377
    ...args: any[]
378 379 380 381
  ): boolean {
    return super.emit(event, ...args)
  }

382 383 384 385
  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 已提交
386 387 388 389 390 391 392 393 394 395

   /**
    * @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 已提交
396
  /**
L
lijiarui 已提交
397 398 399 400 401
   * @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 已提交
402
   */
L
lijiarui 已提交
403

H
hcz 已提交
404
  /**
L
lijiarui 已提交
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 432 433 434 435
   * @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 已提交
436
   */
437
  public on(event: RoomEventName, listener: (...args: any[]) => any): this {
438
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
439

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440
    super.on(event, listener) // Room is `Sayable`
441
    return this
442 443
  }

H
hcz 已提交
444
  /**
L
lijiarui 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
   * 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 已提交
460
   */
461 462
  public async add(contact: Contact): Promise<void> {
    log.verbose('Room', 'add(%s)', contact)
463
    await this.puppet.roomAdd(this.id, contact.id)
464
  }
465

H
hcz 已提交
466
  /**
L
lijiarui 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
   * 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 已提交
482
   */
483 484
  public async del(contact: Contact): Promise<void> {
    log.verbose('Room', 'del(%s)', contact)
485
    await this.puppet.roomDel(this.id, contact.id)
486
    // this.delLocal(contact)
487 488
  }

489 490
  // private delLocal(contact: Contact): void {
  //   log.verbose('Room', 'delLocal(%s)', contact)
491

492 493 494 495 496 497 498 499 500 501
  //   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 (李卓桓) 已提交
502

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

511 512
  public async topic()                : Promise<string>
  public async topic(newTopic: string): Promise<void>
513

L
lijiarui 已提交
514 515 516 517
  /**
   * SET/GET topic from the room
   *
   * @param {string} [newTopic] If set this para, it will change room topic.
518
   * @returns {Promise<string | void>}
L
lijiarui 已提交
519 520 521 522 523 524 525
   *
   * @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) {
526
   *     const topic = await room.topic()
L
lijiarui 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
   *     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()}`)
   *   }
   * })
   */
543
  public async topic(newTopic?: string): Promise<void | string> {
544 545 546
    log.verbose('Room', 'topic(%s)', newTopic ? newTopic : '')
    if (!this.isReady()) {
      log.warn('Room', 'topic() room not ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
547
      throw new Error('not ready')
548 549 550
    }

    if (typeof newTopic === 'undefined') {
551 552 553 554 555 556 557 558 559 560 561 562 563 564
      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
      }
565 566 567
    }

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

    return future
  }
578

579 580 581 582 583 584 585 586 587 588 589 590 591
  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 (李卓桓) 已提交
592 593 594
  /**
   * Room QR Code
   */
595 596
  public async qrcode(): Promise<string> {
    log.verbose('Room', 'qrcode()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597 598
    const qrcode = await this.puppet.roomQrcode(this.id)
    return qrcode
599 600
  }

L
lijiarui 已提交
601
  /**
L
lijiarui 已提交
602
   * Return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
603
   * @param {Contact} contact
L
lijiarui 已提交
604 605 606 607 608 609 610 611 612 613 614 615
   * @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 已提交
616
   */
617
  public async alias(contact: Contact): Promise<null | string> {
618 619
    return this.roomAlias(contact)
  }
620

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

628
    const memberPayload = await this.puppet.roomMemberPayload(this.id, contact.id)
629 630 631

    if (memberPayload && memberPayload.roomAlias) {
      return memberPayload.roomAlias
632
    }
633 634

    return null
635
  }
636

H
hcz 已提交
637
  /**
638
   * Check if the room has member `contact`, the return is a Promise and must be `await`-ed
L
lijiarui 已提交
639 640 641 642 643 644 645
   *
   * @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) {
646
   *   if (await room.has(contact)) {
L
lijiarui 已提交
647 648 649 650 651
   *     console.log(`${contact.name()} is in the room ${room.topic()}!`)
   *   } else {
   *     console.log(`${contact.name()} is not in the room ${room.topic()} !`)
   *   }
   * }
H
hcz 已提交
652
   */
653 654 655 656
  public async has(contact: Contact): Promise<boolean> {
    const memberIdList = await this.puppet.roomMemberList(this.id)

    if (!memberIdList) {
657 658
      return false
    }
659 660 661 662

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

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

L
lijiarui 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
  /**
   * 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 (李卓桓) 已提交
683
   * - `roomAlias`            the name-string set by user-self in the room, should be called roomAlias
L
lijiarui 已提交
684
   * - `contactAlias`         the name-string set by bot for others, should be called alias, equal to `Contact.alias()`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
685
   * @param {(RoomMemberQueryFilter | string)} query -When use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
686 687 688
   * @returns {Contact[]}
   * @memberof Room
   */
689
  public async memberAll(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
690
    query: string | RoomMemberQueryFilter,
691 692
  ): Promise<Contact[]> {
    log.silly('Room', 'memberAll(%s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
693
                      JSON.stringify(query),
694 695
              )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
696 697 698 699
    const contactIdList = await this.puppet.roomMemberSearch(this.id, query)
    const contactList   = contactIdList.map(id => this.wechaty.Contact.load(id))

    return contactList
700
  }
701

702 703
  public async member(name  : string)               : Promise<null | Contact>
  public async member(filter: RoomMemberQueryFilter): Promise<null | Contact>
704

L
lijiarui 已提交
705 706 707
  /**
   * Find all contacts in a room, if get many, return the first one.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
708
   * @param {(RoomMemberQueryFilter | string)} queryArg -When use member(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
   * @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()}`)
   *   }
   * }
   */
733
  public async member(
734
    queryArg: string | RoomMemberQueryFilter,
735
  ): Promise<null | Contact> {
736 737 738 739 740 741
    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') {
742
      memberList =  await this.memberAll(queryArg)
743
    } else {
744
      memberList =  await this.memberAll(queryArg)
745 746 747 748 749 750 751 752 753 754 755
    }

    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]
  }
756

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

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

767
    if (!memberIdList) {
768 769 770
      log.warn('Room', 'memberList() not ready')
      return []
    }
771 772 773 774

    const contactList = memberIdList.map(
      id => this.wechaty.Contact.load(id),
    )
775
    return contactList
776
  }
777

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

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

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

805 806 807 808 809
    const ownerId = this.payload && this.payload.ownerId
    if (!ownerId) {
      return null
    }

810
    const owner = this.wechaty.Contact.load(ownerId)
811
    return owner
812
  }
L
lijiarui 已提交
813

814 815 816 817 818 819
  public async avatar(): Promise<FileBox> {
    log.verbose('Room', 'avatar()')

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
820
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
821 822

export default Room