提交 4a37e649 编写于 作者: Huan (李卓桓)'s avatar Huan (李卓桓)

refactored Config

上级 add630c5
...@@ -47,7 +47,7 @@ let token = config.token ...@@ -47,7 +47,7 @@ let token = config.token
if (!token) { if (!token) {
log.error('Client', 'token not found: please set WECHATY_TOKEN in environment before run io-client') log.error('Client', 'token not found: please set WECHATY_TOKEN in environment before run io-client')
// process.exit(-1) // process.exit(-1)
token = config.DEFAULT_TOKEN token = config.default.DEFAULT_TOKEN
log.warn('Client', `set token to "${token}" for demo purpose`) log.warn('Client', `set token to "${token}" for demo purpose`)
} }
......
...@@ -56,7 +56,7 @@ import { ...@@ -56,7 +56,7 @@ import {
const APIAI_API_KEY = '7217d7bce18c4bcfbe04ba7bdfaf9c08' const APIAI_API_KEY = '7217d7bce18c4bcfbe04ba7bdfaf9c08'
const brainApiAi = ApiAi(APIAI_API_KEY) const brainApiAi = ApiAi(APIAI_API_KEY)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
console.log(` console.log(`
Welcome to api.AI Wechaty Bot. Welcome to api.AI Wechaty Bot.
......
...@@ -54,7 +54,7 @@ Please wait... I'm trying to login in... ...@@ -54,7 +54,7 @@ Please wait... I'm trying to login in...
` `
console.log(welcome) console.log(welcome)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('login' , function(this, user) { .on('login' , function(this, user) {
......
...@@ -63,7 +63,7 @@ Please wait... I'm trying to login in... ...@@ -63,7 +63,7 @@ Please wait... I'm trying to login in...
` `
console.log(welcome) console.log(welcome)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('logout' , user => log.info('Bot', `${user.name()} logouted`)) .on('logout' , user => log.info('Bot', `${user.name()} logouted`))
......
...@@ -57,7 +57,7 @@ Please wait... I'm trying to login in... ...@@ -57,7 +57,7 @@ Please wait... I'm trying to login in...
` `
console.log(welcome) console.log(welcome)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('login' , user => log.info('Bot', `${user.name()} logined`)) .on('login' , user => log.info('Bot', `${user.name()} logined`))
......
...@@ -41,7 +41,7 @@ Please wait... I'm trying to login in... ...@@ -41,7 +41,7 @@ Please wait... I'm trying to login in...
` `
console.log(welcome) console.log(welcome)
Wechaty.instance({ profile: config.DEFAULT_PROFILE }) Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
.on('scan', (url, code) => { .on('scan', (url, code) => {
if (!/201|200/.test(String(code))) { if (!/201|200/.test(String(code))) {
......
...@@ -38,7 +38,7 @@ import { ...@@ -38,7 +38,7 @@ import {
// MsgType, // MsgType,
Wechaty, Wechaty,
} from '../' } from '../'
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('scan', (url, code) => { .on('scan', (url, code) => {
......
...@@ -86,7 +86,7 @@ Please wait... I'm trying to login in... ...@@ -86,7 +86,7 @@ Please wait... I'm trying to login in...
` `
console.log(welcome) console.log(welcome)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('scan', (url, code) => { .on('scan', (url, code) => {
......
...@@ -42,7 +42,7 @@ import { ...@@ -42,7 +42,7 @@ import {
Wechaty, Wechaty,
} from '../' } from '../'
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
bot bot
.on('scan', (url, code) => { .on('scan', (url, code) => {
......
...@@ -53,7 +53,7 @@ import { ...@@ -53,7 +53,7 @@ import {
const TULING123_API_KEY = '18f25157e0446df58ade098479f74b21' const TULING123_API_KEY = '18f25157e0446df58ade098479f74b21'
const tuling = new Tuling123(TULING123_API_KEY) const tuling = new Tuling123(TULING123_API_KEY)
const bot = Wechaty.instance({ profile: config.DEFAULT_PROFILE }) const bot = Wechaty.instance({ profile: config.default.DEFAULT_PROFILE })
console.log(` console.log(`
Welcome to Tuling Wechaty Bot. Welcome to Tuling Wechaty Bot.
......
...@@ -31,10 +31,10 @@ test('important variables', async t => { ...@@ -31,10 +31,10 @@ test('important variables', async t => {
t.true('profile' in config, 'should exist `profile` in Config') t.true('profile' in config, 'should exist `profile` in Config')
t.true('token' in config, 'should exist `token` in Config') t.true('token' in config, 'should exist `token` in Config')
t.ok(config.DEFAULT_PUPPET , 'should export DEFAULT_PUPPET') t.ok(config.default.DEFAULT_PUPPET , 'should export DEFAULT_PUPPET')
t.ok(config.DEFAULT_PROFILE , 'should export DEFAULT_PROFILE') t.ok(config.default.DEFAULT_PROFILE , 'should export DEFAULT_PROFILE')
t.ok(config.DEFAULT_PROTOCOL , 'should export DEFAULT_PROTOCOL') t.ok(config.default.DEFAULT_PROTOCOL , 'should export DEFAULT_PROTOCOL')
t.ok(config.DEFAULT_APIHOST , 'should export DEFAULT_APIHOST') t.ok(config.default.DEFAULT_APIHOST , 'should export DEFAULT_APIHOST')
}) })
test('validApiHost()', async t => { test('validApiHost()', async t => {
......
...@@ -21,6 +21,10 @@ import * as os from 'os' ...@@ -21,6 +21,10 @@ import * as os from 'os'
import * as path from 'path' import * as path from 'path'
import * as readPkgUp from 'read-pkg-up' import * as readPkgUp from 'read-pkg-up'
import * as Raven from 'raven'
import Brolog from 'brolog'
import Puppet from './puppet'
const pkg = readPkgUp.sync({ cwd: __dirname }).pkg const pkg = readPkgUp.sync({ cwd: __dirname }).pkg
export const VERSION = pkg.version export const VERSION = pkg.version
...@@ -28,7 +32,6 @@ export const VERSION = pkg.version ...@@ -28,7 +32,6 @@ export const VERSION = pkg.version
/** /**
* Raven.io * Raven.io
*/ */
import * as Raven from 'raven'
Raven.disableConsoleAlerts() Raven.disableConsoleAlerts()
Raven Raven
...@@ -38,7 +41,7 @@ Raven ...@@ -38,7 +41,7 @@ Raven
{ {
release: VERSION, release: VERSION,
tags: { tags: {
git_commit: 'c0deb10c4', git_commit: '',
platform: !!process.env['WECHATY_DOCKER'] platform: !!process.env['WECHATY_DOCKER']
? 'docker' ? 'docker'
: os.platform(), : os.platform(),
...@@ -59,11 +62,7 @@ Raven.context(function () { ...@@ -59,11 +62,7 @@ Raven.context(function () {
}) })
*/ */
import Brolog from 'brolog'
export const log = new Brolog() export const log = new Brolog()
import { Puppet } from './puppet'
const logLevel = process.env['WECHATY_LOG'] || 'info' const logLevel = process.env['WECHATY_LOG'] || 'info'
if (logLevel) { if (logLevel) {
log.level(logLevel.toLowerCase() as any) log.level(logLevel.toLowerCase() as any)
...@@ -73,14 +72,14 @@ if (logLevel) { ...@@ -73,14 +72,14 @@ if (logLevel) {
/** /**
* to handle unhandled exceptions * to handle unhandled exceptions
*/ */
if (/verbose|silly/i.test(logLevel)) { if (/verbose|silly/i.test(log.level())) {
log.info('Config', 'registering process.on("unhandledRejection") for development/debug') log.info('Config', 'registering process.on("unhandledRejection") for development/debug')
process.on('unhandledRejection', (reason, promise) => { process.on('unhandledRejection', (reason, promise) => {
log.error('Config', '###########################') log.error('Config', '###########################')
log.error('Config', 'unhandledRejection: %s %s', reason, promise) log.error('Config', 'unhandledRejection: %s %s', reason, promise)
log.error('Config', '###########################') log.error('Config', '###########################')
promise.catch(err => { promise.catch(err => {
log.error('Config', 'unhandledRejection::catch(%s)', err.message) log.error('Config', 'process.on(unhandledRejection) promise.catch(%s)', err.message)
console.error('Config', err) // I don't know if log.error has similar full trace print support like console.error console.error('Config', err) // I don't know if log.error has similar full trace print support like console.error
}) })
}) })
...@@ -90,104 +89,49 @@ export type PuppetName = 'web' ...@@ -90,104 +89,49 @@ export type PuppetName = 'web'
| 'android' | 'android'
| 'ios' | 'ios'
export interface ConfigSetting { export interface DefaultSetting {
DEFAULT_HEAD : number, DEFAULT_HEAD : number,
DEFAULT_PORT : number, DEFAULT_PORT : number,
DEFAULT_PUPPET : PuppetName DEFAULT_PUPPET : PuppetName,
DEFAULT_APIHOST : string DEFAULT_APIHOST : string,
DEFAULT_PROFILE : string DEFAULT_PROFILE : string,
DEFAULT_TOKEN : string DEFAULT_TOKEN : string,
DEFAULT_PROTOCOL : string DEFAULT_PROTOCOL : string,
profile : string
token : string
debug : boolean
head: boolean
puppet: PuppetName
apihost: string
validApiHost: (host: string) => boolean
httpPort: number
_puppetInstance: Puppet | null
puppetInstance(): Puppet
puppetInstance(empty: null): void
puppetInstance(instance: Puppet): void
puppetInstance(instance?: Puppet | null): Puppet | void,
gitRevision(): string | null,
docker: boolean,
} }
/* tslint:disable:variable-name */ /* tslint:disable:variable-name */
/* tslint:disable:no-var-requires */ /* tslint:disable:no-var-requires */
export const config: ConfigSetting = pkg.wechaty export const DEFAULT_SETTING = pkg.wechaty as DefaultSetting
/** export class Config {
* 1. ENVIRONMENT VARIABLES + PACKAGES.JSON (default) public default = DEFAULT_SETTING
*/
Object.assign(config, {
apihost: process.env['WECHATY_APIHOST'] || config.DEFAULT_APIHOST,
head: ('WECHATY_HEAD' in process.env) ? (!!process.env['WECHATY_HEAD']) : (!!(config.DEFAULT_HEAD)),
puppet: process.env['WECHATY_PUPPET'] || config.DEFAULT_PUPPET,
validApiHost,
})
function validApiHost(apihost: string): boolean { public apihost = process.env['WECHATY_APIHOST'] || DEFAULT_SETTING.DEFAULT_APIHOST
if (/^[a-zA-Z0-9\.\-\_]+:?[0-9]*$/.test(apihost)) { public head = ('WECHATY_HEAD' in process.env) ? (!!process.env['WECHATY_HEAD']) : (!!(DEFAULT_SETTING.DEFAULT_HEAD))
return true public puppet = (process.env['WECHATY_PUPPET'] || DEFAULT_SETTING.DEFAULT_PUPPET) as PuppetName
}
throw new Error('validApiHost() fail for ' + apihost)
}
validApiHost(config.apihost)
/** public profile = process.env['WECHATY_PROFILE'] || null // DO NOT set DEFAULT_PROFILE, because sometimes user do not want to save session
* 2. ENVIRONMENT VARIABLES (only) 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'])
Object.assign(config, {
// 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,
})
/** public httpPort = process.env['PORT'] || process.env['WECHATY_PORT'] || DEFAULT_SETTING.DEFAULT_PORT
* 3. Service Settings public docker = !!(process.env['WECHATY_DOCKER'])
*/
Object.assign(config, {
// get PORT form cloud service env, ie: heroku
httpPort: process.env['PORT'] || process.env['WECHATY_PORT'] || config.DEFAULT_PORT,
})
/** private _puppetInstance: Puppet | null = null
* 4. Envioronment Identify
*/
Object.assign(config, {
docker: !!process.env['WECHATY_DOCKER'],
isGlobal: isWechatyInstalledGlobal(),
})
function isWechatyInstalledGlobal() { constructor() {
/** log.verbose('Config', 'constructor()')
* TODO: this.validApiHost(this.apihost)
* 1. check /node_modules/wechaty }
* 2. return true if exists
* 3. otherwise return false
*/
return false
}
/** /**
* 5. live setting * 5. live setting
*/ */
function puppetInstance(): Puppet public puppetInstance(): Puppet
function puppetInstance(empty: null): void public puppetInstance(empty: null): void
function puppetInstance(instance: Puppet): void public puppetInstance(instance: Puppet): void
function puppetInstance(instance?: Puppet | null): Puppet | void { public puppetInstance(instance?: Puppet | null): Puppet | void {
if (typeof instance === 'undefined') { if (typeof instance === 'undefined') {
if (!this._puppetInstance) { if (!this._puppetInstance) {
...@@ -205,9 +149,9 @@ function puppetInstance(instance?: Puppet | null): Puppet | void { ...@@ -205,9 +149,9 @@ function puppetInstance(instance?: Puppet | null): Puppet | void {
this._puppetInstance = instance this._puppetInstance = instance
return return
} }
function gitVersion(): string | null { public gitRevision(): string | null {
const dotGitPath = path.join(__dirname, '..', '.git') // only for ts-node, not for dist const dotGitPath = path.join(__dirname, '..', '.git') // only for ts-node, not for dist
// const gitLogArgs = ['log', '--oneline', '-1'] // const gitLogArgs = ['log', '--oneline', '-1']
// TODO: use git rev-parse HEAD ? // TODO: use git rev-parse HEAD ?
...@@ -238,12 +182,15 @@ function gitVersion(): string | null { ...@@ -238,12 +182,15 @@ function gitVersion(): string | null {
log.silly('Wechaty', 'version() form development environment is not availble: %s', e.message) log.silly('Wechaty', 'version() form development environment is not availble: %s', e.message)
return null return null
} }
} }
Object.assign(config, { public validApiHost(apihost: string): boolean {
gitVersion, if (/^[a-zA-Z0-9\.\-\_]+:?[0-9]*$/.test(apihost)) {
puppetInstance, return true
}) }
throw new Error('validApiHost() fail for ' + apihost)
}
}
export interface Sayable { export interface Sayable {
say(content: string, replyTo?: any|any[]): Promise<boolean> say(content: string, replyTo?: any|any[]): Promise<boolean>
...@@ -257,4 +204,5 @@ export { ...@@ -257,4 +204,5 @@ export {
Raven, Raven,
} }
export const config = new Config()
export default config export default config
...@@ -47,7 +47,7 @@ export class IoClient { ...@@ -47,7 +47,7 @@ export class IoClient {
) { ) {
log.verbose('IoClient', 'constructor({ token = %s})', options.token) log.verbose('IoClient', 'constructor({ token = %s})', options.token)
options.token = options.token || config.token || config.DEFAULT_TOKEN, options.token = options.token || config.token || config.default.DEFAULT_TOKEN
options.wechaty = options.wechaty || Wechaty.instance({ profile: this.options.token }) options.wechaty = options.wechaty || Wechaty.instance({ profile: this.options.token })
this.io = new Io({ this.io = new Io({
......
...@@ -70,7 +70,7 @@ export class Io { ...@@ -70,7 +70,7 @@ export class Io {
private options: IoOptions, private options: IoOptions,
) { ) {
options.apihost = options.apihost || config.apihost options.apihost = options.apihost || config.apihost
options.protocol = options.protocol || config.DEFAULT_PROTOCOL options.protocol = options.protocol || config.default.DEFAULT_PROTOCOL
this.uuid = options.wechaty.uuid this.uuid = options.wechaty.uuid
......
...@@ -17,7 +17,7 @@ export class Profile { ...@@ -17,7 +17,7 @@ export class Profile {
private file : string | null private file : string | null
constructor( constructor(
public name: string = config.profile, public name = config.profile,
) { ) {
log.verbose('Profile', 'constructor(%s)', name) log.verbose('Profile', 'constructor(%s)', name)
......
...@@ -59,7 +59,7 @@ test('Export of the Framework', async t => { ...@@ -59,7 +59,7 @@ test('Export of the Framework', async t => {
test('Config setting', async t => { test('Config setting', async t => {
t.ok(config , 'should export Config') t.ok(config , 'should export Config')
t.ok(config.DEFAULT_PUPPET , 'should has DEFAULT_PUPPET') t.ok(config.default.DEFAULT_PUPPET , 'should has DEFAULT_PUPPET')
}) })
test('event:start/stop', async t => { test('event:start/stop', async t => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册