index.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. import axios from 'axios';
  2. import { message as antMessage } from 'ant-design-vue';
  3. export class Msg {
  4. constructor(success = false, msg = "", obj = null) {
  5. this.success = success;
  6. this.msg = msg;
  7. this.obj = obj;
  8. }
  9. }
  10. export class HttpUtil {
  11. static _handleMsg(msg) {
  12. if (!(msg instanceof Msg) || msg.msg === "") {
  13. return;
  14. }
  15. const messageType = msg.success ? 'success' : 'error';
  16. antMessage[messageType](msg.msg);
  17. }
  18. static _respToMsg(resp) {
  19. if (!resp || !resp.data) {
  20. return new Msg(false, 'No response data');
  21. }
  22. const { data } = resp;
  23. if (data == null) {
  24. return new Msg(true);
  25. }
  26. if (typeof data === 'object' && 'success' in data) {
  27. return new Msg(data.success, data.msg, data.obj);
  28. }
  29. return typeof data === 'object' ? data : new Msg(false, 'unknown data:', data);
  30. }
  31. static async get(url, params, options = {}) {
  32. try {
  33. const resp = await axios.get(url, { params, ...options });
  34. const msg = this._respToMsg(resp);
  35. this._handleMsg(msg);
  36. return msg;
  37. } catch (error) {
  38. console.error('GET request failed:', error);
  39. const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
  40. this._handleMsg(errorMsg);
  41. return errorMsg;
  42. }
  43. }
  44. static async post(url, data, options = {}) {
  45. try {
  46. const resp = await axios.post(url, data, options);
  47. const msg = this._respToMsg(resp);
  48. this._handleMsg(msg);
  49. return msg;
  50. } catch (error) {
  51. console.error('POST request failed:', error);
  52. const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
  53. this._handleMsg(errorMsg);
  54. return errorMsg;
  55. }
  56. }
  57. static async postWithModal(url, data, modal) {
  58. if (modal) {
  59. modal.loading(true);
  60. }
  61. const msg = await this.post(url, data);
  62. if (modal) {
  63. modal.loading(false);
  64. if (msg instanceof Msg && msg.success) {
  65. modal.close();
  66. }
  67. }
  68. return msg;
  69. }
  70. }
  71. export function applyDocumentTitle() {
  72. const host = window.location.hostname;
  73. if (!host) return;
  74. const current = document.title.trim();
  75. document.title = current ? `${host} - ${current}` : host;
  76. }
  77. export class PromiseUtil {
  78. static async sleep(timeout) {
  79. await new Promise(resolve => {
  80. setTimeout(resolve, timeout)
  81. });
  82. }
  83. }
  84. export class RandomUtil {
  85. static getSeq({ type = "default", hasNumbers = true, hasLowercase = true, hasUppercase = true } = {}) {
  86. let seq = '';
  87. switch (type) {
  88. case "hex":
  89. seq += "0123456789abcdef";
  90. break;
  91. default:
  92. if (hasNumbers) seq += "0123456789";
  93. if (hasLowercase) seq += "abcdefghijklmnopqrstuvwxyz";
  94. if (hasUppercase) seq += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  95. break;
  96. }
  97. return seq;
  98. }
  99. static randomInteger(min, max) {
  100. const range = max - min + 1;
  101. const randomBuffer = new Uint32Array(1);
  102. window.crypto.getRandomValues(randomBuffer);
  103. return Math.floor((randomBuffer[0] / (0xFFFFFFFF + 1)) * range) + min;
  104. }
  105. static randomSeq(count, options = {}) {
  106. const seq = this.getSeq(options);
  107. const seqLength = seq.length;
  108. const randomValues = new Uint32Array(count);
  109. window.crypto.getRandomValues(randomValues);
  110. return Array.from(randomValues, v => seq[v % seqLength]).join('');
  111. }
  112. static randomShortIds() {
  113. const lengths = [2, 4, 6, 8, 10, 12, 14, 16].sort(() => Math.random() - 0.5);
  114. return lengths.map(len => this.randomSeq(len, { type: "hex" })).join(',');
  115. }
  116. static randomLowerAndNum(len) {
  117. return this.randomSeq(len, { hasUppercase: false });
  118. }
  119. static randomUUID() {
  120. if (window.location.protocol === "https:") {
  121. return window.crypto.randomUUID();
  122. } else {
  123. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
  124. .replace(/[xy]/g, function (c) {
  125. const randomValues = new Uint8Array(1);
  126. window.crypto.getRandomValues(randomValues);
  127. let randomValue = randomValues[0] % 16;
  128. let calculatedValue = (c === 'x') ? randomValue : (randomValue & 0x3 | 0x8);
  129. return calculatedValue.toString(16);
  130. });
  131. }
  132. }
  133. static randomShadowsocksPassword(method = '2022-blake3-aes-256-gcm') {
  134. let length = 32;
  135. if (method === '2022-blake3-aes-128-gcm') {
  136. length = 16;
  137. }
  138. const array = new Uint8Array(length);
  139. window.crypto.getRandomValues(array);
  140. return Base64.alternativeEncode(String.fromCharCode(...array));
  141. }
  142. static randomBase64(length = 16) {
  143. const array = new Uint8Array(length);
  144. window.crypto.getRandomValues(array);
  145. return Base64.alternativeEncode(String.fromCharCode(...array));
  146. }
  147. static randomBase32String(length = 16) {
  148. const array = new Uint8Array(length);
  149. window.crypto.getRandomValues(array);
  150. const base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
  151. let result = '';
  152. let bits = 0;
  153. let buffer = 0;
  154. for (let i = 0; i < array.length; i++) {
  155. buffer = (buffer << 8) | array[i];
  156. bits += 8;
  157. while (bits >= 5) {
  158. bits -= 5;
  159. result += base32Chars[(buffer >>> bits) & 0x1F];
  160. }
  161. }
  162. if (bits > 0) {
  163. result += base32Chars[(buffer << (5 - bits)) & 0x1F];
  164. }
  165. return result;
  166. }
  167. }
  168. export class ObjectUtil {
  169. static getPropIgnoreCase(obj, prop) {
  170. for (const name in obj) {
  171. if (!Object.prototype.hasOwnProperty.call(obj, name)) {
  172. continue;
  173. }
  174. if (name.toLowerCase() === prop.toLowerCase()) {
  175. return obj[name];
  176. }
  177. }
  178. return undefined;
  179. }
  180. static deepSearch(obj, key) {
  181. if (obj instanceof Array) {
  182. for (let i = 0; i < obj.length; ++i) {
  183. if (this.deepSearch(obj[i], key)) {
  184. return true;
  185. }
  186. }
  187. } else if (obj instanceof Object) {
  188. for (let name in obj) {
  189. if (!Object.prototype.hasOwnProperty.call(obj, name)) {
  190. continue;
  191. }
  192. if (this.deepSearch(obj[name], key)) {
  193. return true;
  194. }
  195. }
  196. } else {
  197. return this.isEmpty(obj) ? false : obj.toString().toLowerCase().indexOf(key.toLowerCase()) >= 0;
  198. }
  199. return false;
  200. }
  201. static isEmpty(obj) {
  202. return obj === null || obj === undefined || obj === '';
  203. }
  204. static isArrEmpty(arr) {
  205. return !this.isEmpty(arr) && arr.length === 0;
  206. }
  207. static copyArr(dest, src) {
  208. dest.splice(0);
  209. for (const item of src) {
  210. dest.push(item);
  211. }
  212. }
  213. static clone(obj) {
  214. let newObj;
  215. if (obj instanceof Array) {
  216. newObj = [];
  217. this.copyArr(newObj, obj);
  218. } else if (obj instanceof Object) {
  219. newObj = {};
  220. for (const key of Object.keys(obj)) {
  221. newObj[key] = obj[key];
  222. }
  223. } else {
  224. newObj = obj;
  225. }
  226. return newObj;
  227. }
  228. static deepClone(obj) {
  229. let newObj;
  230. if (obj instanceof Array) {
  231. newObj = [];
  232. for (const item of obj) {
  233. newObj.push(this.deepClone(item));
  234. }
  235. } else if (obj instanceof Object) {
  236. newObj = {};
  237. for (const key of Object.keys(obj)) {
  238. newObj[key] = this.deepClone(obj[key]);
  239. }
  240. } else {
  241. newObj = obj;
  242. }
  243. return newObj;
  244. }
  245. static cloneProps(dest, src, ...ignoreProps) {
  246. if (dest == null || src == null) {
  247. return;
  248. }
  249. const ignoreEmpty = this.isArrEmpty(ignoreProps);
  250. for (const key of Object.keys(src)) {
  251. if (!Object.prototype.hasOwnProperty.call(src, key)) {
  252. continue;
  253. } else if (!Object.prototype.hasOwnProperty.call(dest, key)) {
  254. continue;
  255. } else if (src[key] === undefined) {
  256. continue;
  257. }
  258. if (ignoreEmpty) {
  259. dest[key] = src[key];
  260. } else {
  261. let ignore = false;
  262. for (let i = 0; i < ignoreProps.length; ++i) {
  263. if (key === ignoreProps[i]) {
  264. ignore = true;
  265. break;
  266. }
  267. }
  268. if (!ignore) {
  269. dest[key] = src[key];
  270. }
  271. }
  272. }
  273. }
  274. static delProps(obj, ...props) {
  275. for (const prop of props) {
  276. if (prop in obj) {
  277. delete obj[prop];
  278. }
  279. }
  280. }
  281. static execute(func, ...args) {
  282. if (!this.isEmpty(func) && typeof func === 'function') {
  283. func(...args);
  284. }
  285. }
  286. static orDefault(obj, defaultValue) {
  287. if (obj == null) {
  288. return defaultValue;
  289. }
  290. return obj;
  291. }
  292. static equals(a, b) {
  293. // shallow, symmetric comparison so newly added fields also affect equality
  294. const aKeys = Object.keys(a);
  295. const bKeys = Object.keys(b);
  296. if (aKeys.length !== bKeys.length) return false;
  297. for (const key of aKeys) {
  298. if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
  299. if (a[key] !== b[key]) return false;
  300. }
  301. return true;
  302. }
  303. }
  304. export class Wireguard {
  305. static gf(init) {
  306. var r = new Float64Array(16);
  307. if (init) {
  308. for (var i = 0; i < init.length; ++i)
  309. r[i] = init[i];
  310. }
  311. return r;
  312. }
  313. static pack(o, n) {
  314. let b;
  315. const m = this.gf(), t = this.gf();
  316. for (let i = 0; i < 16; ++i)
  317. t[i] = n[i];
  318. this.carry(t);
  319. this.carry(t);
  320. this.carry(t);
  321. for (let j = 0; j < 2; ++j) {
  322. m[0] = t[0] - 0xffed;
  323. for (let i = 1; i < 15; ++i) {
  324. m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
  325. m[i - 1] &= 0xffff;
  326. }
  327. m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
  328. b = (m[15] >> 16) & 1;
  329. m[14] &= 0xffff;
  330. this.cswap(t, m, 1 - b);
  331. }
  332. for (let i = 0; i < 16; ++i) {
  333. o[2 * i] = t[i] & 0xff;
  334. o[2 * i + 1] = t[i] >> 8;
  335. }
  336. }
  337. static carry(o) {
  338. for (let i = 0; i < 16; ++i) {
  339. o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
  340. o[i] &= 0xffff;
  341. }
  342. }
  343. static cswap(p, q, b) {
  344. const c = ~(b - 1);
  345. let t;
  346. for (let i = 0; i < 16; ++i) {
  347. t = c & (p[i] ^ q[i]);
  348. p[i] ^= t;
  349. q[i] ^= t;
  350. }
  351. }
  352. static add(o, a, b) {
  353. for (let i = 0; i < 16; ++i)
  354. o[i] = (a[i] + b[i]) | 0;
  355. }
  356. static subtract(o, a, b) {
  357. for (let i = 0; i < 16; ++i)
  358. o[i] = (a[i] - b[i]) | 0;
  359. }
  360. static multmod(o, a, b) {
  361. const t = new Float64Array(31);
  362. for (let i = 0; i < 16; ++i) {
  363. for (let j = 0; j < 16; ++j)
  364. t[i + j] += a[i] * b[j];
  365. }
  366. for (let i = 0; i < 15; ++i)
  367. t[i] += 38 * t[i + 16];
  368. for (let i = 0; i < 16; ++i)
  369. o[i] = t[i];
  370. this.carry(o);
  371. this.carry(o);
  372. }
  373. static invert(o, i) {
  374. const c = this.gf();
  375. for (let a = 0; a < 16; ++a)
  376. c[a] = i[a];
  377. for (let a = 253; a >= 0; --a) {
  378. this.multmod(c, c, c);
  379. if (a !== 2 && a !== 4)
  380. this.multmod(c, c, i);
  381. }
  382. for (let a = 0; a < 16; ++a)
  383. o[a] = c[a];
  384. }
  385. static clamp(z) {
  386. z[31] = (z[31] & 127) | 64;
  387. z[0] &= 248;
  388. }
  389. static generatePublicKey(privateKey) {
  390. let r;
  391. const z = new Uint8Array(32);
  392. const a = this.gf([1]),
  393. b = this.gf([9]),
  394. c = this.gf(),
  395. d = this.gf([1]),
  396. e = this.gf(),
  397. f = this.gf(),
  398. _121665 = this.gf([0xdb41, 1]),
  399. _9 = this.gf([9]);
  400. for (let i = 0; i < 32; ++i)
  401. z[i] = privateKey[i];
  402. this.clamp(z);
  403. for (let i = 254; i >= 0; --i) {
  404. r = (z[i >>> 3] >>> (i & 7)) & 1;
  405. this.cswap(a, b, r);
  406. this.cswap(c, d, r);
  407. this.add(e, a, c);
  408. this.subtract(a, a, c);
  409. this.add(c, b, d);
  410. this.subtract(b, b, d);
  411. this.multmod(d, e, e);
  412. this.multmod(f, a, a);
  413. this.multmod(a, c, a);
  414. this.multmod(c, b, e);
  415. this.add(e, a, c);
  416. this.subtract(a, a, c);
  417. this.multmod(b, a, a);
  418. this.subtract(c, d, f);
  419. this.multmod(a, c, _121665);
  420. this.add(a, a, d);
  421. this.multmod(c, c, a);
  422. this.multmod(a, d, f);
  423. this.multmod(d, b, _9);
  424. this.multmod(b, e, e);
  425. this.cswap(a, b, r);
  426. this.cswap(c, d, r);
  427. }
  428. this.invert(c, c);
  429. this.multmod(a, a, c);
  430. this.pack(z, a);
  431. return z;
  432. }
  433. static generatePresharedKey() {
  434. var privateKey = new Uint8Array(32);
  435. window.crypto.getRandomValues(privateKey);
  436. return privateKey;
  437. }
  438. static generatePrivateKey() {
  439. var privateKey = this.generatePresharedKey();
  440. this.clamp(privateKey);
  441. return privateKey;
  442. }
  443. static encodeBase64(dest, src) {
  444. var input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
  445. for (var i = 0; i < 4; ++i)
  446. dest[i] = input[i] + 65 +
  447. (((25 - input[i]) >> 8) & 6) -
  448. (((51 - input[i]) >> 8) & 75) -
  449. (((61 - input[i]) >> 8) & 15) +
  450. (((62 - input[i]) >> 8) & 3);
  451. }
  452. static keyToBase64(key) {
  453. var i, base64 = new Uint8Array(44);
  454. for (i = 0; i < 32 / 3; ++i)
  455. this.encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
  456. this.encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
  457. base64[43] = 61;
  458. return String.fromCharCode.apply(null, base64);
  459. }
  460. static keyFromBase64(encoded) {
  461. const binaryStr = atob(encoded);
  462. const bytes = new Uint8Array(binaryStr.length);
  463. for (let i = 0; i < binaryStr.length; i++) {
  464. bytes[i] = binaryStr.charCodeAt(i);
  465. }
  466. return bytes;
  467. }
  468. static generateKeypair(secretKey = '') {
  469. var privateKey = secretKey.length > 0 ? this.keyFromBase64(secretKey) : this.generatePrivateKey();
  470. var publicKey = this.generatePublicKey(privateKey);
  471. return {
  472. publicKey: this.keyToBase64(publicKey),
  473. privateKey: secretKey.length > 0 ? secretKey : this.keyToBase64(privateKey)
  474. };
  475. }
  476. }
  477. export class ClipboardManager {
  478. static copyText(content = "") {
  479. // !! here old way of copying is used because not everyone can afford https connection
  480. return new Promise((resolve) => {
  481. try {
  482. const textarea = window.document.createElement('textarea');
  483. textarea.style.fontSize = '12pt';
  484. textarea.style.border = '0';
  485. textarea.style.padding = '0';
  486. textarea.style.margin = '0';
  487. textarea.style.position = 'absolute';
  488. textarea.style.left = '-9999px';
  489. textarea.style.top = `${window.pageYOffset || document.documentElement.scrollTop}px`;
  490. textarea.setAttribute('readonly', '');
  491. textarea.value = content;
  492. window.document.body.appendChild(textarea);
  493. textarea.select();
  494. window.document.execCommand("copy");
  495. window.document.body.removeChild(textarea);
  496. resolve(true)
  497. } catch {
  498. resolve(false)
  499. }
  500. })
  501. }
  502. }
  503. export class Base64 {
  504. static encode(content = "", safe = false) {
  505. if (safe) {
  506. return Base64.encode(content)
  507. .replace(/\+/g, '-')
  508. .replace(/=/g, '')
  509. .replace(/\//g, '_')
  510. }
  511. return window.btoa(
  512. String.fromCharCode(...new TextEncoder().encode(content))
  513. )
  514. }
  515. static alternativeEncode(content) {
  516. return window.btoa(
  517. content
  518. )
  519. }
  520. static decode(content = "") {
  521. return new TextDecoder()
  522. .decode(
  523. Uint8Array.from(window.atob(content), c => c.charCodeAt(0))
  524. )
  525. }
  526. }
  527. export class SizeFormatter {
  528. static ONE_KB = 1024;
  529. static ONE_MB = this.ONE_KB * 1024;
  530. static ONE_GB = this.ONE_MB * 1024;
  531. static ONE_TB = this.ONE_GB * 1024;
  532. static ONE_PB = this.ONE_TB * 1024;
  533. static sizeFormat(size) {
  534. if (size <= 0) return "0 B";
  535. if (size < this.ONE_KB) return size.toFixed(0) + " B";
  536. if (size < this.ONE_MB) return (size / this.ONE_KB).toFixed(2) + " KB";
  537. if (size < this.ONE_GB) return (size / this.ONE_MB).toFixed(2) + " MB";
  538. if (size < this.ONE_TB) return (size / this.ONE_GB).toFixed(2) + " GB";
  539. if (size < this.ONE_PB) return (size / this.ONE_TB).toFixed(2) + " TB";
  540. return (size / this.ONE_PB).toFixed(2) + " PB";
  541. }
  542. }
  543. export class CPUFormatter {
  544. static cpuSpeedFormat(speed) {
  545. return speed > 1000 ? (speed / 1000).toFixed(2) + " GHz" : speed.toFixed(2) + " MHz";
  546. }
  547. static cpuCoreFormat(cores) {
  548. return cores === 1 ? "1 Core" : cores + " Cores";
  549. }
  550. }
  551. export class TimeFormatter {
  552. static formatSecond(second) {
  553. if (second < 60) return second.toFixed(0) + 's';
  554. if (second < 3600) return (second / 60).toFixed(0) + 'm';
  555. if (second < 3600 * 24) return (second / 3600).toFixed(0) + 'h';
  556. let day = Math.floor(second / 3600 / 24);
  557. let remain = ((second / 3600) - (day * 24)).toFixed(0);
  558. return day + 'd' + (remain > 0 ? ' ' + remain + 'h' : '');
  559. }
  560. }
  561. export class NumberFormatter {
  562. static addZero(num) {
  563. return num < 10 ? "0" + num : num;
  564. }
  565. static toFixed(num, n) {
  566. n = Math.pow(10, n);
  567. return Math.floor(num * n) / n;
  568. }
  569. }
  570. export class Utils {
  571. static debounce(fn, delay) {
  572. let timeoutID = null;
  573. return function () {
  574. clearTimeout(timeoutID);
  575. let args = arguments;
  576. let that = this;
  577. timeoutID = setTimeout(() => fn.apply(that, args), delay);
  578. };
  579. }
  580. }
  581. export class CookieManager {
  582. static getCookie(cname) {
  583. let name = cname + '=';
  584. let ca = document.cookie.split(';');
  585. for (let c of ca) {
  586. c = c.trim();
  587. if (c.indexOf(name) === 0) {
  588. return decodeURIComponent(c.substring(name.length, c.length));
  589. }
  590. }
  591. return '';
  592. }
  593. static setCookie(cname, cvalue, exdays) {
  594. let expires = '';
  595. if (exdays) {
  596. const d = new Date();
  597. d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  598. expires = 'expires=' + d.toUTCString() + ';';
  599. }
  600. document.cookie = cname + '=' + encodeURIComponent(cvalue) + ';' + expires + 'path=/';
  601. }
  602. }
  603. // AD-Vue 4 semantic palette — kept in one place so the client/inbound
  604. // rows match the rest of the panel. Purple is reserved for the
  605. // "no quota / no expiry / unlimited" sentinel since the AD-Vue green
  606. // would otherwise read as "healthy / under limit".
  607. const COLORS = {
  608. success: '#389e0a', // AD-Vue green-7 — within quota (toned down from green-6 #52c41a, which was too bright on dark themes)
  609. warning: '#faad14', // AD-Vue gold — close to quota / about to expire
  610. danger: '#ff4d4f', // AD-Vue red — depleted / expired
  611. purple: '#722ed1', // AD-Vue purple — unlimited / no expiry
  612. };
  613. export class ColorUtils {
  614. static usageColor(data, threshold, total) {
  615. switch (true) {
  616. case data === null: return "purple";
  617. case total < 0: return "green";
  618. case total == 0: return "purple";
  619. case data < total - threshold: return "green";
  620. case data < total: return "orange";
  621. default: return "red";
  622. }
  623. }
  624. static clientUsageColor(clientStats, trafficDiff) {
  625. switch (true) {
  626. case !clientStats || clientStats.total == 0: return COLORS.purple;
  627. case clientStats.up + clientStats.down < clientStats.total - trafficDiff: return COLORS.success;
  628. case clientStats.up + clientStats.down < clientStats.total: return COLORS.warning;
  629. default: return COLORS.danger;
  630. }
  631. }
  632. static userExpiryColor(threshold, client, isDark = false) {
  633. if (!client.enable) return isDark ? '#2c3950' : '#bcbcbc';
  634. let now = new Date().getTime(), expiry = client.expiryTime;
  635. switch (true) {
  636. case expiry === null: return COLORS.purple;
  637. case expiry < 0: return COLORS.success;
  638. case expiry == 0: return COLORS.purple;
  639. case now < expiry - threshold: return COLORS.success;
  640. case now < expiry: return COLORS.warning;
  641. default: return COLORS.danger;
  642. }
  643. }
  644. }
  645. export class ArrayUtils {
  646. static doAllItemsExist(array1, array2) {
  647. return array1.every(item => array2.includes(item));
  648. }
  649. }
  650. export class URLBuilder {
  651. static buildURL({ host, port, isTLS, base, path }) {
  652. if (!host || host.length === 0) host = window.location.hostname;
  653. if (!port || port.length === 0) port = window.location.port;
  654. if (isTLS === undefined) isTLS = window.location.protocol === "https:";
  655. const protocol = isTLS ? "https:" : "http:";
  656. port = String(port);
  657. if (port === "" || (isTLS && port === "443") || (!isTLS && port === "80")) {
  658. port = "";
  659. } else {
  660. port = `:${port}`;
  661. }
  662. return `${protocol}//${host}${port}${base}${path}`;
  663. }
  664. }
  665. export class LanguageManager {
  666. static supportedLanguages = [
  667. {
  668. name: "العربية",
  669. value: "ar-EG",
  670. icon: "🇪🇬",
  671. },
  672. {
  673. name: "English",
  674. value: "en-US",
  675. icon: "🇺🇸",
  676. },
  677. {
  678. name: "فارسی",
  679. value: "fa-IR",
  680. icon: "🇮🇷",
  681. },
  682. {
  683. name: "简体中文",
  684. value: "zh-CN",
  685. icon: "🇨🇳",
  686. },
  687. {
  688. name: "繁體中文",
  689. value: "zh-TW",
  690. icon: "🇹🇼",
  691. },
  692. {
  693. name: "日本語",
  694. value: "ja-JP",
  695. icon: "🇯🇵",
  696. },
  697. {
  698. name: "Русский",
  699. value: "ru-RU",
  700. icon: "🇷🇺",
  701. },
  702. {
  703. name: "Tiếng Việt",
  704. value: "vi-VN",
  705. icon: "🇻🇳",
  706. },
  707. {
  708. name: "Español",
  709. value: "es-ES",
  710. icon: "🇪🇸",
  711. },
  712. {
  713. name: "Indonesian",
  714. value: "id-ID",
  715. icon: "🇮🇩",
  716. },
  717. {
  718. name: "Український",
  719. value: "uk-UA",
  720. icon: "🇺🇦",
  721. },
  722. {
  723. name: "Türkçe",
  724. value: "tr-TR",
  725. icon: "🇹🇷",
  726. },
  727. {
  728. name: "Português",
  729. value: "pt-BR",
  730. icon: "🇧🇷",
  731. }
  732. ]
  733. static getLanguage() {
  734. let lang = CookieManager.getCookie("lang");
  735. if (!lang) {
  736. if (window.navigator) {
  737. lang = window.navigator.language || window.navigator.userLanguage;
  738. const simularLangs = [
  739. ["ar", this.supportedLanguages[0].value],
  740. ["fa", this.supportedLanguages[2].value],
  741. ["ja", this.supportedLanguages[5].value],
  742. ["ru", this.supportedLanguages[6].value],
  743. ["vi", this.supportedLanguages[7].value],
  744. ["es", this.supportedLanguages[8].value],
  745. ["id", this.supportedLanguages[9].value],
  746. ["uk", this.supportedLanguages[10].value],
  747. ["tr", this.supportedLanguages[11].value],
  748. ["pt", this.supportedLanguages[12].value],
  749. ]
  750. simularLangs.forEach((pair) => {
  751. if (lang === pair[0]) {
  752. lang = pair[1];
  753. }
  754. });
  755. if (LanguageManager.isSupportLanguage(lang)) {
  756. CookieManager.setCookie("lang", lang);
  757. } else {
  758. CookieManager.setCookie("lang", "en-US");
  759. window.location.reload();
  760. }
  761. } else {
  762. CookieManager.setCookie("lang", "en-US");
  763. window.location.reload();
  764. }
  765. }
  766. return lang;
  767. }
  768. static setLanguage(language) {
  769. if (!LanguageManager.isSupportLanguage(language)) {
  770. language = "en-US";
  771. }
  772. CookieManager.setCookie("lang", language);
  773. window.location.reload();
  774. }
  775. static isSupportLanguage(language) {
  776. const languageFilter = LanguageManager.supportedLanguages.filter((lang) => {
  777. return lang.value === language
  778. })
  779. return languageFilter.length > 0;
  780. }
  781. }
  782. export class FileManager {
  783. static downloadTextFile(content, filename = 'file.txt', options = { type: "text/plain" }) {
  784. let link = window.document.createElement('a');
  785. link.download = filename;
  786. link.style.border = '0';
  787. link.style.padding = '0';
  788. link.style.margin = '0';
  789. link.style.position = 'absolute';
  790. link.style.left = '-9999px';
  791. link.style.top = `${window.pageYOffset || window.document.documentElement.scrollTop}px`;
  792. link.href = URL.createObjectURL(new Blob([content], options));
  793. link.click();
  794. URL.revokeObjectURL(link.href);
  795. link.remove();
  796. }
  797. }
  798. export class IntlUtil {
  799. // When `calendar` is "jalalian", append the BCP-47 calendar extension
  800. // so Intl renders the date in the Persian (Jalali/Shamsi) calendar
  801. // regardless of the UI language. Without it, only locales that
  802. // default to Persian (e.g. fa-IR) would show Jalali; en-US/ru/etc.
  803. // would keep showing Gregorian.
  804. static formatDate(date, calendar = "gregorian") {
  805. const language = LanguageManager.getLanguage()
  806. const locale = calendar === "jalalian"
  807. ? `${language}-u-ca-persian`
  808. : language
  809. let intlOptions = {
  810. year: "numeric",
  811. month: "numeric",
  812. day: "numeric",
  813. hour: "numeric",
  814. minute: "numeric",
  815. second: "numeric"
  816. }
  817. const intl = new Intl.DateTimeFormat(
  818. locale,
  819. intlOptions
  820. )
  821. return intl.format(new Date(date))
  822. }
  823. static formatRelativeTime(date) {
  824. const language = LanguageManager.getLanguage()
  825. const now = new Date()
  826. // Handle delayed start (negative expiryTime values)
  827. const diff = date < 0
  828. ? Math.round(date / (1000 * 60 * 60 * 24))
  829. : Math.round((date - now) / (1000 * 60 * 60 * 24))
  830. const formatter = new Intl.RelativeTimeFormat(language, { numeric: 'auto' })
  831. return formatter.format(diff, 'day');
  832. }
  833. }