room.ts 18.2 KB
Newer Older
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 *   Copyright 2016-2017 Huan LI <zixia@zixia.net>
 *
 *   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.
 *
 */
19
import { EventEmitter } from 'events'
20

21
import {
L
lijiarui 已提交
22 23 24
  Config,
  Sayable,
  log,
M
Mukaiu 已提交
25
}                     from './config'
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
26
import Contact        from './contact'
M
Mukaiu 已提交
27 28 29 30
import {
  Message,
  MediaMessage,
}                     from './message'
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
31
import UtilLib        from './util-lib'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
32

33
interface RoomObj {
34 35 36 37 38 39 40 41
  id:               string,
  encryId:          string,
  topic:            string,
  ownerUin:         number,
  memberList:       Contact[],
  nameMap:          Map<string, string>,
  roomAliasMap:     Map<string, string>,
  contactAliasMap:  Map<string, string>,
42 43
}

44
type NameType = 'name' | 'alias' | 'roomAlias' | 'contactAlias'
45

46
export interface RoomRawMember {
L
lijiarui 已提交
47 48 49
  UserName:     string,
  NickName:     string,
  DisplayName:  string,
50 51
}

52
export interface RoomRawObj {
L
lijiarui 已提交
53 54 55 56 57
  UserName:         string,
  EncryChatRoomId:  string,
  NickName:         string,
  OwnerUin:         number,
  ChatRoomOwner:    string,
58
  MemberList?:      RoomRawMember[],
59 60
}

61 62 63
export type RoomEventName = 'join'
                          | 'leave'
                          | 'topic'
64 65
                          | 'EVENT_PARAM_ERROR'

66
export interface RoomQueryFilter {
L
lijiarui 已提交
67
  topic: string | RegExp,
68 69
}

