room.ts 26.0 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 * as 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 118 119 120 121 122 123
    log.verbose('Room', 'findAll({ topic: %s })', query.topic)

    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 132 133 134 135 136 137 138 139 140 141 142
      await Promise.all(roomList.map(room => room.ready()))

      return roomList

    } catch (e) {
      log.verbose('Room', 'findAll() rejected: %s', e.message)
      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 151 152 153 154 155 156 157 158 159 160
    log.verbose('Room', 'find({ topic: %s })', query.topic)

    const roomList = await this.findAll(query)
    if (!roomList || roomList.length < 1) {
      return null
    } else if (roomList.length > 1) {
      log.warn('Room', 'find() got more than one result, return the 1st one.')
    }
    return roomList[0]
  }

  /**
   * @private
161
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
162
   */
163
  public static load<T extends typeof Room>(
164 165
    this : T,
    id   : string,
166
  ): T['prototype'] {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167 168 169 170
    if (!this.pool) {
      this.pool = new Map<string, Room>()
    }

171 172
    const existingRoom = this.pool.get(id)
    if (existingRoom) {
173 174
      if (!existingRoom.payload) {
        existingRoom.payload = this.puppet.cacheRoomPayload.get(id)
175
      }
176
      return existingRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177
    }
178 179

    const newRoom = new (this as any)(id)
180
    newRoom.payload = this.puppet.cacheRoomPayload.get(id)
181

182 183
    this.pool.set(id, newRoom)
    return newRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
184 185
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186 187 188 189 190 191 192
  /**
   *
   *
   * Instance Properties
   *
   *
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
193 194
  protected payload?: RoomPayload

H
hcz 已提交
195 196 197
  /**
   * @private
   */
198
  constructor(
199
    public readonly id: string,
200
  ) {
201
    super()
202
    log.silly('Room', `constructor(${id})`)
203 204 205 206 207 208 209 210 211 212 213 214

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

215
  }
216

H
hcz 已提交
217 218 219
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220
  public toString() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221
    if (this.payload && this.payload.topic) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
      return `Room<${this.payload.topic}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
224
    return `Room<${this.id || ''}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
  }
L
lijiarui 已提交
226

227 228 229 230 231 232 233
  public *[Symbol.iterator](): IterableIterator<Contact> {
    const memberList = this.memberList()
    for (const contact of memberList) {
      yield contact
    }
  }

L
lijiarui 已提交
234 235 236
  /**
   * @private
   */
237 238 239
  public async ready(
    noCache = false,
  ): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
240
    log.verbose('Room', 'ready()')
241

242
    if (!noCache && this.isReady()) {
243 244 245
      return
    }

246
    const payload = await this.puppet.roomPayload(this.id, noCache)
247
    await Promise.all(
248
      payload.memberIdList
249
      .map(id => this.wechaty.Contact.load(id))
250
      .map(contact => contact.ready()),
251
    )
252 253 254
    // log.silly('Room', 'ready() this.payload="%s"',
    //                             util.inspect(payload),
    //           )
255 256 257 258 259 260 261 262

    this.payload = payload
  }

  /**
   * @private
   */
  public isReady(): boolean {
263
    return !!(this.payload && this.payload.memberIdList && this.payload.memberIdList.length)
264 265 266 267 268
  }

  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 (李卓桓) 已提交
269
  public say(file: FileBox)                    : Promise<void>
270
  public say(text: never, ...args: never[])    : never
L
lijiarui 已提交
271 272 273 274

  /**
   * Send message inside Room, if set [replyTo], wechaty will mention the contact as well.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275
   * @param {(string | MediaMessage)} textOrFile - Send `text` or `media file` inside Room.
L
lijiarui 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
   * @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)
   */
293
  public async say(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294
    textOrFile : string | FileBox,
295 296 297
    mention?      : Contact | Contact[],
  ): Promise<void> {
    log.verbose('Room', 'say(%s, %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
298
                                  textOrFile,
299 300 301 302
                                  Array.isArray(mention)
                                  ? mention.map(c => c.name()).join(', ')
                                  : mention ? mention.name() : '',
                )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
303
    let text: string
304

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

    if (typeof textOrFile === 'string') {
308 309 310 311

      if (replyToList.length > 0) {
        const AT_SEPRATOR = String.fromCharCode(8197)
        const mentionList = replyToList.map(c => '@' + c.name()).join(AT_SEPRATOR)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
312
        text = mentionList + ' ' + textOrFile
313
      } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314
        text = textOrFile
315
      }
316 317 318 319
      await this.puppet.messageSendText({
        roomId: this.id,
        contactId: replyToList[0].id,
      }, text)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
320
    } else if (textOrFile instanceof FileBox) {
321 322 323
      await this.puppet.messageSendFile({
        roomId: this.id,
      }, textOrFile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
324 325
    } else {
      throw new Error('arg unsupported')
326 327
    }
  }
L
lijiarui 已提交
328

