room.ts 11.4 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
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
176 177
    }
    return {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178 179 180 181 182
      id:           rawObj.UserName
      , encryId:    rawObj.EncryChatRoomId // ???
      , topic:      rawObj.NickName
      , ownerUin:   rawObj.OwnerUin

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    let user = Config.puppetInstance()
                      .user

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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