room.ts 18.4 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 {
22
  config,
23
  Raven,
L
lijiarui 已提交
24 25
  Sayable,
  log,
M
Mukaiu 已提交
26
}                     from './config'
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
27
import Contact        from './contact'
M
Mukaiu 已提交
28 29 30 31
import {
  Message,
  MediaMessage,
}                     from './message'
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
32
import UtilLib        from './util-lib'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33

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

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

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

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

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

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
78 79 80 81 82 83 84 85 86 87
/**
 *
 * 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 (李卓桓) 已提交
88
export class Room extends EventEmitter implements Sayable {
89 90
  private static pool = new Map<string, Room>()

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

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

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

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

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

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

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

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

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

155
      return this
156

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

164 165 166
  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
167
  public on(event: 'EVENT_PARAM_ERROR', listener: () => void): this
168

169
  public on(event: RoomEventName, listener: (...args: any[]) => any): this {
170
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
171

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
172
    super.on(event, listener) // Room is `Sayable`
173
    return this
174 175
  }

176 177 178 179
  public say(mediaMessage: MediaMessage)
  public say(content: string)
  public say(content: string, replyTo: Contact)
  public say(content: string, replyTo: Contact[])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180

181
  public say(textOrMedia: string | MediaMessage, replyTo?: Contact|Contact[]): Promise<boolean> {
M
Mukaiu 已提交
182
    const content = textOrMedia instanceof MediaMessage ? textOrMedia.filename() : textOrMedia
L
lijiarui 已提交
183 184 185
    log.verbose('Room', 'say(%s, %s)',
                        content,
                        Array.isArray(replyTo)
186
                        ? replyTo.map(c => c.name()).join(', ')
L
lijiarui 已提交
187
                        : replyTo ? replyTo.name() : '',
188
    )
189

M
Mukaiu 已提交
190 191 192
    let m
    if (typeof textOrMedia === 'string') {
      m = new Message()
193

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

M
Mukaiu 已提交
196
      if (replyToList.length > 0) {
197 198
        const AT_SEPRATOR = String.fromCharCode(8197)
        const mentionList = replyToList.map(c => '@' + c.name()).join(AT_SEPRATOR)
M
Mukaiu 已提交
199 200 201 202 203 204 205 206 207
        m.content(mentionList + ' ' + content)
      } else {
        m.content(content)
      }
      // m.to(replyToList[0])
    } else
      m = textOrMedia

    m.room(this)
208

209
    return config.puppetInstance()
210 211 212
                  .send(m)
  }

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

215
  private parse(rawObj: RoomRawObj): RoomObj | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216
    if (!rawObj) {
217
      log.warn('Room', 'parse() on a empty rawObj?')
218
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
219
    }
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
220

221 222 223
    const memberList = (rawObj.MemberList || [])
                        .map(m => Contact.load(m.UserName))

L
lijiarui 已提交
224
    const nameMap    = this.parseMap('name', rawObj.MemberList)
225 226
    const roomAliasMap   = this.parseMap('roomAlias', rawObj.MemberList)
    const contactAliasMap   = this.parseMap('contactAlias', rawObj.MemberList)
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
227

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
228
    return {
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
229 230 231 232 233
      id:         rawObj.UserName,
      encryId:    rawObj.EncryChatRoomId, // ???
      topic:      rawObj.NickName,
      ownerUin:   rawObj.OwnerUin,
      memberList,
234
      nameMap,
235 236
      roomAliasMap,
      contactAliasMap,
237 238 239
    }
  }

L
lijiarui 已提交
240
  private parseMap(parseContent: NameType, memberList?: RoomRawMember[]): Map<string, string> {
241
    const mapList: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
#104  
Huan (李卓桓) 已提交
243
      memberList.forEach(member => {
244
        let tmpName: string
245
        const contact = Contact.load(member.UserName)
246
        switch (parseContent) {
ruiruibupt's avatar
2  
ruiruibupt 已提交
247
          case 'name':
248
            tmpName = contact.name()
249
            break
250
          case 'roomAlias':
L
lijiarui 已提交
251
            tmpName = member.DisplayName
252
            break
253 254 255
          case 'contactAlias':
            tmpName = contact.alias() || ''
            break
256 257 258
          default:
            throw new Error('parseMap failed, member not found')
        }
259 260
        /**
         * ISSUE #64 emoji need to be striped
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
261
         * ISSUE #104 never use remark name because sys group message will never use that
ruiruibupt's avatar
#217  
ruiruibupt 已提交
262
         * @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 已提交
263 264
         * @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
265
         */
266
        mapList[member.UserName] = UtilLib.stripEmoji(tmpName)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268
    }
269
    return mapList
270 271
  }

272
  public dumpRaw() {
273
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
274
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
275
  }