329
  public emit(event: 'leave', leaverList:   Contact[],  remover?: Contact)                    : boolean
330 331 332 333 334 335
  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,
336
    ...args: any[]
337 338 339 340 341 342 343 344
  ): boolean {
    return super.emit(event, ...args)
  }

  public on(event: 'leave', listener: (this: Room, leaver:      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 已提交
345 346 347 348 349 350 351 352 353 354

   /**
    * @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 已提交
355
  /**
L
lijiarui 已提交
356 357 358 359 360
   * @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 已提交
361
   */
L
lijiarui 已提交
362

H
hcz 已提交
363
  /**
L
lijiarui 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
   * @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 已提交
395
   */
396
  public on(event: RoomEventName, listener: (...args: any[]) => any): this {
397
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
398

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399
    super.on(event, listener) // Room is `Sayable`
400
    return this
401 402
  }

H
hcz 已提交
403
  /**
L
lijiarui 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
   * 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 已提交
419
   */
420 421
  public async add(contact: Contact): Promise<void> {
    log.verbose('Room', 'add(%s)', contact)
422
    await this.puppet.roomAdd(this.id, contact.id)
423
  }
424

H
hcz 已提交
425
  /**
L
lijiarui 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
   * 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 已提交
441
   */
442 443
  public async del(contact: Contact): Promise<void> {
    log.verbose('Room', 'del(%s)', contact)
444
    await this.puppet.roomDel(this.id, contact.id)
445 446 447 448 449 450
    this.delLocal(contact)
  }

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

451 452 453 454 455
    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)
456 457 458 459 460
          break
        }
      }
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
461

H
hcz 已提交
462
  /**
L
lijiarui 已提交
463
   * @private
H
hcz 已提交
464
   */
