1
0

index.ts 28 KB

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