room.ts 10.9 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

13 14 15 16 17
import Config        from './config'
import Contact       from './contact'
import Message       from './message'
import UtilLib       from './util-lib'
import WechatyEvent  from './wechaty-event'
18

19
import log           from './brolog-env'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
type RoomObj = {
  id:         string
  encryId:    string
  topic:      string
  ownerUin:   number
  memberList: Contact[]
  nickMap:    Map<string, string>
}

type RoomRawMemberList = {
  UserName:     string
  DisplayName:  string
}

type RoomRawObj = {
  UserName:         string
  EncryChatRoomId:  string
  NickName:         string
  OwnerUin:         number
  MemberList:       RoomRawMemberList[]
}

class Room extends EventEmitter {
  private static pool = new Map<string, Room>()

  private dirtyObj: RoomObj // when refresh, use this to save dirty data for query
  private obj:      RoomObj
  private rawObj:   RoomRawObj

50
  constructor(public id: string) {
51
    super()
52
    log.silly('Room', `constructor(${id})`)
53 54 55
    // this.id = id
    // this.obj = {}
    // this.dirtyObj = {}
56 57
    if (!Config.puppetInstance()) {
      throw new Error('Config.puppetInstance() not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
58
    }
59
  }
60

61 62
  public toString()    { return this.id }
  public toStringEx()  { return `Room(${this.obj.topic}[${this.id}])` }
63

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64
  // @private
65 66
  public isReady(): boolean {
    return !!(this.obj.memberList && this.obj.memberList.length)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
67 68
  }

69
  public refresh(): Promise<Room> {
70 71 72
    if (this.isReady()) {
      this.dirtyObj = this.obj
    }
73
    this.obj = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
74 75 76
    return this.ready()
  }

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

89 90
    contactGetter = contactGetter || Config.puppetInstance()
                                            .getContact.bind(Config.puppetInstance())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91
    return contactGetter(this.id)
92
    .then(data => {
93
      log.silly('Room', `contactGetter(${this.id}) resolved`)
94 95
      this.rawObj = data
      this.obj    = this.parse(data)
96
      return this
97 98 99
    })
    .then(_ => {
      return Promise.all(this.obj.memberList.map(c => c.ready()))
100
                    .then(() => this)
101 102
    })
    .catch(e => {
103 104
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
105 106 107
    })
  }

108 109
  public on(event: string, listener: Function) {
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
110 111 112 113 114

    /**
     * every room event must can be mapped to a global event.
     * such as: `join` to `room-join`
     */
115
    const wrapCallback = WechatyEvent.wrap.call(this, 'room-' + event, listener)
116 117

    // bind(this1, this2): the second this is for simulate the global room-* event
118 119
    super.on(event, wrapCallback.bind(this, this))
    return this
120 121
  }

122
  public say(content, replyTo = null): Promise<any> {
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    log.verbose('Room', 'say(%s, %s)', content, replyTo)

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

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

    let mentionList
    if (replyTo.map) {
      m.to(replyTo[0])
      mentionList = replyTo.map(c => '@' + c.name()).join(' ')
    } else {
      m.to(replyTo)
      mentionList = '@' + replyTo.name()
    }

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

149
  public get(prop): string { return this.obj[prop] || this.dirtyObj[prop] }
150

151
  private parse(rawObj: RoomRawObj): RoomObj {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152
    if (!rawObj) {
153
      return null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
154 155
    }
    return {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156 157 158 159 160
      id:           rawObj.UserName
      , encryId:    rawObj.EncryChatRoomId // ???
      , topic:      rawObj.NickName
      , ownerUin:   rawObj.OwnerUin

161 162
      , memberList: this.parseMemberList(rawObj.MemberList)
      , nickMap:    this.parseNickMap(rawObj.MemberList)
163 164 165
    }
  }

166
  private parseMemberList(memberList) {
167 168 169
    if (!memberList || !memberList.map) {
      return []
    }
170
    return memberList.map(m => Contact.load(m.UserName))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
171 172
  }

173 174
  private parseNickMap(memberList): Map<string, string> {
    const nickMap: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
    let contact, remark
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
176
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177
      memberList.forEach(m => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178 179 180 181 182 183 184
        contact = Contact.load(m.UserName)
        if (contact) {
          remark = contact.remark()
        } else {
          remark = null
        }
        nickMap[m.UserName] = remark || m.DisplayName || m.NickName
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186 187
    }
    return nickMap
188 189
  }

190
  public dumpRaw() {
191
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
192
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
193
  }
194
  public dump() {
195
    console.error('======= dump Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
196
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj[k]}`))
197 198
  }

199
  public add(contact: Contact): Promise<any> {
200
    log.verbose('Room', 'add(%s)', contact)
201 202 203 204 205 206 207 208 209

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

    return Config.puppetInstance()
                  .roomAdd(this, contact)
  }

210
  public del(contact: Contact): Promise<any> {
211
    log.verbose('Room', 'del(%s)', contact)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
212 213 214 215

    if (!contact) {
      throw new Error('contact not found')
    }
216 217
    return Config.puppetInstance()
                  .roomDel(this, contact)
218
                  .then(_ => this.delLocal(contact))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
219 220
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221
  // @private
222
  private delLocal(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223 224
    log.verbose('Room', 'delLocal(%s)', contact)

225 226
    const memberList = this.obj.memberList
    if (!memberList || memberList.length === 0) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228 229 230
      return true // already in refreshing
    }

    let i
231 232
    for (i = 0; i < memberList.length; i++) {
      if (memberList[i].id === contact.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
233 234 235
        break
      }
    }
236 237
    if (i < memberList.length) {
      memberList.splice(i, 1)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
238 239 240
      return true
    }
    return false
241
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242

243
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
244 245
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
246
  }
247

248
  public topic(newTopic: string): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249 250 251
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
253
    if (newTopic) {
254
      Config.puppetInstance().roomTopic(this, newTopic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
255 256
      return newTopic
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257 258
    // return this.get('topic')
    return UtilLib.plainText(this.obj.topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
259 260
  }

261
  public nick(contact: Contact): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
262 263 264
    if (!this.obj.nickMap) {
      return ''
    }
265 266 267
    return this.obj.nickMap[contact.id]
  }

268
  public has(contact: Contact): boolean {
269 270 271 272 273 274 275 276
    if (!this.obj.memberList) {
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

277
  public owner(): Contact {
278 279 280 281 282 283 284 285 286 287
    const ownerUin = this.obj.ownerUin
    let memberList = this.obj.memberList || []

    let user = Config.puppetInstance()
                      .user

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

288
    memberList = memberList.filter(m => m.get('uin') === ownerUin)
289 290 291 292 293 294 295
    if (memberList.length > 0) {
      return memberList[0]
    } else {
      return null
    }
  }

296
  public member(name): string {
297 298
    log.verbose('Room', 'member(%s)', name)

299
    if (!this.obj.memberList) {
300
      log.warn('Room', 'member() not ready')
301 302 303 304 305
      return null
    }
    const nickMap = this.obj.nickMap
    const idList = Object.keys(nickMap)
                          .filter(k => nickMap[k] === name)
306 307 308

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

309 310 311 312 313
    if (idList.length) {
      return Contact.load(idList[0])
    } else {
      return null
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
314 315
  }

316
  public static create(contactList, topic): Promise<Room> {
317
    log.verbose('Room', 'create(%s, %s)', contactList.join(','), topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
318

319
    if (!contactList || !(typeof contactList === 'array')) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
320 321
      throw new Error('contactList not found')
    }
322

323
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
324
                  .roomCreate(contactList, topic)
325 326 327 328 329
                  .then(roomId => {
                    if (typeof roomId === 'object') {
                      // It is a Error Object send back by callback in browser(WechatyBro)
                      throw roomId
                    }
330
                    return Room.load(roomId)
331
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
332 333 334
  }

  // private
335
  private static _find({
336
    topic
337
  }): Promise<string[]> {
338
    log.silly('Room', '_find(%s)', topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
339

340 341
    if (!topic) {
      throw new Error('topic not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
342 343 344
    }

    let filterFunction
345 346 347 348
    if (topic instanceof RegExp) {
      filterFunction = `c => ${topic.toString()}.test(c)`
    } else if (typeof topic === 'string') {
      filterFunction = `c => c === '${topic}'`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
349
    } else {
350
      throw new Error('unsupport topic type')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
351 352
    }

353
    return Config.puppetInstance().roomFind(filterFunction)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354 355 356 357 358 359 360 361 362
              .then(idList => {
                return idList
              })
              .catch(e => {
                log.error('Room', '_find() rejected: %s', e.message)
                throw e
              })
  }

363
  public static find({
364
    topic
365
  }): Promise<Room> {
366
    log.verbose('Room', 'find(%s)', topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
367

368
    return Room._find({topic})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
369
              .then(idList => {
370
                if (!idList || !Array.isArray(idList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
371 372 373 374 375 376 377 378 379 380
                  throw new Error('_find return error')
                }
                if (idList.length < 1) {
                  return null
                }
                const id = idList[0]
                return Room.load(id)
              })
              .catch(e => {
                log.error('Room', 'find() rejected: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
381
                return null // fail safe
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
382
                // throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
383 384 385
              })
  }

386
  public static findAll({
387
    topic
388
  }): Promise<Room[]> {
389
    log.verbose('Room', 'findAll(%s)', topic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
390

391
    return Room._find({topic})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
392 393
              .then(idList => {
                // console.log(idList)
394
                if (!idList || !Array.isArray(idList)) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
395 396 397 398 399 400 401 402
                  throw new Error('_find return error')
                }
                if (idList.length < 1) {
                  return []
                }
                return idList.map(i => Room.load(i))
              })
              .catch(e => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
403
                // log.error('Room', 'findAll() rejected: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
404
                return [] // fail safe
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
405 406 407
              })
  }

408
  public static load(id: string): Room {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
409 410 411 412 413 414 415 416
    if (!id) { return null }

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

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

419
// Room.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420

421 422
// module.exports = Room
export default Room