276
  public dump() {
277
    console.error('======= dump Room =======')
278
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
279 280
  }

Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
281
  public async add(contact: Contact): Promise<number> {
282
    log.verbose('Room', 'add(%s)', contact)
283 284 285 286 287

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

288
    const n = config.puppetInstance()
Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
289 290
                      .roomAdd(this, contact)
    return n
291 292
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
293
  public async del(contact: Contact): Promise<number> {
294
    log.verbose('Room', 'del(%s)', contact.name())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
295 296 297 298

    if (!contact) {
      throw new Error('contact not found')
    }
299
    const n = await config.puppetInstance()
Huan (李卓桓)'s avatar
#119  
Huan (李卓桓) 已提交
300 301
                            .roomDel(this, contact)
                            .then(_ => this.delLocal(contact))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
302
    return n
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
303 304
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
308
    const memberList = this.obj && this.obj.memberList
309
    if (!memberList || memberList.length === 0) {
310
      return 0 // already in refreshing
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
311 312 313
    }

    let i
314 315
    for (i = 0; i < memberList.length; i++) {
      if (memberList[i].id === contact.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
316 317 318
        break
      }
    }
319 320
    if (i < memberList.length) {
      memberList.splice(i, 1)
321
      return 1
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
322
    }
323
    return 0
324
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
325

326
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327 328
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
329
  }
330

331 332 333 334 335 336 337 338 339 340
  /**
   * get topic
   */
  public topic(): string
  /**
   * set topic
   */
  public topic(newTopic: string): void

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345 346
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
347
      config.puppetInstance()
348 349 350 351 352
            .roomTopic(this, newTopic)
            .catch(e => {
              log.warn('Room', 'topic(newTopic=%s) exception: %s',
                                newTopic, e && e.message || e,
                      )
353
              Raven.captureException(e)
354
            })
355 356 357 358
      if (!this.obj) {
        this.obj = <RoomObj>{}
      }
      Object.assign(this.obj, { topic: newTopic })
359
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
360
    }
361
    return UtilLib.plainText(this.obj ? this.obj.topic : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
362 363
  }

364 365 366 367
  /**
   * should be deprecated
   * @deprecated
   */
ruiruibupt's avatar
2  
ruiruibupt 已提交
368
  public nick(contact: Contact): string | null {
ruiruibupt's avatar
1  
ruiruibupt 已提交
369
    log.warn('Room', 'nick(Contact) DEPRECATED, use alias(Contact) instead.')
ruiruibupt's avatar
#217  
ruiruibupt 已提交
370
    return this.alias(contact)
371 372
  }

L
lijiarui 已提交
373
  /**
374
   * return contact's roomAlias in the room, the same as roomAlias
L
lijiarui 已提交
375
   * @param {Contact} contact
376
   * @returns {string | null} If a contact has an alias in room, return string, otherwise return null
L
lijiarui 已提交
377
   */
ruiruibupt's avatar
2  
ruiruibupt 已提交
378
  public alias(contact: Contact): string | null {
379 380 381 382 383
    return this.roomAlias(contact)
  }

  public roomAlias(contact: Contact): string | null {
    if (!this.obj || !this.obj.roomAliasMap) {
ruiruibupt's avatar
2  
ruiruibupt 已提交
384
      return null
385
    }
386
    return this.obj.roomAliasMap[contact.id] || null
387 388
  }

389
  public has(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
390
    if (!this.obj || !this.obj.memberList) {
391 392 393 394 395 396 397
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

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

401
    const user = config.puppetInstance()
402 403 404 405 406 407
                      .user

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

J
jaslin 已提交
408
    if (this.rawObj.ChatRoomOwner) {
409 410 411
      return Contact.load(this.rawObj.ChatRoomOwner)
    }

412
    log.info('Room', 'owner() is limited by Tencent API, sometimes work sometimes not')
413
    return null
414 415
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
416
  /**
417 418
   * find member by name | roomAlias(alias) | contactAlias
   * when use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420
  public memberAll(filter: MemberQueryFilter): Contact[]
421
  public memberAll(name: string): Contact[]
422

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423
  public memberAll(queryArg: MemberQueryFilter | string): Contact[] {
424
    if (typeof queryArg === 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
      //
      // 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 (李卓桓) 已提交
444 445
        this.memberAll({name:         queryArg}),
        this.memberAll({roomAlias:    queryArg}),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
446 447
        this.memberAll({contactAlias: queryArg}),
      )
448 449
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
450 451 452
    /**
     * We got filter parameter
     */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453
    log.silly('Room', 'memberAll({ %s })',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
454 455 456
                      Object.keys(queryArg)
                            .map(k => `${k}: ${queryArg[k]}`)
                            .join(', '),
457 458 459
            )

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

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

    const keyMap = {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
474
      contactAlias: 'contactAliasMap',
475 476
      name:         'nameMap',
      alias:        'roomAliasMap',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
477
      roomAlias:    'roomAliasMap',
478 479
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
480 481 482
    const filterMapName = keyMap[filterKey]
    if (!filterMapName) {
      throw new Error('unsupport filter key: ' + filterKey)
483 484 485 486 487
    }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
489
    const filterMap = this.obj[filterMapName]
490
    const idList = Object.keys(filterMap)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
491
                          .filter(id => filterMap[id] === filterValue)
492

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

495
    if (idList.length) {
496
      return idList.map(id => Contact.load(id))
497
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
498
      return []
499
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
500 501
  }

502
  public member(name: string): Contact | null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503
  public member(filter: MemberQueryFilter): Contact | null
504 505 506 507

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

508 509 510 511 512 513 514 515 516
    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)
    }

517 518 519 520 521
    if (!memberList || !memberList.length) {
      return null
    }

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

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

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

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

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

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

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

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

565 566
    if (!topicFilter) {
      throw new Error('topicFilter not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
567 568
    }

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

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

580
    const roomList = await config.puppetInstance()
581 582 583
                                  .roomFind(filterFunction)
                                  .catch(e => {
                                    log.verbose('Room', 'findAll() rejected: %s', e.message)
584
                                    Raven.captureException(e)
585 586 587 588
                                    return [] // fail safe
                                  })

    for (let i = 0; i < roomList.length; i++) {
589 590 591 592
      await roomList[i].ready()
    }

    return roomList
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
593 594
  }

595 596 597 598 599 600
  /**
   * 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> {
601
    log.verbose('Room', 'find({ topic: %s })', query.topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
602

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

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
626
}
Huan (李卓桓)'s avatar
merge  
Huan (李卓桓) 已提交
627 628

export default Room