room.ts 26.1 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
import { PuppetAccessory }  from './puppet-accessory'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36

37 38
import { Contact }          from './contact'
// import Message          from './message'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
39

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
47
export interface RoomMemberQueryFilter {
48 49 50
  name?:         string,
  roomAlias?:    string,
  contactAlias?: string,
51 52
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
53 54 55 56
export interface RoomQueryFilter {
  topic: string | RegExp,
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57 58 59
export interface RoomPayload {
  // id:               string,
  // encryId:          string,
60 61 62
  topic        : string,
  memberIdList : string[],
  ownerId?     : string,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63 64 65 66 67 68 69

  nameMap:          Map<string, string>,
  roomAliasMap:     Map<string, string>,
  contactAliasMap:  Map<string, string>,
  // [index: string]:  Map<string, string> | string | number | PuppeteerContact[],
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70
/**
L
lijiarui 已提交
71
 * All wechat rooms(groups) will be encapsulated as a Room.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72
 *
L
lijiarui 已提交
73
 * `Room` is `Sayable`,
74
 * [Examples/Room-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/room-bot.ts}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
75
 */
76
export class Room extends PuppetAccessory implements Sayable {
77

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  /**
   * 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 {
105 106 107
      const contactIdList = contactList.map(contact => contact.id)
      const roomId = await this.puppet.roomCreate(contactIdList, topic)
      const room = this.load(roomId)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
      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'
   */
126 127 128 129
  public static async findAll<T extends typeof Room>(
    this  : T,
    query : RoomQueryFilter = { topic: /.*/ },
  ): Promise<T['prototype'][]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130 131 132 133 134 135 136
    log.verbose('Room', 'findAll({ topic: %s })', query.topic)

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