70
export interface MemberQueryFilter {
71 72 73 74
  name?:         string,
  alias?:        string,
  roomAlias?:    string,
  contactAlias?: string,
75 76
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77 78 79 80 81 82 83 84 85 86
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 * Add/Del/Topic: https://github.com/wechaty/wechaty/issues/32
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87
export class Room extends EventEmitter implements Sayable {
88 89
  private static pool = new Map<string, Room>()

90 91
  private dirtyObj: RoomObj | null // when refresh, use this to save dirty data for query
  private obj:      RoomObj | null
92 93
  private rawObj:   RoomRawObj

94
  constructor(public id: string) {
95
    super()
96
    log.silly('Room', `constructor(${id})`)
97
  }
98

99
  public toString()    { return this.id }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100
  public toStringEx()  { return `Room(${this.obj && this.obj.topic}[${this.id}])` }
101

102
  public isReady(): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103
    return !!(this.obj && this.obj.memberList && this.obj.memberList.length)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
104 105
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106
  public async refresh(): Promise<void> {
107 108 109
    if (this.isReady()) {
      this.dirtyObj = this.obj
    }
110
    this.obj = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
111 112
    await this.ready()
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113 114
  }

115
  private async readyAllMembers(memberList: RoomRawMember[]): Promise<void> {
116 117
    for (const member of memberList) {
      const contact = Contact.load(member.UserName)
118
      await contact.ready()
119 120 121 122
    }
    return
  }

123
  public async ready(contactGetter?: (id: string) => Promise<any>): Promise<Room> {
124
    log.silly('Room', 'ready(%s)', contactGetter ? contactGetter.constructor.name : '')
125
    if (!this.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126 127
      const e = new Error('ready() on a un-inited Room')
      log.warn('Room', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
128
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
129
    } else if (this.isReady()) {
130
      return this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131
    } else if (this.obj && this.obj.id) {
132
      log.warn('Room', 'ready() has obj.id but memberList empty in room %s. reloading', this.obj.topic)
133
    }
134

135 136 137 138 139 140 141 142
    if (!contactGetter) {
      contactGetter = Config.puppetInstance()
                            .getContact.bind(Config.puppetInstance())
    }
    if (!contactGetter) {
      throw new Error('no contactGetter')
    }

143 144
    try {
      const data = await contactGetter(this.id)
145
      log.silly('Room', `contactGetter(${this.id}) resolved`)
146
      this.rawObj = data
147
      await this.readyAllMembers(this.rawObj.MemberList || [])
148
      this.obj    = this.parse(this.rawObj)
149 150 151
      if (!this.obj) {
        throw new Error('no this.obj set after contactGetter')
      }
152
      await Promise.all(this.obj.memberList.map(c => c.ready(contactGetter)))
153

154
      return this
155

156
    } catch (e) {
157 158
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
159
    }
160 161
  }

162 163 164
  public on(event: 'leave', listener: (this: Room, leaver: 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
165
  public on(event: 'EVENT_PARAM_ERROR', listener: () => void): this
166

167
  public on(event: RoomEventName, listener: Function): this {
168
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
169

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
170 171 172 173 174 175 176 177 178 179 180
    // const thisWithSay = {
    //   say: (content: string) => {
    //     return Config.puppetInstance()
    //                   .say(content)
    //   }
    // }
    // super.on(event, function() {
    //   return listener.apply(thisWithSay, arguments)
    // })

    super.on(event, listener) // Room is `Sayable`
181
    return this
182 183
  }

184 185 186 187
  public say(mediaMessage: MediaMessage)
  public say(content: string)
  public say(content: string, replyTo: Contact)
  public say(content: string, replyTo: Contact[])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
188

189
  public say(textOrMedia: string | MediaMessage, replyTo?: Contact|Contact[]): Promise<boolean> {
M
Mukaiu 已提交
190
    const content = textOrMedia instanceof MediaMessage ? textOrMedia.filename() : textOrMedia
L
lijiarui 已提交
191 192 193
    log.verbose('Room', 'say(%s, %s)',
                        content,
                        Array.isArray(replyTo)
194
                        ? replyTo.map(c => c.name()).join(', ')
L
lijiarui 已提交
195
                        : replyTo ? replyTo.name() : '',
196
    )
197

M
Mukaiu 已提交
198 199 200
    let m
    if (typeof textOrMedia === 'string') {
      m = new Message()
201

M
Mukaiu 已提交
202
      const replyToList: Contact[] = [].concat(replyTo as any || [])
203

M
Mukaiu 已提交
204
      if (replyToList.length > 0) {
205 206
        const AT_SEPRATOR = String.fromCharCode(8197)
        const mentionList = replyToList.map(c => '@' + c.name()).join(AT_SEPRATOR)
M
Mukaiu 已提交
207 208 209 210 211 212 213 214 215
        m.content(mentionList + ' ' + content)
      } else {
        m.content(content)
      }
      // m.to(replyToList[0])
    } else
      m = textOrMedia

    m.room(this)
216 217 218 219 220

    return Config.puppetInstance()
                  .send(m)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221
  public get(prop): string { return (this.obj && this.obj[prop]) || (this.dirtyObj && this.dirtyObj[prop]) }
222

223
  private parse(rawObj: RoomRawObj): RoomObj | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
224
    if (!rawObj) {
225
      log.warn('Room', 'parse() on a empty rawObj?')
226
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227
    }
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
228

229 230 231
    const memberList = (rawObj.MemberList || [])
                        .map(m => Contact.load(m.UserName))

L
lijiarui 已提交
232
    const nameMap    = this.parseMap('name', rawObj.MemberList)
233 234
    const roomAliasMap   = this.parseMap('roomAlias', rawObj.MemberList)
    const contactAliasMap   = this.parseMap('contactAlias', rawObj.MemberList)
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
235

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
236
    return {
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
237 238 239 240 241
      id:         rawObj.UserName,
      encryId:    rawObj.EncryChatRoomId, // ???
      topic:      rawObj.NickName,
      ownerUin:   rawObj.OwnerUin,
      memberList,
242
      nameMap,
243 244
      roomAliasMap,
      contactAliasMap,
245 246 247
    }
  }

L
lijiarui 已提交
248
  private parseMap(parseContent: NameType, memberList?: RoomRawMember[]): Map<string, string> {
249
    const mapList: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
250
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
251
      memberList.forEach(member => {
252
        let tmpName: string
253
        const contact = Contact.load(member.UserName)
254
        switch (parseContent) {
ruiruibupt's avatar
2  
ruiruibupt 已提交
255
          case 'name':
256
            tmpName = contact.name()
257
            break
258
          case 'roomAlias':
L
lijiarui 已提交
259
            tmpName = member.DisplayName
260
            break
261 262 263
          case 'contactAlias':
            tmpName = contact.alias() || ''
            break
264 265 266
          default:
            throw new Error('parseMap failed, member not found')
        }
267 268
        /**
         * ISSUE #64 emoji need to be striped
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
269
         * ISSUE #104 never use remark name because sys group message will never use that
ruiruibupt's avatar
#217  
ruiruibupt 已提交
270
         * @rui: Wrong for 'never use remark name because sys group message will never use that', see more in the latest comment in #104
ruiruibupt's avatar
1  
ruiruibupt 已提交
271 272
         * @rui: webwx's NickName here return contactAlias, if not set contactAlias, return name
         * @rui: 2017-7-2 webwx's NickName just ruturn name, no contactAlias
273
         */
274
        mapList[member.UserName] = UtilLib.stripEmoji(tmpName)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
276
    }
277
    return mapList
278 279
  }

280
  public dumpRaw() {
281
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
282
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
283
  }
284
  public dump() {
285
    console.error('======= dump Room =======')
286
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
287 288
  }

Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
289
  public async add(contact: Contact): Promise<number> {
290
    log.verbose('Room', 'add(%s)', contact)
291 292 293 294 295

    if (!contact) {
      throw new Error('contact not found')
    }

Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
296 297 298
    const n = Config.puppetInstance()
                      .roomAdd(this, contact)
    return n
299 300
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
301
  public async del(contact: Contact): Promise<number> {
302
    log.verbose('Room', 'del(%s)', contact.name())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
303 304 305 306

    if (!contact) {
      throw new Error('contact not found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307
    const n = await Config.puppetInstance()
Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
308 309
                            .roomDel(this, contact)
                            .then(_ => this.delLocal(contact))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
310
    return n
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
311 312
  }

313
  private delLocal(contact: Contact): number {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314 315
    log.verbose('Room', 'delLocal(%s)', contact)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
316
    const memberList = this.obj && this.obj.memberList
317
    if (!memberList || memberList.length === 0) {
318
      return 0 // already in refreshing
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
319 320 321
    }

    let i
322 323
    for (i = 0; i < memberList.length; i++) {
      if (memberList[i].id === contact.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
324 325 326
        break
      }
    }
327 328
    if (i < memberList.length) {
      memberList.splice(i, 1)
329
      return 1
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
330
    }
331
    return 0
332
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
333

334
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
335 336
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
337
  }
338

339 340 341 342 343 344 345 346 347 348
  /**
   * get topic
   */
  public topic(): string
  /**
   * set topic
   */
  public topic(newTopic: string): void

  public topic(newTopic?: string): string | void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349
    if (!this.isReady()) {
350
      log.warn('Room', 'topic() room not ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
351 352
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
353 354
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
355
      Config.puppetInstance().roomTopic(this, newTopic)
356 357
                              .catch(e => {
                                log.warn('Room', 'topic(newTopic=%s) exception: %s',
L
lijiarui 已提交
358
                                                  newTopic, e && e.message || e,
359 360 361 362 363 364
                                )
                              })
      if (!this.obj) {
        this.obj = <RoomObj>{}
      }
      Object.assign(this.obj, { topic: newTopic })
365
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366
    }
367
    return UtilLib.plainText(this.obj ? this.obj.topic : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
368 369
  }

370 371 372 373
  /**
   * should be deprecated
   * @deprecated
   */
ruiruibupt's avatar
2  
ruiruibupt 已提交
374
  public nick(contact: Contact): string | null {
ruiruibupt's avatar
1  
ruiruibupt 已提交
375
    log.warn('Room', 'nick(Contact) DEPRECATED, use alias(Contact) instead.')
ruiruibupt's avatar
#217  
ruiruibupt 已提交
376
    return this.alias(contact)
377 378
  }

L
lijiarui 已提交
379
  /**
380
   * return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
381
   * @param {Contact} contact
382
   * @returns {string | null} If a contact has an alias in room, return string, otherwise return null
L
lijiarui 已提交
383
   */
ruiruibupt's avatar
2  
ruiruibupt 已提交
384
  public alias(contact: Contact): string | null {
385 386 387 388 389
    return this.roomAlias(contact)
  }

  public roomAlias(contact: Contact): string | null {
    if (!this.obj || !this.obj.roomAliasMap) {
ruiruibupt's avatar
2  
ruiruibupt 已提交
390
      return null
391
    }
392
    return this.obj.roomAliasMap[contact.id] || null
393 394
  }

395
  public has(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
396
    if (!this.obj || !this.obj.memberList) {
397 398 399 400 401 402 403
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

404
  public owner(): Contact | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
405
    const ownerUin = this.obj && this.obj.ownerUin
406

407
    const user = Config.puppetInstance()
408 409 410 411 412 413
                      .user

    if (user && user.get('uin') === ownerUin) {
      return user
    }

J
jaslin 已提交
414
    if (this.rawObj.ChatRoomOwner) {
415 416 417
      return Contact.load(this.rawObj.ChatRoomOwner)
    }

418
    log.info('Room', 'owner() is limited by Tencent API, sometimes work sometimes not')
419
    return null
420 421
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
422
  /**
423 424
   * find member by name | roomAlias(alias) | contactAlias
   * when use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
425
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
426 427
  public memberAll(name: string): Contact[]
  public memberAll(filter: MemberQueryFilter): Contact[]
428

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429
  public memberAll(queryArg: MemberQueryFilter | string): Contact[] {
430
    if (typeof queryArg === 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
      //
      // use the following `return` statement to do this job.
      //

      // const nameList = this.memberAll({name: queryArg})
      // const roomAliasList = this.memberAll({roomAlias: queryArg})
      // const contactAliasList = this.memberAll({contactAlias: queryArg})

      // if (nameList) {
      //   contactList = contactList.concat(nameList)
      // }
      // if (roomAliasList) {
      //   contactList = contactList.concat(roomAliasList)
      // }
      // if (contactAliasList) {
      //   contactList = contactList.concat(contactAliasList)
      // }

      return ([] as Contact[]).concat(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
450 451
        this.memberAll({name:         queryArg}),
        this.memberAll({roomAlias:    queryArg}),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
452 453
        this.memberAll({contactAlias: queryArg}),
      )
454 455
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
456 457 458
    /**
     * We got filter parameter
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
459
    log.silly('Room', 'memberAll({ %s })',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
460 461 462
                      Object.keys(queryArg)
                            .map(k => `${k}: ${queryArg[k]}`)
                            .join(', '),
463 464 465
            )

    if (Object.keys(queryArg).length !== 1) {
ruiruibupt's avatar
1  
ruiruibupt 已提交
466
      throw new Error('Room member find queryArg only support one key. multi key support is not availble now.')
467
    }
468

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
469
    if (!this.obj || !this.obj.memberList) {
470
      log.warn('Room', 'member() not ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
471
      return []
472
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473
    const filterKey            = Object.keys(queryArg)[0]
474 475 476
    /**
     * ISSUE #64 emoji need to be striped
     */
477
    const filterValue: string  = UtilLib.stripEmoji(queryArg[filterKey])
478 479

    const keyMap = {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
480
      contactAlias: 'contactAliasMap',
481 482
      name:         'nameMap',
      alias:        'roomAliasMap',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
483
      roomAlias:    'roomAliasMap',
484 485
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
486 487 488
    const filterMapName = keyMap[filterKey]
    if (!filterMapName) {
      throw new Error('unsupport filter key: ' + filterKey)
489 490 491 492 493
    }

    if (!filterValue) {
      throw new Error('filterValue not found')
    }
494

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
495
    const filterMap = this.obj[filterMapName]
496
    const idList = Object.keys(filterMap)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
497
                          .filter(id => filterMap[id] === filterValue)
498

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
499
    log.silly('Room', 'memberAll() check %s from %s: %s', filterValue, filterKey, JSON.stringify(filterMap))
500

501
    if (idList.length) {
502
      return idList.map(id => Contact.load(id))
503
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
504
      return []
505
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506 507
  }

508
  public member(name: string): Contact | null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
509
  public member(filter: MemberQueryFilter): Contact | null
510 511 512 513 514 515 516 517 518 519

  public member(queryArg: MemberQueryFilter | string): Contact | null {
    log.verbose('Room', 'member(%s)', JSON.stringify(queryArg))

    const memberList =  this.memberAll(queryArg)
    if (!memberList || !memberList.length) {
      return null
    }

    if (memberList.length > 1) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
520
      log.warn('Room', 'member(%s) get %d contacts, use the first one by default', JSON.stringify(queryArg), memberList.length)
521 522 523 524
    }
    return memberList[0]
  }

525
  public memberList(): Contact[] {
526
    log.verbose('Room', 'memberList')
527 528 529

    if (!this.obj || !this.obj.memberList || this.obj.memberList.length < 1) {
      log.warn('Room', 'memberList() not ready')
530 531 532 533
      log.verbose('Room', 'memberList() trying call refresh() to update')
      this.refresh().then(() => {
        log.verbose('Room', 'memberList() refresh() done')
      })
534
      return []
535 536 537 538
    }
    return this.obj.memberList
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
539
  public static create(contactList: Contact[], topic?: string): Promise<Room> {
540
    log.verbose('Room', 'create(%s, %s)', contactList.join(','), topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
541

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
542
    if (!contactList || !Array.isArray(contactList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
543 544
      throw new Error('contactList not found')
    }
545

546
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
547
                  .roomCreate(contactList, topic)
548 549 550
                  .catch(e => {
                    log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
                    throw e
551
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
552 553
  }

554 555 556 557
  public static async findAll(query?: RoomQueryFilter): Promise<Room[]> {
    if (!query) {
      query = { topic: /.*/ }
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
558
    log.verbose('Room', 'findAll({ topic: %s })', query.topic)
559

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
560
    let topicFilter = query.topic
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
561

562 563
    if (!topicFilter) {
      throw new Error('topicFilter not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
564 565
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
566 567
    let filterFunction: string

568
    if (topicFilter instanceof RegExp) {
569
      filterFunction = `(function (c) { return ${topicFilter.toString()}.test(c) })`
570
    } else if (typeof topicFilter === 'string') {
571
      topicFilter = topicFilter.replace(/'/g, '\\\'')
572
      filterFunction = `(function (c) { return c === '${topicFilter}' })`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
573
    } else {
574
      throw new Error('unsupport topic type')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
575 576
    }

577 578 579 580 581 582 583 584
    const roomList = await Config.puppetInstance()
                                  .roomFind(filterFunction)
                                  .catch(e => {
                                    log.verbose('Room', 'findAll() rejected: %s', e.message)
                                    return [] // fail safe
                                  })

    for (let i = 0; i < roomList.length; i++) {
585 586 587 588
      await roomList[i].ready()
    }

    return roomList
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
589 590
  }

591 592 593 594 595 596
  /**
   * try to find a room by filter: {topic: string | RegExp}
   * @param {RoomQueryFilter} query
   * @returns {Promise<Room | null>} If can find the room, return Room, or return null
   */
  public static async find(query: RoomQueryFilter): Promise<Room | null> {
597
    log.verbose('Room', 'find({ topic: %s })', query.topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
598

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
599 600
    const roomList = await Room.findAll(query)
    if (!roomList || roomList.length < 1) {
601
      return null
602 603
    } else if (roomList.length > 1) {
      log.warn('Room', 'find() got more than one result, return the 1st one.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
604
    }
605
    return roomList[0]
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
606 607
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
608 609 610
  /**
   * @todo document me
   */
611 612 613 614
  public static load(id: string): Room {
    if (!id) {
      throw new Error('Room.load() no id')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
615 616 617 618 619 620 621

    if (id in Room.pool) {
      return Room.pool[id]
    }
    return Room.pool[id] = new Room(id)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
622
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
623 624

export default Room