mirror of
https://github.com/louislam/uptime-kuma.git
synced 2025-08-21 00:05:34 +08:00
Merge branch 'master' into 1.23.14-to-2.0.0
# Conflicts: # src/lang/en.json # src/util.js # src/util.ts
This commit is contained in:
309
src/util.ts
309
src/util.ts
@@ -1,16 +1,24 @@
|
||||
/* eslint-disable camelcase */
|
||||
/*!
|
||||
// Common Util for frontend and backend
|
||||
//
|
||||
// DOT NOT MODIFY util.js!
|
||||
// Need to run "tsc" to compile if there are any changes.
|
||||
// Need to run "npm run tsc" to compile if there are any changes.
|
||||
//
|
||||
// Backend uses the compiled file util.js
|
||||
// Frontend uses util.ts
|
||||
*/
|
||||
|
||||
import dayjs from "dayjs";
|
||||
|
||||
// For loading dayjs plugins, don't remove event though it is not used in this file
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import * as timezone from "dayjs/plugin/timezone";
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import * as utc from "dayjs/plugin/utc";
|
||||
|
||||
export const isDev = process.env.NODE_ENV === "development";
|
||||
export const isNode = typeof process !== "undefined" && process?.versions?.node;
|
||||
export const appName = "Uptime Kuma";
|
||||
export const DOWN = 0;
|
||||
export const UP = 1;
|
||||
@@ -29,6 +37,67 @@ export const SQL_DATETIME_FORMAT_WITHOUT_SECOND = "YYYY-MM-DD HH:mm";
|
||||
export const MAX_INTERVAL_SECOND = 2073600; // 24 days
|
||||
export const MIN_INTERVAL_SECOND = 20; // 20 seconds
|
||||
|
||||
// Console colors
|
||||
// https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color
|
||||
export const CONSOLE_STYLE_Reset = "\x1b[0m";
|
||||
export const CONSOLE_STYLE_Bright = "\x1b[1m";
|
||||
export const CONSOLE_STYLE_Dim = "\x1b[2m";
|
||||
export const CONSOLE_STYLE_Underscore = "\x1b[4m";
|
||||
export const CONSOLE_STYLE_Blink = "\x1b[5m";
|
||||
export const CONSOLE_STYLE_Reverse = "\x1b[7m";
|
||||
export const CONSOLE_STYLE_Hidden = "\x1b[8m";
|
||||
|
||||
export const CONSOLE_STYLE_FgBlack = "\x1b[30m";
|
||||
export const CONSOLE_STYLE_FgRed = "\x1b[31m";
|
||||
export const CONSOLE_STYLE_FgGreen = "\x1b[32m";
|
||||
export const CONSOLE_STYLE_FgYellow = "\x1b[33m";
|
||||
export const CONSOLE_STYLE_FgBlue = "\x1b[34m";
|
||||
export const CONSOLE_STYLE_FgMagenta = "\x1b[35m";
|
||||
export const CONSOLE_STYLE_FgCyan = "\x1b[36m";
|
||||
export const CONSOLE_STYLE_FgWhite = "\x1b[37m";
|
||||
export const CONSOLE_STYLE_FgGray = "\x1b[90m";
|
||||
export const CONSOLE_STYLE_FgOrange = "\x1b[38;5;208m";
|
||||
export const CONSOLE_STYLE_FgLightGreen = "\x1b[38;5;119m";
|
||||
export const CONSOLE_STYLE_FgLightBlue = "\x1b[38;5;117m";
|
||||
export const CONSOLE_STYLE_FgViolet = "\x1b[38;5;141m";
|
||||
export const CONSOLE_STYLE_FgBrown = "\x1b[38;5;130m";
|
||||
export const CONSOLE_STYLE_FgPink = "\x1b[38;5;219m";
|
||||
|
||||
export const CONSOLE_STYLE_BgBlack = "\x1b[40m";
|
||||
export const CONSOLE_STYLE_BgRed = "\x1b[41m";
|
||||
export const CONSOLE_STYLE_BgGreen = "\x1b[42m";
|
||||
export const CONSOLE_STYLE_BgYellow = "\x1b[43m";
|
||||
export const CONSOLE_STYLE_BgBlue = "\x1b[44m";
|
||||
export const CONSOLE_STYLE_BgMagenta = "\x1b[45m";
|
||||
export const CONSOLE_STYLE_BgCyan = "\x1b[46m";
|
||||
export const CONSOLE_STYLE_BgWhite = "\x1b[47m";
|
||||
export const CONSOLE_STYLE_BgGray = "\x1b[100m";
|
||||
|
||||
const consoleModuleColors = [
|
||||
CONSOLE_STYLE_FgCyan,
|
||||
CONSOLE_STYLE_FgGreen,
|
||||
CONSOLE_STYLE_FgLightGreen,
|
||||
CONSOLE_STYLE_FgBlue,
|
||||
CONSOLE_STYLE_FgLightBlue,
|
||||
CONSOLE_STYLE_FgMagenta,
|
||||
CONSOLE_STYLE_FgOrange,
|
||||
CONSOLE_STYLE_FgViolet,
|
||||
CONSOLE_STYLE_FgBrown,
|
||||
CONSOLE_STYLE_FgPink,
|
||||
];
|
||||
|
||||
const consoleLevelColors : Record<string, string> = {
|
||||
"INFO": CONSOLE_STYLE_FgCyan,
|
||||
"WARN": CONSOLE_STYLE_FgYellow,
|
||||
"ERROR": CONSOLE_STYLE_FgRed,
|
||||
"DEBUG": CONSOLE_STYLE_FgGray,
|
||||
};
|
||||
|
||||
/**
|
||||
* Flip the status of s
|
||||
* @param s input status: UP or DOWN
|
||||
* @returns {number} UP or DOWN
|
||||
*/
|
||||
export const badgeConstants = {
|
||||
naColor: "#999",
|
||||
defaultUpColor: "#66c20a",
|
||||
@@ -65,6 +134,7 @@ export function flipStatus(s: number) {
|
||||
/**
|
||||
* Delays for specified number of seconds
|
||||
* @param ms Number of milliseconds to sleep for
|
||||
* @returns {Promise<void>} Promise that resolves after ms
|
||||
*/
|
||||
export function sleep(ms: number) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
@@ -72,7 +142,8 @@ export function sleep(ms: number) {
|
||||
|
||||
/**
|
||||
* PHP's ucfirst
|
||||
* @param str
|
||||
* @param str string input
|
||||
* @returns {string} string with first letter capitalized
|
||||
*/
|
||||
export function ucfirst(str: string) {
|
||||
if (!str) {
|
||||
@@ -84,11 +155,11 @@ export function ucfirst(str: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use log.debug
|
||||
* @since https://github.com/louislam/uptime-kuma/pull/910
|
||||
* @param msg
|
||||
* @deprecated Use log.debug (https://github.com/louislam/uptime-kuma/pull/910)
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
export function debug(msg: any) {
|
||||
export function debug(msg: unknown) {
|
||||
log.log("", msg, "debug");
|
||||
}
|
||||
|
||||
@@ -103,20 +174,23 @@ class Logger {
|
||||
* "info_monitor",
|
||||
* ]
|
||||
*/
|
||||
hideLog : any = {
|
||||
hideLog : Record<string, string[]> = {
|
||||
info: [],
|
||||
warn: [],
|
||||
error: [],
|
||||
debug: [],
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
constructor() {
|
||||
if (typeof process !== "undefined" && process.env.UPTIME_KUMA_HIDE_LOG) {
|
||||
let list = process.env.UPTIME_KUMA_HIDE_LOG.split(",").map(v => v.toLowerCase());
|
||||
const list = process.env.UPTIME_KUMA_HIDE_LOG.split(",").map(v => v.toLowerCase());
|
||||
|
||||
for (let pair of list) {
|
||||
for (const pair of list) {
|
||||
// split first "_" only
|
||||
let values = pair.split(/_(.*)/s);
|
||||
const values = pair.split(/_(.*)/s);
|
||||
|
||||
if (values.length >= 2) {
|
||||
this.hideLog[values[0]].push(values[1]);
|
||||
@@ -133,6 +207,7 @@ class Logger {
|
||||
* @param module The module the log comes from
|
||||
* @param msg Message to write
|
||||
* @param level Log level. One of INFO, WARN, ERROR, DEBUG or can be customized.
|
||||
* @returns {void}
|
||||
*/
|
||||
log(module: string, msg: any, level: string) {
|
||||
if (level === "DEBUG" && !isDev) {
|
||||
@@ -152,20 +227,76 @@ class Logger {
|
||||
} else {
|
||||
now = dayjs().format();
|
||||
}
|
||||
const formattedMessage = (typeof msg === "string") ? `${now} [${module}] ${level}: ${msg}` : msg;
|
||||
|
||||
if (level === "INFO") {
|
||||
console.info(formattedMessage);
|
||||
} else if (level === "WARN") {
|
||||
console.warn(formattedMessage);
|
||||
} else if (level === "ERROR") {
|
||||
console.error(formattedMessage);
|
||||
} else if (level === "DEBUG") {
|
||||
if (isDev) {
|
||||
console.log(formattedMessage);
|
||||
const levelColor = consoleLevelColors[level];
|
||||
const moduleColor = consoleModuleColors[intHash(module, consoleModuleColors.length)];
|
||||
|
||||
let timePart: string;
|
||||
let modulePart: string;
|
||||
let levelPart: string;
|
||||
let msgPart: string;
|
||||
|
||||
if (isNode) {
|
||||
// Add console colors
|
||||
switch (level) {
|
||||
case "DEBUG":
|
||||
timePart = CONSOLE_STYLE_FgGray + now + CONSOLE_STYLE_Reset;
|
||||
break;
|
||||
default:
|
||||
timePart = CONSOLE_STYLE_FgCyan + now + CONSOLE_STYLE_Reset;
|
||||
break;
|
||||
}
|
||||
|
||||
modulePart = "[" + moduleColor + module + CONSOLE_STYLE_Reset + "]";
|
||||
|
||||
levelPart = levelColor + `${level}:` + CONSOLE_STYLE_Reset;
|
||||
|
||||
switch (level) {
|
||||
case "ERROR":
|
||||
if (typeof msg === "string") {
|
||||
msgPart = CONSOLE_STYLE_FgRed + msg + CONSOLE_STYLE_Reset;
|
||||
} else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
case "DEBUG":
|
||||
if (typeof msg === "string") {
|
||||
msgPart = CONSOLE_STYLE_FgGray + msg + CONSOLE_STYLE_Reset;
|
||||
} else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
msgPart = msg;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
console.log(formattedMessage);
|
||||
// No console colors
|
||||
timePart = now;
|
||||
modulePart = `[${module}]`;
|
||||
levelPart = `${level}:`;
|
||||
msgPart = msg;
|
||||
}
|
||||
|
||||
// Write to console
|
||||
switch (level) {
|
||||
case "ERROR":
|
||||
console.error(timePart, modulePart, levelPart, msgPart);
|
||||
break;
|
||||
case "WARN":
|
||||
console.warn(timePart, modulePart, levelPart, msgPart);
|
||||
break;
|
||||
case "INFO":
|
||||
console.info(timePart, modulePart, levelPart, msgPart);
|
||||
break;
|
||||
case "DEBUG":
|
||||
if (isDev) {
|
||||
console.debug(timePart, modulePart, levelPart, msgPart);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
console.log(timePart, modulePart, levelPart, msgPart);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,8 +304,9 @@ class Logger {
|
||||
* Log an INFO message
|
||||
* @param module Module log comes from
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
info(module: string, msg: any) {
|
||||
info(module: string, msg: unknown) {
|
||||
this.log(module, msg, "info");
|
||||
}
|
||||
|
||||
@@ -182,8 +314,9 @@ class Logger {
|
||||
* Log a WARN message
|
||||
* @param module Module log comes from
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
warn(module: string, msg: any) {
|
||||
warn(module: string, msg: unknown) {
|
||||
this.log(module, msg, "warn");
|
||||
}
|
||||
|
||||
@@ -191,34 +324,37 @@ class Logger {
|
||||
* Log an ERROR message
|
||||
* @param module Module log comes from
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
error(module: string, msg: any) {
|
||||
this.log(module, msg, "error");
|
||||
error(module: string, msg: unknown) {
|
||||
this.log(module, msg, "error");
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a DEBUG message
|
||||
* @param module Module log comes from
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
debug(module: string, msg: any) {
|
||||
this.log(module, msg, "debug");
|
||||
debug(module: string, msg: unknown) {
|
||||
this.log(module, msg, "debug");
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an exeption as an ERROR
|
||||
* Log an exception as an ERROR
|
||||
* @param module Module log comes from
|
||||
* @param exception The exeption to include
|
||||
* @param exception The exception to include
|
||||
* @param msg The message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
exception(module: string, exception: any, msg: any) {
|
||||
let finalMessage = exception
|
||||
exception(module: string, exception: unknown, msg: unknown) {
|
||||
let finalMessage = exception;
|
||||
|
||||
if (msg) {
|
||||
finalMessage = `${msg}: ${exception}`
|
||||
finalMessage = `${msg}: ${exception}`;
|
||||
}
|
||||
|
||||
this.log(module, finalMessage , "error");
|
||||
this.log(module, finalMessage, "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +367,7 @@ declare global { interface String { replaceAll(str: string, newStr: string): str
|
||||
* https://gomakethings.com/how-to-replace-a-section-of-a-string-with-another-one-with-vanilla-js/
|
||||
* @author Chris Ferdinandi
|
||||
* @license MIT
|
||||
* @returns {void}
|
||||
*/
|
||||
export function polyfill() {
|
||||
if (!String.prototype.replaceAll) {
|
||||
@@ -249,22 +386,30 @@ export function polyfill() {
|
||||
export class TimeLogger {
|
||||
startTime: number;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
constructor() {
|
||||
this.startTime = dayjs().valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* Output time since start of monitor
|
||||
* @param name Name of monitor
|
||||
* @returns {void}
|
||||
*/
|
||||
print(name: string) {
|
||||
if (isDev && process.env.TIMELOGGER === "1") {
|
||||
console.log(name + ": " + (dayjs().valueOf() - this.startTime) + "ms")
|
||||
console.log(name + ": " + (dayjs().valueOf() - this.startTime) + "ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random number between min (inclusive) and max (exclusive)
|
||||
* @param min minumim value, inclusive
|
||||
* @param max maximum value, exclusive
|
||||
* @returns {number} Random number
|
||||
*/
|
||||
export function getRandomArbitrary(min: number, max: number) {
|
||||
return Math.random() * (max - min) + min;
|
||||
@@ -278,6 +423,9 @@ export function getRandomArbitrary(min: number, max: number) {
|
||||
* if min isn't an integer) and no greater than max (or the next integer
|
||||
* lower than max if max isn't an integer).
|
||||
* Using Math.round() will give you a non-uniform distribution!
|
||||
* @param min minumim value, inclusive
|
||||
* @param max maximum value, exclusive
|
||||
* @returns {number} Random number
|
||||
*/
|
||||
export function getRandomInt(min: number, max: number) {
|
||||
min = Math.ceil(min);
|
||||
@@ -288,14 +436,15 @@ export function getRandomInt(min: number, max: number) {
|
||||
/**
|
||||
* Returns either the NodeJS crypto.randomBytes() function or its
|
||||
* browser equivalent implemented via window.crypto.getRandomValues()
|
||||
* @returns {Uint8Array} Random bytes
|
||||
*/
|
||||
let getRandomBytes = (
|
||||
(typeof window !== 'undefined' && window.crypto)
|
||||
const getRandomBytes = (
|
||||
(typeof window !== "undefined" && window.crypto)
|
||||
|
||||
// Browsers
|
||||
? function () {
|
||||
return (numBytes: number) => {
|
||||
let randomBytes = new Uint8Array(numBytes);
|
||||
const randomBytes = new Uint8Array(numBytes);
|
||||
for (let i = 0; i < numBytes; i += 65536) {
|
||||
window.crypto.getRandomValues(randomBytes.subarray(i, i + Math.min(numBytes - i, 65536)));
|
||||
}
|
||||
@@ -303,8 +452,9 @@ let getRandomBytes = (
|
||||
};
|
||||
}
|
||||
|
||||
// Node
|
||||
: function() {
|
||||
// Node
|
||||
: function () {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require("crypto").randomBytes;
|
||||
}
|
||||
)();
|
||||
@@ -320,35 +470,38 @@ export function getCryptoRandomInt(min: number, max: number):number {
|
||||
|
||||
// synchronous version of: https://github.com/joepie91/node-random-number-csprng
|
||||
|
||||
const range = max - min
|
||||
if (range >= Math.pow(2, 32))
|
||||
console.log("Warning! Range is too large.")
|
||||
|
||||
let tmpRange = range
|
||||
let bitsNeeded = 0
|
||||
let bytesNeeded = 0
|
||||
let mask = 1
|
||||
|
||||
while (tmpRange > 0) {
|
||||
if (bitsNeeded % 8 === 0) bytesNeeded += 1
|
||||
bitsNeeded += 1
|
||||
mask = mask << 1 | 1
|
||||
tmpRange = tmpRange >>> 1
|
||||
const range = max - min;
|
||||
if (range >= Math.pow(2, 32)) {
|
||||
console.log("Warning! Range is too large.");
|
||||
}
|
||||
|
||||
const randomBytes = getRandomBytes(bytesNeeded)
|
||||
let randomValue = 0
|
||||
let tmpRange = range;
|
||||
let bitsNeeded = 0;
|
||||
let bytesNeeded = 0;
|
||||
let mask = 1;
|
||||
|
||||
while (tmpRange > 0) {
|
||||
if (bitsNeeded % 8 === 0) {
|
||||
bytesNeeded += 1;
|
||||
}
|
||||
bitsNeeded += 1;
|
||||
mask = mask << 1 | 1;
|
||||
tmpRange = tmpRange >>> 1;
|
||||
}
|
||||
|
||||
const randomBytes = getRandomBytes(bytesNeeded);
|
||||
let randomValue = 0;
|
||||
|
||||
for (let i = 0; i < bytesNeeded; i++) {
|
||||
randomValue |= randomBytes[i] << 8 * i
|
||||
randomValue |= randomBytes[i] << 8 * i;
|
||||
}
|
||||
|
||||
randomValue = randomValue & mask;
|
||||
|
||||
if (randomValue <= range) {
|
||||
return min + randomValue
|
||||
return min + randomValue;
|
||||
} else {
|
||||
return getCryptoRandomInt(min, max)
|
||||
return getCryptoRandomInt(min, max);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,6 +542,7 @@ export function getMaintenanceRelativeURL(id: string) {
|
||||
* Parse to Time Object that used in VueDatePicker
|
||||
* @param {string} time E.g. 12:00
|
||||
* @returns object
|
||||
* @throws {Error} if time string is invalid
|
||||
*/
|
||||
export function parseTimeObject(time: string) {
|
||||
if (!time) {
|
||||
@@ -398,17 +552,17 @@ export function parseTimeObject(time: string) {
|
||||
};
|
||||
}
|
||||
|
||||
let array = time.split(":");
|
||||
const array = time.split(":");
|
||||
|
||||
if (array.length < 2) {
|
||||
throw new Error("parseVueDatePickerTimeFormat: Invalid Time");
|
||||
}
|
||||
|
||||
let obj = {
|
||||
const obj = {
|
||||
hours: parseInt(array[0]),
|
||||
minutes: parseInt(array[1]),
|
||||
seconds: 0,
|
||||
}
|
||||
};
|
||||
if (array.length >= 3) {
|
||||
obj.seconds = parseInt(array[2]);
|
||||
}
|
||||
@@ -416,7 +570,9 @@ export function parseTimeObject(time: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns string e.g. 12:00
|
||||
* Parse time to string from object {hours: number, minutes: number, seconds?: number}
|
||||
* @param obj object to parse
|
||||
* @returns {string} e.g. 12:00
|
||||
*/
|
||||
export function parseTimeFromTimeObject(obj : any) {
|
||||
if (!obj) {
|
||||
@@ -425,10 +581,10 @@ export function parseTimeFromTimeObject(obj : any) {
|
||||
|
||||
let result = "";
|
||||
|
||||
result += obj.hours.toString().padStart(2, "0") + ":" + obj.minutes.toString().padStart(2, "0")
|
||||
result += obj.hours.toString().padStart(2, "0") + ":" + obj.minutes.toString().padStart(2, "0");
|
||||
|
||||
if (obj.seconds) {
|
||||
result += ":" + obj.seconds.toString().padStart(2, "0")
|
||||
result += ":" + obj.seconds.toString().padStart(2, "0");
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -444,7 +600,8 @@ export function isoToUTCDateTime(input : string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param input
|
||||
* @param input valid datetime string
|
||||
* @returns {string} ISO DateTime string
|
||||
*/
|
||||
export function utcToISODateTime(input : string) {
|
||||
return dayjs.utc(input).toISOString();
|
||||
@@ -452,8 +609,11 @@ export function utcToISODateTime(input : string) {
|
||||
|
||||
/**
|
||||
* For SQL_DATETIME_FORMAT
|
||||
* @param input valid datetime string
|
||||
* @param format Format to return
|
||||
* @returns A string date of SQL_DATETIME_FORMAT
|
||||
*/
|
||||
export function utcToLocal(input : string, format = SQL_DATETIME_FORMAT) {
|
||||
export function utcToLocal(input : string, format = SQL_DATETIME_FORMAT) : string {
|
||||
return dayjs.utc(input).local().format(format);
|
||||
}
|
||||
|
||||
@@ -466,3 +626,20 @@ export function utcToLocal(input : string, format = SQL_DATETIME_FORMAT) {
|
||||
export function localToUTC(input : string, format = SQL_DATETIME_FORMAT) {
|
||||
return dayjs(input).utc().format(format);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a decimal integer number from a string
|
||||
* @param str Input
|
||||
* @param length Default is 10 which means 0 - 9
|
||||
* @returns {number} output number
|
||||
*/
|
||||
export function intHash(str : string, length = 10) : number {
|
||||
// A simple hashing function (you can use more complex hash functions if needed)
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash += str.charCodeAt(i);
|
||||
}
|
||||
// Normalize the hash to the range [0, 10]
|
||||
return (hash % length + length) % length; // Ensure the result is non-negative
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user