| 21 | } |
| 22 | |
| 23 | async run() { |
| 24 | if (this.isDestroy) { |
| 25 | return |
| 26 | } |
| 27 | const link = Store.Links.shift() |
| 28 | if (!link) { |
| 29 | await wait() |
| 30 | this.run().then() |
| 31 | return |
| 32 | } |
| 33 | if (link) { |
| 34 | if (checkIsExcludeUrl(link.url, false)) { |
| 35 | this.run().then() |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | if (link.retry && link.retry >= Config.maxRetryTimes) { |
| 40 | console.log('fetchLink retryCount out: ', link.retry, link) |
| 41 | link.state = 'fail' |
| 42 | this.run().then() |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | link.state = 'running' |
| 47 | |
| 48 | if (!link.retry) { |
| 49 | link.retry = 1 |
| 50 | } else { |
| 51 | link.retry += 1 |
| 52 | } |
| 53 | |
| 54 | let timer: NodeJS.Timeout |
| 55 | const next = () => { |
| 56 | clearTimeout(timer) |
| 57 | link.state = 'success' |
| 58 | this.run().then() |
| 59 | } |
| 60 | const saveFile = link.saveFile |
| 61 | let size = 0 |
| 62 | if (existsSync(saveFile)) { |
| 63 | const info = await stat(saveFile) |
| 64 | size = info.size |
| 65 | } |
| 66 | if (size > 0) { |
| 67 | next() |
| 68 | } else { |
| 69 | const dir = dirname(saveFile) |
| 70 | try { |
| 71 | await mkdirp(dir) |
| 72 | } catch {} |
| 73 | const stream = createWriteStream(saveFile) |
| 74 | const onError = () => { |
| 75 | this.#retry(link) |
| 76 | try { |
| 77 | stream.close(() => { |
| 78 | if (existsSync(saveFile)) { |
| 79 | unlinkSync(saveFile) |
| 80 | } |