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,
34
}                       from '../config'
35 36
import {
  Accessory,
37
}               from '../accessory'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
38

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

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

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

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

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

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

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

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

      return roomList

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

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

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

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

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

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

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

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

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

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

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

246
  }
247

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

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

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

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

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

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

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

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

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

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

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

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

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

365
  public emit(event: 'leave', leaverList:   Contact[],  remover?: Contact)                    : boolean
366 367 368 369 370 371
  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,
372
    ...args: any[]
373 374 375 376
  ): boolean {
    return super.emit(event, ...args)
  }

377 378 379 380
  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 已提交
381 382 383 384 385 386 387 388 389 390

   /**
    * @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 已提交
391
  /**
L
lijiarui 已提交
392 393 394 395 396
   * @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 已提交
397
   */
L
lijiarui 已提交
398

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

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

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

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

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

487 488 489 490 491 492 493 494 495 496
  //   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 (李卓桓) 已提交
497

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

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

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

    if (typeof newTopic === 'undefined') {
546 547 548 549 550 551 552 553 554 555 556 557 558 559
      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
      }
560 561 562
    }

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

    return future
  }
573

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

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

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

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

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

    return null
630
  }
631

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

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

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

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

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

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

    return contactList
695
  }
696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

export default Room