    try {
137 138
      const roomIdList = await this.puppet.roomFindAll(query)
      const roomList = roomIdList.map(id => this.load(id))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      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
   */
156

157 158 159 160
  public static async find<T extends typeof Room>(
    this  : T,
    query : RoomQueryFilter,
  ): Promise<T['prototype'] | null> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173
    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
174
   * About the Generic: https://stackoverflow.com/q/43003970/1123955
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
   */
176 177 178 179
  public static load<T extends typeof Room>(
    this : T,
    id   : string,
  ): T['prototype'] {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180 181 182 183
    if (!this.pool) {
      this.pool = new Map<string, Room>()
    }

184 185 186
    const existingRoom = this.pool.get(id)
    if (existingRoom) {
      return existingRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
187
    }
188 189 190 191

    const newRoom = new (this as any)(id)
    this.pool.set(id, newRoom)
    return newRoom
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
192 193
  }

194 195 196 197 198 199 200 201 202
  // public load(
  //   this : Room,
  //   id   : string,
  // ): Room {
  //   const klass = instanceToClass(this, Room)
  //   const room = klass.load(id)
  //   return room
  // }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
203 204 205 206 207 208 209
  /**
   *
   *
   * Instance Properties
   *
   *
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
210 211
  protected payload?: RoomPayload

H
hcz 已提交
212 213 214
  /**
   * @private
   */
215
  constructor(
216
    public readonly id: string,
217
  ) {
218
    super()
219
    log.silly('Room', `constructor(${id})`)
220 221 222 223 224 225 226 227 228 229 230 231

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

232
  }
233

H
hcz 已提交
234 235 236
  /**
   * @private
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
237
  public toString() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
238 239 240 241
    if (this.isReady()) {
      return `Room<${this.topic()}>`
    }
    return `Room<${this.id}>`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242
  }
L
lijiarui 已提交
243

244 245 246 247 248 249 250
  public *[Symbol.iterator](): IterableIterator<Contact> {
    const memberList = this.memberList()
    for (const contact of memberList) {
      yield contact
    }
  }

L
lijiarui 已提交
251 252 253
  /**
   * @private
   */
254
  public async ready(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
255
    log.verbose('Room', 'ready()')
256 257 258 259 260

    if (this.isReady()) {
      return
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
261
    const payload = await this.puppet.roomPayload(this.id)
262
    await Promise.all(
263 264 265
      payload.memberIdList
      .map(id => this.puppet.Contact.load(id))
      .map(contact => contact.ready()),
266
    )
267 268 269
    // log.silly('Room', 'ready() this.payload="%s"',
    //                             util.inspect(payload),
    //           )
270 271 272 273 274 275 276 277

    this.payload = payload
  }

  /**
   * @private
   */
  public isReady(): boolean {
278
    return !!(this.payload && this.payload.memberIdList && this.payload.memberIdList.length)
279 280 281 282 283
  }

  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 (李卓桓) 已提交
284
  public say(file: FileBox)                    : Promise<void>
285
  public say(text: never, ...args: never[])    : never
L
lijiarui 已提交
286 287 288 289

  /**
   * Send message inside Room, if set [replyTo], wechaty will mention the contact as well.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
290
   * @param {(string | MediaMessage)} textOrFile - Send `text` or `media file` inside Room.
L
lijiarui 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
   * @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)
   */
308
  public async say(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
309
    textOrFile : string | FileBox,
310 311 312
    mention?      : Contact | Contact[],
  ): Promise<void> {
    log.verbose('Room', 'say(%s, %s)',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
313
                                  textOrFile,
314 315 316 317
                                  Array.isArray(mention)
                                  ? mention.map(c => c.name()).join(', ')
                                  : mention ? mention.name() : '',
                )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
318
    let text: string
319

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

    if (typeof textOrFile === 'string') {
323 324 325 326

      if (replyToList.length > 0) {
        const AT_SEPRATOR = String.fromCharCode(8197)
        const mentionList = replyToList.map(c => '@' + c.name()).join(AT_SEPRATOR)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327
        text = mentionList + ' ' + textOrFile
328
      } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
329
        text = textOrFile
330
      }
331 332 333 334
      await this.puppet.messageSendText({
        roomId: this.id,
        contactId: replyToList[0].id,
      }, text)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
335
    } else if (textOrFile instanceof FileBox) {
336 337 338
      await this.puppet.messageSendFile({
        roomId: this.id,
      }, textOrFile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
339 340
    } else {
      throw new Error('arg unsupported')
341 342
    }
  }
L
lijiarui 已提交
343

344 345 346 347 348 349 350
  public emit(event: 'leave', leaver:       Contact[],  remover?: Contact)                    : boolean
  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,
351
    ...args: any[]
352 353 354 355 356 357 358 359
  ): 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 已提交
360 361 362 363 364 365 366 367 368 369

   /**
    * @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 已提交
370
  /**
L
lijiarui 已提交
371 372 373 374 375
   * @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 已提交
376
   */
L
lijiarui 已提交
377

H
hcz 已提交
378
  /**
L
lijiarui 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
   * @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 已提交
410
   */
411
  public on(event: RoomEventName, listener: (...args: any[]) => any): this {
412
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
413

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
414
    super.on(event, listener) // Room is `Sayable`
415
    return this
416 417
  }

H
hcz 已提交
418
  /**
L
lijiarui 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
   * 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 已提交
434
   */
435 436
  public async add(contact: Contact): Promise<void> {
    log.verbose('Room', 'add(%s)', contact)
437
    await this.puppet.roomAdd(this.id, contact.id)
438
  }
439

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

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

466 467 468 469 470
    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)
471 472 473 474 475
          break
        }
      }
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
476

H
hcz 已提交
477
  /**
L
lijiarui 已提交
478
   * @private
H
hcz 已提交
479
   */
480 481
  public async quit(): Promise<void> {
    log.verbose('Room', 'quit() %s', this)
482
    await this.puppet.roomQuit(this.id)
483
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
484

485 486
  public topic()                : string
  public topic(newTopic: string): Promise<void>
487

L
lijiarui 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  /**
   * 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()}`)
   *   }
   * })
   */
517 518 519 520
  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 (李卓桓) 已提交
521
      throw new Error('not ready')
522 523 524 525 526 527 528
    }

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