465 466
  public async quit(): Promise<void> {
    log.verbose('Room', 'quit() %s', this)
467
    await this.puppet.roomQuit(this.id)
468
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
469

470 471
  public topic()                : string
  public topic(newTopic: string): Promise<void>
472

L
lijiarui 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  /**
   * SET/GET topic from the room
   *
   * @param {string} [newTopic] If set this para, it will change room topic.
   * @returns {(string | void)}
   *
   * @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) {
   *     const topic = room.topic()
   *     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()}`)
   *   }
   * })
   */
502 503 504 505
  public topic(newTopic?: string): string | Promise<void> {
    log.verbose('Room', 'topic(%s)', newTopic ? newTopic : '')
    if (!this.isReady()) {
      log.warn('Room', 'topic() room not ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506
      throw new Error('not ready')
507 508 509 510 511 512 513
    }

    if (typeof newTopic === 'undefined') {
      return this.payload && this.payload.topic || ''
    }

    const future = this.puppet
514
        .roomTopic(this.id, newTopic)
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        .then(() => {
          this.payload = {
            ...this.payload || {} as RoomPayload,
            topic: newTopic,
          }
        })
        .catch(e => {
          log.warn('Room', 'topic(newTopic=%s) exception: %s',
                            newTopic, e && e.message || e,
                  )
          Raven.captureException(e)
        })

    return future
  }
530

L
lijiarui 已提交
531
  /**
L
lijiarui 已提交
532
   * Return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
533
   * @param {Contact} contact
L
lijiarui 已提交
534 535 536 537 538 539 540 541 542 543 544 545
   * @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 已提交
546
   */
547 548 549
  public alias(contact: Contact): null | string {
    return this.roomAlias(contact)
  }
550

H
hcz 已提交
551
  /**
L
lijiarui 已提交
552 553 554
   * Same as function alias
   * @param {Contact} contact
   * @returns {(string | null)}
H
hcz 已提交
555
   */
556
  public roomAlias(contact: Contact): null | string {
557
    if (!this.payload || !this.payload.aliasDict) {
558 559
      return null
    }
560
    return this.payload.aliasDict[contact.id] || null
561
  }
562

H
hcz 已提交
563
  /**
L
lijiarui 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577
   * Check if the room has member `contact`.
   *
   * @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) {
   *   if (room.has(contact)) {
   *     console.log(`${contact.name()} is in the room ${room.topic()}!`)
   *   } else {
   *     console.log(`${contact.name()} is not in the room ${room.topic()} !`)
   *   }
   * }
H
hcz 已提交
578
   */
579
  public has(contact: Contact): boolean {
580
    if (!this.payload || !this.payload.memberIdList) {
581 582
      return false
    }
583 584
    return this.payload.memberIdList
                        .filter(id => id === contact.id)
585 586
                        .length > 0
  }
L
lijiarui 已提交
587

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

L
lijiarui 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
  /**
   * 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 (李卓桓) 已提交
606
   * - `roomAlias`            the name-string set by user-self in the room, should be called roomAlias
L
lijiarui 已提交
607
   * - `contactAlias`         the name-string set by bot for others, should be called alias, equal to `Contact.alias()`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
608
   * @param {(RoomMemberQueryFilter | string)} query -When use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
609 610 611
   * @returns {Contact[]}
   * @memberof Room
   */
612
  public async memberAll(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
613
    query: string | RoomMemberQueryFilter,
614 615
  ): Promise<Contact[]> {
    log.silly('Room', 'memberAll(%s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
616
                      JSON.stringify(query),
617 618
              )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631
    const contactIdList = await this.puppet.roomMemberSearch(this.id, query)
    const contactList   = contactIdList.map(id => this.wechaty.Contact.load(id))

    return contactList

    // if (typeof query === 'string') {
    //   // TODO: filter the duplicated result
    //   return ([] as Contact[]).concat(
    //     await this.memberAll({name:         query}),
    //     await this.memberAll({roomAlias:    query}),
    //     await this.memberAll({contactAlias: query}),
    //   )
    // }
632 633

    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
634
     * We got filter parameter
635 636
     */

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
637 638
    // if (Object.keys(query).length !== 1) {
    //   throw new Error('Room member find queryArg only support one key. multi key support is not availble now.')
639
    // }
640

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
641 642 643 644 645 646 647 648 649 650 651 652
    // if (!this.payload || !this.payload.memberIdList) {
    //   log.warn('Room', 'member() not ready')
    //   return []
    // }
    // const filterKey = Object.keys(query)[0] as keyof RoomMemberQueryFilter

    // /**
    //  * ISSUE #64 emoji need to be striped
    //  */
    // const filterValue: string | undefined = /* Misc.stripEmoji(Misc.plainText( */ query[filterKey] // ))
    // if (!filterValue) {
    //   throw new Error('filterValue not found')
653
    // }
654

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
655
    // const idList = await this.puppet.roomMemberSearch(this.id, query)
656

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
657 658 659
    // if (query.roomAlias === '田美坤') {
    //   console.log('田美坤:')
    //   console.log(this.payload.aliasDict)
660

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    //   console.log(idList)
    // }

    // // const keyMap = {
    // //   contactAlias: 'contactAliasMap',
    // //   name:         'nameMap',
    // //   alias:        'roomAliasMap',
    // //   roomAlias:    'roomAliasMap',
    // // }

    // // const filterMapName = keyMap[filterKey] as keyof RoomPayload
    // // if (!filterMapName) {
    // //   throw new Error('unsupport filter key: ' + filterKey)
    // // }

    // // const filterMap = this.payload[filterMapName] as Map<string, string>
    // // const idList = Array.from(filterMap.keys())
    // //                       .filter(id => filterMap.get(id) === filterValue)

    // // log.silly('Room', 'memberAll() check %s from %s: %s', filterValue, filterKey, JSON.stringify(filterMap))

    // if (idList.length) {
    //   return idList.map(id => this.wechaty.Contact.load(id))
    // } else {
    //   return []
    // }
687
  }
688

689 690
  public async member(name  : string)               : Promise<null | Contact>
  public async member(filter: RoomMemberQueryFilter): Promise<null | Contact>
691

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

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

H
hcz 已提交
744
  /**
L
lijiarui 已提交
745 746 747
   * Get all room member from the room
   *
   * @returns {Contact[]}
H
hcz 已提交
748
   */
749 750 751
  public memberList(): Contact[] {
    log.verbose('Room', 'memberList')

752
    if (!this.payload || !this.payload.memberIdList || this.payload.memberIdList.length < 1) {
753 754
      log.warn('Room', 'memberList() not ready')
      log.verbose('Room', 'memberList() trying call refresh() to update')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
755
      this.sync().then(() => {
756 757 758 759
        log.verbose('Room', 'memberList() refresh() done')
      })
      return []
    }
760 761
    const contactList = this.payload.memberIdList.map(id => this.wechaty.Contact.load(id))
    return contactList
762
  }
763

L
lijiarui 已提交
764 765
  /**
   * Force reload data for Room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
766
   * @deprecated use sync() instead
L
lijiarui 已提交
767 768
   * @returns {Promise<void>}
   */
769 770 771
  public async refresh(): Promise<void> {
    return this.sync()
  }
L
lijiarui 已提交
772

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
773 774 775 776 777
  /**
   * Sync data for Room
   *
   * @returns {Promise<void>}
   */
778
  public async sync(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
779
    await this.ready(true)
780
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
781

L
lijiarui 已提交
782 783 784 785 786 787
  /**
   * @private
   * Get room's owner from the room.
   * Not recommend, because cannot always get the owner
   * @returns {(Contact | null)}
   */
788 789 790
  public owner(): Contact | null {
    log.info('Room', 'owner()')

791 792 793 794 795
    const ownerId = this.payload && this.payload.ownerId
    if (!ownerId) {
      return null
    }

796
    const owner = this.wechaty.Contact.load(ownerId)
797
    return owner
798
  }
L
lijiarui 已提交
799

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
800
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
801 802

export default Room