room.ts 11.6 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
8 9
 * Add/Del/Topic: https://github.com/wechaty/wechaty/issues/32
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
10
 */
11
import { EventEmitter } from 'events'
12
const arrify = require('arrify')
13

14 15 16
import {
    Config
  , Sayable
17
  , log
18
}                 from './config'
19 20 21
import { Contact }    from './contact'
import { Message }    from './message'
import { UtilLib }    from './util-lib'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
22

23 24 25 26 27 28 29 30 31
type RoomObj = {
  id:         string
  encryId:    string
  topic:      string
  ownerUin:   number
  memberList: Contact[]
  nickMap:    Map<string, string>
}

32
export type RoomRawMember = {
33 34 35 36
  UserName:     string
  DisplayName:  string
}

37
export type RoomRawObj = {
38 39 40 41
  UserName:         string
  EncryChatRoomId:  string
  NickName:         string
  OwnerUin:         number
42
  MemberList:       RoomRawMember[]
43 44
}

45 46 47
export type RoomEventName = 'join'
                          | 'leave'
                          | 'topic'
48 49
                          | 'EVENT_PARAM_ERROR'

50
export type RoomQueryFilter = {
51 52 53
  topic: string | RegExp
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54
export class Room extends EventEmitter implements Sayable {
55 56
  private static pool = new Map<string, Room>()

57 58
  private dirtyObj: RoomObj | null // when refresh, use this to save dirty data for query
  private obj:      RoomObj | null
59 60
  private rawObj:   RoomRawObj

61
  constructor(public id: string) {
62
    super()
63
    log.silly('Room', `constructor(${id})`)
64
  }
65

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

69
  public isReady(): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70
    return !!(this.obj && this.obj.memberList && this.obj.memberList.length)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71 72
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
73
  public async refresh(): Promise<void> {
74 75 76
    if (this.isReady()) {
      this.dirtyObj = this.obj
    }
77
    this.obj = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
78 79
    await this.ready()
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80 81
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
82
  public async ready(contactGetter?: (id: string) => Promise<any>): Promise<void> {
83
    log.silly('Room', 'ready(%s)', contactGetter ? contactGetter.constructor.name : '')
84
    if (!this.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85 86
      const e = new Error('ready() on a un-inited Room')
      log.warn('Room', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
    } else if (this.isReady()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90
    } else if (this.obj && this.obj.id) {
91
      log.warn('Room', 'ready() has obj.id but memberList empty in room %s. reloading', this.obj.topic)
92
    }
93

94 95 96 97 98 99 100 101
    if (!contactGetter) {
      contactGetter = Config.puppetInstance()
                            .getContact.bind(Config.puppetInstance())
    }
    if (!contactGetter) {
      throw new Error('no contactGetter')
    }

102 103
    try {
      const data = await contactGetter(this.id)
104
      log.silly('Room', `contactGetter(${this.id}) resolved`)
105 106
      this.rawObj = data
      this.obj    = this.parse(data)
107

108 109 110
      if (!this.obj) {
        throw new Error('no this.obj set after contactGetter')
      }
111
      await Promise.all(this.obj.memberList.map(c => c.ready(contactGetter)))
112

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113
      return
114

115
    } catch (e) {
116 117
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
118
    }
119 120
  }

121 122 123
  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
124
  public on(event: 'EVENT_PARAM_ERROR', listener: () => void): this
125

126
  public on(event: RoomEventName, listener: Function): this {
127
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
128

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
129 130 131 132 133 134 135 136 137 138 139
    // 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`
140
    return this
141 142
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143 144 145 146
  public say(content: string): Promise<any> {
  public say(content: string, replyTo: Contact): Promise<any> {
  public say(content: string, replyTo: Contact[]): Promise<any> {

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147
  public say(content: string, replyTo?: Contact|Contact[]): Promise<any> {
148 149 150 151
    log.verbose('Room', 'say(%s, %s)'
                      , content
                      , Array.isArray(replyTo)
                        ? replyTo.map(c => c.name()).join(', ')
152
                        : replyTo ? replyTo.name() : ''
153
    )
154 155 156 157

    const m = new Message()
    m.room(this)

158 159
    const replyToList: Contact[] = arrify(replyTo)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160 161 162 163 164 165 166
    if (replyToList.length > 0) {
      const mentionList = replyToList.map(c => '@' + c.name()).join(' ')
      m.content(mentionList + ' ' + content)
    } else {
      m.content(content)
    }
    // m.to(replyToList[0])
167 168 169 170 171

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

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

174
  private parse(rawObj: RoomRawObj): RoomObj | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
    if (!rawObj) {
176
      log.warn('Room', 'parse() on a empty rawObj?')
177
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178 179
    }
    return {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180 181 182 183 184
      id:           rawObj.UserName
      , encryId:    rawObj.EncryChatRoomId // ???
      , topic:      rawObj.NickName
      , ownerUin:   rawObj.OwnerUin

185 186
      , memberList: this.parseMemberList(rawObj.MemberList)
      , nickMap:    this.parseNickMap(rawObj.MemberList)
187 188 189
    }
  }

190 191
  private parseMemberList(rawMemberList: RoomRawMember[]): Contact[] {
    if (!rawMemberList || !rawMemberList.map) {
192 193
      return []
    }
194
    return rawMemberList.map(m => Contact.load(m.UserName))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195 196
  }

197 198
  private parseNickMap(memberList): Map<string, string> {
    const nickMap: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
199
    let contact, remark
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
201
      memberList.forEach(m => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202 203 204 205 206 207
        contact = Contact.load(m.UserName)
        if (contact) {
          remark = contact.remark()
        } else {
          remark = null
        }
208 209 210 211 212

        /**
         * ISSUE #64 emoji need to be striped
         */
        nickMap[m.UserName] = UtilLib.stripEmoji(
213 214
          remark || m.DisplayName || m.NickName
        )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216 217
    }
    return nickMap
218 219
  }

220
  public dumpRaw() {
221
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
223
  }
224
  public dump() {
225
    console.error('======= dump Room =======')
226
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
227 228
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
229
  public async add(contact: Contact): Promise<any> {
230
    log.verbose('Room', 'add(%s)', contact)
231 232 233 234 235

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
236 237 238
    await Config.puppetInstance()
                .roomAdd(this, contact)
    return
239 240
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
241
  public async del(contact: Contact): Promise<number> {
242
    log.verbose('Room', 'del(%s)', contact.name())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
243 244 245 246

    if (!contact) {
      throw new Error('contact not found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247
    const n = await Config.puppetInstance()
248
                  .roomDel(this, contact)
249
                  .then(_ => this.delLocal(contact))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
250
    return n
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
251 252
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256
    const memberList = this.obj && this.obj.memberList
257
    if (!memberList || memberList.length === 0) {
258
      return 0 // already in refreshing
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
259 260 261
    }

    let i
262 263
    for (i = 0; i < memberList.length; i++) {
      if (memberList[i].id === contact.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
264 265 266
        break
      }
    }
267 268
    if (i < memberList.length) {
      memberList.splice(i, 1)
269
      return 1
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270
    }
271
    return 0
272
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
273

274
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275 276
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
277
  }
278

279 280 281 282 283 284 285 286 287 288
  /**
   * get topic
   */
  public topic(): string
  /**
   * set topic
   */
  public topic(newTopic: string): void

  public topic(newTopic?: string): string | void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
289 290 291 292
    if (!this.isReady()) {
      throw new Error('room not ready')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
293 294 295
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
296

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
297
    if (newTopic) {
298
      Config.puppetInstance().roomTopic(this, newTopic)
299
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300
    }
301
    return UtilLib.plainText(this.obj ? this.obj.topic : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
302 303
  }

304
  public nick(contact: Contact): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
305
    if (!this.obj || !this.obj.nickMap) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
306 307
      return ''
    }
308 309 310
    return this.obj.nickMap[contact.id]
  }

311
  public has(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
312
    if (!this.obj || !this.obj.memberList) {
313 314 315 316 317 318 319
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

320
  public owner(): Contact | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
321 322
    const ownerUin = this.obj && this.obj.ownerUin
    let memberList = (this.obj && this.obj.memberList) || []
323 324 325 326 327 328 329 330

    let user = Config.puppetInstance()
                      .user

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

331
    memberList = memberList.filter(m => m.get('uin') === ownerUin)
332 333 334 335 336 337 338
    if (memberList.length > 0) {
      return memberList[0]
    } else {
      return null
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
339 340 341
  /**
   * NickName / DisplayName / RemarkName of member
   */
342
  public member(name: string): Contact | null {
343 344
    log.verbose('Room', 'member(%s)', name)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345
    if (!this.obj || !this.obj.memberList) {
346
      log.warn('Room', 'member() not ready')
347 348
      return null
    }
349

350 351 352 353
    /**
     * ISSUE #64 emoji need to be striped
     */
    name = UtilLib.stripEmoji(name)
354

355 356 357
    const nickMap = this.obj.nickMap
    const idList = Object.keys(nickMap)
                          .filter(k => nickMap[k] === name)
358 359 360

    log.silly('Room', 'member() check nickMap: %s', JSON.stringify(nickMap))

361 362 363 364 365
    if (idList.length) {
      return Contact.load(idList[0])
    } else {
      return null
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366 367
  }

368
  public memberList(): Contact[] {
369
    log.verbose('Room', 'memberList')
370 371 372

    if (!this.obj || !this.obj.memberList || this.obj.memberList.length < 1) {
      log.warn('Room', 'memberList() not ready')
373
      return []
374 375 376 377
    }
    return this.obj.memberList
  }

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

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
381
    if (!contactList || !Array.isArray(contactList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
382 383
      throw new Error('contactList not found')
    }
384

385
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
386
                  .roomCreate(contactList, topic)
387 388 389
                  .catch(e => {
                    log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
                    throw e
390
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
391 392
  }

393
  public static async findAll(query: RoomQueryFilter): Promise<Room[]> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
394
    log.verbose('Room', 'findAll({ topic: %s })', query.topic)
395 396

    const topic = query.topic
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397

398 399
    if (!topic) {
      throw new Error('topic not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
400 401
    }

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

404 405 406 407
    if (topic instanceof RegExp) {
      filterFunction = `c => ${topic.toString()}.test(c)`
    } else if (typeof topic === 'string') {
      filterFunction = `c => c === '${topic}'`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
408
    } else {
409
      throw new Error('unsupport topic type')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
410 411
    }

412 413 414
    return Config.puppetInstance()
                  .roomFind(filterFunction)
                  .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415
                    log.verbose('Room', 'findAll() rejected: %s', e.message)
416 417
                    return [] // fail safe
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
418 419
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420
  public static async find(query: RoomQueryFilter): Promise<Room> {
421
    log.verbose('Room', 'find({ topic: %s })', query.topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
422

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
423 424 425 426
    const roomList = await Room.findAll(query)
    if (!roomList || roomList.length < 1) {
      throw new Error('no room found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
427 428 429
    const room = roomList[0]
    await room.ready()
    return room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
430 431
  }

432
  public static load(id: string): Room | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
433 434 435 436 437 438 439 440
    if (!id) { return null }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
441
}