Skip to content

Commit

Permalink
feat: support msg push(wechat&mail)
Browse files Browse the repository at this point in the history
  • Loading branch information
umuoy1 committed Jan 23, 2022
1 parent 775b04b commit 1081a07
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 24 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"log4js": "^5.3.0",
"md5-node": "^1.0.1",
"node-rsa": "^1.0.8",
"nodemailer": "^6.7.2",
"qr-image": "^3.2.0",
"qrcode-terminal": "^0.12.0",
"qs": "^6.9.4",
Expand Down
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global.config = require('../templates/info.json')
16 changes: 7 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import "@/config"

import * as fs from "fs";
import { join, basename } from "path";

Expand All @@ -8,23 +10,23 @@ import { getExtendedLogger } from "@/log";
import { changeFileStatus, emitter } from "@/util/utils";
import { Scheduler } from "@/type/scheduler";
import { Recorder } from "@/engine/message";
import { Config } from "@/type/config";
import { FileStatus } from "@/type/fileStatus";
import { FileHound } from "@/util/utils"


type Schedulers = {
[key: string]: {
scheduler: Scheduler,
timer?: NodeJS.Timer
}
}


export class App {
private _logger: Logger;
private _user!: User; // will init in initUser()
private _schedulers: Schedulers;
private _recorderPool: Map<string, Recorder>;
private _config: Config;
static _i: any;

get logger(): Logger {
Expand All @@ -43,13 +45,7 @@ export class App {
return this._recorderPool
}

get config(): Config {
return this._config
}

constructor() {
global.config = this._config = require('../templates/info.json')

this._logger = getExtendedLogger(`APP`)
this._schedulers = {}
this._recorderPool = new Map<string, Recorder>()
Expand Down Expand Up @@ -77,6 +73,8 @@ export class App {
await this.initStreamDisconnect()
await this.initSyncFileStatus()
await this.initSchedule()

this.logger.error("啊?", "发生了错误", "怎么会是呢")
} catch (e) {
return reject(e)
}
Expand Down Expand Up @@ -192,7 +190,7 @@ export class App {

this.logger.debug(`Sync fileStatus: ${file} ${JSON.stringify(obj, null, 2)}`)

const streamer = this.config.streamerInfo.find(elem => elem.name === obj.recorderName)
const streamer = global.config.streamerInfo.find(elem => elem.name === obj.recorderName)
if (!streamer)
continue

Expand Down
42 changes: 30 additions & 12 deletions src/log/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { log4js } from "@/log/config";
import { pushMsg } from "@/push";
import { LogLevel } from "@/type/config";

export function getExtendedLogger(category?: string | undefined): log4js.Logger {
return extend(log4js.getLogger(category), extendHandler)
}

// log4js/lib/levels.js
const ALL_VALUE = Number.MIN_VALUE,
TRACE = 5000,
DEBUG = 10000,
Expand All @@ -15,7 +14,7 @@ const ALL_VALUE = Number.MIN_VALUE,
OFF = Number.MAX_VALUE


const levels: any = {
const levels: { [key in LogLevel]: any } = {
ALL: { value: ALL_VALUE, colour: 'grey' },
TRACE: { value: TRACE, colour: 'blue' },
DEBUG: { value: DEBUG, colour: 'cyan' },
Expand All @@ -27,16 +26,35 @@ const levels: any = {
OFF: { value: OFF, colour: 'grey' }
}

const levelStrs = Object.keys(levels)

export function getExtendedLogger(category?: string | undefined): log4js.Logger {
return extend(log4js.getLogger(category), extendHandler)
}


const extendHandler: ProxyHandler<log4js.Logger> = {
get: (obj: any, prop) => {
const propName = prop.toString().toUpperCase()
const level = levels[propName]
if (level && level.value >= WARN) {
// 推送至用户
console.log("should push tu user")
get: function (obj: any, prop) {
const propStr = prop.toString().toUpperCase()

// Methods other than logger.<level>
if (levelStrs.indexOf(propStr) == -1) {
return obj[prop]
}

return obj[prop]
const level = levels[propStr as LogLevel]
const ori = obj[prop]

return async (...args: string[]) => {
const levelStr = global.config.StreamerHelper.logLevel.toUpperCase() as LogLevel

if (level && level.value >= levels[levelStr].value) {
process.nextTick(() => pushMsg(propStr as LogLevel, ...args))
}

return ori.apply(obj, args)

}

}
}
Expand Down
27 changes: 27 additions & 0 deletions src/push/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { LogLevel } from "@/type/config";
import { mail } from "@/push/mail";
import { wechat } from "@/push/wechat";

type AllowTypes = keyof typeof global.config.StreamerHelper.push
export type PushFunc = (level: LogLevel, ...args: string[]) => void

const pushConfig = global.config.StreamerHelper.push
const enables = Object.keys(pushConfig).filter(elem => pushConfig[elem as AllowTypes].enable) as Array<AllowTypes>
const pushFuncMap = new Map<AllowTypes, PushFunc>(
[
["mail", mail],
["wechat", wechat]
]
)

export const pushMsg = async (level: LogLevel, ...args: string[]) => {

for (const enable of enables) {
const pushFunc = pushFuncMap.get(enable)

if (pushFunc) {
pushFunc(level, ...args)
}
}

}
31 changes: 31 additions & 0 deletions src/push/mail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as dayjs from "dayjs"
const nodemailer = require("nodemailer")

import { PushFunc } from "@/push";
import { LogLevel } from "@/type/config";

export const mail: PushFunc = async (level: LogLevel, ...args: string[]) => {

const mailConfig = global.config.StreamerHelper.push.mail

const transporter = nodemailer.createTransport({
host: mailConfig.host,
port: mailConfig.port,
secure: mailConfig.secure,
auth: {
user: mailConfig.from,
pass: mailConfig.pwd,
},
});

const msg = args.join(";")
const html = `<p>告警信息: ${msg}</p> <p>级别: ${level}</p> <p>时间: ${dayjs().format()}</p>
`

transporter.sendMail({
from: mailConfig.from,
to: mailConfig.to,
subject: `StreamerHelper 发生 ${level} 级别告警`,
html,
})
}
21 changes: 21 additions & 0 deletions src/push/wechat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as dayjs from "dayjs"

import { $axios } from "@/http"
import { LogLevel } from "@/type/config"

export const wechat = async (level: LogLevel, ...args: string[]) => {

const msg = args.join(";")
const desp = `告警信息: ${msg}\n \n级别: ${level}\n \n时间: ${dayjs().format()}`

const params = {
text: decodeURIComponent(`StreamerHelper 发生 ${level} 级别告警`),
desp: decodeURIComponent(desp)
}

$axios.request({
url: `https://sctapi.ftqq.com/${global.config.StreamerHelper.push.wechat.sendKey}.send`,
method: "post",
params
})
}
22 changes: 20 additions & 2 deletions src/type/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,23 @@ export interface Config {
roomCheckTime: number,
recycleCheckTime: number,
videoPartLimitSize: number,
enableUpload: boolean
logLevel: LogLevel,
push: {
mail: {
enable: boolean,
host: string,
port: number,
from: string,
pwd: string,
to: string,
secure: boolean

},
wechat: {
enable: boolean,
sendKey: string
}
}
},
personInfo: PersonInfo,
streamerInfo: StreamerInfo[]
Expand Down Expand Up @@ -33,4 +49,6 @@ export interface StreamerInfo {
tid: number,
tags: string[]

}
}

export type LogLevel = "ALL" | "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL" | "MARK" | "OFF"
18 changes: 17 additions & 1 deletion templates/info-example.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,23 @@
"debug": false,
"roomCheckTime": 600,
"recycleCheckTime": 1800,
"videoPartLimitSize": 100
"videoPartLimitSize": 100,
"logLevel": "error",
"push": {
"email": {
"enable": true,
"host": "",
"port": 465,
"from": "",
"pwd": "",
"to": "",
"secure": true
},
"wechat": {
"enable": false,
"sendkey": ""
}
}
},
"personInfo": {
"nickname": "",
Expand Down

0 comments on commit 1081a07

Please sign in to comment.