返回 AiToEarn
utils.ts
1 // 根据文件路径获取文件名和后缀
2 import { ProxyInfo } from '@@/utils.type';
3
4 // 提取路径中的文件名
5 export function getFilePathNameCommon(path: string) {
6 if (!path)
7 return {
8 filename: '',
9 suffix: '',
10 };
11 const path1 = path.split('\\')[path.split('\\').length - 1];
12 const filename = path1.split('/')[path1.split('/').length - 1];
13 return {
14 filename,
15 suffix: filename.split('.')[filename.split('.').length - 1],
16 };
17 }
18
19 // 等待n毫秒
20 export function sleep(ms: number) {
21 return new Promise((resolve) => setTimeout(resolve, ms));
22 }
23
24 /**
25 * 重试
26 * @param max 重试上限
27 * @param callback 每次循环的回调,返回boolean,为true则会结束循环
28 * @param interval 重试间隔时间
29 * @returns true=成功,false=失败
30 */
31 export async function RetryWhile(
32 callback: (count: number) => Promise<boolean | undefined>,
33 max: number,
34 interval: number = 1000,
35 ) {
36 let count = 0;
37 let flag = true;
38 while (true) {
39 const isEnd = await callback(count);
40 if (isEnd === true) break;
41 if (count > max) {
42 flag = false;
43 break;
44 }
45 count++;
46 await sleep(interval);
47 console.log(`开始第 ${count} 次重试`);
48 }
49 return flag;
50 }
51
52 /**
53 * 代理解析
54 * @param proxyString
55 */
56 export function parseProxyString(proxyString: string): ProxyInfo | false {
57 const regex =
58 /^(?:(\w+):\/\/)?([\d.]+:\d+)(?::([^:]+):([^{}\s]+))?(?:\[(.*?)\])?(?:{(.*?)})?$/;
59
60 const match = proxyString.match(regex);
61 if (!match) {
62 return false; // 无法解析则返回 false
63 }
64
65 const [, protocol, ipAndPort, username, password, refreshUrl, remark] = match;
66
67 return {
68 protocol: protocol || 'http', // 如果未提供协议,默认为 http
69 ipAndPort,
70 username,
71 password,
72 refreshUrl,
73 remark,
74 };
75 }
76
76 lines TYPESCRIPT