room.js 6.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 12 13 14
const Wechaty   = require('./wechaty')
const log       = require('./brolog-env')
const UtilLib   = require('./util-lib')
const Config    = require('./config')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
15

16
class Room {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
17
  constructor(id) {
18
    log.silly('Room', `constructor(${id})`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19
    this.id = id
20
    this.obj = {}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21
    this.dirtyObj = {} // when refresh, use this to save dirty data for query
22 23
    if (!Config.puppetInstance) {
      throw new Error('Config.puppetInstance not found')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
24
    }
25
  }
26

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
  toString()    { return this.id }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
28
  toStringEx()  { return `Room(${this.obj.topic}[${this.id}])` }
29

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
30
  // @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
31
  isReady() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
32
    return this.obj.memberList && this.obj.memberList.length
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33 34 35
  }

  refresh() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36
    this.dirtyObj = this.obj
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
37 38 39 40
    this.obj = {}
    return this.ready()
  }

41
  ready(contactGetter) {
42
    log.silly('Room', 'ready(%s)', contactGetter ? contactGetter.constructor.name : '')
43
    if (!this.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44 45 46 47
      const e = new Error('ready() on a un-inited Room')
      log.warn('Room', e.message)
      return Promise.reject(e)
    } else if (this.isReady()) {
48
      return Promise.resolve(this)
49
    } else if (this.obj.id) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
50
      log.warn('Room', 'ready() has obj.id but memberList empty in room %s. reloading', this.obj.topic)
51
    }
52

53 54
    contactGetter = contactGetter || Config.puppetInstance()
                                            .getContact.bind(Config.puppetInstance())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
55
    return contactGetter(this.id)
56
    .then(data => {
57
      log.silly('Room', `contactGetter(${this.id}) resolved`)
58 59
      this.rawObj = data
      this.obj    = this.parse(data)
60
      return this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61
    }).catch(e => {
62 63
      log.error('Room', 'contactGetter(%s) exception: %s', this.id, e.message)
      throw e
64 65 66
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
67
  name() { return UtilLib.plainText(this.obj.topic) }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
68
  get(prop) { return this.obj[prop] || this.dirtyObj[prop] }
69

70
  parse(rawObj) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71 72 73 74
    if (!rawObj) {
      return {}
    }
    return {
75
      id:         rawObj.UserName
76
      , encryId:  rawObj.EncryChatRoomId // ???
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77
      , topic:    rawObj.NickName
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
78
      , memberList:  this.parseMemberList(rawObj.MemberList)
79 80 81
    }
  }

82 83 84 85 86 87
  parseMemberList(memberList) {
    if (!memberList || !memberList.map) {
      return []
    }
    return memberList.map(m => {
      return {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
        id:       m.UserName
89
        , name:   m.DisplayName // nick name for this room?
90 91 92 93
      }
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94
  dumpRaw() {
95
    console.error('======= dump raw Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96
    Object.keys(this.rawObj).forEach(k => console.error(`${k}: ${this.rawObj[k]}`))
97
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
  dump()    {
99
    console.error('======= dump Room =======')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100
    Object.keys(this.obj).forEach(k => console.error(`${k}: ${this.obj[k]}`))
101 102
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103 104 105 106 107 108
  del(contact) {
    log.verbose('Room', 'del(%s) from %s', contact, this)

    if (!contact) {
      throw new Error('contact not found')
    }
109
    return Config.puppetInstance.roomDel(this, contact)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110 111 112
                      .then(r => this.delLocal(contact))
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113
  // @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  delLocal(contact) {
    log.verbose('Room', 'delLocal(%s)', contact)

    const memberList = this.obj.memberList
    if (!memberList || memberList.length === 0) {
      return true // already in refreshing
    }

    let i
    for (i=0; i<memberList.length; i++) {
// XXX
// console.log('########################')
// console.log(i)
// console.log(memberList[i].id)
// console.log(contact.get('id'))
// console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!')
      if (memberList[i].id === contact.get('id')) {
        break
      }
    }
// console.log('found i=' + i)
    if (i < memberList.length) {
// console.log('splicing before: ' + memberList.length)
      memberList.splice(i, 1)
// console.log('splicing after: ' + memberList.length)
      return true
    }
    return false
142
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143 144 145 146

  quit() {
    throw new Error('wx web not implement yet')
    // WechatyBro.glue.chatroomFactory.quit("@@1c066dfcab4ef467cd0a8da8bec90880035aa46526c44f504a83172a9086a5f7"
147
  }
148

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149 150 151 152 153 154
  add(contact) {
    log.verbose('Room', 'add(%s) to %s', contact, this)

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

156
    return Config.puppetInstance.roomAdd(this, contact)
157
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
158

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159 160
  topic(newTopic) {
    log.verbose('Room', 'topic(%s)', newTopic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
162
    if (newTopic) {
163
      Config.puppetInstance.roomTopic(this, newTopic)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
164 165 166
      return newTopic
    }
    return this.get('topic')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167 168
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
169 170 171 172 173 174
  static create(contactList) {
    log.verbose('Room', 'create(%s)', contactList.join(','))

    if (!contactList || ! typeof contactList === 'array') {
      throw new Error('contactList not found')
    }
175
    return Config.puppetInstance.roomCreate(contactList)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  }

  // private
  static _find({
    name
  }) {
    log.silly('Room', '_find(%s)', name)

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

    let filterFunction
    if (name instanceof RegExp) {
      filterFunction = `c => ${name.toString()}.test(c)`
    } else if (typeof name === 'string') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
192
      filterFunction = `c => c === '${name}'`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
193 194 195 196
    } else {
      throw new Error('unsupport name type')
    }

197
    return Config.puppetInstance.roomFind(filterFunction)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
              .then(idList => {
                return idList
              })
              .catch(e => {
                log.error('Room', '_find() rejected: %s', e.message)
                throw e
              })
  }

  static find({
    name
  }) {
    log.verbose('Room', 'find(%s)', name)

    return Room._find({name})
              .then(idList => {
                if (!idList || !Array.isArray(idList)){
                  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 (李卓桓) 已提交
225
                return null // fail safe
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
              })
  }

  static findAll({
    name
  }) {
    log.verbose('Room', 'findAll(%s)', name)

    return Room._find({name})
              .then(idList => {
                // console.log(idList)
                if (!idList || !Array.isArray(idList)){
                  throw new Error('_find return error')
                }
                if (idList.length < 1) {
                  return []
                }
                return idList.map(i => Room.load(i))
              })
              .catch(e => {
                log.error('Room', 'findAll() rejected: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247
                return [] // fail safe
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261
              })
  }

  static init() { Room.pool = {} }

  static load(id) {
    if (!id) { return null }

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

262 263 264 265 266 267
  // static attach(puppet) {
  //   // if (!puppet) {
  //   //   throw new Error('Room.attach got no puppet to attach!')
  //   // }
  //   Config.puppetInstance = puppet
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
271 272
Room.init()

273
module.exports = Room