| 109 | // ── Subtitle file downloader (used during run-download completion) ───────────── |
| 110 | |
| 111 | function downloadSubtitleFile(url, destPath) { |
| 112 | return new Promise((resolve) => { |
| 113 | try { |
| 114 | const parsedUrl = new URL(url); |
| 115 | if (parsedUrl.protocol === "file:") { |
| 116 | try { |
| 117 | fs.copyFileSync(decodeURIComponent(parsedUrl.pathname), destPath); |
| 118 | resolve(true); |
| 119 | } catch { |
| 120 | resolve(false); |
| 121 | } |
| 122 | return; |
| 123 | } |
| 124 | const lib = parsedUrl.protocol === "https:" ? https : http; |
| 125 | const req = lib.get( |
| 126 | url, |
| 127 | { |
| 128 | headers: { |
| 129 | "User-Agent": |
| 130 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0", |
| 131 | Referer: parsedUrl.origin, |
| 132 | Accept: "*/*", |
| 133 | }, |
| 134 | }, |
| 135 | (res) => { |
| 136 | if ( |
| 137 | res.statusCode >= 300 && |
| 138 | res.statusCode < 400 && |
| 139 | res.headers.location |
| 140 | ) { |
| 141 | const loc = res.headers.location.startsWith("http") |
| 142 | ? res.headers.location |
| 143 | : parsedUrl.origin + res.headers.location; |
| 144 | downloadSubtitleFile(loc, destPath).then(resolve); |
| 145 | return; |
| 146 | } |
| 147 | if (res.statusCode !== 200) { |
| 148 | res.resume(); |
| 149 | resolve(false); |
| 150 | return; |
| 151 | } |
| 152 | const file = fs.createWriteStream(destPath); |
| 153 | res.pipe(file); |
| 154 | file.on("finish", () => { |
| 155 | file.close(); |
| 156 | resolve(true); |
| 157 | }); |
| 158 | file.on("error", () => { |
| 159 | try { |
| 160 | fs.unlinkSync(destPath); |
| 161 | } catch {} |
| 162 | resolve(false); |
| 163 | }); |
| 164 | res.on("error", () => resolve(false)); |
| 165 | }, |
| 166 | ); |
| 167 | req.on("error", () => resolve(false)); |
| 168 | req.setTimeout(20000, () => { |