wechaty.ts 9.0 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2
/**
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
3 4
 * Wechaty: Wechat for ChatBots.
 * Connect ChatBots
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
5
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
6
 * Class Wechaty
7
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
8 9 10 11
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 */
12 13
import { EventEmitter } from 'events'
import * as fs          from 'fs'
14
import * as path        from 'path'
15

16 17 18
import {
    Config
  , HeadType
19
  , PuppetType
20
  , Sayable
21
}                     from './config'
22

23 24 25 26
import Contact        from './contact'
import FriendRequest  from './friend-request'
import Message        from './message'
import Puppet         from './puppet'
27
import PuppetWeb      from './puppet-web/'
28 29
import Room           from './room'
import UtilLib        from './util-lib'
30

31
import log            from './brolog-env'
32

33
export type WechatySetting = {
34
  profile?:    string
35 36
  head?:       HeadType
  type?:       PuppetType
37
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
38

39 40 41 42 43 44 45 46 47 48 49 50
type WechatyEventName = 'error'
                      | 'friend'
                      | 'heartbeat'
                      | 'login'
                      | 'logout'
                      | 'message'
                      | 'room-join'
                      | 'room-leave'
                      | 'room-topic'
                      | 'scan'
                      | 'EVENT_PARAM_ERROR'

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
51
export class Wechaty extends EventEmitter implements Sayable {
52
  private static _instance: Wechaty
53

54
  public puppet: Puppet
55

56 57
  private inited:     boolean = false
  private npmVersion: string
58 59

  public uuid:        string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
60

61 62 63 64 65 66 67 68 69 70
  public static instance(setting?: WechatySetting) {
    if (setting && this._instance) {
      throw new Error('there has already a instance. no params allowed any more')
    }
    if (!this._instance) {
      this._instance = new Wechaty(setting)
    }
    return this._instance
  }

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
71
  private constructor(private setting: WechatySetting = {}) {
72
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
73 74
    log.verbose('Wechaty', 'contructor()')

75 76 77
    // if (Wechaty._instance instanceof Wechaty) {
    //   throw new Error('Wechaty must be singleton')
    // }
78

79 80 81 82
    setting.type    = setting.type    || Config.puppet
    setting.head    = setting.head    || Config.head
    // setting.port    = setting.port    || Config.port
    setting.profile = setting.profile || Config.profile  // no profile, no session save/restore
83

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84 85
    if (setting.profile) {
      setting.profile  = /\.wechaty\.json$/i.test(setting.profile)
86 87
                        ? setting.profile
                        : setting.profile + '.wechaty.json'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
90
    this.npmVersion = require('../package.json').version
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91

92
    this.uuid = UtilLib.guid()
93

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94
    this.inited = false
95

96
    // Wechaty._instance = this
97 98 99
  }

  public toString() { return 'Class Wechaty(' + this.setting.type + ')'}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100

101
  public version(forceNpm = false) {
102 103 104
    const dotGitPath  = path.join(__dirname, '..', '.git')
    const gitLogCmd   = 'git'
    const gitLogArgs  = ['log', '--oneline', '-1']
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
105

106 107
    if (!forceNpm) {
      try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108 109
        /**
         * Synchronous version of fs.access().
110
         * This throws if any accessibility checks fail, and does nothing otherwise.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
111
         */
112
        fs.accessSync(dotGitPath, fs['F_OK'])
113 114 115 116 117 118 119 120 121 122

        const ss = require('child_process')
                    .spawnSync(gitLogCmd, gitLogArgs, { cwd:  __dirname })
        if (ss.status !== 0) {
          throw new Error(ss.error)
        }

        const revision = ss.stdout
                          .toString()
                          .trim()
123
        return `#git[${revision}]`
124
      } catch (e) { /* fall safe */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125 126 127 128
        /**
         *  1. .git not exist
         *  2. git log fail
         */
129
        log.silly('Wechaty', 'version() test %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130
      }
131 132 133
    }

    return this.npmVersion
134
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135

136
  public user(): Contact { return this.puppet && this.puppet.user }
137

138
  public reset(reason?: string) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139
    log.verbose('Wechaty', 'reset() because %s', reason)
140
    return this.puppet.reset(reason)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
141
  }
142

143
  public async init(): Promise<Wechaty> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
144
    log.info('Wechaty', 'v%s initializing...' , this.version())
145 146 147
    log.verbose('Wechaty', 'puppet: %s'       , this.setting.type)
    log.verbose('Wechaty', 'head: %s'         , this.setting.head)
    log.verbose('Wechaty', 'profile: %s'      , this.setting.profile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148
    log.verbose('Wechaty', 'uuid: %s'         , this.uuid)
149

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150 151 152 153 154
    if (this.inited) {
      log.error('Wechaty', 'init() already inited. return and do nothing.')
      return Promise.resolve(this)
    }

155 156
    try {
      await this.initPuppet()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
      this.inited = true
158
    } catch (e) {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
159
      log.error('Wechaty', 'init() exception: %s', e && e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160
      throw e
161 162
    }
    return this
163
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
164

165 166 167 168 169
  public on(event: 'error'      , listener: (this: Sayable, error: Error) => void): this
  public on(event: 'friend'     , listener: (this: Sayable, friend: Contact, request: FriendRequest) => void): this
  public on(event: 'heartbeat'  , listener: (this: Sayable, data: any) => void): this
  public on(event: 'logout'     , listener: (this: Sayable, user: Contact) => void): this
  public on(event: 'login'      , listener: (this: Sayable, user: Contact) => void): this
170 171 172
  public on(event: 'message'    , listener: (this: Sayable, message: Message) => void): this
  public on(event: 'room-join'  , listener: (this: Sayable, room: Room, invitee:      Contact,    inviter: Contact) => void): this
  public on(event: 'room-join'  , listener: (this: Sayable, room: Room, inviteeList:  Contact[],  inviter: Contact) => void): this
173 174 175
  public on(event: 'room-leave' , listener: (this: Sayable, room: Room, leaver: Contact) => void): this
  public on(event: 'room-topic' , listener: (this: Sayable, room: Room, topic: string, oldTopic: string, changer: Contact) => void): this
  public on(event: 'scan'       , listener: (this: Sayable, url: string, code: number) => void): this
176
  public on(event: 'EVENT_PARAM_ERROR', listener: () => void): this
177

178
  public on(event: WechatyEventName, listener: Function): this {
179
    log.verbose('Wechaty', 'on(%s, %s)', event, typeof listener)
180

181 182 183 184 185 186 187 188 189
    const thisWithSay: Sayable = {
      say: (content: string) => {
        return Config.puppetInstance()
                      .say(content)
      }
    }
    super.on(event, function() {
      return listener.apply(thisWithSay, arguments)
    })
190

191
    return this
192 193
  }

194
  public initPuppet() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195
    let puppet
196
    switch (this.setting.type) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
197
      case 'web':
198 199 200 201
        puppet = new PuppetWeb({
            head:     this.setting.head
          , profile:  this.setting.profile
        })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202
        break
203

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204
      default:
205
        throw new Error('Puppet unsupport(yet): ' + this.setting.type)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
207

208 209 210 211 212 213 214 215 216 217 218 219
  ; // must have a semicolon here to seperate the last line with `[]`
  [   'error'
    , 'friend'
    , 'heartbeat'
    , 'login'
    , 'logout'
    , 'message'
    , 'room-join'
    , 'room-leave'
    , 'room-topic'
    , 'scan'
  ].map(e => {
220 221 222 223 224
      // https://strongloop.com/strongblog/an-introduction-to-javascript-es6-arrow-functions/
      // We’ve lost () around the argument list when there’s just one argument (rest arguments are an exception, eg (...args) => ...)
      puppet.on(e, (...args) => {
        // this.emit(e, data)
        this.emit.apply(this, [e, ...args])
225
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226
    })
227 228 229 230 231 232 233 234
    /**
     * TODO: support more events:
     * 2. send
     * 3. reply
     * 4. quit
     * 5. ...
     */

235
    // set puppet before init, because we need this.puppet if we quit() before init() finish
236
    this.puppet = puppet
237 238 239

    // set puppet instance to Wechaty Static variable, for using by Contact/Room/Message/FriendRequest etc.
    Config.puppetInstance(puppet)
240

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
241
    return puppet.init()
242 243
  }

244
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
245
    log.verbose('Wechaty', 'quit()')
246

247 248
    if (!this.puppet) {
      log.warn('Wechaty', 'quit() without this.puppet')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249 250 251
      return Promise.resolve()
    }

252
    const puppetBeforeDie = this.puppet
253 254
    this.puppet     = null
    Config.puppetInstance(null)
255 256
    this.inited = false

257
    return puppetBeforeDie.quit()
258 259 260 261 262
    .catch(e => {
      log.error('Wechaty', 'quit() exception: %s', e.message)
      throw e
    })
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
263

264
  public logout()  {
265
    return this.puppet.logout()
266 267 268 269
                      .catch(e => {
                        log.error('Wechaty', 'logout() exception: %s', e.message)
                        throw e
                      })
270
  }
271

272
  public self(message?: Message): boolean | Contact {
273 274
    return this.puppet.self(message)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
275

276
  public send(message: Message): Promise<any> {
277
    return this.puppet.send(message)
278 279 280 281
                      .catch(e => {
                        log.error('Wechaty', 'send() exception: %s', e.message)
                        throw e
                      })
282
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
283

284 285 286 287 288
  public say(content: string) {
    return this.puppet.say(content)
  }

  /// @deprecated
289
  public reply(message: Message, reply: string) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
290 291
    log.warn('Wechaty', 'reply() @deprecated, please use Message.say()')

292 293 294 295 296 297
    return this.puppet.reply(message, reply)
    .catch(e => {
      log.error('Wechaty', 'reply() exception: %s', e.message)
      throw e
    })
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
298

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
299
  public ding() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
300 301 302 303
    if (!this.puppet) {
      return Promise.reject(new Error('wechaty cant ding coz no puppet'))
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
304
    return this.puppet.ding() // should return 'dong'
305 306 307 308
                      .catch(e => {
                        log.error('Wechaty', 'ding() exception: %s', e.message)
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
309
  }
310 311
}

312
export default Wechaty