room.ts 11.5 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
  }

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

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

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

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

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

112
      return this
113

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

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

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

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

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

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

    if (!replyTo) {
      m.content(content)
      m.to(this)
      return Config.puppetInstance()
                    .send(m)
    }

160 161 162 163 164
    const replyToList: Contact[] = arrify(replyTo)
    let mentionList: string

    m.to(replyToList[0])
    mentionList = replyToList.map(c => '@' + c.name()).join(' ')
165 166 167 168 169 170

    m.content(mentionList + ' ' + content)
    return Config.puppetInstance()
                  .send(m)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    let user = Config.puppetInstance()
                      .user

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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