index.ts 29 KB

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