config.ts 7.8 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
2
 *   Wechaty - https://github.com/chatie/wechaty
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 *   Copyright 2016-2017 Huan LI <zixia@zixia.net>
 *
 *   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 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import * as fs    from 'fs'
import * as os    from 'os'
import * as path  from 'path'

/**
 * Raven.io
 */
import * as Raven from 'raven'
Raven.disableConsoleAlerts()

Raven
.config(
  process.env.NODE_ENV === 'production'
    && 'https://f6770399ee65459a82af82650231b22c:d8d11b283deb441e807079b8bb2c45cd@sentry.io/179672',
  {
    release: require('../package.json').version,
    tags: {
      git_commit: 'c0deb10c4',
37
      platform:   !!process.env['WECHATY_DOCKER']
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
                  ? 'docker'
                  : os.platform(),
    },
  },
)
.install()

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

Raven.context(function () {
  doSomething(a[0])
})
 */
56 57 58

// const isCi      = require('is-ci')
// const isDocker  = require('is-docker')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
59

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
60 61 62 63
import {
  log,
  Loggable,
}    from 'brolog'
64

65
import { Puppet } from './puppet'
66

67
const logLevel = process.env['WECHATY_LOG'] || 'info'
68
if (logLevel) {
69
  log.level(logLevel.toLowerCase() as any)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  log.silly('Brolog', 'WECHATY_LOG set level to %s', logLevel)
}

/**
 * to handle unhandled exceptions
 */
if (/verbose|silly/i.test(logLevel)) {
  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 => {
      log.error('Config', 'unhandledRejection::catch(%s)', err.message)
      console.error('Config', err) // I don't know if log.error has similar full trace print support like console.error
    })
  })
87
}
88

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
export type PuppetName = 'web' | 'android' | 'ios'
90
export type HeadName = 'chrome' | 'phantomjs' | 'firefox'
91

92
export interface ConfigSetting {
93

94
  DEFAULT_HEAD: HeadName
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
95
  DEFAULT_PUPPET: PuppetName
96 97 98
  DEFAULT_APIHOST: string
  DEFAULT_PROFILE: string
  DEFAULT_TOKEN:  string
99 100
  DEFAULT_PROTOCOL: string
  CMD_CHROMIUM: string
101 102 103 104 105 106 107
  DEFAULT_PORT: number

  port: number
  profile: string
  token: string
  debug: boolean

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108
  puppet: PuppetName
109
  head: HeadName
110 111

  apihost: string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112
  validApiHost: (host: string) => boolean
113 114 115

  httpPort: number

116 117 118
  _puppetInstance: Puppet | null
  puppetInstance(): Puppet
  puppetInstance(empty: null): void
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
  puppetInstance(instance: Puppet): void
120
  puppetInstance(instance?: Puppet | null): Puppet | void,
121

122 123
  gitVersion(): string | null,
  npmVersion(): string,
124

125
  dockerMode: boolean,
126
}
127 128
/* tslint:disable:variable-name */
/* tslint:disable:no-var-requires */
129
export const config: ConfigSetting = require('../package.json').wechaty
130

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131 132 133
/**
 * 1. ENVIRONMENT VARIABLES + PACKAGES.JSON (default)
 */
134 135 136 137
Object.assign(config, {
  apihost:    process.env['WECHATY_APIHOST']   || config.DEFAULT_APIHOST,
  head:       process.env['WECHATY_HEAD']      || config.DEFAULT_HEAD,
  puppet:     process.env['WECHATY_PUPPET']    || config.DEFAULT_PUPPET,
L
lijiarui 已提交
138
  validApiHost,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139 140
})

141
function validApiHost(apihost: string): boolean {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
142 143 144 145 146
  if (/^[a-zA-Z0-9\.\-\_]+:?[0-9]*$/.test(apihost)) {
    return true
  }
  throw new Error('validApiHost() fail for ' + apihost)
}
147
validApiHost(config.apihost)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149 150 151
/**
 * 2. ENVIRONMENT VARIABLES (only)
 */
