room.ts 10.2 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
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[]
}

43 44 45 46
type RoomQueryFilter = {
  topic: string | RegExp
}

47 48 49 50 51 52 53
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

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

65 66
  public toString()    { return this.id }
  public toStringEx()  { return `Room(${this.obj.topic}[${this.id}])` }
67

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

73
  public refresh(): Promise<Room> {
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 ready(contactGetter?: (id: string) => Promise<RoomRawObj>): Promise<Room|void> {
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)
89
    } else if (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
    contactGetter = contactGetter || Config.puppetInstance()
                                            .getContact.bind(Config.puppetInstance())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95
    return contactGetter(this.id)
96
    .then(data => {
97
      log.silly('Room', `contactGetter(${this.id}) resolved`)
98 99
      this.rawObj = data
      this.obj    = this.parse(data)
100
      return this
101 102 103
    })
    .then(_ => {
      return Promise.all(this.obj.memberList.map(c => c.ready()))
104
                    .then(() => this)
105 106
    })
    .catch(e => {
107 108
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
109 110 111
    })
  }

112 113
  public on(event: string, listener: Function) {
    log.verbose('Room', 'on(%s, %s)', event, typeof listener)
114 115 116 117 118

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

    // bind(this1, this2): the second this is for simulate the global room-* event
122 123
    super.on(event, wrapCallback.bind(this, this))
    return this
124 125
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126
  public say(content: string, replyTo?: Contact|Contact[]): Promise<any> {
127 128 129 130 131 132 133 134 135 136 137 138 139
    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
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
140
    if (Array.isArray(replyTo)) {
141 142 143 144 145 146 147 148 149 150 151 152
      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)
  }

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

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

165 166
      , memberList: this.parseMemberList(rawObj.MemberList)
      , nickMap:    this.parseNickMap(rawObj.MemberList)
167 168 169
    }
  }

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

177 178
  private parseNickMap(memberList): Map<string, string> {
    const nickMap: Map<string, string> = new Map<string, string>()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
179
    let contact, remark
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
180
    if (memberList && memberList.map) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
181
      memberList.forEach(m => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
182 183 184 185 186 187 188
        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 (李卓桓) 已提交
189
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
190 191
    }
    return nickMap
192 193
  }

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

203
  public add(contact: Contact): Promise<any> {
204
    log.verbose('Room', 'add(%s)', contact)
205 206 207 208 209 210 211 212 213

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

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

214
  public del(contact: Contact): Promise<number> {
215
    log.verbose('Room', 'del(%s)', contact)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
216 217 218 219

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
  // @private
226
  private delLocal(contact: Contact): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228
    log.verbose('Room', 'delLocal(%s)', contact)

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

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252
  public topic(newTopic?: string): string {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
253 254 255
    if (newTopic) {
      log.verbose('Room', 'topic(%s)', newTopic)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256

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

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

272
  public has(contact: Contact): boolean {
273 274 275 276 277 278 279 280
    if (!this.obj.memberList) {
      return false
    }
    return this.obj.memberList
                    .filter(c => c.id === contact.id)
                    .length > 0
  }

281
  public owner(): Contact {
282 283 284 285 286 287 288 289 290 291
    const ownerUin = this.obj.ownerUin
    let memberList = this.obj.memberList || []

    let user = Config.puppetInstance()
                      .user

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

292
    memberList = memberList.filter(m => m.get('uin') === ownerUin)
293 294 295 296 297 298 299
    if (memberList.length > 0) {
      return memberList[0]
    } else {
      return null
    }
  }

300
  public member(name): Contact {
301 302
    log.verbose('Room', 'member(%s)', name)

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

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

313 314 315 316 317
    if (idList.length) {
      return Contact.load(idList[0])
    } else {
      return null
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
318 319
  }

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

323
    if (!contactList || !(typeof contactList === 'array')) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
324 325
      throw new Error('contactList not found')
    }
326

327
    return Config.puppetInstance()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
328
                  .roomCreate(contactList, topic)
329 330 331
                  .catch(e => {
                    log.error('Room', 'create() exception: %s', e && e.stack || e.message || e)
                    throw e
332
                  })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
333 334
  }

335 336 337 338
  public static findAll(query: RoomQueryFilter): Promise<Room[]> {
    log.silly('Room', 'findAll({ topic: %s })', query.topic)

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344 345 346
    // see also Contact.findAll
    let filterFunction: string

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

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

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

366 367 368 369 370 371 372 373 374 375 376 377
    return Room.findAll(query)
                .then(roomList => {
                  if (roomList && roomList.length > 0) {
                    return roomList[0]
                  }
                  return null
                })
                .catch(e => {
                  log.error('Room', 'find() rejected: %s', e.message)
                  return null // fail safe
                  // throw e
                })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378 379
  }

380
  public static load(id: string): Room {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
381 382 383 384 385 386 387 388
    if (!id) { return null }

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

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

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

393 394
// module.exports = Room
export default Room