config.ts 6.8 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
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19
/// <reference path="./typings.d.ts" />
20

21 22 23
import fs    from 'fs'
import os    from 'os'
import path  from 'path'
24

25 26 27
import readPkgUp from 'read-pkg-up'
import Raven     from 'raven'
import qrImage   from 'qr-image'
28 29 30 31 32

import { log }    from 'brolog'
import {
  FileBox,
}                 from 'file-box'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33

34 35 36
import {
  PuppetName,
}             from './puppet-config'
37

38 39 40 41 42
// https://github.com/Microsoft/TypeScript/issues/14151#issuecomment-280812617
if (!Symbol.asyncIterator) {
  (<any>Symbol).asyncIterator = Symbol.for('Symbol.asyncIterator')
}

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

46 47 48 49 50 51 52 53 54 55
/**
 * Raven.io
 */
Raven.disableConsoleAlerts()

Raven
.config(
  process.env.NODE_ENV === 'production'
    && 'https://f6770399ee65459a82af82650231b22c:d8d11b283deb441e807079b8bb2c45cd@sentry.io/179672',
  {
56
    release: VERSION,
57
    tags: {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
58
      git_commit: '',
59
      platform:   !!process.env['WECHATY_DOCKER']
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
                  ? 'docker'
                  : os.platform(),
    },
  },
)
.install()

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

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

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
79
const logLevel = process.env['WECHATY_LOG']
80
if (logLevel) {
81
  log.level(logLevel.toLowerCase() as any)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
82
  log.silly('Config', 'WECHATY_LOG set level to %s', logLevel)
83 84 85 86 87
}

/**
 * to handle unhandled exceptions
 */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
88
if (log.level() === 'verbose' || log.level() === 'silly') {
89 90 91 92 93 94
  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 (李卓桓) 已提交
95
      log.error('Config', 'process.on(unhandledRejection) promise.catch(%s)', err.message)
96 97 98
      console.error('Config', err) // I don't know if log.error has similar full trace print support like console.error
    })
  })
99
}
100

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
101
export interface DefaultSetting {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
102 103
  DEFAULT_HEAD     : number,
  DEFAULT_PORT     : number,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
104 105 106 107 108
  DEFAULT_PUPPET   : PuppetName,
  DEFAULT_APIHOST  : string,
  DEFAULT_PROFILE  : string,
  DEFAULT_TOKEN    : string,
  DEFAULT_PROTOCOL : string,
109
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
115 116
export class Config {
  public default = DEFAULT_SETTING
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
118 119
  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))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
120
  public puppet  = (process.env['WECHATY_PUPPET']    || DEFAULT_SETTING.DEFAULT_PUPPET).toLowerCase() as PuppetName
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
121

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122 123 124
  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 (李卓桓) 已提交
125

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

129
  // private _puppetInstance: Puppet | null = null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130 131 132 133 134

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

136
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137
   * 5. live setting
138
   */
139 140 141
  // public puppetInstance(): Puppet
  // public puppetInstance(empty: null): void
  // public puppetInstance(instance: Puppet): void
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
142

143
  // public puppetInstance(instance?: Puppet | null): Puppet | void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
144

145 146 147 148 149
  //   if (typeof instance === 'undefined') {
  //     if (!this._puppetInstance) {
  //       throw new Error('no puppet instance')
  //     }
  //     return this._puppetInstance
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150

151 152 153 154 155
  //   } else if (instance === null) {
  //     log.verbose('Config', 'puppetInstance(null)')
  //     this._puppetInstance = null
  //     return
  //   }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156

157 158 159
  //   log.verbose('Config', 'puppetInstance(%s)', instance.constructor.name)
  //   this._puppetInstance = instance
  //   return
160

161
  // }
162

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  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
193
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
194
  }
195

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
196 197 198 199 200
  public validApiHost(apihost: string): boolean {
    if (/^[a-zA-Z0-9\.\-\_]+:?[0-9]*$/.test(apihost)) {
      return true
    }
    throw new Error('validApiHost() fail for ' + apihost)
201 202 203
  }
}

204 205 206 207 208 209 210 211 212 213 214
export const CHATIE_OFFICIAL_ACCOUNT_ID = 'gh_051c89260e5d'

export function qrCodeForChatie(): FileBox {
  const CHATIE_OFFICIAL_ACCOUNT_QRCODE = 'http://weixin.qq.com/r/qymXj7DEO_1ErfTs93y5'
  const name                           = 'qrcode-for-chatie.png'
  const type                           = 'png'

  const qrStream = qrImage.image(CHATIE_OFFICIAL_ACCOUNT_QRCODE, { type })
  return FileBox.fromStream(qrStream, name)
}

215
export interface Sayable {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
216
  say(text: string, replyTo?: any|any[]): Promise<void>
217
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
219 220 221 222
// http://jkorpela.fi/chars/spaces.html
// String.fromCharCode(8197)
export const FOUR_PER_EM_SPACE = String.fromCharCode(0x2005)

223 224 225 226
export function qrcodeValueToImageUrl(qrcodeValue: string): string {
  return [
    'https://api.qrserver.com/v1/create-qr-code/?data=',
    encodeURIComponent(qrcodeValue),
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227
    '&size=220x220&margin=20',
228 229 230
  ].join('')
}

231
export {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
232
  log,
233
  Raven,
234 235
}

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