2020-02-09 02:35:16 +00:00
|
|
|
using System;
|
2017-07-01 16:23:57 +00:00
|
|
|
using System.Collections.Generic;
|
2017-07-20 21:55:42 +00:00
|
|
|
using System.Linq;
|
2017-08-07 20:33:23 +00:00
|
|
|
using System.Threading.Tasks;
|
2017-07-20 21:55:42 +00:00
|
|
|
using System.Xml.Linq;
|
2017-07-01 16:23:57 +00:00
|
|
|
|
2018-03-10 08:05:56 +00:00
|
|
|
namespace Jackett.Common.Utils
|
2017-07-01 16:23:57 +00:00
|
|
|
{
|
2017-08-08 15:02:16 +00:00
|
|
|
public static class EnumerableExtension
|
2017-07-01 16:23:57 +00:00
|
|
|
{
|
2020-03-27 03:13:38 +00:00
|
|
|
public static T FirstIfSingleOrDefault<T>(this IEnumerable<T> source, T replace = default)
|
2020-03-25 17:54:51 +00:00
|
|
|
{
|
2020-03-27 03:13:38 +00:00
|
|
|
if (source is ICollection<T> collection)
|
|
|
|
return collection.Count == 1 ? collection.First() : replace;
|
|
|
|
var test = source.Take(2).ToList();
|
2020-03-25 17:54:51 +00:00
|
|
|
return test.Count == 1 ? test[0] : replace;
|
|
|
|
}
|
2017-07-10 20:58:44 +00:00
|
|
|
}
|
2017-07-20 21:55:42 +00:00
|
|
|
|
|
|
|
public static class XElementExtension
|
|
|
|
{
|
2020-02-25 16:08:03 +00:00
|
|
|
public static XElement First(this XElement element, string name) => element.Descendants(name).First();
|
2017-07-20 21:55:42 +00:00
|
|
|
|
2020-02-25 16:08:03 +00:00
|
|
|
public static string FirstValue(this XElement element, string name) => element.First(name).Value;
|
2017-07-20 21:55:42 +00:00
|
|
|
}
|
2017-08-06 18:44:22 +00:00
|
|
|
|
2017-08-07 20:33:23 +00:00
|
|
|
public static class TaskExtensions
|
|
|
|
{
|
|
|
|
public static Task<IEnumerable<TResult>> Until<TResult>(this IEnumerable<Task<TResult>> tasks, TimeSpan timeout)
|
|
|
|
{
|
|
|
|
var timeoutTask = Task.Delay(timeout);
|
|
|
|
var aggregateTask = Task.WhenAll(tasks);
|
|
|
|
var anyTask = Task.WhenAny(timeoutTask, aggregateTask);
|
|
|
|
var continuation = anyTask.ContinueWith((_) =>
|
|
|
|
{
|
|
|
|
var completedTasks = tasks.Where(t => t.Status == TaskStatus.RanToCompletion);
|
|
|
|
var results = completedTasks.Select(t => t.Result);
|
|
|
|
return results;
|
|
|
|
});
|
|
|
|
|
|
|
|
return continuation;
|
|
|
|
}
|
|
|
|
}
|
2017-07-01 16:23:57 +00:00
|
|
|
}
|