From e03042e6cf65e29ee0526fe74819b4fb761c4516 Mon Sep 17 00:00:00 2001 From: zakary Date: Sat, 16 Dec 2023 01:48:31 -0600 Subject: [PATCH] follow 3xx redirects on snatch (#567) previously we were explicitly _not_ following redirects so that we could intercept redirects to magnet links, but that was a workaround because the errors thrown by redirecting to magnet links were uncatchable. Since we've switched to fetch, that's no longer a problem and we can now catch the errors caused by redirecting to magnet links, and let fetch follow the redirects otherwise. #549 --------- Co-authored-by: Michael Goodnow --- src/torrent.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/torrent.ts b/src/torrent.ts index 8b45e3137..e5bd30b2a 100644 --- a/src/torrent.ts +++ b/src/torrent.ts @@ -34,6 +34,16 @@ export async function parseTorrentFromFilename( return Metafile.decode(data); } +function isMagnetRedirectError(error: Error): boolean { + return ( + // node-fetch + error.message.includes('URL scheme "magnet" is not supported.') || + // undici + // @ts-expect-error error causes "not supported yet" + error?.cause.message.includes("URL scheme must be a HTTP(S) scheme") + ); +} + export async function parseTorrentFromURL( url: string ): Promise> { @@ -49,25 +59,21 @@ export async function parseTorrentFromURL( response = await fetch(url, { headers: { "User-Agent": USER_AGENT }, signal: abortController.signal, - redirect: "manual", }); } catch (e) { if (e.name === "AbortError") { logger.error(`snatching ${url} timed out`); return resultOfErr(SnatchError.ABORTED); + } else if (isMagnetRedirectError(e)) { + logger.error(`Unsupported: magnet link detected at ${url}`); + return resultOfErr(SnatchError.MAGNET_LINK); } logger.error(`failed to access ${url}`); logger.debug(e); return resultOfErr(SnatchError.UNKNOWN_ERROR); } - if ( - response.status.toString().startsWith("3") && - response.headers.get("location")?.startsWith("magnet:") - ) { - logger.error(`Unsupported: magnet link detected at ${url}`); - return resultOfErr(SnatchError.MAGNET_LINK); - } else if (response.status === 429) { + if (response.status === 429) { return resultOfErr(SnatchError.RATE_LIMITED); } else if (!response.ok) { logger.error(