config.ts 6.2 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5 6 7 8 9 10 11 12 13 14 15 16
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
17
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
18
 */
19 20 21 22
import * as fs    from 'fs'
import * as os    from 'os'
import * as path  from 'path'

23
import * as readPkgUp from 'read-pkg-up'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
24
import * as Raven     from 'raven'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
25
import { log }        from 'brolog'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26 27

import Puppet from './puppet'
28

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
29
const pkg = readPkgUp.sync({ cwd: __dirname }).pkg
30 31
export const VERSION = pkg.version

32 33 34 35 36 37 38 39 40 41
/**
 * Raven.io
 */
Raven.disableConsoleAlerts()

Raven
.config(
  process.env.NODE_ENV === 'production'
    && 'https://f6770399ee65459a82af82650231b22c:d8d11b283deb441e807079b8bb2c45cd@sentry.io/179672',
  {
42
    release: VERSION,
43
    tags: {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44
      git_commit: '',
45
      platform:   !!process.env['WECHATY_DOCKER']
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
                  ? 'docker'
                  : os.platform(),
    },
  },
)
.install()

/*
try {
    doSomething(a[0])
} catch (e) {
    Raven.captureException(e)
}

Raven.context(function () {
  doSomething(a[0])
})
 */
64

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
65
const logLevel = process.env['WECHATY_LOG']
66
if (logLevel) {
67
  log.level(logLevel.toLowerCase() as any)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
68
  log.silly('Config', 'WECHATY_LOG set level to %s', logLevel)
69 70 71 72 73
}

/**
 * to handle unhandled exceptions
 */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
74
if (log.level() === 'verbose' || log.level() === 'silly') {
75 76 77 78 79 80
  log.info('Config', 'registering process.on("unhandledRejection") for development/debug')
  process.on('unhandledRejection', (reason, promise) => {
    log.error('Config', '###########################')
    log.error('Config', 'unhandledRejection: %s %s', reason, promise)
    log.error('Config', '###########################')
    promise.catch(err => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
81
      log.error('Config', 'process.on(unhandledRejection) promise.catch(%s)', err.message)
82 83 84
      console.error('Config', err) // I don't know if log.error has similar full trace print support like console.error
    })
  })
85
}
86

87 88 89 90
export type PuppetName = 'web'
                        | 'android'
                        | 'ios'

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91
export interface DefaultSetting {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92 93
  DEFAULT_HEAD     : number,
  DEFAULT_PORT     : number,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94 95 96 97 98
  DEFAULT_PUPPET   : PuppetName,
  DEFAULT_APIHOST  : string,
  DEFAULT_PROFILE  : string,
  DEFAULT_TOKEN    : string,
  DEFAULT_PROTOCOL : string,
99
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100

101 102
/* tslint:disable:variable-name */
/* tslint:disable:no-var-requires */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
103
const DEFAULT_SETTING = pkg.wechaty as DefaultSetting
104

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
105 106
export class Config {
  public default = DEFAULT_SETTING
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
107

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108 109 110
  public apihost = process.env['WECHATY_APIHOST']    || DEFAULT_SETTING.DEFAULT_APIHOST
  public head    = ('WECHATY_HEAD' in process.env) ? (!!process.env['WECHATY_HEAD']) : (!!(DEFAULT_SETTING.DEFAULT_HEAD))
  public puppet  = (process.env['WECHATY_PUPPET']    || DEFAULT_SETTING.DEFAULT_PUPPET) as PuppetName
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
111

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112 113 114
  public profile = process.env['WECHATY_PROFILE']    || null    // DO NOT set DEFAULT_PROFILE, because sometimes user do not want to save session
  public token   = process.env['WECHATY_TOKEN']      || null    // DO NOT set DEFAULT, because sometimes user do not want to connect to io cloud service
  public debug   = !!(process.env['WECHATY_DEBUG'])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
115

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116 117
  public httpPort = process.env['PORT'] || process.env['WECHATY_PORT'] || DEFAULT_SETTING.DEFAULT_PORT
  public docker = !!(process.env['WECHATY_DOCKER'])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
118

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119 120 121 122 123 124
  private _puppetInstance: Puppet | null = null

  constructor() {
    log.verbose('Config', 'constructor()')
    this.validApiHost(this.apihost)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125

126
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127
   * 5. live setting
128
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  public puppetInstance(): Puppet
  public puppetInstance(empty: null): void
  public puppetInstance(instance: Puppet): void

  public puppetInstance(instance?: Puppet | null): Puppet | void {

    if (typeof instance === 'undefined') {
      if (!this._puppetInstance) {
        throw new Error('no puppet instance')
      }
      return this._puppetInstance

    } else if (instance === null) {
      log.verbose('Config', 'puppetInstance(null)')
      this._puppetInstance = null
      return
145
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147 148
    log.verbose('Config', 'puppetInstance(%s)', instance.constructor.name)
    this._puppetInstance = instance
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149
    return
150

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151
  }
152

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  public gitRevision(): string | null {
    const dotGitPath  = path.join(__dirname, '..', '.git') // only for ts-node, not for dist
    // const gitLogArgs  = ['log', '--oneline', '-1']
    // TODO: use git rev-parse HEAD ?
    const gitArgs  = ['rev-parse', 'HEAD']

    try {
      // Make sure this is a Wechaty repository
      fs.statSync(dotGitPath).isDirectory()

      const ss = require('child_process')
                  .spawnSync('git', gitArgs, { cwd:  __dirname })

      if (ss.status !== 0) {
        throw new Error(ss.error)
      }

      const revision = ss.stdout
                        .toString()
                        .trim()
                        .slice(0, 7)
      return revision

    } catch (e) { /* fall safe */
      /**
       *  1. .git not exist
       *  2. git log fail
       */
      log.silly('Wechaty', 'version() form development environment is not availble: %s', e.message)
      return null
183
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
184
  }
185

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186 187 188 189 190
  public validApiHost(apihost: string): boolean {
    if (/^[a-zA-Z0-9\.\-\_]+:?[0-9]*$/.test(apihost)) {
      return true
    }
    throw new Error('validApiHost() fail for ' + apihost)
191 192 193
  }
}

194
export interface Sayable {
195
  say(content: string, replyTo?: any|any[]): Promise<boolean>
196
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
197

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211
export type WechatEvent = 'friend'
                          | 'login'
                          | 'logout'
                          | 'message'
                          | 'room-join'
                          | 'room-leave'
                          | 'room-topic'
                          | 'scan'

export type WechatyEvent = WechatEvent
                          | 'error'
                          | 'heartbeat'
                          | 'start'
                          | 'stop'
212

213
export {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
214
  log,
215
  Raven,
216 217
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218
export const config = new Config()
219
export default config