From 08372d5adb22411b1e20537cbfaa9d1198b18f8b Mon Sep 17 00:00:00 2001 From: "Shishkevich D." <135337715+shishkevichd@users.noreply.github.com> Date: Fri, 7 Mar 2025 07:11:03 +0000 Subject: [PATCH 1/3] refactor: delete `base64js` instead of base64 library you can use built-in JS functions `btoa()` and `atob()` --- web/assets/base64/base64.min.js | 1 - web/assets/js/model/inbound.js | 4 ++-- web/assets/js/util/common.js | 11 ----------- web/assets/js/util/utils.js | 17 +++++++++++++++++ web/html/xui/inbounds.html | 1 - 5 files changed, 19 insertions(+), 15 deletions(-) delete mode 100644 web/assets/base64/base64.min.js diff --git a/web/assets/base64/base64.min.js b/web/assets/base64/base64.min.js deleted file mode 100644 index 37f374a4..00000000 --- a/web/assets/base64/base64.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory(global):typeof define==="function"&&define.amd?define(factory):factory(global)})(typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this,function(global){"use strict";var _Base64=global.Base64;var version="2.5.0";var buffer;if(typeof module!=="undefined"&&module.exports){try{buffer=eval("require('buffer').Buffer")}catch(err){buffer=undefined}}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64tab=function(bin){var t={};for(var i=0,l=bin.length;i>>6)+fromCharCode(128|cc&63):fromCharCode(224|cc>>>12&15)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}else{var cc=65536+(c.charCodeAt(0)-55296)*1024+(c.charCodeAt(1)-56320);return fromCharCode(240|cc>>>18&7)+fromCharCode(128|cc>>>12&63)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}};var re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;var utob=function(u){return u.replace(re_utob,cb_utob)};var cb_encode=function(ccc){var padlen=[0,2,1][ccc.length%3],ord=ccc.charCodeAt(0)<<16|(ccc.length>1?ccc.charCodeAt(1):0)<<8|(ccc.length>2?ccc.charCodeAt(2):0),chars=[b64chars.charAt(ord>>>18),b64chars.charAt(ord>>>12&63),padlen>=2?"=":b64chars.charAt(ord>>>6&63),padlen>=1?"=":b64chars.charAt(ord&63)];return chars.join("")};var btoa=global.btoa?function(b){return global.btoa(b)}:function(b){return b.replace(/[\s\S]{1,3}/g,cb_encode)};var _encode=buffer?buffer.from&&Uint8Array&&buffer.from!==Uint8Array.from?function(u){return(u.constructor===buffer.constructor?u:buffer.from(u)).toString("base64")}:function(u){return(u.constructor===buffer.constructor?u:new buffer(u)).toString("base64")}:function(u){return btoa(utob(u))};var encode=function(u,urisafe){return!urisafe?_encode(String(u)):_encode(String(u)).replace(/[+\/]/g,function(m0){return m0=="+"?"-":"_"}).replace(/=/g,"")};var encodeURI=function(u){return encode(u,true)};var re_btou=new RegExp(["[À-ß][€-¿]","[à-ï][€-¿]{2}","[ð-÷][€-¿]{3}"].join("|"),"g");var cb_btou=function(cccc){switch(cccc.length){case 4:var cp=(7&cccc.charCodeAt(0))<<18|(63&cccc.charCodeAt(1))<<12|(63&cccc.charCodeAt(2))<<6|63&cccc.charCodeAt(3),offset=cp-65536;return fromCharCode((offset>>>10)+55296)+fromCharCode((offset&1023)+56320);case 3:return fromCharCode((15&cccc.charCodeAt(0))<<12|(63&cccc.charCodeAt(1))<<6|63&cccc.charCodeAt(2));default:return fromCharCode((31&cccc.charCodeAt(0))<<6|63&cccc.charCodeAt(1))}};var btou=function(b){return b.replace(re_btou,cb_btou)};var cb_decode=function(cccc){var len=cccc.length,padlen=len%4,n=(len>0?b64tab[cccc.charAt(0)]<<18:0)|(len>1?b64tab[cccc.charAt(1)]<<12:0)|(len>2?b64tab[cccc.charAt(2)]<<6:0)|(len>3?b64tab[cccc.charAt(3)]:0),chars=[fromCharCode(n>>>16),fromCharCode(n>>>8&255),fromCharCode(n&255)];chars.length-=[0,0,2,1][padlen];return chars.join("")};var _atob=global.atob?function(a){return global.atob(a)}:function(a){return a.replace(/\S{1,4}/g,cb_decode)};var atob=function(a){return _atob(String(a).replace(/[^A-Za-z0-9\+\/]/g,""))};var _decode=buffer?buffer.from&&Uint8Array&&buffer.from!==Uint8Array.from?function(a){return(a.constructor===buffer.constructor?a:buffer.from(a,"base64")).toString()}:function(a){return(a.constructor===buffer.constructor?a:new buffer(a,"base64")).toString()}:function(a){return btou(_atob(a))};var decode=function(a){return _decode(String(a).replace(/[-_]/g,function(m0){return m0=="-"?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))};var noConflict=function(){var Base64=global.Base64;global.Base64=_Base64;return Base64};global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict,__buffer__:buffer};if(typeof Object.defineProperty==="function"){var noEnum=function(v){return{value:v,enumerable:false,writable:true,configurable:true}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)}));Object.defineProperty(String.prototype,"toBase64",noEnum(function(urisafe){return encode(this,urisafe)}));Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,true)}))}}if(global["Meteor"]){Base64=global.Base64}if(typeof module!=="undefined"&&module.exports){module.exports.Base64=global.Base64}else if(typeof define==="function"&&define.amd){define([],function(){return global.Base64})}return{Base64:global.Base64}}); \ No newline at end of file diff --git a/web/assets/js/model/inbound.js b/web/assets/js/model/inbound.js index d3d7d297..49fc8a7b 100644 --- a/web/assets/js/model/inbound.js +++ b/web/assets/js/model/inbound.js @@ -1302,7 +1302,7 @@ class Inbound extends XrayCommonClass { } } - return 'vmess://' + base64(JSON.stringify(obj, null, 2)); + return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2)); } genVLESSLink(address = '', port = this.port, forceTls, remark = '', clientId, flow) { @@ -1474,7 +1474,7 @@ class Inbound extends XrayCommonClass { if (this.isSS2022) password.push(settings.password); if (this.isSSMultiUser) password.push(clientPassword); - let link = `ss://${safeBase64(settings.method + ':' + password.join(':'))}@${address}:${port}`; + let link = `ss://${Base64.encode(`${settings.method}:${password.join(':')}`, true)}@${address}:${port}`; const url = new URL(link); for (const [key, value] of params) { url.searchParams.set(key, value) diff --git a/web/assets/js/util/common.js b/web/assets/js/util/common.js index df826aa9..3aa1549e 100644 --- a/web/assets/js/util/common.js +++ b/web/assets/js/util/common.js @@ -39,17 +39,6 @@ function cpuCoreFormat(cores) { } } -function base64(str) { - return Base64.encode(str); -} - -function safeBase64(str) { - return base64(str) - .replace(/\+/g, '-') - .replace(/=/g, '') - .replace(/\//g, '_'); -} - function formatSecond(second) { if (second < 60) { return second.toFixed(0) + 's'; diff --git a/web/assets/js/util/utils.js b/web/assets/js/util/utils.js index 30f1f6a2..a79ce3a0 100644 --- a/web/assets/js/util/utils.js +++ b/web/assets/js/util/utils.js @@ -478,4 +478,21 @@ class Wireguard { privateKey: secretKey.length > 0 ? secretKey : this.keyToBase64(privateKey) }; } +} + +class Base64 { + static encode(content = "", safe = false) { + if (safe) { + return window.btoa(content) + .replace(/\+/g, '-') + .replace(/=/g, '') + .replace(/\//g, '_') + } + + return window.btoa(content) + } + + static decode(content = "") { + return window.atob(content) + } } \ No newline at end of file diff --git a/web/html/xui/inbounds.html b/web/html/xui/inbounds.html index 86890926..93999e97 100644 --- a/web/html/xui/inbounds.html +++ b/web/html/xui/inbounds.html @@ -544,7 +544,6 @@ {{template "js" .}} - From be20335d558fc59da4823bbfe9a39ec5cc1c397a Mon Sep 17 00:00:00 2001 From: "Shishkevich D." <135337715+shishkevichd@users.noreply.github.com> Date: Fri, 7 Mar 2025 07:27:33 +0000 Subject: [PATCH 2/3] refactor: move copy function to utils.js --- web/assets/js/util/common.js | 18 ---------------- web/assets/js/util/utils.js | 32 ++++++++++++++++++++++++++++ web/html/common/qrcode_modal.html | 16 ++++++++------ web/html/common/text_modal.html | 10 +++++---- web/html/xui/inbound_info_modal.html | 22 ++++++++++--------- web/html/xui/inbounds.html | 8 +++---- 6 files changed, 63 insertions(+), 43 deletions(-) diff --git a/web/assets/js/util/common.js b/web/assets/js/util/common.js index 3aa1549e..9ad2e01f 100644 --- a/web/assets/js/util/common.js +++ b/web/assets/js/util/common.js @@ -53,24 +53,6 @@ function formatSecond(second) { } } -function copyToClipboard(text) { - // !! here old way of copying is used because not everyone can afford https connection - return new Promise((resolve) => { - const textarea = document.createElement("textarea"); - - textarea.value = text; - - document.body.appendChild(textarea); - - textarea.select(); - document.execCommand("copy"); - - document.body.removeChild(textarea); - - resolve(text) - }) -} - function addZero(num) { if (num < 10) { return "0" + num; diff --git a/web/assets/js/util/utils.js b/web/assets/js/util/utils.js index a79ce3a0..ab7c977a 100644 --- a/web/assets/js/util/utils.js +++ b/web/assets/js/util/utils.js @@ -480,6 +480,38 @@ class Wireguard { } } +class ClipboardManager { + static copyText(content = "") { + // !! here old way of copying is used because not everyone can afford https connection + return new Promise((resolve) => { + try { + const textarea = window.document.createElement('textarea'); + + textarea.style.fontSize = '12pt'; + textarea.style.border = '0'; + textarea.style.padding = '0'; + textarea.style.margin = '0'; + textarea.style.position = 'absolute'; + textarea.style.left = '-9999px'; + textarea.style.top = `${window.pageYOffset || document.documentElement.scrollTop}px`; + textarea.setAttribute('readonly', ''); + textarea.value = content; + + window.document.body.appendChild(textarea); + + textarea.select(); + window.document.execCommand("copy"); + + window.document.body.removeChild(textarea); + + resolve(true) + } catch { + resolve(false) + } + }) + } +} + class Base64 { static encode(content = "", safe = false) { if (safe) { diff --git a/web/html/common/qrcode_modal.html b/web/html/common/qrcode_modal.html index 117dd640..914290f6 100644 --- a/web/html/common/qrcode_modal.html +++ b/web/html/common/qrcode_modal.html @@ -10,7 +10,7 @@ {{ i18n "pages.settings.subSettings"}} - + @@ -18,7 +18,7 @@ {{ i18n "pages.settings.subSettings"}} Json - + @@ -27,7 +27,7 @@ [[ row.remark ]] - + @@ -78,10 +78,12 @@ qrModal: qrModal, }, methods: { - copyToClipboard(content) { - return copyToClipboard(content).then(() => { - app.$message.success('{{ i18n "copied" }}') - }) + copy(content) { + ClipboardManager + .copyText(content) + .then(() => { + app.$message.success('{{ i18n "copied" }}') + }) }, setQrCode(elementId, content) { new QRious({ diff --git a/web/html/common/text_modal.html b/web/html/common/text_modal.html index 36589199..c15282b9 100644 --- a/web/html/common/text_modal.html +++ b/web/html/common/text_modal.html @@ -28,10 +28,12 @@ this.visible = true; }, copy: function (content = '') { - copyToClipboard(content).then(() => { - app.$message.success('{{ i18n "copied" }}') - this.close(); - }) + ClipboardManager + .copyText(content) + .then(() => { + app.$message.success('{{ i18n "copied" }}') + this.close(); + }) }, close: function () { this.visible = false; diff --git a/web/html/xui/inbound_info_modal.html b/web/html/xui/inbound_info_modal.html index f95461e2..1c561aa6 100644 --- a/web/html/xui/inbound_info_modal.html +++ b/web/html/xui/inbound_info_modal.html @@ -258,7 +258,7 @@ Subscription Link - + [[ infoModal.subLink ]] @@ -267,7 +267,7 @@ Json Link - + [[ infoModal.subJsonLink ]] @@ -279,7 +279,7 @@ [[ infoModal.clientSettings.tgId ]] - + @@ -290,7 +290,7 @@ [[ link.remark ]] - + [[ link.link ]] @@ -304,7 +304,7 @@ [[ link.remark ]] - + [[ link.link ]] @@ -431,7 +431,7 @@ Config - +
@@ -532,10 +532,12 @@ }, }, methods: { - copyToClipboard(content) { - return copyToClipboard(content).then(() => { - app.$message.success('{{ i18n "copied" }}') - }) + copy(content) { + ClipboardManager + .copyText(content) + .then(() => { + app.$message.success('{{ i18n "copied" }}') + }) }, statsColor(stats) { return usageColor(stats.up + stats.down, app.trafficDiff, stats.total); diff --git a/web/html/xui/inbounds.html b/web/html/xui/inbounds.html index 93999e97..7dc5ff5f 100644 --- a/web/html/xui/inbounds.html +++ b/web/html/xui/inbounds.html @@ -883,7 +883,7 @@ this.exportSubs(dbInbound.id); break; case "clipboard": - this.copyToClipboard(dbInbound.id); + this.copy(dbInbound.id); break; case "resetTraffic": this.resetTraffic(dbInbound.id); @@ -1382,9 +1382,9 @@ } txtModal.show('{{ i18n "pages.inbounds.export"}}', copyText.join('\r\n'), 'All-Inbounds'); }, - copyToClipboard(dbInboundId) { - dbInbound = this.dbInbounds.find(row => row.id === dbInboundId); - txtModal.show('{{ i18n "pages.inbounds.inboundData" }}', JSON.stringify(dbInbound, null, 2)); + copy(dbInboundId) { + dbInbound = this.dbInbounds.find(row => row.id === dbInboundId); + txtModal.show('{{ i18n "pages.inbounds.inboundData" }}', JSON.stringify(dbInbound, null, 2)); }, async startDataRefreshLoop() { while (this.isRefreshEnabled) { From 4e261a0b13ded156438ac3024f3c8320dc04805f Mon Sep 17 00:00:00 2001 From: "Shishkevich D." <135337715+shishkevichd@users.noreply.github.com> Date: Fri, 7 Mar 2025 09:07:23 +0000 Subject: [PATCH 3/3] refactor: merging all util functions into classes --- web/assets/js/langs.js | 10 +- web/assets/js/model/dbinbound.js | 4 +- web/assets/js/model/inbound.js | 16 +- web/assets/js/util/common.js | 183 ---------------------- web/assets/js/util/date-util.js | 4 +- web/assets/js/util/{utils.js => index.js} | 142 +++++++++++++++++ web/html/common/js.html | 3 +- web/html/xui/form/client.html | 8 +- web/html/xui/inbound_client_table.html | 22 +-- web/html/xui/inbound_info_modal.html | 12 +- web/html/xui/inbounds.html | 44 +++--- web/html/xui/index.html | 28 ++-- web/html/xui/settings.html | 2 +- web/html/xui/warp_modal.html | 6 +- web/html/xui/xray.html | 8 +- 15 files changed, 225 insertions(+), 267 deletions(-) delete mode 100644 web/assets/js/util/common.js rename web/assets/js/util/{utils.js => index.js} (76%) diff --git a/web/assets/js/langs.js b/web/assets/js/langs.js index 823160ad..8681761c 100644 --- a/web/assets/js/langs.js +++ b/web/assets/js/langs.js @@ -62,20 +62,20 @@ const supportLangs = [ ]; function getLang() { - let lang = getCookie("lang"); + let lang = CookieManager.getCookie("lang"); if (!lang) { if (window.navigator) { lang = window.navigator.language || window.navigator.userLanguage; if (isSupportLang(lang)) { - setCookie("lang", lang, 150); + CookieManager.setCookie("lang", lang, 150); } else { - setCookie("lang", "en-US", 150); + CookieManager.setCookie("lang", "en-US", 150); window.location.reload(); } } else { - setCookie("lang", "en-US", 150); + CookieManager.setCookie("lang", "en-US", 150); window.location.reload(); } } @@ -88,7 +88,7 @@ function setLang(lang) { lang = "en-US"; } - setCookie("lang", lang, 150); + CookieManager.setCookie("lang", lang, 150); window.location.reload(); } diff --git a/web/assets/js/model/dbinbound.js b/web/assets/js/model/dbinbound.js index aeae1a75..45301ddd 100644 --- a/web/assets/js/model/dbinbound.js +++ b/web/assets/js/model/dbinbound.js @@ -25,11 +25,11 @@ class DBInbound { } get totalGB() { - return toFixed(this.total / ONE_GB, 2); + return NumberFormatter.toFixed(this.total / SizeFormatter.ONE_GB, 2); } set totalGB(gb) { - this.total = toFixed(gb * ONE_GB, 0); + this.total = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0); } get isVMess() { diff --git a/web/assets/js/model/inbound.js b/web/assets/js/model/inbound.js index 49fc8a7b..5c3235e1 100644 --- a/web/assets/js/model/inbound.js +++ b/web/assets/js/model/inbound.js @@ -1837,11 +1837,11 @@ Inbound.VmessSettings.VMESS = class extends XrayCommonClass { } } get _totalGB() { - return toFixed(this.totalGB / ONE_GB, 2); + return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2); } set _totalGB(gb) { - this.totalGB = toFixed(gb * ONE_GB, 0); + this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0); } }; @@ -1947,11 +1947,11 @@ Inbound.VLESSSettings.VLESS = class extends XrayCommonClass { } } get _totalGB() { - return toFixed(this.totalGB / ONE_GB, 2); + return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2); } set _totalGB(gb) { - this.totalGB = toFixed(gb * ONE_GB, 0); + this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0); } }; Inbound.VLESSSettings.Fallback = class extends XrayCommonClass { @@ -2099,11 +2099,11 @@ Inbound.TrojanSettings.Trojan = class extends XrayCommonClass { } } get _totalGB() { - return toFixed(this.totalGB / ONE_GB, 2); + return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2); } set _totalGB(gb) { - this.totalGB = toFixed(gb * ONE_GB, 0); + this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0); } }; @@ -2263,11 +2263,11 @@ Inbound.ShadowsocksSettings.Shadowsocks = class extends XrayCommonClass { } } get _totalGB() { - return toFixed(this.totalGB / ONE_GB, 2); + return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2); } set _totalGB(gb) { - this.totalGB = toFixed(gb * ONE_GB, 0); + this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0); } }; diff --git a/web/assets/js/util/common.js b/web/assets/js/util/common.js deleted file mode 100644 index 9ad2e01f..00000000 --- a/web/assets/js/util/common.js +++ /dev/null @@ -1,183 +0,0 @@ -const ONE_KB = 1024; -const ONE_MB = ONE_KB * 1024; -const ONE_GB = ONE_MB * 1024; -const ONE_TB = ONE_GB * 1024; -const ONE_PB = ONE_TB * 1024; - -function sizeFormat(size) { - if (size <= 0) return "0 B"; - - if (size < ONE_KB) { - return size.toFixed(0) + " B"; - } else if (size < ONE_MB) { - return (size / ONE_KB).toFixed(2) + " KB"; - } else if (size < ONE_GB) { - return (size / ONE_MB).toFixed(2) + " MB"; - } else if (size < ONE_TB) { - return (size / ONE_GB).toFixed(2) + " GB"; - } else if (size < ONE_PB) { - return (size / ONE_TB).toFixed(2) + " TB"; - } else { - return (size / ONE_PB).toFixed(2) + " PB"; - } -} - -function cpuSpeedFormat(speed) { - if (speed > 1000) { - const GHz = speed / 1000; - return GHz.toFixed(2) + " GHz"; - } else { - return speed.toFixed(2) + " MHz"; - } -} - -function cpuCoreFormat(cores) { - if (cores === 1) { - return "1 Core"; - } else { - return cores + " Cores"; - } -} - -function formatSecond(second) { - if (second < 60) { - return second.toFixed(0) + 's'; - } else if (second < 3600) { - return (second / 60).toFixed(0) + 'm'; - } else if (second < 3600 * 24) { - return (second / 3600).toFixed(0) + 'h'; - } else { - day = Math.floor(second / 3600 / 24); - remain = ((second / 3600) - (day * 24)).toFixed(0); - return day + 'd' + (remain > 0 ? ' ' + remain + 'h' : ''); - } -} - -function addZero(num) { - if (num < 10) { - return "0" + num; - } else { - return num; - } -} - -function toFixed(num, n) { - n = Math.pow(10, n); - return Math.floor(num * n) / n; -} - -function debounce(fn, delay) { - var timeoutID = null; - return function () { - clearTimeout(timeoutID); - var args = arguments; - var that = this; - timeoutID = setTimeout(function () { - fn.apply(that, args); - }, delay); - }; -} - -function getCookie(cname) { - let name = cname + '='; - let ca = document.cookie.split(';'); - for (let i = 0; i < ca.length; i++) { - let c = ca[i]; - while (c.charAt(0) == ' ') { - c = c.substring(1); - } - if (c.indexOf(name) == 0) { - // decode cookie value only - return decodeURIComponent(c.substring(name.length, c.length)); - } - } - return ''; -} - - -function setCookie(cname, cvalue, exdays) { - const d = new Date(); - d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000); - let expires = 'expires=' + d.toUTCString(); - // encode cookie value - document.cookie = cname + '=' + encodeURIComponent(cvalue) + ';' + expires + ';path=/'; -} - -function usageColor(data, threshold, total) { - switch (true) { - case data === null: - return "purple"; - case total < 0: - return "green"; - case total == 0: - return "purple"; - case data < total - threshold: - return "green"; - case data < total: - return "orange"; - default: - return "red"; - } -} - -function clientUsageColor(clientStats, trafficDiff) { - switch (true) { - case !clientStats || clientStats.total == 0: - return "#7a316f"; // purple - case clientStats.up + clientStats.down < clientStats.total - trafficDiff: - return "#008771"; // Green - case clientStats.up + clientStats.down < clientStats.total: - return "#f37b24"; // Orange - default: - return "#cf3c3c"; // Red - } -} - -function userExpiryColor(threshold, client, isDark = false) { - if (!client.enable) { - return isDark ? '#2c3950' : '#bcbcbc'; - } - now = new Date().getTime(), - expiry = client.expiryTime; - switch (true) { - case expiry === null: - return "#7a316f"; // purple - case expiry < 0: - return "#008771"; // Green - case expiry == 0: - return "#7a316f"; // purple - case now < expiry - threshold: - return "#008771"; // Green - case now < expiry: - return "#f37b24"; // Orange - default: - return "#cf3c3c"; // Red - } -} - -function doAllItemsExist(array1, array2) { - for (let i = 0; i < array1.length; i++) { - if (!array2.includes(array1[i])) { - return false; - } - } - return true; -} - -function buildURL({ host, port, isTLS, base, path }) { - if (!host || host.length === 0) host = window.location.hostname; - if (!port || port.length === 0) port = window.location.port; - - if (isTLS === undefined) isTLS = window.location.protocol === "https:"; - - const protocol = isTLS ? "https:" : "http:"; - - port = String(port); - if (port === "" || (isTLS && port === "443") || (!isTLS && port === "80")) { - port = ""; - } else { - port = `:${port}`; - } - - return `${protocol}//${host}${port}${base}${path}`; -} diff --git a/web/assets/js/util/date-util.js b/web/assets/js/util/date-util.js index 50efd6fe..9b4b0f81 100644 --- a/web/assets/js/util/date-util.js +++ b/web/assets/js/util/date-util.js @@ -108,14 +108,14 @@ Date.prototype.setMaxTime = function () { * Formatting date */ Date.prototype.formatDate = function () { - return this.getFullYear() + "-" + addZero(this.getMonth() + 1) + "-" + addZero(this.getDate()); + return this.getFullYear() + "-" + NumberFormatter.addZero(this.getMonth() + 1) + "-" + NumberFormatter.addZero(this.getDate()); }; /** * Format time */ Date.prototype.formatTime = function () { - return addZero(this.getHours()) + ":" + addZero(this.getMinutes()) + ":" + addZero(this.getSeconds()); + return NumberFormatter.addZero(this.getHours()) + ":" + NumberFormatter.addZero(this.getMinutes()) + ":" + NumberFormatter.addZero(this.getSeconds()); }; /** diff --git a/web/assets/js/util/utils.js b/web/assets/js/util/index.js similarity index 76% rename from web/assets/js/util/utils.js rename to web/assets/js/util/index.js index ab7c977a..8a6a4703 100644 --- a/web/assets/js/util/utils.js +++ b/web/assets/js/util/index.js @@ -527,4 +527,146 @@ class Base64 { static decode(content = "") { return window.atob(content) } +} + +class SizeFormatter { + static ONE_KB = 1024; + static ONE_MB = this.ONE_KB * 1024; + static ONE_GB = this.ONE_MB * 1024; + static ONE_TB = this.ONE_GB * 1024; + static ONE_PB = this.ONE_TB * 1024; + + static sizeFormat(size) { + if (size <= 0) return "0 B"; + if (size < this.ONE_KB) return size.toFixed(0) + " B"; + if (size < this.ONE_MB) return (size / this.ONE_KB).toFixed(2) + " KB"; + if (size < this.ONE_GB) return (size / this.ONE_MB).toFixed(2) + " MB"; + if (size < this.ONE_TB) return (size / this.ONE_GB).toFixed(2) + " GB"; + if (size < this.ONE_PB) return (size / this.ONE_TB).toFixed(2) + " TB"; + return (size / this.ONE_PB).toFixed(2) + " PB"; + } +} + +class CPUFormatter { + static cpuSpeedFormat(speed) { + return speed > 1000 ? (speed / 1000).toFixed(2) + " GHz" : speed.toFixed(2) + " MHz"; + } + + static cpuCoreFormat(cores) { + return cores === 1 ? "1 Core" : cores + " Cores"; + } +} + +class TimeFormatter { + static formatSecond(second) { + if (second < 60) return second.toFixed(0) + 's'; + if (second < 3600) return (second / 60).toFixed(0) + 'm'; + if (second < 3600 * 24) return (second / 3600).toFixed(0) + 'h'; + let day = Math.floor(second / 3600 / 24); + let remain = ((second / 3600) - (day * 24)).toFixed(0); + return day + 'd' + (remain > 0 ? ' ' + remain + 'h' : ''); + } +} + +class NumberFormatter { + static addZero(num) { + return num < 10 ? "0" + num : num; + } + + static toFixed(num, n) { + n = Math.pow(10, n); + return Math.floor(num * n) / n; + } +} + +class Utils { + static debounce(fn, delay) { + let timeoutID = null; + return function () { + clearTimeout(timeoutID); + let args = arguments; + let that = this; + timeoutID = setTimeout(() => fn.apply(that, args), delay); + }; + } +} + +class CookieManager { + static getCookie(cname) { + let name = cname + '='; + let ca = document.cookie.split(';'); + for (let c of ca) { + c = c.trim(); + if (c.indexOf(name) === 0) { + return decodeURIComponent(c.substring(name.length, c.length)); + } + } + return ''; + } + + static setCookie(cname, cvalue, exdays) { + const d = new Date(); + d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000); + let expires = 'expires=' + d.toUTCString(); + document.cookie = cname + '=' + encodeURIComponent(cvalue) + ';' + expires + ';path=/'; + } +} + +class ColorUtils { + static usageColor(data, threshold, total) { + switch (true) { + case data === null: return "purple"; + case total < 0: return "green"; + case total == 0: return "purple"; + case data < total - threshold: return "green"; + case data < total: return "orange"; + default: return "red"; + } + } + + static clientUsageColor(clientStats, trafficDiff) { + switch (true) { + case !clientStats || clientStats.total == 0: return "#7a316f"; + case clientStats.up + clientStats.down < clientStats.total - trafficDiff: return "#008771"; + case clientStats.up + clientStats.down < clientStats.total: return "#f37b24"; + default: return "#cf3c3c"; + } + } + + static userExpiryColor(threshold, client, isDark = false) { + if (!client.enable) return isDark ? '#2c3950' : '#bcbcbc'; + let now = new Date().getTime(), expiry = client.expiryTime; + switch (true) { + case expiry === null: return "#7a316f"; + case expiry < 0: return "#008771"; + case expiry == 0: return "#7a316f"; + case now < expiry - threshold: return "#008771"; + case now < expiry: return "#f37b24"; + default: return "#cf3c3c"; + } + } +} + +class ArrayUtils { + static doAllItemsExist(array1, array2) { + return array1.every(item => array2.includes(item)); + } +} + +class URLBuilder { + static buildURL({ host, port, isTLS, base, path }) { + if (!host || host.length === 0) host = window.location.hostname; + if (!port || port.length === 0) port = window.location.port; + if (isTLS === undefined) isTLS = window.location.protocol === "https:"; + + const protocol = isTLS ? "https:" : "http:"; + port = String(port); + if (port === "" || (isTLS && port === "443") || (!isTLS && port === "80")) { + port = ""; + } else { + port = `:${port}`; + } + + return `${protocol}//${host}${port}${base}${path}`; + } } \ No newline at end of file diff --git a/web/html/common/js.html b/web/html/common/js.html index 301b1df7..2d93935f 100644 --- a/web/html/common/js.html +++ b/web/html/common/js.html @@ -5,9 +5,8 @@ - - +