room.ts 12.1 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
  ChatRoomOwner:    string
43
  MemberList:       RoomRawMember[]
44 45
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294 295
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
296
      Config.puppetInstance().roomTopic(this, newTopic)
297 298 299 300 301 302 303 304 305
                              .catch(e => {
                                log.warn('Room', 'topic(newTopic=%s) exception: %s',
                                                  newTopic, e && e.message || e
                                )
                              })
      if (!this.obj) {
        this.obj = <RoomObj>{}
      }
      Object.assign(this.obj, { topic: newTopic })
306
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
307
    }
308
    return UtilLib.plainText(this.obj ? this.obj.topic : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
309 310
  }

311
  public nick(contact: Contact): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
312
    if (!this.obj || !this.obj.nickMap) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
313 314
      return ''
    }
315 316 317
    return this.obj.nickMap[contact.id]
  }

318
  public has(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
319
    if (!this.obj || !this.obj.memberList) {
320 321 322 323 324 325 326
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

327
  public owner(): Contact | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
328 329
    const ownerUin = this.obj && this.obj.ownerUin
    let memberList = (this.obj && this.obj.memberList) || []
330 331 332 333 334 335 336 337

    let user = Config.puppetInstance()
                      .user

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

338
    memberList = memberList.filter(m => m.get('uin') === ownerUin)
339 340 341
    if (memberList.length > 0) {
      return memberList[0]
    }
J
jaslin 已提交
342 343

    if (this.rawObj.ChatRoomOwner) {
344 345 346 347
      return Contact.load(this.rawObj.ChatRoomOwner)
    }

    return null
348 349
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
350 351 352
  /**
   * NickName / DisplayName / RemarkName of member
   */
353
  public member(name: string): Contact | null {
354 355
    log.verbose('Room', 'member(%s)', name)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356
    if (!this.obj || !this.obj.memberList) {
357
      log.warn('Room', 'member() not ready')
358 359
      return null
    }
360

361 362 363 364
    /**
     * ISSUE #64 emoji need to be striped
     */
    name = UtilLib.stripEmoji(name)
365

366 367 368
    const nickMap = this.obj.nickMap
    const idList = Object.keys(nickMap)
                          .filter(k => nickMap[k] === name)
369 370 371

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

372 373 374 375 376
    if (idList.length) {
      return Contact.load(idList[0])
    } else {
      return null
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
377 378
  }

379
  public memberList(): Contact[] {
380
    log.verbose('Room', 'memberList')
381 382 383

    if (!this.obj || !this.obj.memberList || this.obj.memberList.length < 1) {
      log.warn('Room', 'memberList() not ready')
384
      return []
385 386 387 388
    }
    return this.obj.memberList
  }

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

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
392
    if (!contactList || !Array.isArray(contactList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
393 394
      throw new Error('contactList not found')
    }
395

396
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397
                  .roomCreate(contactList, topic)
398 399 400
                  .catch(e => {
                    log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
                    throw e
401
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
402 403
  }

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

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

409 410
    if (!topicFilter) {
      throw new Error('topicFilter not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
411 412
    }

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

415
    if (topicFilter instanceof RegExp) {
416
      filterFunction = `(function (c) { return ${topicFilter.toString()}.test(c) })`
417
    } else if (typeof topicFilter === 'string') {
418
      filterFunction = `(function (c) { return c === '${topicFilter}' })`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419
    } else {
420
      throw new Error('unsupport topic type')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
421 422
    }

423 424 425
    return Config.puppetInstance()
                  .roomFind(filterFunction)
                  .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
426
                    log.verbose('Room', 'findAll() rejected: %s', e.message)
427 428
                    return [] // fail safe
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429 430
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
434 435 436 437
    const roomList = await Room.findAll(query)
    if (!roomList || roomList.length < 1) {
      throw new Error('no room found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
438 439 440
    const room = roomList[0]
    await room.ready()
    return room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
441 442
  }

443 444 445 446
  public static load(id: string): Room {
    if (!id) {
      throw new Error('Room.load() no id')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
447 448 449 450 451 452 453

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

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