room.ts 12.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
  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 75 76 77 78
  // public refresh() {
  //   log.warn('Room', 'refresh() DEPRECATED. use reload() instead.')
  //   return this.reload()
  // }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
79
  public async refresh(): Promise<void> {
80 81 82
    if (this.isReady()) {
      this.dirtyObj = this.obj
    }
83
    this.obj = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84 85
    await this.ready()
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86 87
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88 89 90 91 92
  // public ready(contactGetter?: (id: string) => Promise<any>) {
  //   log.warn('Room', 'ready() DEPRECATED. use load() instad.')
  //   return this.load(contactGetter)
  // }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
93
  public async ready(contactGetter?: (id: string) => Promise<any>): Promise<void> {
94
    log.silly('Room', 'ready(%s)', contactGetter ? contactGetter.constructor.name : '')
95
    if (!this.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96 97
      const e = new Error('ready() on a un-inited Room')
      log.warn('Room', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
99
    } else if (this.isReady()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
101
    } else if (this.obj && this.obj.id) {
102
      log.warn('Room', 'ready() has obj.id but memberList empty in room %s. reloading', this.obj.topic)
103
    }
104

105 106 107 108 109 110 111 112
    if (!contactGetter) {
      contactGetter = Config.puppetInstance()
                            .getContact.bind(Config.puppetInstance())
    }
    if (!contactGetter) {
      throw new Error('no contactGetter')
    }

113 114
    try {
      const data = await contactGetter(this.id)
115
      log.silly('Room', `contactGetter(${this.id}) resolved`)
116 117
      this.rawObj = data
      this.obj    = this.parse(data)
118

119 120 121
      if (!this.obj) {
        throw new Error('no this.obj set after contactGetter')
      }
122
      await Promise.all(this.obj.memberList.map(c => c.ready(contactGetter)))
123

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124
      return
125

126
    } catch (e) {
127 128
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
129
    }
130 131
  }

132 133 134
  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
135
  public on(event: 'EVENT_PARAM_ERROR', listener: () => void): this
136

137
  public on(event: RoomEventName, listener: Function): this {
138
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
139

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
140 141 142 143 144 145 146 147 148 149 150
    // 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`
151
    return this
152 153
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
154 155 156
  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 (李卓桓) 已提交
157

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
158
  public say(content: string, replyTo?: Contact|Contact[]): Promise<void> {
159 160 161 162
    log.verbose('Room', 'say(%s, %s)'
                      , content
                      , Array.isArray(replyTo)
                        ? replyTo.map(c => c.name()).join(', ')
163
                        : replyTo ? replyTo.name() : ''
164
    )
165 166 167 168

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

169 170
    const replyToList: Contact[] = arrify(replyTo)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
171 172 173 174 175 176 177
    if (replyToList.length > 0) {
      const mentionList = replyToList.map(c => '@' + c.name()).join(' ')
      m.content(mentionList + ' ' + content)
    } else {
      m.content(content)
    }
    // m.to(replyToList[0])
178 179 180 181 182

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

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

185
  private parse(rawObj: RoomRawObj): RoomObj | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186
    if (!rawObj) {
187
      log.warn('Room', 'parse() on a empty rawObj?')
188
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189 190
    }
    return {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
191 192 193 194 195
      id:           rawObj.UserName
      , encryId:    rawObj.EncryChatRoomId // ???
      , topic:      rawObj.NickName
      , ownerUin:   rawObj.OwnerUin

196 197
      , memberList: this.parseMemberList(rawObj.MemberList)
      , nickMap:    this.parseNickMap(rawObj.MemberList)
198 199 200
    }
  }

201 202
  private parseMemberList(rawMemberList: RoomRawMember[]): Contact[] {
    if (!rawMemberList || !rawMemberList.map) {
203 204
      return []
    }
205
    return rawMemberList.map(m => Contact.load(m.UserName))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206 207
  }

208 209
  private parseNickMap(memberList): Map<string, string> {
    const nickMap: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
210
    let contact, remark
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
212
      memberList.forEach(m => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213 214 215 216 217 218
        contact = Contact.load(m.UserName)
        if (contact) {
          remark = contact.remark()
        } else {
          remark = null
        }
219 220 221 222 223

        /**
         * ISSUE #64 emoji need to be striped
         */
        nickMap[m.UserName] = UtilLib.stripEmoji(
224 225
          remark || m.DisplayName || m.NickName
        )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228
    }
    return nickMap
229 230
  }

231
  public dumpRaw() {
232
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
233
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
234
  }
235
  public dump() {
236
    console.error('======= dump Room =======')
237
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj && this.obj[k]}`))
238 239
  }

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247 248 249
    await Config.puppetInstance()
                .roomAdd(this, contact)
    return
250 251
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252
  public async del(contact: Contact): Promise<number> {
253
    log.verbose('Room', 'del(%s)', contact.name())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254 255 256 257

    if (!contact) {
      throw new Error('contact not found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
258
    const n = await Config.puppetInstance()
259
                  .roomDel(this, contact)
260
                  .then(_ => this.delLocal(contact))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
261
    return n
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
262 263
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267
    const memberList = this.obj && this.obj.memberList
268
    if (!memberList || memberList.length === 0) {
269
      return 0 // already in refreshing
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270 271 272
    }

    let i
273 274
    for (i = 0; i < memberList.length; i++) {
      if (memberList[i].id === contact.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275 276 277
        break
      }
    }
278 279
    if (i < memberList.length) {
      memberList.splice(i, 1)
280
      return 1
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
281
    }
282
    return 0
283
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
284

285
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
286 287
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
288
  }
289

290 291 292 293 294 295 296 297 298 299
  /**
   * get topic
   */
  public topic(): string
  /**
   * set topic
   */
  public topic(newTopic: string): void

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
304 305
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
306
      Config.puppetInstance().roomTopic(this, newTopic)
307 308 309 310 311 312 313 314 315
                              .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 })
316
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
317
    }
318
    return UtilLib.plainText(this.obj ? this.obj.topic : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
319 320
  }

321
  public nick(contact: Contact): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
322
    if (!this.obj || !this.obj.nickMap) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
323 324
      return ''
    }
325 326 327
    return this.obj.nickMap[contact.id]
  }

328
  public has(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
329
    if (!this.obj || !this.obj.memberList) {
330 331 332 333 334 335 336
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

337
  public owner(): Contact | null {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
338 339
    const ownerUin = this.obj && this.obj.ownerUin
    let memberList = (this.obj && this.obj.memberList) || []
340 341 342 343 344 345 346 347

    let user = Config.puppetInstance()
                      .user

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

348
    memberList = memberList.filter(m => m.get('uin') === ownerUin)
349 350 351
    if (memberList.length > 0) {
      return memberList[0]
    }
J
jaslin 已提交
352 353

    if (this.rawObj.ChatRoomOwner) {
354 355 356 357
      return Contact.load(this.rawObj.ChatRoomOwner)
    }

    return null
358 359
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
360 361 362
  /**
   * NickName / DisplayName / RemarkName of member
   */
363
  public member(name: string): Contact | null {
364 365
    log.verbose('Room', 'member(%s)', name)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
366
    if (!this.obj || !this.obj.memberList) {
367
      log.warn('Room', 'member() not ready')
368 369
      return null
    }
370

371 372 373 374
    /**
     * ISSUE #64 emoji need to be striped
     */
    name = UtilLib.stripEmoji(name)
375

376 377 378
    const nickMap = this.obj.nickMap
    const idList = Object.keys(nickMap)
                          .filter(k => nickMap[k] === name)
379 380 381

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

382 383 384 385 386
    if (idList.length) {
      return Contact.load(idList[0])
    } else {
      return null
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
387 388
  }

389
  public memberList(): Contact[] {
390
    log.verbose('Room', 'memberList')
391 392 393

    if (!this.obj || !this.obj.memberList || this.obj.memberList.length < 1) {
      log.warn('Room', 'memberList() not ready')
394
      return []
395 396 397 398
    }
    return this.obj.memberList
  }

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

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
402
    if (!contactList || !Array.isArray(contactList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
403 404
      throw new Error('contactList not found')
    }
405

406
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
407
                  .roomCreate(contactList, topic)
408 409 410
                  .catch(e => {
                    log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
                    throw e
411
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
412 413
  }

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

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

419 420
    if (!topicFilter) {
      throw new Error('topicFilter not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
421 422
    }

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

425
    if (topicFilter instanceof RegExp) {
426
      filterFunction = `(function (c) { return ${topicFilter.toString()}.test(c) })`
427
    } else if (typeof topicFilter === 'string') {
428
      filterFunction = `(function (c) { return c === '${topicFilter}' })`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429
    } else {
430
      throw new Error('unsupport topic type')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
431 432
    }

433 434 435
    return Config.puppetInstance()
                  .roomFind(filterFunction)
                  .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
436
                    log.verbose('Room', 'findAll() rejected: %s', e.message)
437 438
                    return [] // fail safe
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
439 440
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
444 445 446 447
    const roomList = await Room.findAll(query)
    if (!roomList || roomList.length < 1) {
      throw new Error('no room found')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
448 449 450
    const room = roomList[0]
    await room.ready()
    return room
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
451 452
  }

453 454 455 456
  public static load(id: string): Room {
    if (!id) {
      throw new Error('Room.load() no id')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
457 458 459 460 461 462 463

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

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