Use Array.Empty and fix a few multiple enumerations (#14194)

This commit is contained in:
Stepan Goremykin 2023-04-02 08:57:30 -07:00 committed by GitHub
parent 37f68715f9
commit 97c4a976c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 37 additions and 36 deletions

View File

@ -60,11 +60,11 @@ namespace Jackett.Common.Indexers.Feeds
protected override ReleaseInfo ResultFromFeedItem(XElement item)
{
var release = base.ResultFromFeedItem(item);
var enclosures = item.Descendants("enclosure").Where(e => e.Attribute("type").Value == "application/x-bittorrent");
if (enclosures.Any())
var enclosure = item.Descendants("enclosure").FirstOrDefault(e => e.Attribute("type").Value == "application/x-bittorrent");
if (enclosure != null)
{
var enclosure = enclosures.First().Attribute("url").Value;
release.Link = new Uri(enclosure);
var enclosureUrl = enclosure.Attribute("url").Value;
release.Link = new Uri(enclosureUrl);
}
// add some default values if none returned by feed
release.Seeders = release.Seeders > 0 ? release.Seeders : 0;

View File

@ -132,11 +132,11 @@ namespace Jackett.Common.Indexers.Feeds
protected override ReleaseInfo ResultFromFeedItem(XElement item)
{
var release = base.ResultFromFeedItem(item);
var enclosures = item.Descendants("enclosure").Where(e => e.Attribute("type").Value == "application/x-bittorrent");
if (enclosures.Any())
var enclosure = item.Descendants("enclosure").FirstOrDefault(e => e.Attribute("type").Value == "application/x-bittorrent");
if (enclosure != null)
{
var enclosure = enclosures.First().Attribute("url").Value;
release.Link = new Uri(enclosure);
var enclosureUrl = enclosure.Attribute("url").Value;
release.Link = new Uri(enclosureUrl);
}
// add some default values if none returned by feed
release.Seeders = release.Seeders > 0 ? release.Seeders : 0;

View File

@ -161,7 +161,7 @@ namespace Jackett.Common.Indexers
}
else
{
configData.CaptchaImage.Value = new byte[0];
configData.CaptchaImage.Value = Array.Empty<byte>();
}
configData.CaptchaCookie.Value = loginPage.Cookies;
UpdateCookieHeader(loginPage.Cookies);
@ -656,7 +656,7 @@ namespace Jackett.Common.Indexers
#endregion
#region Tracker parsing
private async Task<List<ReleaseInfo>> FetchTrackerReleases(TrackerUrlDetails details)
private async Task<IReadOnlyList<ReleaseInfo>> FetchTrackerReleases(TrackerUrlDetails details)
{
var queryCollection = new NameValueCollection
{
@ -696,7 +696,7 @@ namespace Jackett.Common.Indexers
}
// Failure path
return new List<ReleaseInfo>();
return Array.Empty<ReleaseInfo>();
}
private async Task<List<ReleaseInfo>> FollowTrackerRedirection(string url, TrackerUrlDetails details)

View File

@ -71,7 +71,7 @@ namespace Jackett.Common.Indexers.Meta
var fallbackStrategies = fallbackStrategyProvider.FallbackStrategiesForQuery(query);
var fallbackQueries = fallbackStrategies.Select(async f => await f.FallbackQueries()).SelectMany(t => t.Result);
var fallbackTasks = fallbackQueries.SelectMany(q => indexers.Where(i => !i.CanHandleQuery(query) && i.CanHandleQuery(q)).Select(i => i.ResultsForQuery(q, true)));
var tasks = supportedTasks.Concat(fallbackTasks.ToList()); // explicit conversion to List to execute LINQ query
var tasks = supportedTasks.Concat(fallbackTasks).ToList(); // explicit conversion to List to execute LINQ query
// When there are many indexers used by a metaindexer querying each and every one of them can take very very
// long. This may result in a problem especially with Sonarr, which does consecutive searches when searching

View File

@ -49,8 +49,8 @@ namespace Jackett.Common.Indexers.Meta
}
else
{
wrongResults = new ReleaseInfo[] { };
perfectResults = new ReleaseInfo[] { };
wrongResults = Array.Empty<ReleaseInfo>();
perfectResults = Array.Empty<ReleaseInfo>();
}
var remainingResults = results.Except(wrongResults).Except(perfectResults);

View File

@ -85,7 +85,7 @@ namespace Jackett.Common.Models
public ICollection<int> MapTrackerCatToNewznab(string trackerCategory)
{
if (string.IsNullOrWhiteSpace(trackerCategory))
return new List<int>();
return Array.Empty<int>();
var cats = _categoryMapping
.Where(m =>
!string.IsNullOrWhiteSpace(m.TrackerCategory) &&
@ -97,7 +97,7 @@ namespace Jackett.Common.Models
public ICollection<int> MapTrackerCatDescToNewznab(string trackerCategoryDesc)
{
if (string.IsNullOrWhiteSpace(trackerCategoryDesc))
return new List<int>();
return Array.Empty<int>();
var cats = _categoryMapping
.Where(m =>
!string.IsNullOrWhiteSpace(m.TrackerCategoryDesc) &&
@ -109,7 +109,7 @@ namespace Jackett.Common.Models
public int[] SupportedCategories(int[] categories)
{
if (categories == null || categories.Length == 0)
return new int[0];
return Array.Empty<int>();
var subCategories = _torznabCategoryTree.SelectMany(c => c.SubCategories);
var allCategories = _torznabCategoryTree.Concat(subCategories);
return allCategories.Where(c => categories.Contains(c.ID)).Select(c => c.ID).ToArray();

View File

@ -114,12 +114,12 @@ namespace Jackett.Common.Services
}
}
public List<TrackerCacheResult> GetCachedResults()
public IReadOnlyList<TrackerCacheResult> GetCachedResults()
{
lock (_cache)
{
if (!IsCacheEnabled())
return new List<TrackerCacheResult>();
return Array.Empty<TrackerCacheResult>();
PruneCacheByTtl(); // remove expired results

View File

@ -9,7 +9,7 @@ namespace Jackett.Common.Services.Interfaces
{
List<ReleaseInfo> Search(IIndexer indexer, TorznabQuery query);
void CacheResults(IIndexer indexer, TorznabQuery query, List<ReleaseInfo> releases);
List<TrackerCacheResult> GetCachedResults();
IReadOnlyList<TrackerCacheResult> GetCachedResults();
void CleanIndexerCache(IIndexer indexer);
void CleanCache();
TimeSpan CacheTTL { get; }

View File

@ -50,7 +50,7 @@ namespace Jackett.Common.Utils
var table = (Hashtable)cookieJar
.GetType()
.InvokeMember("m_domainTable", BindingFlags.NonPublic | BindingFlags.GetField |
BindingFlags.Instance, null, cookieJar, new object[] { });
BindingFlags.Instance, null, cookieJar, Array.Empty<object>());
foreach (var key in table.Keys)
{
var domain = (string)key;

View File

@ -26,7 +26,7 @@ namespace Jackett.Common.Utils
public static class TaskExtensions
{
public static Task<IEnumerable<TResult>> Until<TResult>(this IEnumerable<Task<TResult>> tasks, TimeSpan timeout)
public static Task<IEnumerable<TResult>> Until<TResult>(this IReadOnlyCollection<Task<TResult>> tasks, TimeSpan timeout)
{
var timeoutTask = Task.Delay(timeout);
var aggregateTask = Task.WhenAll(tasks);

View File

@ -100,7 +100,7 @@ namespace Jackett.Common.Utils
private static char[] MakeValidFileName_invalids;
/// <summary>Replaces characters in <c>text</c> that are not allowed in
/// <summary>Replaces characters in <c>text</c> that are not allowed in
/// file names with the specified replacement character.</summary>
/// <param name="text">Text to make into a valid filename. The same string is returned if it is valid already.</param>
/// <param name="replacement">Replacement character, or null to simply remove bad characters.</param>
@ -226,16 +226,16 @@ namespace Jackett.Common.Utils
/// </summary>
public static IEnumerable<string> FindSubstringsBetween(this string source, char opening, char closing, bool includeOpeningAndClosing)
{
var openingIndexes = source.AllIndexesOf(opening).ToList();
var openingIndexes = source.AllIndexesOf(opening).OrderByDescending(_ => _).ToList();
var closingIndexes = source.AllIndexesOf(closing);
foreach (var closingIndex in closingIndexes.OrderBy(_ => _))
{
var potentialOpeningIndexes = openingIndexes.Where(x => x < closingIndex);
if (!potentialOpeningIndexes.Any())
var potentialOpeningIndex = openingIndexes.Where(x => x < closingIndex).Cast<int?>().FirstOrDefault();
if (!potentialOpeningIndex.HasValue)
continue;
var openingIndex = potentialOpeningIndexes.OrderByDescending(_ => _).First();
var openingIndex = potentialOpeningIndex.Value;
var substringIndex = openingIndex + 1;
var substringLength = closingIndex - substringIndex;
if (includeOpeningAndClosing)

View File

@ -155,7 +155,7 @@ namespace Jackett.Server.Controllers
// This should go to ServerConfigurationController
[Route("Cache")]
[HttpGet]
public List<TrackerCacheResult> Cache()
public IReadOnlyList<TrackerCacheResult> Cache()
{
var results = cacheService.GetCachedResults();
ConfigureCacheResults(results);

View File

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Jackett.Common.Models;
@ -340,15 +341,15 @@ namespace Jackett.Test.Common.Models
tcc.SupportedCategories(new[] { 100040 }));
Assert.AreEqual(new[] { TorznabCatType.Movies.ID }, // mixed good and bad
tcc.SupportedCategories(new[] { TorznabCatType.Movies.ID, 9999 }));
Assert.AreEqual(new int[] { }, // not supported child cat
Assert.AreEqual(Array.Empty<int>(), // not supported child cat
tcc.SupportedCategories(new[] { TorznabCatType.Movies3D.ID }));
Assert.AreEqual(new int[] { }, // unknown cat
Assert.AreEqual(Array.Empty<int>(), // unknown cat
tcc.SupportedCategories(new[] { 9999 }));
Assert.AreEqual(new int[] { }, // unknown custom cat
Assert.AreEqual(Array.Empty<int>(), // unknown custom cat
tcc.SupportedCategories(new[] { 100001 }));
Assert.AreEqual(new int[] { }, // empty list
tcc.SupportedCategories(new int[] { }));
Assert.AreEqual(new int[] { }, // null
Assert.AreEqual(Array.Empty<int>(), // empty list
tcc.SupportedCategories(Array.Empty<int>()));
Assert.AreEqual(Array.Empty<int>(), // null
tcc.SupportedCategories(null));
}

View File

@ -14,7 +14,7 @@ namespace Jackett.Test.TestHelpers
public List<ReleaseInfo> Search(IIndexer indexer, TorznabQuery query) => null;
public List<TrackerCacheResult> GetCachedResults() => new List<TrackerCacheResult>();
public IReadOnlyList<TrackerCacheResult> GetCachedResults() => Array.Empty<TrackerCacheResult>();
public void CleanIndexerCache(IIndexer indexer)
{

View File

@ -131,7 +131,7 @@ namespace Jackett.Updater
if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/")))
updateLocation += Path.DirectorySeparatorChar;
var pids = new int[] { };
var pids = Array.Empty<int>();
if (options.KillPids != null)
{
var pidsStr = options.KillPids.Split(',').Where(pid => !string.IsNullOrWhiteSpace(pid)).ToArray();