File size: 7,203 Bytes
6e41657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import dayjs from 'dayjs';
import PQueue from 'p-queue';
import { v4 as uuid } from 'uuid';
import { sleep } from '#shared/utils/helpers';
import { PUBLIC_PROXY_LIST } from '~/config/public-proxy';
import type { DownloadableArticle } from '~/types/types';
import type { AudioResource, VideoResource } from '~/types/video';

/**

 * 代理实例

 */
export interface ProxyInstance {
  // 唯一标识
  id: string;

  // 代理地址
  address: string;

  // 是否正在被使用
  busy: boolean;

  // 是否处于冷静期
  cooldown: boolean;

  // 使用次数
  usageCount: number;

  // 成功次数
  successCount: number;

  // 失败次数
  failureCount: number;

  // 下载流量
  traffic: number;
}

// 使用代理下载的资源类型
type DownloadResource =
  | string
  | HTMLLinkElement
  | HTMLImageElement
  | DownloadableArticle
  | AudioResource
  | VideoResource;

// 资源下载函数,返回资源大小
type DownloadFn<T extends DownloadResource> = (resource: T, proxy: string) => Promise<number>;

// 资源下载结果
export interface DownloadResult {
  // 总耗时 (s)
  totalTime: number;

  // 是否成功
  success: boolean;

  // 重试次数
  attempts: number;

  // 资源url
  url: string;

  // 资源大小
  size: number;
}

function now() {
  return dayjs(new Date()).format('HH:mm:ss.SSS');
}

class ProxyPool {
  proxies: ProxyInstance[] = [];

  constructor(proxyUrls: string[]) {
    this.proxies = proxyUrls.map(url => ({
      id: uuid(),
      address: url,
      busy: false,
      cooldown: false,
      usageCount: 0,
      successCount: 0,
      failureCount: 0,
      traffic: 0,
    }));
  }

  /**

   * 初始化代理池

   * 可以传入新的代理地址列表(私有代理地址)

   */
  init(proxyUrls: string[] = []) {
    if (proxyUrls.length > 0) {
      this.proxies = proxyUrls.map(url => ({
        id: uuid(),
        address: url,
        busy: false,
        cooldown: false,
        usageCount: 0,
        successCount: 0,
        failureCount: 0,
        traffic: 0,
      }));
    } else {
      this.proxies.forEach(proxy => {
        proxy.busy = false;
        proxy.cooldown = false;
        proxy.usageCount = 0;
        proxy.successCount = 0;
        proxy.failureCount = 0;
      });
    }
  }

  /**

   * 获取可用代理

   */
  async getAvailableProxy() {
    let time = 0;
    while (true) {
      for (const proxy of this.proxies) {
        if (!proxy.busy && !proxy.cooldown) {
          proxy.busy = true;
          proxy.usageCount++;
          return proxy;
        }
      }
      // 如果没有可用代理,稍微等待一下
      await sleep(100);
      time += 100;
      if (time >= 60_000) {
        // 超时1分钟
        throw new Error('无可用代理');
      }
    }
  }

  /**

   * 释放代理

   * @param proxy 代理对象

   * @param success 使用当前代理的本次下载是否成功

   */
  releaseProxy(proxy: ProxyInstance, success: boolean) {
    proxy.busy = false;

    if (success) {
      proxy.successCount++;
    } else {
      proxy.failureCount++;
      proxy.cooldown = true;

      // 2秒冷却时间
      setTimeout(() => {
        proxy.cooldown = false;
      }, 2_000);

      if (proxy.failureCount >= 10 && proxy.successCount === 0) {
        // 代理被识别为不可用,从代理池中移除
        console.warn(`代理 ${proxy.address} 不可用,将被移除`);
        this.removeProxy(proxy);
      }
    }
  }

  /**

   * 移除代理

   */
  removeProxy(proxy: ProxyInstance) {
    this.proxies = this.proxies.filter(p => p.id !== proxy.id);
  }
}

// 代理池
export const pool = new ProxyPool(PUBLIC_PROXY_LIST);

/**

 * 使用代理 proxy 下载资源

 * @param proxy

 * @param resource

 * @param downloadFn

 */
async function downloadResource<T extends DownloadResource>(
  proxy: ProxyInstance,
  resource: T,
  downloadFn: DownloadFn<T>
): Promise<[boolean, number]> {
  try {
    // 执行下载任务
    const size = await downloadFn(resource, proxy.address);
    return [true, size];
  } catch (error) {
    return [false, 0];
  }
}

/**

 * 使用代理池下载资源

 * @param pool

 * @param resource

 * @param downloadFn

 * @param useProxy

 * @param maxRetries

 */
async function downloadWithRetry<T extends DownloadResource>(
  pool: ProxyPool,
  resource: T,
  downloadFn: DownloadFn<T>,
  useProxy = true,
  maxRetries = 10
): Promise<DownloadResult> {
  let attempts = 0;
  let isSuccess = false;
  let size: number = 0;

  let resourceURL: string;
  if (resource instanceof HTMLLinkElement) {
    resourceURL = resource.href;
  } else if (resource instanceof HTMLImageElement) {
    resourceURL = resource.src || resource.dataset.src!;
  } else if (typeof resource === 'string') {
    resourceURL = resource;
  } else {
    resourceURL = resource.url;
  }

  const startTime = Date.now();

  while (attempts < maxRetries) {
    let success: boolean;

    if (useProxy) {
      // 使用代理下载
      const proxy = await pool.getAvailableProxy();
      [success, size] = await downloadResource<T>(proxy, resource, downloadFn);
      pool.releaseProxy(proxy, success);
    } else {
      // 不使用代理下载
      [success, size] = await downloadResource<T>({} as ProxyInstance, resource, downloadFn);
    }

    if (success) {
      isSuccess = true;
      break;
    } else {
      attempts++;
      await sleep(200);
      console.log(`[${now()}] Retrying ${resourceURL} (attempt ${attempts}/${maxRetries})`);
    }
  }

  const endTime = Date.now();
  const totalTime = (endTime - startTime) / 1000;

  if (!isSuccess) {
    console.warn(`[${now()}] Failed to download ${resourceURL} after ${maxRetries} attempts`);
  }

  return {
    totalTime,
    success: isSuccess,
    attempts,
    url: resourceURL,
    size,
  };
}

/**

 * 使用代理池下载单个资源

 * @param resource

 * @param downloadFn

 * @param useProxy

 */
async function download<T extends DownloadResource>(resource: T, downloadFn: DownloadFn<T>, useProxy = true) {
  return await downloadWithRetry<T>(pool, resource, downloadFn, useProxy);
}

/**

 * 使用代理池下载多个资源

 * @param resources

 * @param downloadFn

 * @param useProxy

 */
export async function downloads<T extends DownloadResource>(
  resources: T[],
  downloadFn: DownloadFn<T>,
  useProxy = true
) {
  // 检查是否设置了私有代理地址
  const privateProxy: string[] = [];
  try {
    const proxy = JSON.parse(window.localStorage.getItem('wechat-proxy')!);
    if (Array.isArray(proxy) && proxy.length > 0) {
      privateProxy.push(...proxy);
    }
  } catch (e) {
    console.log(e);
  }

  // 初始化 pool
  pool.init(privateProxy);

  const queue = new PQueue({ concurrency: pool.proxies.length });

  const tasks = resources.map(resource => queue.add(() => download<T>(resource, downloadFn, useProxy)));
  await Promise.all(tasks);
}