Skip to content

Commit

Permalink
Fixed: Handle download redirects to magnet links
Browse files Browse the repository at this point in the history
  • Loading branch information
mynameisbogdan committed Apr 28, 2024
1 parent 15fabbe commit eee21de
Showing 1 changed file with 38 additions and 4 deletions.
42 changes: 38 additions & 4 deletions src/NzbDrone.Core/Indexers/HttpIndexerBase.cs
Expand Up @@ -27,6 +27,7 @@ public abstract class HttpIndexerBase<TSettings> : IndexerBase<TSettings>
where TSettings : IIndexerSettings, new()
{
protected const int MaxNumResultsPerQuery = 1000;
private const int MaxRedirects = 5;

protected readonly IIndexerHttpClient _httpClient;
protected readonly IEventAggregator _eventAggregator;
Expand Down Expand Up @@ -239,11 +240,47 @@ public override async Task<byte[]> Download(Uri link)
request.RateLimit = RateLimit;
}

request.AllowAutoRedirect = false;

byte[] fileData;

try
{
var response = await _httpClient.ExecuteProxiedAsync(request, Definition);

if (response.StatusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther)
{
var autoRedirectChain = new List<string> { request.Url.ToString() };

do
{
var redirectUrl = response.RedirectUrl;

_logger.Debug("Download request is being redirected to: {0}", redirectUrl);

if (redirectUrl.IsNullOrWhiteSpace())
{
throw new WebException("Remote website tried to redirect without providing a location.");
}

if (redirectUrl.StartsWith("magnet:"))
{
return await Download(new Uri(redirectUrl));
}

request.Url = new HttpUri(redirectUrl);
autoRedirectChain.Add(request.Url.ToString());

if (autoRedirectChain.Count > MaxRedirects)
{
throw new WebException($"Too many download redirections were attempted for {autoRedirectChain.Join(" -> ")}", WebExceptionStatus.ProtocolError);
}

response = await _httpClient.ExecuteProxiedAsync(request, Definition);
}
while (response.StatusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther);
}

fileData = response.ResponseData;

_logger.Debug("Downloaded for release finished ({0} bytes from {1})", fileData.Length, link.AbsoluteUri);
Expand Down Expand Up @@ -287,10 +324,7 @@ public override async Task<byte[]> Download(Uri link)

protected virtual Task<HttpRequest> GetDownloadRequest(Uri link)
{
var requestBuilder = new HttpRequestBuilder(link.AbsoluteUri)
{
AllowAutoRedirect = FollowRedirect
};
var requestBuilder = new HttpRequestBuilder(link.AbsoluteUri);

if (Cookies != null)
{
Expand Down

0 comments on commit eee21de

Please sign in to comment.