-
-
Notifications
You must be signed in to change notification settings - Fork 242
/
UTorrent.cs
321 lines (266 loc) · 11.5 KB
/
UTorrent.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FluentValidation.Results;
using NLog;
using NzbDrone.Common.Cache;
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.UTorrent
{
public class UTorrent : TorrentClientBase<UTorrentSettings>
{
private readonly IUTorrentProxy _proxy;
private readonly ICached<UTorrentTorrentCache> _torrentCache;
public UTorrent(IUTorrentProxy proxy,
ICacheManager cacheManager,
ITorrentFileInfoReader torrentFileInfoReader,
IHttpClient httpClient,
IConfigService configService,
IDiskProvider diskProvider,
IRemotePathMappingService remotePathMappingService,
IBlocklistService blocklistService,
Logger logger)
: base(torrentFileInfoReader, httpClient, configService, diskProvider, remotePathMappingService, blocklistService, logger)
{
_proxy = proxy;
_torrentCache = cacheManager.GetCache<UTorrentTorrentCache>(GetType(), "differentialTorrents");
}
public override void MarkItemAsImported(DownloadClientItem downloadClientItem)
{
// set post-import category
if (Settings.MusicImportedCategory.IsNotNullOrWhiteSpace() &&
Settings.MusicImportedCategory != Settings.MusicCategory)
{
_proxy.SetTorrentLabel(downloadClientItem.DownloadId.ToLower(), Settings.MusicImportedCategory, Settings);
// old label must be explicitly removed
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
_proxy.RemoveTorrentLabel(downloadClientItem.DownloadId.ToLower(), Settings.MusicCategory, Settings);
}
}
}
protected override string AddFromMagnetLink(RemoteAlbum remoteAlbum, string hash, string magnetLink)
{
_proxy.AddTorrentFromUrl(magnetLink, Settings);
_proxy.SetTorrentSeedingConfiguration(hash, remoteAlbum.SeedConfiguration, Settings);
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
_proxy.SetTorrentLabel(hash, Settings.MusicCategory, Settings);
}
var isRecentAlbum = remoteAlbum.IsRecentAlbum();
if ((isRecentAlbum && Settings.RecentMusicPriority == (int)UTorrentPriority.First) ||
(!isRecentAlbum && Settings.OlderMusicPriority == (int)UTorrentPriority.First))
{
_proxy.MoveTorrentToTopInQueue(hash, Settings);
}
_proxy.SetState(hash, (UTorrentState)Settings.IntialState, Settings);
return hash;
}
protected override string AddFromTorrentFile(RemoteAlbum remoteAlbum, string hash, string filename, byte[] fileContent)
{
_proxy.AddTorrentFromFile(filename, fileContent, Settings);
_proxy.SetTorrentSeedingConfiguration(hash, remoteAlbum.SeedConfiguration, Settings);
if (Settings.MusicCategory.IsNotNullOrWhiteSpace())
{
_proxy.SetTorrentLabel(hash, Settings.MusicCategory, Settings);
}
var isRecentAlbum = remoteAlbum.IsRecentAlbum();
if ((isRecentAlbum && Settings.RecentMusicPriority == (int)UTorrentPriority.First) ||
(!isRecentAlbum && Settings.OlderMusicPriority == (int)UTorrentPriority.First))
{
_proxy.MoveTorrentToTopInQueue(hash, Settings);
}
_proxy.SetState(hash, (UTorrentState)Settings.IntialState, Settings);
return hash;
}
public override string Name => "uTorrent";
public override IEnumerable<DownloadClientItem> GetItems()
{
var torrents = GetTorrents();
var queueItems = new List<DownloadClientItem>();
foreach (var torrent in torrents)
{
if (torrent.Label != Settings.MusicCategory)
{
continue;
}
var item = new DownloadClientItem();
item.DownloadId = torrent.Hash;
item.Title = torrent.Name;
item.TotalSize = torrent.Size;
item.Category = torrent.Label;
item.DownloadClientInfo = DownloadClientItemClientInfo.FromDownloadClient(this);
item.RemainingSize = torrent.Remaining;
item.SeedRatio = torrent.Ratio;
if (torrent.Eta != -1)
{
item.RemainingTime = TimeSpan.FromSeconds(torrent.Eta);
}
var outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, new OsPath(torrent.RootDownloadPath));
if (outputPath.FileName == torrent.Name)
{
item.OutputPath = outputPath;
}
else
{
item.OutputPath = outputPath + torrent.Name;
}
if (torrent.Status.HasFlag(UTorrentTorrentStatus.Error))
{
item.Status = DownloadItemStatus.Warning;
item.Message = "uTorrent is reporting an error";
}
else if (torrent.Status.HasFlag(UTorrentTorrentStatus.Loaded) &&
torrent.Status.HasFlag(UTorrentTorrentStatus.Checked) && torrent.Remaining == 0 && torrent.Progress == 1.0)
{
item.Status = DownloadItemStatus.Completed;
}
else if (torrent.Status.HasFlag(UTorrentTorrentStatus.Paused))
{
item.Status = DownloadItemStatus.Paused;
}
else if (torrent.Status.HasFlag(UTorrentTorrentStatus.Started))
{
item.Status = DownloadItemStatus.Downloading;
}
else
{
item.Status = DownloadItemStatus.Queued;
}
// 'Started' without 'Queued' is when the torrent is 'forced seeding'
item.CanMoveFiles = item.CanBeRemoved =
!torrent.Status.HasFlag(UTorrentTorrentStatus.Queued) &&
!torrent.Status.HasFlag(UTorrentTorrentStatus.Started);
queueItems.Add(item);
}
return queueItems;
}
private List<UTorrentTorrent> GetTorrents()
{
List<UTorrentTorrent> torrents;
var cacheKey = string.Format("{0}:{1}:{2}", Settings.Host, Settings.Port, Settings.MusicCategory);
var cache = _torrentCache.Find(cacheKey);
var response = _proxy.GetTorrents(cache == null ? null : cache.CacheID, Settings);
if (cache != null && response.Torrents == null)
{
var removedAndUpdated = new HashSet<string>(response.TorrentsChanged.Select(v => v.Hash).Concat(response.TorrentsRemoved));
torrents = cache.Torrents
.Where(v => !removedAndUpdated.Contains(v.Hash))
.Concat(response.TorrentsChanged)
.ToList();
}
else
{
torrents = response.Torrents;
}
cache = new UTorrentTorrentCache
{
CacheID = response.CacheNumber,
Torrents = torrents
};
_torrentCache.Set(cacheKey, cache, TimeSpan.FromMinutes(15));
return torrents;
}
public override void RemoveItem(DownloadClientItem item, bool deleteData)
{
_proxy.RemoveTorrent(item.DownloadId, deleteData, Settings);
}
public override DownloadClientInfo GetStatus()
{
var config = _proxy.GetConfig(Settings);
var destDir = new OsPath(null);
if (config.GetValueOrDefault("dir_active_download_flag") == "true")
{
destDir = new OsPath(config.GetValueOrDefault("dir_active_download"));
}
if (config.GetValueOrDefault("dir_completed_download_flag") == "true")
{
destDir = new OsPath(config.GetValueOrDefault("dir_completed_download"));
if (config.GetValueOrDefault("dir_add_label") == "true")
{
destDir = destDir + Settings.MusicCategory;
}
}
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(TestGetTorrents());
}
private ValidationFailure TestConnection()
{
try
{
var version = _proxy.GetVersion(Settings);
if (version < 25406)
{
return new ValidationFailure(string.Empty, "Old uTorrent client with unsupported API, need 3.0 or higher");
}
}
catch (DownloadClientAuthenticationException ex)
{
_logger.Error(ex, "Unable to authenticate");
return new NzbDroneValidationFailure("Username", "Authentication failure")
{
DetailedDescription = "Please verify your username and password."
};
}
catch (WebException ex)
{
_logger.Error(ex, "Unable to connect to uTorrent");
if (ex.Status == WebExceptionStatus.ConnectFailure)
{
return new NzbDroneValidationFailure("Host", "Unable to connect")
{
DetailedDescription = "Please verify the hostname and port."
};
}
return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message);
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to test uTorrent");
return new NzbDroneValidationFailure("Host", "Unable to connect to uTorrent")
{
DetailedDescription = ex.Message
};
}
return null;
}
private ValidationFailure TestGetTorrents()
{
try
{
_proxy.GetTorrents(null, Settings);
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to get torrents");
return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message);
}
return null;
}
}
}