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

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

21 22 23
import Contact      from './contact'
import Message      from './message'
import Puppet       from './puppet'
24
import PuppetWeb    from './puppet-web/index'
25 26 27 28 29 30 31
import UtilLib      from './util-lib'
import WechatyEvent from './wechaty-event'

import log          from './brolog-env'

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

37 38
class Wechaty extends EventEmitter {
  private static _instance: Wechaty
39

40
  public puppet: Puppet
41

42 43
  private inited:     boolean = false
  private npmVersion: string
44 45

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

47
  constructor(private setting: WechatySetting) {
48
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
49 50
    log.verbose('Wechaty', 'contructor()')

51
    if (Wechaty._instance instanceof Wechaty) {
52 53 54
      throw new Error('Wechaty must be singleton')
    }

55 56 57 58
    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
59

60 61 62
    setting.profile  = /\.wechaty\.json$/i.test(setting.profile)
                        ? setting.profile
                        : setting.profile + '.wechaty.json'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63

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

66
    this.uuid = UtilLib.guid()
67

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

70 71 72 73 74
    Wechaty._instance = this
  }

  public static instance() {
    return this._instance
75
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
76

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

79
  public version(forceNpm = false) {
80 81 82
    const dotGitPath  = path.join(__dirname, '..', '.git')
    const gitLogCmd   = 'git'
    const gitLogArgs  = ['log', '--oneline', '-1']
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
83

84 85
    if (!forceNpm) {
      try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86 87
        /**
         * Synchronous version of fs.access().
88
         * This throws if any accessibility checks fail, and does nothing otherwise.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
         */
90
        fs.accessSync(dotGitPath, fs['F_OK'])
91 92 93 94 95 96 97 98 99 100

        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()
101
        return `#git[${revision}]`
102
      } catch (e) { /* fall safe */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103 104 105 106
        /**
         *  1. .git not exist
         *  2. git log fail
         */
107
        log.silly('Wechaty', 'version() test %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108
      }
109 110 111
    }

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

114
  public user(): Contact { return this.puppet && this.puppet.user }
115

116
  public reset(reason?: string) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117
    log.verbose('Wechaty', 'reset() because %s', reason)
118
    return this.puppet.reset(reason)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
  }
120

121
  public async init(): Promise<Wechaty> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122
    log.info('Wechaty', 'v%s initializing...' , this.version())
123 124 125
    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 (李卓桓) 已提交
126
    log.verbose('Wechaty', 'uuid: %s'         , this.uuid)
127

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
128 129 130 131 132
    if (this.inited) {
      log.error('Wechaty', 'init() already inited. return and do nothing.')
      return Promise.resolve(this)
    }

133 134 135
    // return co.call(this, function* () {
    try {
      await this.initPuppet()
136

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137
      this.inited = true
138 139 140
      // return this // for chaining
    // }).catch(e => {
    } catch (e) {
141
      log.error('Wechaty', 'init() exception: %s', e.message)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
142
      throw e
143 144
    }
    return this
145
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146

147 148
  public on(event: string, listener: Function) {
    log.verbose('Wechaty', 'on(%s, %s)', event, typeof listener)
149

150 151
    const wrapListener = WechatyEvent.wrap.call(this, event, listener)
    super.on(event, wrapListener)
152

153
    return this
154 155
  }

156
  public initPuppet() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
    let puppet
158
    switch (this.setting.type) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159
      case 'web':
160 161 162 163
        puppet = new PuppetWeb(
            this.setting.head
          , this.setting.profile
        )
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
164 165
        break
      default:
166
        throw new Error('Puppet unsupport(yet): ' + this.setting.type)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
168

169
    WechatyEvent.list().map(e => {
170 171 172 173 174
      // 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])
175
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
176
    })
177 178 179 180 181 182 183 184
    /**
     * TODO: support more events:
     * 2. send
     * 3. reply
     * 4. quit
     * 5. ...
     */

185
    // set puppet before init, because we need this.puppet if we quit() before init() finish
186 187 188 189
    this.puppet     = puppet

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
191
    return puppet.init()
192 193
  }

194
  public quit() {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195
    log.verbose('Wechaty', 'quit()')
196

197 198
    if (!this.puppet) {
      log.warn('Wechaty', 'quit() without this.puppet')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
199 200 201
      return Promise.resolve()
    }

202
    const puppetBeforeDie = this.puppet
203 204
    this.puppet     = null
    Config.puppetInstance(null)
205 206
    this.inited = false

207
    return puppetBeforeDie.quit()
208 209 210 211 212
    .catch(e => {
      log.error('Wechaty', 'quit() exception: %s', e.message)
      throw e
    })
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213

214
  public logout()  {
215
    return this.puppet.logout()
216 217 218 219
                      .catch(e => {
                        log.error('Wechaty', 'logout() exception: %s', e.message)
                        throw e
                      })
220
  }
221

222
  public self(message?: Message): boolean | Contact {
223 224
    return this.puppet.self(message)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225

226
  public send(message) {
227
    return this.puppet.send(message)
228 229 230 231
                      .catch(e => {
                        log.error('Wechaty', 'send() exception: %s', e.message)
                        throw e
                      })
232
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
233

234
  public reply(message, reply) {
235 236 237 238 239 240
    return this.puppet.reply(message, reply)
    .catch(e => {
      log.error('Wechaty', 'reply() exception: %s', e.message)
      throw e
    })
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
241

242
  public ding(data: string) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
243 244 245 246
    if (!this.puppet) {
      return Promise.reject(new Error('wechaty cant ding coz no puppet'))
    }

247
    return this.puppet.ding(data)
248 249 250 251
                      .catch(e => {
                        log.error('Wechaty', 'ding() exception: %s', e.message)
                        throw e
                      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252
  }
253 254
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
255 256 257
/**
 * Expose `Wechaty`.
 */
258 259
// module.exports = Wechaty.default = Wechaty.Wechaty = Wechaty
export default Wechaty