152
Object.assign(config, {
L
lijiarui 已提交
153 154 155 156
  port:       process.env['WECHATY_PORT']     || null, // 0 for disable port
  profile:  process.env['WECHATY_PROFILE']    || null, // DO NOT set DEFAULT_PROFILE, because sometimes user do not want to save session
  token:    process.env['WECHATY_TOKEN']      || null, // DO NOT set DEFAULT, because sometimes user do not want to connect to io cloud service
  debug:    !!(process.env['WECHATY_DEBUG'])  || false,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
158

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159 160 161
/**
 * 3. Service Settings
 */
162
Object.assign(config, {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
163
  // get PORT form cloud service env, ie: heroku
164
  httpPort: process.env['PORT'] || process.env['WECHATY_PORT'] || config.DEFAULT_PORT,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
165 166 167 168 169
})

/**
 * 4. Envioronment Identify
 */
170
Object.assign(config, {
171
  dockerMode: !!process.env['WECHATY_DOCKER'],
172
  isGlobal:  isWechatyInstalledGlobal(),
173
})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
174

175 176 177 178 179 180 181 182 183 184
function isWechatyInstalledGlobal() {
  /**
   * TODO:
   * 1. check /node_modules/wechaty
   * 2. return true if exists
   * 3. otherwise return false
   */
   return false
}

185 186 187 188
/**
 * @DEPRECATED on Jun 2017 by zixia
 */
// function dockerMode() {
189
  /**
190
   * false for Continuous Integration System
191
   */
192 193 194
  // if (isCi) {
  //   return false
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195

196
  /**
197
   * false Cloud9 IDE
198
   */
199 200 201 202 203 204
  // const c9 = Object.keys(process.env)
  //                 .filter(k => /^C9_/.test(k))
  //                 .length
  // if (c9 > 7 && process.env['C9_PORT']) {
  //   return false
  // }
Huan (李卓桓)'s avatar
lint  
Huan (李卓桓) 已提交
205

206 207 208
  /**
   * return indentify result by NPM module `is-docker`
   */
209 210
  // return isDocker()
// }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
211

212 213 214
/**
 * 5. live setting
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215 216 217 218
function puppetInstance(): Puppet
function puppetInstance(empty: null): void
function puppetInstance(instance: Puppet): void

219
function puppetInstance(instance?: Puppet | null): Puppet | void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
220 221

  if (instance === undefined) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
222
    if (!this._puppetInstance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
      throw new Error('no puppet instance')
224
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
    return this._puppetInstance
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
226 227

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
233
  log.verbose('Config', 'puppetInstance(%s)', instance.constructor.name)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
234
  this._puppetInstance = instance
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
235 236
  return

237 238
}

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
function gitVersion(): 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
  }
}

function npmVersion(): string {
  try {
    return require('../package.json').version
  } catch (e) {
    log.error('Wechaty', 'npmVersion() exception %s', e.message)
    Raven.captureException(e)
    return '0.0.0'
  }
}

Object.assign(config, {
  gitVersion,
  npmVersion,
L
lijiarui 已提交
285
  puppetInstance,
286 287
})

Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
288 289 290 291
export type WatchdogFoodName = 'HEARTBEAT'
                              | 'POISON'
                              | 'SCAN'

292
export interface WatchdogFood {
L
lijiarui 已提交
293 294 295
  data: any,
  timeout?: number,  // millisecond
  type?: WatchdogFoodName,
296 297
}

298
export interface ScanInfo {
L
lijiarui 已提交
299 300
  url: string,
  code: number,
301 302
}

303 304 305
/**
 * from Message
 */
306
export interface RecommendInfo {
L
lijiarui 已提交
307 308 309 310
  UserName:   string,
  NickName:   string,  // display_name
  Content:    string,  // request message
  HeadImgUrl: string,  // message.RecommendInfo.HeadImgUrl
311

L
lijiarui 已提交
312 313
  Ticket:     string,  // a pass token
  VerifyFlag: number,
314

315 316
}

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
321 322 323
export interface Sleepable {
  sleep(millisecond: number): Promise<void>
}
324

325 326
export {
  log,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
327
  Loggable,
328
  Raven,
329 330
}

331
export default config