Skip to content

Commit

Permalink
fix: time schedule and tencent update
Browse files Browse the repository at this point in the history
  • Loading branch information
Cnily03 committed Mar 14, 2024
1 parent 432fd46 commit 31ebfa1
Show file tree
Hide file tree
Showing 15 changed files with 358 additions and 257 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,4 @@ node_modules/**/*

dist/

*.self.js
*.self.json
data/**/*
29 changes: 15 additions & 14 deletions compile-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,22 @@ if (!fs.existsSync(templateOutDir)) {
const templateRootDir = path.resolve(rootDir, 'template')
const templateFiles = fs.readdirSync(templateRootDir).filter(file => file.endsWith('.ejs'))
for (let fn of templateFiles) {
let content = fs.readFileSync(path.resolve(templateRootDir, fn), 'utf8')
// <style inject="css/spectre.min.css" escape="false"></style>
content = content.replace(/<([a-zA-Z\-]+)\s+inject="([^"]+)"\s+escape="([^"]+)"\s*><\/([a-zA-Z\-]+)>/g,
function (substring, tag, inject, escape, closeTag) {
let injectFilePath = path.resolve(templateRootDir, inject)
let injectContent = fs.readFileSync(injectFilePath, 'utf8')
escape = escape === 'true' || escape === '1'
if (escape) {
injectContent = escapeHtml(injectContent)
}
return `<${tag}>${injectContent}</${closeTag}>`
}
)
// let content = fs.readFileSync(path.resolve(templateRootDir, fn), 'utf8')
// // <style inject="css/spectre.min.css" escape="false"></style>
// content = content.replace(/<([a-zA-Z\-]+)\s+inject="([^"]+)"\s+escape="([^"]+)"\s*><\/([a-zA-Z\-]+)>/g,
// function (substring, tag, inject, escape, closeTag) {
// let injectFilePath = path.resolve(templateRootDir, inject)
// let injectContent = fs.readFileSync(injectFilePath, 'utf8')
// escape = escape === 'true' || escape === '1'
// if (escape) {
// injectContent = escapeHtml(injectContent)
// }
// return `<${tag}>${injectContent}</${closeTag}>`
// }
// )

// write to outDir
let outFilePath = path.resolve(templateOutDir, fn)
fs.writeFileSync(outFilePath, content, 'utf8')
// fs.writeFileSync(outFilePath, content, 'utf8')
fs.copyFileSync(path.resolve(templateRootDir, fn), outFilePath)
}
7 changes: 5 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ssl-autoupdater",
"version": "0.1.0",
"version": "0.1.5",
"description": "Automatically update SSL certificate on different cloud platforms",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
26 changes: 24 additions & 2 deletions src/components/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ import "colors"

const date_string = () => new Date().toLocaleString().replace(/\/(\d)([^\d])/, "/0$1$2").replace(/\/(\d)([^\d])/, "/0$1$2").replace(/\//g, "-")

export class Output {
private session: Session;
export type OutputConstructor = new (session: Session, identifier?: string) => Output

export abstract class Output {
protected session: Session;
public identifier: string;

/**
* Output template class
* - Remember to implement session output via `session.appendLine`
*/
constructor(session: Session, identifier?: string) {
this.session = session;
if (typeof identifier === "string") {
Expand All @@ -15,6 +22,21 @@ export class Output {
}
}

abstract log(...args: any[]): any
abstract info(...args: any[]): any
abstract warn(...args: any[]): any
abstract error(...args: any[]): any
abstract debug(...args: any[]): any
abstract success(...args: any[]): any
abstract failure(...args: any[]): any
}

export class ConsoleOutput extends Output {

constructor(session: Session, identifier?: string) {
super(session, identifier)
}

private _output(consoleFunc: Function, append: string[], args: any[]) {
let date_str = date_string().gray
let append_str = append.join(" ")
Expand Down
91 changes: 52 additions & 39 deletions src/components/ssl-updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import MailSender from "@/utils/mail-sender"
import Timer from "@/utils/timer"
import Cache from "@/utils/cache"
import { Session } from "@/components/session"
import { Output } from "@/components/output"
import { ConsoleOutput, Output, OutputConstructor } from "@/components/output"
import fs from "fs"
import path from "path"
import { sha256 } from "@/utils/utils"
Expand All @@ -12,6 +12,17 @@ export type CertificateData = {
private: string
}

export type TriggerReturnTyoe<T> = {
/**
* 生成消息的原料
*/
msg_material: T,
/**
* 是否发送邮件
*/
send_mail: boolean
}

/**
* 根据域名和算法获取证书内容的函数,返回证书内容和私钥内容 \
* 如果文件不存在,则该文件内容返回 `undefined`
Expand Down Expand Up @@ -48,17 +59,11 @@ export type SSLUpdaterOptions = {
* 邮件发送器(默认不发送邮件)
*/
mailer?: MailSender
}

export type StatusRecord = {
new_cert_id: string,
old_cert_id: string,
domain: string,
sans: string[],
uploaded: boolean | null,
updated: boolean | null,
old_deleted: boolean | null,
comment: string
/**
* 输出的类构造器
* @experimental 该选项可能在未来的版本中移除
*/
outputCreator?: OutputConstructor
}

function genTimeBasedHash(identifier: string, random_upper: boolean = false) {
Expand Down Expand Up @@ -140,6 +145,12 @@ export default abstract class SSLUpdater {
}
else throw new TypeError("mailer must be an instance of MailSender");

// opts.outputCreator
let outputCreator = ConsoleOutput as OutputConstructor
if (opts.outputCreator instanceof Function && typeof opts.outputCreator.name === "string") {
outputCreator = opts.outputCreator;
}

// timer
let defaultTimerStart = new Date();
defaultTimerStart.setHours(4, 0, 0, 0)
Expand All @@ -149,7 +160,7 @@ export default abstract class SSLUpdater {
this.cache = new Cache();

this.session = new Session()
this.output = new Output(this.session, this.identifier);
this.output = new outputCreator(this.session, this.identifier);

// ID of setInterval
this.watch_pool = new Set();
Expand Down Expand Up @@ -178,41 +189,43 @@ export default abstract class SSLUpdater {
if (typeof d !== "string") throw new TypeError("Domains must be string or array of string")
});

let on_running = false, trigger_cnt = 0;
let func: () => any;
const itvid = setInterval(func = async () => {
if (on_running) return;
if (that.timer.is_expired()) {
that.timer.set_future();
let trigger_cnt = 0;
// let on_running = false;
const itvid = this.timer.watch(async (run_time) => {
// if (on_running) return;

on_running = true;
that.session.start();
// on_running = true;
that.session.start();

let trigger_id = genTimeBasedHash(this.identifier, false);
that.output.log(`[#${trigger_cnt}] Timer triggered, ID: ${trigger_id}`);
let status_record_array = await that.triggerUpdate(domains as string[])
.catch(err => {
that.output.error(err);
return [];
})
that.output.log(`[#${trigger_cnt}] Trigger complete`);
let trigger_id = genTimeBasedHash(this.identifier, false);
that.output.log(`[#${trigger_cnt}] Timer triggered, ID: ${trigger_id}`);
let { msg_material, send_mail } = await that.triggerUpdate(domains as string[])
.catch(err => {
that.output.error(err);
return { msg_material: [], send_mail: true }
})
that.output.log(`[#${trigger_cnt}] Trigger complete`);

that.session.end();
on_running = false;
that.session.end();
// on_running = false;

let message = that.genMsg(trigger_id, status_record_array, that.session.lines());
let message = that.genMsg(trigger_id, msg_material, that.session.lines());

if (send_mail) {
this.output.log("Sending message...")
let send_result = await that.sendMsg("[SSL Updater] 证书更新结果通知", message)
.catch(err => { that.output.error(err); })
if (send_result === "cancel") this.output.log("Send canceled")
else if (send_result === "failure") this.output.error("Send failed")
else this.output.log("Send done")

++trigger_cnt;
}
}, 10 * 1000)
func();

++trigger_cnt;

}, {
preventWhenRunning: true,
InstantlyRun: true
})

this.watch_pool.add(itvid);
return itvid;
Expand All @@ -222,15 +235,15 @@ export default abstract class SSLUpdater {
* 触发更新
* @param domains 检测的域名列表
*/
abstract triggerUpdate(domains: string[]): Promise<any[]>;
abstract triggerUpdate(domains: string[]): Promise<TriggerReturnTyoe<Object>>;

/**
* 解析状态记录
* @param trigger_id 触发 ID
* @param record_list 状态记录列表
* @param msg_material 生成消息的原料
* @param terminal_lines 终端输出
*/
abstract genMsg(trigger_id: string, record_list: any[], terminal_lines: string[]): string;
abstract genMsg(trigger_id: string, msg_material: Object, terminal_lines: string[]): string;

/**
* 发送消息
Expand Down
1 change: 0 additions & 1 deletion src/template/css/spectre-exp.min.css

This file was deleted.

1 change: 0 additions & 1 deletion src/template/css/spectre-icons.min.css

This file was deleted.

1 change: 0 additions & 1 deletion src/template/css/spectre.min.css

This file was deleted.

Loading

0 comments on commit 31ebfa1

Please sign in to comment.