    const future = this.puppet
529
        .roomTopic(this.id, newTopic)
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        .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
  }
545

L
lijiarui 已提交
546
  /**
L
lijiarui 已提交
547
   * Return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
548
   * @param {Contact} contact
L
lijiarui 已提交
549 550 551 552 553 554 555 556 557 558 559 560
   * @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 已提交
561
   */
562 563 564
  public alias(contact: Contact): null | string {
    return this.roomAlias(contact)
  }
565

H
hcz 已提交
566
  /**
L
lijiarui 已提交
567 568 569
   * Same as function alias
   * @param {Contact} contact
   * @returns {(string | null)}
H
hcz 已提交
570
   */
571 572 573 574 575 576
  public roomAlias(contact: Contact): null | string {
    if (!this.payload || !this.payload.roomAliasMap) {
      return null
    }
    return this.payload.roomAliasMap.get(contact.id) || null
  }
577

H
hcz 已提交
578
  /**
L
lijiarui 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592
   * 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 已提交
593
   */
594
  public has(contact: Contact): boolean {
595
    if (!this.payload || !this.payload.memberIdList) {
596 597
      return false
    }
598 599
    return this.payload.memberIdList
                        .filter(id => id === contact.id)
600 601
                        .length > 0
  }
L
lijiarui 已提交
602

603 604
  public memberAll(filter: RoomMemberQueryFilter): Contact[]
  public memberAll(name: string): Contact[]
605

L
lijiarui 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
  /**
   * 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 (李卓桓) 已提交
621
   * - `roomAlias`            the name-string set by user-self in the room, should be called roomAlias
L
lijiarui 已提交
622
   * - `contactAlias`         the name-string set by bot for others, should be called alias, equal to `Contact.alias()`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
623
   * @param {(RoomMemberQueryFilter | string)} queryArg -When use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
L
lijiarui 已提交
624 625 626
   * @returns {Contact[]}
   * @memberof Room
   */
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  public memberAll(queryArg: RoomMemberQueryFilter | string): Contact[] {
    if (typeof queryArg === 'string') {
      // TODO: filter the duplicated result
      return ([] as Contact[]).concat(
        this.memberAll({name:         queryArg}),
        this.memberAll({roomAlias:    queryArg}),
        this.memberAll({contactAlias: queryArg}),
      )
    }

    /**
     * We got filter parameter
     */
    log.silly('Room', 'memberAll({ %s })',
                                JSON.stringify(queryArg),
                      // Object.keys(queryArg)
                      //       .map((k: keyof RoomMemberQueryFilter) => `${k}: ${queryArg[k]}`)
                      //       .join(', '),
              )

    if (Object.keys(queryArg).length !== 1) {
      throw new Error('Room member find queryArg only support one key. multi key support is not availble now.')
    }

651
    if (!this.payload || !this.payload.memberIdList) {
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
      log.warn('Room', 'member() not ready')
      return []
    }
    const filterKey = Object.keys(queryArg)[0] as keyof RoomMemberQueryFilter
    /**
     * ISSUE #64 emoji need to be striped
     */
    const filterValue: string | undefined = /* Misc.stripEmoji(Misc.plainText( */ queryArg[filterKey] // ))
    if (!filterValue) {
      throw new Error('filterValue not found')
    }

    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) {
683
      return idList.map(id => this.puppet.Contact.load(id))
684 685 686 687
    } else {
      return []
    }
  }
688

689 690
  public member(name  : string)               : null | Contact
  public member(filter: RoomMemberQueryFilter): 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
  public member(
    queryArg: string | RoomMemberQueryFilter,
  ): null | Contact {
    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') {
      memberList =  this.memberAll(queryArg)
    } else {
      memberList =  this.memberAll(queryArg)
    }

    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 memberList = this.payload.memberIdList.map(id => this.puppet.Contact.load(id))
    return memberList
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 779 780 781 782 783 784 785 786
  public async sync(): Promise<void> {
    // TODO: make it work with the old dirty payload when in re-syncing...

    // if (this.isReady()) {
    //   this.dirtyObj = this.payload
    // }
    this.payload = undefined
    await this.ready()
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
787

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

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

    const owner = this.puppet.Contact.load(ownerId)
    return owner
804
  }
L
lijiarui 已提交
805

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
806
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
807 808

export default Room