-
-
Notifications
You must be signed in to change notification settings - Fork 242
/
Deluge.cs
356 lines (303 loc) · 13.4 KB
/
Deluge.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FluentValidation.Results;
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.MediaFiles.TorrentInfo;
using NzbDrone.Core.Parser.Model;
using NzbDrone.Core.RemotePathMappings;
using NzbDrone.Core.Validation;
namespace NzbDrone.Core.Download.Clients.Deluge
{
public class Deluge : TorrentClientBase<DelugeSettings>
{
private readonly IDelugeProxy _proxy;
public Deluge(IDelugeProxy proxy,
ITorrentFileInfoReader torrentFileInfoReader,
IHttpClient httpClient,
IConfigService configService,
IDiskProvider diskProvider,
IRemotePathMappingService remotePathMappingService,
IBlocklistService blocklistService,
Logger logger)
: base(torrentFileInfoReader, httpClient, configService, diskProvider, remotePathMappingService, blocklistService, logger)
{
_proxy = proxy;
}
public override void MarkItemAsImported(DownloadClientItem downloadClientItem)
{
// set post-import category
if (Settings.MusicImportedCategory.IsNotNullOrWhiteSpace() &&
Settings.MusicImportedCategory != Settings.MusicCategory)
{
try
{
_proxy.SetTorrentLabel(downloadClientItem.DownloadId.ToLower(), Settings.MusicImportedCategory, Settings);
}
catch (DownloadClientUnavailableException)
{
_logger.Warn("Failed to set torrent post-import label \"{0}\" for {1} in Deluge. Does the label exist?",
Settings.MusicImportedCategory,
downloadClientItem.Title);
}
}
}
protected override string AddFromMagnetLink(RemoteAlbum remoteAlbum, string hash, string magnetLink)
{
var actualHash = _proxy.AddTorrentFromMagnet(magnetLink, Settings);
if (actualHash.IsNullOrWhiteSpace())
{
throw new DownloadClientException("Deluge failed to add magnet " + magnetLink);
}
_proxy.SetTorrentSeedingConfiguration(actualHash, remoteAlbum.SeedConfiguration, Settings);
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
_proxy.SetTorrentLabel(actualHash, Settings.MusicCategory, Settings);
}
var isRecentAlbum = remoteAlbum.IsRecentAlbum();
if ((isRecentAlbum && Settings.RecentMusicPriority == (int)DelugePriority.First) ||
(!isRecentAlbum && Settings.OlderMusicPriority == (int)DelugePriority.First))
{
_proxy.MoveTorrentToTopInQueue(actualHash, Settings);
}
return actualHash.ToUpper();
}
protected override string AddFromTorrentFile(RemoteAlbum remoteAlbum, string hash, string filename, byte[] fileContent)
{
var actualHash = _proxy.AddTorrentFromFile(filename, fileContent, Settings);
if (actualHash.IsNullOrWhiteSpace())
{
throw new DownloadClientException("Deluge failed to add torrent " + filename);
}
_proxy.SetTorrentSeedingConfiguration(actualHash, remoteAlbum.SeedConfiguration, Settings);
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
_proxy.SetTorrentLabel(actualHash, Settings.MusicCategory, Settings);
}
var isRecentAlbum = remoteAlbum.IsRecentAlbum();
if ((isRecentAlbum && Settings.RecentMusicPriority == (int)DelugePriority.First) ||
(!isRecentAlbum && Settings.OlderMusicPriority == (int)DelugePriority.First))
{
_proxy.MoveTorrentToTopInQueue(actualHash, Settings);
}
return actualHash.ToUpper();
}
public override string Name => "Deluge";
public override IEnumerable<DownloadClientItem> GetItems()
{
IEnumerable<DelugeTorrent> torrents;
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
torrents = _proxy.GetTorrentsByLabel(Settings.MusicCategory, Settings);
}
else
{
torrents = _proxy.GetTorrents(Settings);
}
var items = new List<DownloadClientItem>();
foreach (var torrent in torrents)
{
if (torrent.Hash == null)
{
continue;
}
var item = new DownloadClientItem();
item.DownloadId = torrent.Hash.ToUpper();
item.Title = torrent.Name;
item.Category = Settings.MusicCategory;
item.DownloadClientInfo = DownloadClientItemClientInfo.FromDownloadClient(this);
var outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, new OsPath(torrent.DownloadPath));
item.OutputPath = outputPath + torrent.Name;
item.RemainingSize = torrent.Size - torrent.BytesDownloaded;
item.SeedRatio = torrent.Ratio;
try
{
item.RemainingTime = TimeSpan.FromSeconds(torrent.Eta);
}
catch (OverflowException ex)
{
_logger.Debug(ex, "ETA for {0} is too long: {1}", torrent.Name, torrent.Eta);
item.RemainingTime = TimeSpan.MaxValue;
}
item.TotalSize = torrent.Size;
if (torrent.State == DelugeTorrentStatus.Error)
{
item.Status = DownloadItemStatus.Warning;
item.Message = "Deluge is reporting an error";
}
else if (torrent.IsFinished && torrent.State != DelugeTorrentStatus.Checking)
{
item.Status = DownloadItemStatus.Completed;
}
else if (torrent.State == DelugeTorrentStatus.Queued)
{
item.Status = DownloadItemStatus.Queued;
}
else if (torrent.State == DelugeTorrentStatus.Paused)
{
item.Status = DownloadItemStatus.Paused;
}
else
{
item.Status = DownloadItemStatus.Downloading;
}
// Here we detect if Deluge is managing the torrent and whether the seed criteria has been met.
// This allows drone to delete the torrent as appropriate.
item.CanMoveFiles = item.CanBeRemoved =
torrent.IsAutoManaged &&
torrent.StopAtRatio &&
torrent.Ratio >= torrent.StopRatio &&
torrent.State == DelugeTorrentStatus.Paused;
items.Add(item);
}
return items;
}
public override void RemoveItem(DownloadClientItem item, bool deleteData)
{
_proxy.RemoveTorrent(item.DownloadId.ToLower(), deleteData, Settings);
}
public override DownloadClientInfo GetStatus()
{
var config = _proxy.GetConfig(Settings);
var label = _proxy.GetLabelOptions(Settings);
OsPath destDir;
if (label != null && label.ApplyMoveCompleted && label.MoveCompleted)
{
// if label exists and a label completed path exists and is enabled use it instead of global
destDir = new OsPath(label.MoveCompletedPath);
}
else if (config.GetValueOrDefault("move_completed", false).ToString() == "True")
{
destDir = new OsPath(config.GetValueOrDefault("move_completed_path") as string);
}
else
{
destDir = new OsPath(config.GetValueOrDefault("download_location") as string);
}
var status = new DownloadClientInfo
{
IsLocalhost = Settings.Host == "127.0.0.1" || Settings.Host == "localhost"
};
if (!destDir.IsEmpty)
{
status.OutputRootFolders = new List<OsPath> { _remotePathMappingService.RemapRemoteToLocal(Settings.Host, destDir) };
}
return status;
}
protected override void Test(List<ValidationFailure> failures)
{
failures.AddIfNotNull(TestConnection());
if (failures.HasErrors())
{
return;
}
failures.AddIfNotNull(TestCategory());
failures.AddIfNotNull(TestGetTorrents());
}
private ValidationFailure TestConnection()
{
try
{
_proxy.GetVersion(Settings);
}
catch (DownloadClientAuthenticationException ex)
{
_logger.Error(ex, "Unable to authenticate");
return new NzbDroneValidationFailure("Password", "Authentication failed");
}
catch (WebException ex)
{
_logger.Error(ex, "Unable to test connection");
switch (ex.Status)
{
case WebExceptionStatus.ConnectFailure:
return new NzbDroneValidationFailure("Host", "Unable to connect")
{
DetailedDescription = "Please verify the hostname and port."
};
case WebExceptionStatus.ConnectionClosed:
return new NzbDroneValidationFailure("UseSsl", "Verify SSL settings")
{
DetailedDescription = "Please verify your SSL configuration on both Deluge and Lidarr."
};
case WebExceptionStatus.SecureChannelFailure:
return new NzbDroneValidationFailure("UseSsl", "Unable to connect through SSL")
{
DetailedDescription = "Lidarr is unable to connect to Deluge using SSL. This problem could be computer related. Please try to configure both drone and Deluge to not use SSL."
};
default:
return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message);
}
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to test connection");
return new NzbDroneValidationFailure("Host", "Unable to connect to Deluge")
{
DetailedDescription = ex.Message
};
}
return null;
}
private ValidationFailure TestCategory()
{
if (Settings.MusicCategory.IsNullOrWhiteSpace() && Settings.MusicImportedCategory.IsNullOrWhiteSpace())
{
return null;
}
var enabledPlugins = _proxy.GetEnabledPlugins(Settings);
if (!enabledPlugins.Contains("Label"))
{
return new NzbDroneValidationFailure("MusicCategory", "Label plugin not activated")
{
DetailedDescription = "You must have the Label plugin enabled in Deluge to use categories."
};
}
var labels = _proxy.GetAvailableLabels(Settings);
if (Settings.MusicCategory.IsNotNullOrWhiteSpace() && !labels.Contains(Settings.MusicCategory))
{
_proxy.AddLabel(Settings.MusicCategory, Settings);
labels = _proxy.GetAvailableLabels(Settings);
if (!labels.Contains(Settings.MusicCategory))
{
return new NzbDroneValidationFailure("MusicCategory", "Configuration of label failed")
{
DetailedDescription = "Lidarr was unable to add the label to Deluge."
};
}
}
if (Settings.MusicImportedCategory.IsNotNullOrWhiteSpace() && !labels.Contains(Settings.MusicImportedCategory))
{
_proxy.AddLabel(Settings.MusicImportedCategory, Settings);
labels = _proxy.GetAvailableLabels(Settings);
if (!labels.Contains(Settings.MusicImportedCategory))
{
return new NzbDroneValidationFailure("MusicImportedCategory", "Configuration of label failed")
{
DetailedDescription = "Lidarr was unable to add the label to Deluge."
};
}
}
return null;
}
private ValidationFailure TestGetTorrents()
{
try
{
_proxy.GetTorrents(Settings);
}
catch (Exception ex)
{
_logger.Error(ex, "Unable to get torrents");
return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message);
}
return null;
}
}
}