utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. class Msg {
  2. constructor(success = false, msg = "", obj = null) {
  3. this.success = success;
  4. this.msg = msg;
  5. this.obj = obj;
  6. }
  7. }
  8. class HttpUtil {
  9. static _handleMsg(msg) {
  10. if (!(msg instanceof Msg) || msg.msg === "") {
  11. return;
  12. }
  13. const messageType = msg.success ? 'success' : 'error';
  14. Vue.prototype.$message[messageType](msg.msg);
  15. }
  16. static _respToMsg(resp) {
  17. if (!resp || !resp.data) {
  18. return new Msg(false, 'No response data');
  19. }
  20. const { data } = resp;
  21. if (data == null) {
  22. return new Msg(true);
  23. }
  24. if (typeof data === 'object' && 'success' in data) {
  25. return new Msg(data.success, data.msg, data.obj);
  26. }
  27. return typeof data === 'object' ? data : new Msg(false, 'unknown data:', data);
  28. }
  29. static async get(url, params, options = {}) {
  30. try {
  31. const resp = await axios.get(url, { params, ...options });
  32. const msg = this._respToMsg(resp);
  33. this._handleMsg(msg);
  34. return msg;
  35. } catch (error) {
  36. console.error('GET request failed:', error);
  37. const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
  38. this._handleMsg(errorMsg);
  39. return errorMsg;
  40. }
  41. }
  42. static async post(url, data, options = {}) {
  43. try {
  44. const resp = await axios.post(url, data, options);
  45. const msg = this._respToMsg(resp);
  46. this._handleMsg(msg);
  47. return msg;
  48. } catch (error) {
  49. console.error('POST request failed:', error);
  50. const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
  51. this._handleMsg(errorMsg);
  52. return errorMsg;
  53. }
  54. }
  55. static async postWithModal(url, data, modal) {
  56. if (modal) {
  57. modal.loading(true);
  58. }
  59. const msg = await this.post(url, data);
  60. if (modal) {
  61. modal.loading(false);
  62. if (msg instanceof Msg && msg.success) {
  63. modal.close();
  64. }
  65. }
  66. return msg;
  67. }
  68. static async jsonPost(url, data) {
  69. let msg;
  70. try {
  71. const requestOptions = {
  72. method: 'POST',
  73. headers: {
  74. 'Content-Type': 'application/json',
  75. },
  76. body: JSON.stringify(data),
  77. };
  78. const resp = await fetch(url, requestOptions);
  79. const response = await resp.json();
  80. msg = this._respToMsg({data : response});
  81. } catch (e) {
  82. msg = new Msg(false, e.toString());
  83. }
  84. this._handleMsg(msg);
  85. return msg;
  86. }
  87. static async postWithModalJson(url, data, modal) {
  88. if (modal) {
  89. modal.loading(true);
  90. }
  91. const msg = await this.jsonPost(url, data);
  92. if (modal) {
  93. modal.loading(false);
  94. if (msg instanceof Msg && msg.success) {
  95. modal.close();
  96. }
  97. }
  98. return msg;
  99. }
  100. }
  101. class PromiseUtil {
  102. static async sleep(timeout) {
  103. await new Promise(resolve => {
  104. setTimeout(resolve, timeout)
  105. });
  106. }
  107. }
  108. const seq = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
  109. class RandomUtil {
  110. static randomIntRange(min, max) {
  111. return Math.floor(Math.random() * (max - min) + min);
  112. }
  113. static randomInt(n) {
  114. return this.randomIntRange(0, n);
  115. }
  116. static randomSeq(count) {
  117. let str = '';
  118. for (let i = 0; i < count; ++i) {
  119. str += seq[this.randomInt(62)];
  120. }
  121. return str;
  122. }
  123. static randomShortIds() {
  124. const lengths = [2, 4, 6, 8, 10, 12, 14, 16];
  125. for (let i = lengths.length - 1; i > 0; i--) {
  126. const j = Math.floor(Math.random() * (i + 1));
  127. [lengths[i], lengths[j]] = [lengths[j], lengths[i]];
  128. }
  129. let shortIds = [];
  130. for (let length of lengths) {
  131. let shortId = '';
  132. for (let i = 0; i < length; i++) {
  133. shortId += seq[this.randomInt(16)];
  134. }
  135. shortIds.push(shortId);
  136. }
  137. return shortIds.join(',');
  138. }
  139. static randomLowerAndNum(len) {
  140. let str = '';
  141. for (let i = 0; i < len; ++i) {
  142. str += seq[this.randomInt(36)];
  143. }
  144. return str;
  145. }
  146. static randomUUID() {
  147. const template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
  148. return template.replace(/[xy]/g, function (c) {
  149. const randomValues = new Uint8Array(1);
  150. crypto.getRandomValues(randomValues);
  151. let randomValue = randomValues[0] % 16;
  152. let calculatedValue = (c === 'x') ? randomValue : (randomValue & 0x3 | 0x8);
  153. return calculatedValue.toString(16);
  154. });
  155. }
  156. static randomShadowsocksPassword() {
  157. let array = new Uint8Array(32);
  158. window.crypto.getRandomValues(array);
  159. return btoa(String.fromCharCode.apply(null, array));
  160. }
  161. }
  162. class ObjectUtil {
  163. static getPropIgnoreCase(obj, prop) {
  164. for (const name in obj) {
  165. if (!obj.hasOwnProperty(name)) {
  166. continue;
  167. }
  168. if (name.toLowerCase() === prop.toLowerCase()) {
  169. return obj[name];
  170. }
  171. }
  172. return undefined;
  173. }
  174. static deepSearch(obj, key) {
  175. if (obj instanceof Array) {
  176. for (let i = 0; i < obj.length; ++i) {
  177. if (this.deepSearch(obj[i], key)) {
  178. return true;
  179. }
  180. }
  181. } else if (obj instanceof Object) {
  182. for (let name in obj) {
  183. if (!obj.hasOwnProperty(name)) {
  184. continue;
  185. }
  186. if (this.deepSearch(obj[name], key)) {
  187. return true;
  188. }
  189. }
  190. } else {
  191. return this.isEmpty(obj) ? false : obj.toString().toLowerCase().indexOf(key.toLowerCase()) >= 0;
  192. }
  193. return false;
  194. }
  195. static isEmpty(obj) {
  196. return obj === null || obj === undefined || obj === '';
  197. }
  198. static isArrEmpty(arr) {
  199. return !this.isEmpty(arr) && arr.length === 0;
  200. }
  201. static copyArr(dest, src) {
  202. dest.splice(0);
  203. for (const item of src) {
  204. dest.push(item);
  205. }
  206. }
  207. static clone(obj) {
  208. let newObj;
  209. if (obj instanceof Array) {
  210. newObj = [];
  211. this.copyArr(newObj, obj);
  212. } else if (obj instanceof Object) {
  213. newObj = {};
  214. for (const key of Object.keys(obj)) {
  215. newObj[key] = obj[key];
  216. }
  217. } else {
  218. newObj = obj;
  219. }
  220. return newObj;
  221. }
  222. static deepClone(obj) {
  223. let newObj;
  224. if (obj instanceof Array) {
  225. newObj = [];
  226. for (const item of obj) {
  227. newObj.push(this.deepClone(item));
  228. }
  229. } else if (obj instanceof Object) {
  230. newObj = {};
  231. for (const key of Object.keys(obj)) {
  232. newObj[key] = this.deepClone(obj[key]);
  233. }
  234. } else {
  235. newObj = obj;
  236. }
  237. return newObj;
  238. }
  239. static cloneProps(dest, src, ...ignoreProps) {
  240. if (dest == null || src == null) {
  241. return;
  242. }
  243. const ignoreEmpty = this.isArrEmpty(ignoreProps);
  244. for (const key of Object.keys(src)) {
  245. if (!src.hasOwnProperty(key)) {
  246. continue;
  247. } else if (!dest.hasOwnProperty(key)) {
  248. continue;
  249. } else if (src[key] === undefined) {
  250. continue;
  251. }
  252. if (ignoreEmpty) {
  253. dest[key] = src[key];
  254. } else {
  255. let ignore = false;
  256. for (let i = 0; i < ignoreProps.length; ++i) {
  257. if (key === ignoreProps[i]) {
  258. ignore = true;
  259. break;
  260. }
  261. }
  262. if (!ignore) {
  263. dest[key] = src[key];
  264. }
  265. }
  266. }
  267. }
  268. static delProps(obj, ...props) {
  269. for (const prop of props) {
  270. if (prop in obj) {
  271. delete obj[prop];
  272. }
  273. }
  274. }
  275. static execute(func, ...args) {
  276. if (!this.isEmpty(func) && typeof func === 'function') {
  277. func(...args);
  278. }
  279. }
  280. static orDefault(obj, defaultValue) {
  281. if (obj == null) {
  282. return defaultValue;
  283. }
  284. return obj;
  285. }
  286. static equals(a, b) {
  287. for (const key in a) {
  288. if (!a.hasOwnProperty(key)) {
  289. continue;
  290. }
  291. if (!b.hasOwnProperty(key)) {
  292. return false;
  293. } else if (a[key] !== b[key]) {
  294. return false;
  295. }
  296. }
  297. return true;
  298. }
  299. }
  300. class Wireguard {
  301. static gf(init) {
  302. var r = new Float64Array(16);
  303. if (init) {
  304. for (var i = 0; i < init.length; ++i)
  305. r[i] = init[i];
  306. }
  307. return r;
  308. }
  309. static pack(o, n) {
  310. var b, m = this.gf(), t = this.gf();
  311. for (var i = 0; i < 16; ++i)
  312. t[i] = n[i];
  313. this.carry(t);
  314. this.carry(t);
  315. this.carry(t);
  316. for (var j = 0; j < 2; ++j) {
  317. m[0] = t[0] - 0xffed;
  318. for (var i = 1; i < 15; ++i) {
  319. m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
  320. m[i - 1] &= 0xffff;
  321. }
  322. m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
  323. b = (m[15] >> 16) & 1;
  324. m[14] &= 0xffff;
  325. this.cswap(t, m, 1 - b);
  326. }
  327. for (var i = 0; i < 16; ++i) {
  328. o[2 * i] = t[i] & 0xff;
  329. o[2 * i + 1] = t[i] >> 8;
  330. }
  331. }
  332. static carry(o) {
  333. var c;
  334. for (var i = 0; i < 16; ++i) {
  335. o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
  336. o[i] &= 0xffff;
  337. }
  338. }
  339. static cswap(p, q, b) {
  340. var t, c = ~(b - 1);
  341. for (var i = 0; i < 16; ++i) {
  342. t = c & (p[i] ^ q[i]);
  343. p[i] ^= t;
  344. q[i] ^= t;
  345. }
  346. }
  347. static add(o, a, b) {
  348. for (var i = 0; i < 16; ++i)
  349. o[i] = (a[i] + b[i]) | 0;
  350. }
  351. static subtract(o, a, b) {
  352. for (var i = 0; i < 16; ++i)
  353. o[i] = (a[i] - b[i]) | 0;
  354. }
  355. static multmod(o, a, b) {
  356. var t = new Float64Array(31);
  357. for (var i = 0; i < 16; ++i) {
  358. for (var j = 0; j < 16; ++j)
  359. t[i + j] += a[i] * b[j];
  360. }
  361. for (var i = 0; i < 15; ++i)
  362. t[i] += 38 * t[i + 16];
  363. for (var i = 0; i < 16; ++i)
  364. o[i] = t[i];
  365. this.carry(o);
  366. this.carry(o);
  367. }
  368. static invert(o, i) {
  369. var c = this.gf();
  370. for (var a = 0; a < 16; ++a)
  371. c[a] = i[a];
  372. for (var a = 253; a >= 0; --a) {
  373. this.multmod(c, c, c);
  374. if (a !== 2 && a !== 4)
  375. this.multmod(c, c, i);
  376. }
  377. for (var a = 0; a < 16; ++a)
  378. o[a] = c[a];
  379. }
  380. static clamp(z) {
  381. z[31] = (z[31] & 127) | 64;
  382. z[0] &= 248;
  383. }
  384. static generatePublicKey(privateKey) {
  385. var r, z = new Uint8Array(32);
  386. var a = this.gf([1]),
  387. b = this.gf([9]),
  388. c = this.gf(),
  389. d = this.gf([1]),
  390. e = this.gf(),
  391. f = this.gf(),
  392. _121665 = this.gf([0xdb41, 1]),
  393. _9 = this.gf([9]);
  394. for (var i = 0; i < 32; ++i)
  395. z[i] = privateKey[i];
  396. this.clamp(z);
  397. for (var i = 254; i >= 0; --i) {
  398. r = (z[i >>> 3] >>> (i & 7)) & 1;
  399. this.cswap(a, b, r);
  400. this.cswap(c, d, r);
  401. this.add(e, a, c);
  402. this.subtract(a, a, c);
  403. this.add(c, b, d);
  404. this.subtract(b, b, d);
  405. this.multmod(d, e, e);
  406. this.multmod(f, a, a);
  407. this.multmod(a, c, a);
  408. this.multmod(c, b, e);
  409. this.add(e, a, c);
  410. this.subtract(a, a, c);
  411. this.multmod(b, a, a);
  412. this.subtract(c, d, f);
  413. this.multmod(a, c, _121665);
  414. this.add(a, a, d);
  415. this.multmod(c, c, a);
  416. this.multmod(a, d, f);
  417. this.multmod(d, b, _9);
  418. this.multmod(b, e, e);
  419. this.cswap(a, b, r);
  420. this.cswap(c, d, r);
  421. }
  422. this.invert(c, c);
  423. this.multmod(a, a, c);
  424. this.pack(z, a);
  425. return z;
  426. }
  427. static generatePresharedKey() {
  428. var privateKey = new Uint8Array(32);
  429. window.crypto.getRandomValues(privateKey);
  430. return privateKey;
  431. }
  432. static generatePrivateKey() {
  433. var privateKey = this.generatePresharedKey();
  434. this.clamp(privateKey);
  435. return privateKey;
  436. }
  437. static encodeBase64(dest, src) {
  438. 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]);
  439. for (var i = 0; i < 4; ++i)
  440. dest[i] = input[i] + 65 +
  441. (((25 - input[i]) >> 8) & 6) -
  442. (((51 - input[i]) >> 8) & 75) -
  443. (((61 - input[i]) >> 8) & 15) +
  444. (((62 - input[i]) >> 8) & 3);
  445. }
  446. static keyToBase64(key) {
  447. var i, base64 = new Uint8Array(44);
  448. for (i = 0; i < 32 / 3; ++i)
  449. this.encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
  450. this.encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
  451. base64[43] = 61;
  452. return String.fromCharCode.apply(null, base64);
  453. }
  454. static keyFromBase64(encoded) {
  455. const binaryStr = atob(encoded);
  456. const bytes = new Uint8Array(binaryStr.length);
  457. for (let i = 0; i < binaryStr.length; i++) {
  458. bytes[i] = binaryStr.charCodeAt(i);
  459. }
  460. return bytes;
  461. }
  462. static generateKeypair(secretKey = '') {
  463. var privateKey = secretKey.length > 0 ? this.keyFromBase64(secretKey) : this.generatePrivateKey();
  464. var publicKey = this.generatePublicKey(privateKey);
  465. return {
  466. publicKey: this.keyToBase64(publicKey),
  467. privateKey: secretKey.length > 0 ? secretKey : this.keyToBase64(privateKey)
  468. };
  469. }
  470. }