diff --git a/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerDownloadClientApi.cs b/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerDownloadClientApi.cs new file mode 100644 index 000000000..be336754a --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerDownloadClientApi.cs @@ -0,0 +1,238 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace NzbDrone.Core.Download.Clients.Tribler +{ + public enum DownloadStatus + { + [EnumMember(Value = @"WAITING4HASHCHECK")] + Waiting4HashCheck = 0, + + [EnumMember(Value = @"HASHCHECKING")] + Hashchecking = 1, + + [EnumMember(Value = @"METADATA")] + Metadata = 2, + + [EnumMember(Value = @"DOWNLOADING")] + Downloading = 3, + + [EnumMember(Value = @"SEEDING")] + Seeding = 4, + + [EnumMember(Value = @"STOPPED")] + Stopped = 5, + + [EnumMember(Value = @"ALLOCATING_DISKSPACE")] + AllocatingDiskspace = 6, + + [EnumMember(Value = @"EXIT_NODES")] + Exitnodes = 7, + + [EnumMember(Value = @"CIRCUITS")] + Circuits = 8, + + [EnumMember(Value = @"STOPPED_ON_ERROR")] + StoppedOnError = 9, + } + + public class Trackers + { + [JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)] + public string Url { get; set; } + + [JsonProperty("peers", NullValueHandling = NullValueHandling.Ignore)] + public object Peers { get; set; } + + [JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] + public string Status { get; set; } + } + + public class Download + { + [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] + public string Name { get; set; } + + [JsonProperty("progress", NullValueHandling = NullValueHandling.Ignore)] + public float? Progress { get; set; } + + [JsonProperty("anon_download", NullValueHandling = NullValueHandling.Ignore)] + public bool? AnonDownload { get; set; } + + [JsonProperty("availability", NullValueHandling = NullValueHandling.Ignore)] + public float? Availability { get; set; } + + [JsonProperty("eta", NullValueHandling = NullValueHandling.Ignore)] + public double? Eta { get; set; } + + [JsonProperty("total_pieces", NullValueHandling = NullValueHandling.Ignore)] + public long? TotalPieces { get; set; } + + [JsonProperty("num_seeds", NullValueHandling = NullValueHandling.Ignore)] + public long? NumSeeds { get; set; } + + [JsonProperty("total_up", NullValueHandling = NullValueHandling.Ignore)] + public long? TotalUp { get; set; } + + [JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] + [JsonConverter(typeof(StringEnumConverter))] + public DownloadStatus? Status { get; set; } + + [JsonProperty("infohash", NullValueHandling = NullValueHandling.Ignore)] + public string Infohash { get; set; } + + [JsonProperty("ratio", NullValueHandling = NullValueHandling.Ignore)] + public float? Ratio { get; set; } + + [JsonProperty("vod_mode", NullValueHandling = NullValueHandling.Ignore)] + public bool? VideoOnDemandMode { get; set; } + + [JsonProperty("time_added", NullValueHandling = NullValueHandling.Ignore)] + public long? TimeAdded { get; set; } + + [JsonProperty("max_upload_speed", NullValueHandling = NullValueHandling.Ignore)] + public long? MaxUploadSpeed { get; set; } + + [JsonProperty("max_download_speed", NullValueHandling = NullValueHandling.Ignore)] + public long? MaxDownloadSpeed { get; set; } + + [JsonProperty("hops", NullValueHandling = NullValueHandling.Ignore)] + public long? Hops { get; set; } + + [JsonProperty("safe_seeding", NullValueHandling = NullValueHandling.Ignore)] + public bool? SafeSeeding { get; set; } + + [JsonProperty("error", NullValueHandling = NullValueHandling.Ignore)] + public string Error { get; set; } + + [JsonProperty("total_down", NullValueHandling = NullValueHandling.Ignore)] + public long? TotalDown { get; set; } + + [JsonProperty("vod_prebuffering_progress", NullValueHandling = NullValueHandling.Ignore)] + public float? VideoOnDemandPrebufferingProgress { get; set; } + + [JsonProperty("trackers", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Trackers { get; set; } + + [JsonProperty("size", NullValueHandling = NullValueHandling.Ignore)] + public long? Size { get; set; } + + [JsonProperty("peers", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Peers { get; set; } + + [JsonProperty("destination", NullValueHandling = NullValueHandling.Ignore)] + public string Destination { get; set; } + + [JsonProperty("speed_down", NullValueHandling = NullValueHandling.Ignore)] + public float? SpeedDown { get; set; } + + [JsonProperty("speed_up", NullValueHandling = NullValueHandling.Ignore)] + public float? SpeedUp { get; set; } + + [JsonProperty("vod_prebuffering_progress_consec", NullValueHandling = NullValueHandling.Ignore)] + public float? VideoOnDemandPrebufferingProgressConsec { get; set; } + + [JsonProperty("files", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Files { get; set; } + + [JsonProperty("num_peers", NullValueHandling = NullValueHandling.Ignore)] + public long? NumPeers { get; set; } + + [JsonProperty("channel_download", NullValueHandling = NullValueHandling.Ignore)] + public bool? ChannelDownload { get; set; } + } + + public class DownloadsResponse + { + [JsonProperty("downloads", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Downloads { get; set; } + } + + public class AddDownloadRequest + { + [JsonProperty("anon_hops", NullValueHandling = NullValueHandling.Ignore)] + public long? AnonymityHops { get; set; } + + [JsonProperty("safe_seeding", NullValueHandling = NullValueHandling.Ignore)] + public bool? SafeSeeding { get; set; } + + [JsonProperty("destination", NullValueHandling = NullValueHandling.Ignore)] + public string Destination { get; set; } + + [JsonProperty("uri", Required = Newtonsoft.Json.Required.Always)] + [Required(AllowEmptyStrings = true)] + public string Uri { get; set; } + } + + public class AddDownloadResponse + { + [JsonProperty("infohash", NullValueHandling = NullValueHandling.Ignore)] + public string Infohash { get; set; } + + [JsonProperty("started", NullValueHandling = NullValueHandling.Ignore)] + public bool? Started { get; set; } + } + + public class RemoveDownloadRequest + { + [JsonProperty("remove_data", NullValueHandling = NullValueHandling.Ignore)] + public bool? RemoveData { get; set; } + } + + public class DeleteDownloadResponse + { + [JsonProperty("removed", NullValueHandling = NullValueHandling.Ignore)] + public bool? Removed { get; set; } + + [JsonProperty("infohash", NullValueHandling = NullValueHandling.Ignore)] + public string Infohash { get; set; } + } + + public class UpdateDownloadRequest + { + [JsonProperty("anon_hops", NullValueHandling = NullValueHandling.Ignore)] + public long? AnonHops { get; set; } + + [JsonProperty("selected_files", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Selected_files { get; set; } + + [JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)] + public string State { get; set; } + } + + public class UpdateDownloadResponse + { + [JsonProperty("modified", NullValueHandling = NullValueHandling.Ignore)] + public bool? Modified { get; set; } + + [JsonProperty("infohash", NullValueHandling = NullValueHandling.Ignore)] + public string Infohash { get; set; } + } + + public class File + { + [JsonProperty("size", NullValueHandling = NullValueHandling.Ignore)] + public long? Size { get; set; } + + [JsonProperty("index", NullValueHandling = NullValueHandling.Ignore)] + public long? Index { get; set; } + + [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] + public string Name { get; set; } + + [JsonProperty("progress", NullValueHandling = NullValueHandling.Ignore)] + public float? Progress { get; set; } + + [JsonProperty("included", NullValueHandling = NullValueHandling.Ignore)] + public bool? Included { get; set; } + } + + public class GetFilesResponse + { + [JsonProperty("files", NullValueHandling = NullValueHandling.Ignore)] + public ICollection Files { get; set; } + } +} diff --git a/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerSettingsApi.cs b/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerSettingsApi.cs new file mode 100644 index 000000000..ca51d6cd4 --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Tribler/Models/TriblerSettingsApi.cs @@ -0,0 +1,112 @@ +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace NzbDrone.Core.Indexers.Tribler +{ + public class GetTriblerSettingsResponse + { + [JsonProperty("settings", NullValueHandling = NullValueHandling.Ignore)] + public Settings Settings { get; set; } + } + + public class Settings + { + [JsonProperty("general", NullValueHandling = NullValueHandling.Ignore)] + public General General { get; set; } + + [JsonProperty("tunnel_community", NullValueHandling = NullValueHandling.Ignore)] + public TunnelCommunity TunnelCommunity { get; set; } + + [JsonProperty("dht", NullValueHandling = NullValueHandling.Ignore)] + public Dht Dht { get; set; } + + [JsonProperty("download_defaults", NullValueHandling = NullValueHandling.Ignore)] + public DownloadDefaults DownloadDefaults { get; set; } + } + + public class General + { + [JsonProperty("log_dir", NullValueHandling = NullValueHandling.Ignore)] + public string LogDir { get; set; } + + [JsonProperty("version", NullValueHandling = NullValueHandling.Ignore)] + public string Version { get; set; } + + [JsonProperty("version_checker_enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? VersionCheckerEnabled { get; set; } + + [JsonProperty("testnet", NullValueHandling = NullValueHandling.Ignore)] + public bool? TestNet { get; set; } + } + + public class TunnelCommunity + { + [JsonProperty("exitnode_enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? ExitNodeEnabled { get; set; } + + [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? Enabled { get; set; } + + [JsonProperty("random_slots", NullValueHandling = NullValueHandling.Ignore)] + public int? RandomSlots { get; set; } + + [JsonProperty("competing_slots", NullValueHandling = NullValueHandling.Ignore)] + public int? CompetingSlots { get; set; } + + [JsonProperty("min_circuits", NullValueHandling = NullValueHandling.Ignore)] + public int? MinCircuits { get; set; } + + [JsonProperty("max_circuits", NullValueHandling = NullValueHandling.Ignore)] + public int? MaxCircuits { get; set; } + + [JsonProperty("testnet", NullValueHandling = NullValueHandling.Ignore)] + public bool? TestNet { get; set; } + } + + public class Dht + { + [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? Enabled { get; set; } + } + + public class DownloadDefaults + { + [JsonProperty("anonymity_enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? AnonymityEnabled { get; set; } + + [JsonProperty("number_hops", NullValueHandling = NullValueHandling.Ignore)] + public int? NumberHops { get; set; } + + [JsonProperty("safeseeding_enabled", NullValueHandling = NullValueHandling.Ignore)] + public bool? SafeSeedingEnabled { get; set; } + + [JsonProperty("saveas", NullValueHandling = NullValueHandling.Ignore)] + public string SaveAS { get; set; } + + [JsonProperty("seeding_mode", NullValueHandling = NullValueHandling.Ignore)] + [JsonConverter(typeof(StringEnumConverter))] + public DownloadDefaultsSeedingMode? SeedingMode { get; set; } + + [JsonProperty("seeding_ratio", NullValueHandling = NullValueHandling.Ignore)] + public double? SeedingRatio { get; set; } + + [JsonProperty("seeding_time", NullValueHandling = NullValueHandling.Ignore)] + public double? SeedingTime { get; set; } + } + + public enum DownloadDefaultsSeedingMode + { + [EnumMember(Value = @"ratio")] + Ratio = 0, + + [EnumMember(Value = @"forever")] + Forever = 1, + + [EnumMember(Value = @"time")] + Time = 2, + + [EnumMember(Value = @"never")] + Never = 3, + } +} diff --git a/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClient.cs b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClient.cs new file mode 100644 index 000000000..5ecdc4b49 --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClient.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using FluentValidation.Results; +using MonoTorrent; +using NLog; +using NzbDrone.Common.Disk; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; + +using NzbDrone.Core.Blocklisting; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Indexers.Tribler; +using NzbDrone.Core.Localization; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; + +namespace NzbDrone.Core.Download.Clients.Tribler +{ + public class TriblerDownloadClient : TorrentClientBase + { + private readonly ITriblerDownloadClientProxy _proxy; + + public TriblerDownloadClient( + ITriblerDownloadClientProxy triblerDownloadClientProxy, + ITorrentFileInfoReader torrentFileInfoReader, + IHttpClient httpClient, + IConfigService configService, + IDiskProvider diskProvider, + IRemotePathMappingService remotePathMappingService, + ILocalizationService localizationService, + IBlocklistService blocklistService, + Logger logger) + : base(torrentFileInfoReader, httpClient, configService, diskProvider, remotePathMappingService, localizationService, blocklistService, logger) + { + _proxy = triblerDownloadClientProxy; + } + + public override string Name => "Tribler"; + + public override bool PreferTorrentFile => false; + + public override IEnumerable GetItems() + { + var configAsync = _proxy.GetConfig(Settings); + + var items = new List(); + + var downloads = _proxy.GetDownloads(Settings); + + foreach (var download in downloads) + { + // If totalsize == 0 the torrent is a magnet downloading metadata + if (download.Size == null || download.Size == 0) + { + continue; + } + + // skip channel downloads + if (download.ChannelDownload == true) + { + continue; + } + + var item = new DownloadClientItem + { + DownloadId = InfoHash.FromHex(download.Infohash).ToHex(), + Title = download.Name, + + DownloadClientInfo = DownloadClientItemClientInfo.FromDownloadClient(this, false) // TODO: WHAT IS POST-IMPORT + }; + + // some concurrency could make this faster. + var files = _proxy.GetDownloadFiles(Settings, download); + + item.OutputPath = new OsPath(download.Destination); + + if (files.Count == 1) + { + item.OutputPath += files.First().Name; + } + else + { + item.OutputPath += item.Title; + } + + item.TotalSize = (long)download.Size; + item.RemainingSize = (long)(download.Size * (1 - download.Progress)); // TODO: i expect progress to be between 0 and 1 + item.SeedRatio = download.Ratio; + + if (download.Eta.HasValue) + { + if (download.Eta.Value >= TimeSpan.FromDays(365).TotalSeconds) + { + item.RemainingTime = TimeSpan.FromDays(365); + } + else if (download.Eta.Value < 0) + { + item.RemainingTime = TimeSpan.FromSeconds(0); + } + else + { + item.RemainingTime = TimeSpan.FromSeconds(download.Eta.Value); + } + } + + // TODO: the item's message should not be equal to Error + item.Message = download.Error; + + // tribler always saves files unencrypted to disk. + item.IsEncrypted = false; + + // state handling + + // TODO: impossible states? + // Failed = 4, + // Warning = 5 + + // Queued = 0, + // Completed = 3, + // Downloading = 2, + + // Paused is guesstimated + // Paused = 1, + + switch (download.Status) + { + case DownloadStatus.Hashchecking: + case DownloadStatus.Waiting4HashCheck: + case DownloadStatus.Circuits: + case DownloadStatus.Exitnodes: + case DownloadStatus.Downloading: + item.Status = DownloadItemStatus.Downloading; + break; + case DownloadStatus.Metadata: + case DownloadStatus.AllocatingDiskspace: + item.Status = DownloadItemStatus.Queued; + break; + case DownloadStatus.Seeding: + case DownloadStatus.Stopped: + item.Status = DownloadItemStatus.Completed; + break; + case DownloadStatus.StoppedOnError: + item.Status = DownloadItemStatus.Failed; + break; + default: // new status in API? default to downloading + item.Message = "Unknown download state: " + download.Status; + _logger.Info(item.Message); + item.Status = DownloadItemStatus.Downloading; + break; + } + + // override status' if completed but progress is not finished + if (download.Status == DownloadStatus.Stopped && download.Progress < 1) + { + item.Status = DownloadItemStatus.Paused; + } + + // override status if error is set + if (download.Error != null && download.Error.Length > 0) + { + item.Status = DownloadItemStatus.Warning; // maybe this should be an error? + } + + // done (finished seeding & stopped, guessed) + item.CanBeRemoved = HasReachedSeedLimit(download, configAsync); + + // seeding or done, or stopped + item.CanMoveFiles = download.Progress == 1.0; + + items.Add(item); + } + + return items; + } + + public override void RemoveItem(DownloadClientItem item, bool deleteData) + { + _proxy.RemoveDownload(Settings, item, deleteData); + } + + public override DownloadClientInfo GetStatus() + { + var config = _proxy.GetConfig(Settings); + var destDir = config.Settings.DownloadDefaults.SaveAS; + + if (Settings.TvCategory.IsNotNullOrWhiteSpace()) + { + destDir = string.Format("{0}/.{1}", destDir, Settings.TvCategory); + } + + return new DownloadClientInfo + { + IsLocalhost = Settings.Host == "127.0.0.1" || Settings.Host == "localhost", + OutputRootFolders = new List { _remotePathMappingService.RemapRemoteToLocal(Settings.Host, new OsPath(destDir)) } + }; + } + + /** + * this basically checks if torrent is stopped because of seeding has finished + */ + protected static bool HasReachedSeedLimit(Download torrent, GetTriblerSettingsResponse config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + if (torrent == null) + { + throw new ArgumentNullException(nameof(torrent)); + } + + // if download is still running then it's not finished. + if (torrent.Status != DownloadStatus.Stopped) + { + return false; + } + + switch (config.Settings.DownloadDefaults.SeedingMode) + { + // if in ratio mode, wait for ratio to become larger than expeced. Tribler's DownloadStatus will switch from SEEDING to STOPPED + case DownloadDefaultsSeedingMode.Ratio: + + return torrent.Ratio.HasValue + && torrent.Ratio >= config.Settings.DownloadDefaults.SeedingRatio; + + case DownloadDefaultsSeedingMode.Time: + var downloadStarted = DateTimeOffset.FromUnixTimeSeconds(torrent.TimeAdded.Value); + var maxSeedingTime = TimeSpan.FromSeconds(config.Settings.DownloadDefaults.SeedingTime ?? 0); + + return torrent.TimeAdded.HasValue + && downloadStarted.Add(maxSeedingTime) < DateTimeOffset.Now; + + case DownloadDefaultsSeedingMode.Never: + return true; + + case DownloadDefaultsSeedingMode.Forever: + default: + return false; + } + } + + protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string hash, string magnetLink) + { + var addDownloadRequestObject = new AddDownloadRequest + { + Destination = GetDownloadDirectory(), + Uri = magnetLink, + SafeSeeding = Settings.SafeSeeding, + AnonymityHops = Settings.AnonymityLevel + }; + + return _proxy.AddFromMagnetLink(Settings, addDownloadRequestObject); + } + + protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent) + { + // tribler api currently do not support recieving a torrent file direcly. + throw new NotSupportedException("Tribler download client only support magnet links currently"); + } + + protected override void Test(List failures) + { + failures.AddIfNotNull(TestConnection()); + if (failures.HasErrors()) + { + return; + } + + // failures.AddIfNotNull(TestGetTorrents()); + } + + protected string GetDownloadDirectory() + { + if (Settings.TvDirectory.IsNotNullOrWhiteSpace()) + { + return Settings.TvDirectory; + } + + if (!Settings.TvCategory.IsNotNullOrWhiteSpace()) + { + return null; + } + + var config = _proxy.GetConfig(Settings); + var destDir = config.Settings.DownloadDefaults.SaveAS; + + return $"{destDir.TrimEnd('/')}/{Settings.TvCategory}"; + } + + protected ValidationFailure TestConnection() + { + try + { + var downloads = GetItems(); + return null; + } + catch (DownloadClientAuthenticationException ex) + { + _logger.Error(ex, ex.Message); + + return new ValidationFailure("APIKey", _localizationService.GetLocalizedString("DownloadClientValidationApiKeyIncorrect")); + } + catch (DownloadClientUnavailableException ex) + { + _logger.Error(ex, ex.Message); + + return new NzbDroneValidationFailure("Host", _localizationService.GetLocalizedString("DownloadClientValidationUnableToConnect", new Dictionary { { "clientName", Name } })) + { + DetailedDescription = ex.Message + }; + } + catch (Exception ex) + { + _logger.Error(ex, "Failed to test"); + + return new NzbDroneValidationFailure(string.Empty, _localizationService.GetLocalizedString("DownloadClientValidationUnknownException", new Dictionary { { "exception", ex.Message } })); + } + } + } +} diff --git a/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClientProxy.cs b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClientProxy.cs new file mode 100644 index 000000000..5e8f37d5c --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadClientProxy.cs @@ -0,0 +1,137 @@ +using System.Collections.Generic; +using NLog; +using NzbDrone.Common.Http; +using NzbDrone.Common.Serializer; +using NzbDrone.Core.Indexers.Tribler; + +namespace NzbDrone.Core.Download.Clients.Tribler +{ + public interface ITriblerDownloadClientProxy + { + ICollection GetDownloads(TriblerDownloadSettings settings); + + ICollection GetDownloadFiles(TriblerDownloadSettings settings, Download downloadItem); + + GetTriblerSettingsResponse GetConfig(TriblerDownloadSettings settings); + + void RemoveDownload(TriblerDownloadSettings settings, DownloadClientItem item, bool deleteData); + + string AddFromMagnetLink(TriblerDownloadSettings settings, AddDownloadRequest downloadRequest); + } + + public class TriblerDownloadClientProxy : ITriblerDownloadClientProxy + { + protected readonly IHttpClient _httpClient; + private readonly Logger _logger; + + public TriblerDownloadClientProxy(IHttpClient httpClient, Logger logger) + { + _httpClient = httpClient; + _logger = logger; + } + + private HttpRequestBuilder getRequestBuilder(TriblerDownloadSettings settings, string relativePath = null) + { + var requestBuilder = new HttpRequestBuilder(GetBaseUrl(settings, relativePath)) + .Accept(HttpAccept.Json); + + requestBuilder.Headers.Add("X-Api-Key", settings.ApiKey); + + requestBuilder.LogResponseContent = true; + + return requestBuilder; + } + + public string GetBaseUrl(TriblerDownloadSettings settings, string relativePath = null) + { + var baseUrl = HttpRequestBuilder.BuildBaseUrl(settings.UseSsl, settings.Host, settings.Port, settings.UrlBase); + baseUrl = HttpUri.CombinePath(baseUrl, relativePath); + + return baseUrl; + } + + private T ProcessRequest(HttpRequestBuilder requestBuilder) + where T : new() + { + return ProcessRequest(requestBuilder.Build()); + } + + private T ProcessRequest(HttpRequest requestBuilder) + where T : new() + { + var httpRequest = requestBuilder; + + HttpResponse response; + + _logger.Debug("Url: {0}", httpRequest.Url); + + try + { + response = _httpClient.Execute(httpRequest); + } + catch (HttpException ex) + { + if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) + { + throw new DownloadClientAuthenticationException("Unauthorized - AuthToken is invalid", ex); + } + + throw new DownloadClientUnavailableException("Unable to connect to Tribler. Status Code: {0}", ex.Response.StatusCode, ex); + } + + return Json.Deserialize(response.Content); + } + + public GetTriblerSettingsResponse GetConfig(TriblerDownloadSettings settings) + { + var configRequest = getRequestBuilder(settings, "settings"); + return ProcessRequest(configRequest); + } + + public ICollection GetDownloadFiles(TriblerDownloadSettings settings, Download downloadItem) + { + var filesRequest = getRequestBuilder(settings, "downloads/" + downloadItem.Infohash + "/files"); + return ProcessRequest(filesRequest).Files; + } + + public ICollection GetDownloads(TriblerDownloadSettings settings) + { + var downloadRequest = getRequestBuilder(settings, "downloads"); + var downloads = ProcessRequest(downloadRequest); + return downloads.Downloads; + } + + public void RemoveDownload(TriblerDownloadSettings settings, DownloadClientItem item, bool deleteData) + { + var deleteDownloadRequestObject = new RemoveDownloadRequest + { + RemoveData = deleteData + }; + + var deleteRequestBuilder = getRequestBuilder(settings, "downloads/" + item.DownloadId.ToLower()); + deleteRequestBuilder.Method = System.Net.Http.HttpMethod.Delete; + + // manually set content of delete request. + var deleteRequest = deleteRequestBuilder.Build(); + deleteRequest.SetContent(Json.ToJson(deleteDownloadRequestObject)); + + ProcessRequest(deleteRequest); + } + + public string AddFromMagnetLink(TriblerDownloadSettings settings, AddDownloadRequest downloadRequest) + { + var addDownloadRequestBuilder = getRequestBuilder(settings, "downloads"); + addDownloadRequestBuilder.Method = System.Net.Http.HttpMethod.Put; + + // manually set content of download request. + var addDownloadRequest = addDownloadRequestBuilder.Build(); + addDownloadRequest.SetContent(Json.ToJson(downloadRequest)); + + var infoHashAsString = ProcessRequest(addDownloadRequest).Infohash; + + // run hash through InfoHash class to ensure the correct casing. + var infoHash = MonoTorrent.InfoHash.FromHex(infoHashAsString); + return infoHash.ToHex(); + } + } +} diff --git a/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadSettings.cs b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadSettings.cs new file mode 100644 index 000000000..cb9405112 --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Tribler/TriblerDownloadSettings.cs @@ -0,0 +1,81 @@ +using System.Text.RegularExpressions; +using FluentValidation; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Annotations; +using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.Validation; + +namespace NzbDrone.Core.Download.Clients.Tribler +{ + public class TriblerSettingsValidator : AbstractValidator + { + public TriblerSettingsValidator() + { + RuleFor(c => c.Host).ValidHost(); + RuleFor(c => c.Port).InclusiveBetween(1, 65535); + + RuleFor(c => c.UrlBase).ValidUrlBase(); + + RuleFor(c => c.ApiKey).NotEmpty(); + + RuleFor(c => c.TvCategory).Matches(@"^\.?[-a-z]*$", RegexOptions.IgnoreCase).WithMessage("Allowed characters a-z and -"); + + RuleFor(c => c.TvCategory).Empty() + .When(c => c.TvDirectory.IsNotNullOrWhiteSpace()) + .WithMessage("Cannot use Category and Directory"); + + RuleFor(c => c.AnonymityLevel).GreaterThanOrEqualTo(0); + } + } + + public class TriblerDownloadSettings : IProviderConfig + { + private static readonly TriblerSettingsValidator Validator = new TriblerSettingsValidator(); + + public TriblerDownloadSettings() + { + Host = "localhost"; + Port = 20100; + UrlBase = ""; + + AnonymityLevel = 1; + SafeSeeding = true; + } + + [FieldDefinition(1, Label = "Host", Type = FieldType.Textbox)] + public string Host { get; set; } + + [FieldDefinition(2, Label = "Port", Type = FieldType.Textbox)] + public int Port { get; set; } + + [FieldDefinition(3, Label = "UseSsl", Type = FieldType.Checkbox, HelpText = "DownloadClientSettingsUseSslHelpText")] + public bool UseSsl { get; set; } + + [FieldDefinition(4, Label = "UrlBase", Type = FieldType.Textbox, Advanced = true, HelpText = "DownloadClientSettingsUrlBaseHelpText")] + [FieldToken(TokenField.HelpText, "UrlBase", "clientName", "Tribler")] + [FieldToken(TokenField.HelpText, "UrlBase", "url", "http://[host]:[port]/[urlBase]")] + + public string UrlBase { get; set; } + + [FieldDefinition(5, Label = "ApiKey", Type = FieldType.Textbox, Privacy = PrivacyLevel.ApiKey, HelpText = "DownloadClientTriblerSettingsApiKeyHelpText")] + public string ApiKey { get; set; } + + [FieldDefinition(6, Label = "Category", Type = FieldType.Textbox, HelpText = "DownloadClientSettingsCategoryHelpText")] + public string TvCategory { get; set; } + + [FieldDefinition(7, Label = "Directory", Type = FieldType.Textbox, Advanced = true, HelpText = "DownloadClientTriblerSettingsDirectoryHelpText")] + public string TvDirectory { get; set; } + + [FieldDefinition(8, Label = "DownloadClientTriblerSettingsAnonymityLevel", Type = FieldType.Number, HelpText = "DownloadClientTriblerSettingsAnonymityLevelHelpText")] + [FieldToken(TokenField.HelpText, "DownloadClientTriblerSettingsAnonymityLevel", "url", "https://www.tribler.org/anonymity.html")] + public int AnonymityLevel { get; set; } + + [FieldDefinition(9, Label = "DownloadClientTriblerSettingsSafeSeeding", Type = FieldType.Checkbox, HelpText = "DownloadClientTriblerSettingsSafeSeedingHelpText")] + public bool SafeSeeding { get; set; } + + public NzbDroneValidationResult Validate() + { + return new NzbDroneValidationResult(Validator.Validate(this)); + } + } +} diff --git a/src/NzbDrone.Core/Localization/Core/en.json b/src/NzbDrone.Core/Localization/Core/en.json index 8d7d90087..60bce7cc5 100644 --- a/src/NzbDrone.Core/Localization/Core/en.json +++ b/src/NzbDrone.Core/Localization/Core/en.json @@ -534,6 +534,12 @@ "DownloadClientStatusSingleClientHealthCheckMessage": "Download clients unavailable due to failures: {downloadClientNames}", "DownloadClientTransmissionSettingsDirectoryHelpText": "Optional location to put downloads in, leave blank to use the default Transmission location", "DownloadClientTransmissionSettingsUrlBaseHelpText": "Adds a prefix to the {clientName} rpc url, eg {url}, defaults to '{defaultUrl}'", + "DownloadClientTriblerSettingsAnonymityLevel": "Anonymity level", + "DownloadClientTriblerSettingsAnonymityLevelHelpText": "Number of proxies to use when downloading content. To disable set to 0. Proxies reduce download/upload speed. See {url}", + "DownloadClientTriblerSettingsApiKeyHelpText": "[api].key from triblerd.conf", + "DownloadClientTriblerSettingsDirectoryHelpText": "Optional location to put downloads in, leave blank to use the default Tribler location", + "DownloadClientTriblerSettingsSafeSeeding": "Safe Seeding", + "DownloadClientTriblerSettingsSafeSeedingHelpText": "Only Seed through proxies.", "DownloadClientUTorrentTorrentStateError": "uTorrent is reporting an error", "DownloadClientValidationApiKeyIncorrect": "API Key Incorrect", "DownloadClientValidationApiKeyRequired": "API Key Required",