ChannelDownloadScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Progress;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Common.Security;
  6. using MediaBrowser.Controller.Channels;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Channels;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.MediaInfo;
  16. using MediaBrowser.Model.Querying;
  17. using MoreLinq;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. namespace MediaBrowser.Server.Implementations.Channels
  26. {
  27. public class ChannelDownloadScheduledTask : IScheduledTask, IConfigurableScheduledTask
  28. {
  29. private readonly IChannelManager _manager;
  30. private readonly IServerConfigurationManager _config;
  31. private readonly ILogger _logger;
  32. private readonly IHttpClient _httpClient;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly ILibraryManager _libraryManager;
  35. private readonly IUserManager _userManager;
  36. private readonly ISecurityManager _security;
  37. public ChannelDownloadScheduledTask(IChannelManager manager, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem, ILibraryManager libraryManager, IUserManager userManager, ISecurityManager security)
  38. {
  39. _manager = manager;
  40. _config = config;
  41. _logger = logger;
  42. _httpClient = httpClient;
  43. _fileSystem = fileSystem;
  44. _libraryManager = libraryManager;
  45. _userManager = userManager;
  46. _security = security;
  47. }
  48. public string Name
  49. {
  50. get { return "Download channel content"; }
  51. }
  52. public string Description
  53. {
  54. get { return "Downloads channel content based on configuration."; }
  55. }
  56. public string Category
  57. {
  58. get { return "Channels"; }
  59. }
  60. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  61. {
  62. CleanChannelContent(cancellationToken);
  63. var users = _userManager.Users
  64. .DistinctBy(GetUserDistinctValue)
  65. .Select(i => i.Id.ToString("N"))
  66. .ToList();
  67. var numComplete = 0;
  68. foreach (var user in users)
  69. {
  70. double percentPerUser = 1;
  71. percentPerUser /= users.Count;
  72. var startingPercent = numComplete * percentPerUser * 100;
  73. var innerProgress = new ActionableProgress<double>();
  74. innerProgress.RegisterAction(p => progress.Report(startingPercent + (percentPerUser * p)));
  75. await DownloadContent(user, cancellationToken, innerProgress).ConfigureAwait(false);
  76. numComplete++;
  77. double percent = numComplete;
  78. percent /= users.Count;
  79. progress.Report(percent * 100);
  80. }
  81. progress.Report(100);
  82. }
  83. public static string GetUserDistinctValue(User user)
  84. {
  85. var channels = user.Policy.EnabledChannels
  86. .OrderBy(i => i)
  87. .ToList();
  88. return string.Join("|", channels.ToArray());
  89. }
  90. private async Task DownloadContent(string user,
  91. CancellationToken cancellationToken,
  92. IProgress<double> progress)
  93. {
  94. var innerProgress = new ActionableProgress<double>();
  95. innerProgress.RegisterAction(p => progress.Report(0 + (.8 * p)));
  96. await DownloadAllChannelContent(user, cancellationToken, innerProgress).ConfigureAwait(false);
  97. progress.Report(80);
  98. innerProgress = new ActionableProgress<double>();
  99. innerProgress.RegisterAction(p => progress.Report(80 + (.2 * p)));
  100. await DownloadLatestChannelContent(user, cancellationToken, progress).ConfigureAwait(false);
  101. progress.Report(100);
  102. }
  103. private async Task DownloadLatestChannelContent(string userId,
  104. CancellationToken cancellationToken,
  105. IProgress<double> progress)
  106. {
  107. var result = await _manager.GetLatestChannelItemsInternal(new AllChannelMediaQuery
  108. {
  109. UserId = userId
  110. }, cancellationToken).ConfigureAwait(false);
  111. progress.Report(5);
  112. var innerProgress = new ActionableProgress<double>();
  113. innerProgress.RegisterAction(p => progress.Report(5 + (.95 * p)));
  114. var path = _manager.ChannelDownloadPath;
  115. await DownloadChannelContent(result, path, cancellationToken, innerProgress).ConfigureAwait(false);
  116. }
  117. private async Task DownloadAllChannelContent(string userId,
  118. CancellationToken cancellationToken,
  119. IProgress<double> progress)
  120. {
  121. var result = await _manager.GetAllMediaInternal(new AllChannelMediaQuery
  122. {
  123. UserId = userId
  124. }, cancellationToken).ConfigureAwait(false);
  125. progress.Report(5);
  126. var innerProgress = new ActionableProgress<double>();
  127. innerProgress.RegisterAction(p => progress.Report(5 + (.95 * p)));
  128. var path = _manager.ChannelDownloadPath;
  129. await DownloadChannelContent(result, path, cancellationToken, innerProgress).ConfigureAwait(false);
  130. }
  131. private async Task DownloadChannelContent(QueryResult<BaseItem> result,
  132. string path,
  133. CancellationToken cancellationToken,
  134. IProgress<double> progress)
  135. {
  136. var numComplete = 0;
  137. var options = _config.GetChannelsConfiguration();
  138. foreach (var item in result.Items)
  139. {
  140. var channelItem = (IChannelItem)item;
  141. if (options.DownloadingChannels.Contains(channelItem.ChannelId))
  142. {
  143. try
  144. {
  145. await DownloadChannelItem(item, options, cancellationToken, path);
  146. }
  147. catch (OperationCanceledException)
  148. {
  149. break;
  150. }
  151. catch (ChannelDownloadException)
  152. {
  153. // Logged at lower levels
  154. }
  155. catch (Exception ex)
  156. {
  157. _logger.ErrorException("Error downloading channel content for {0}", ex, item.Name);
  158. }
  159. }
  160. numComplete++;
  161. double percent = numComplete;
  162. percent /= result.Items.Length;
  163. progress.Report(percent * 100);
  164. }
  165. progress.Report(100);
  166. }
  167. private double? GetDownloadLimit(ChannelOptions channelOptions)
  168. {
  169. return channelOptions.DownloadSizeLimit;
  170. }
  171. private async Task DownloadChannelItem(BaseItem item,
  172. ChannelOptions channelOptions,
  173. CancellationToken cancellationToken,
  174. string path)
  175. {
  176. var itemId = item.Id.ToString("N");
  177. var sources = await _manager.GetChannelItemMediaSources(itemId, false, cancellationToken)
  178. .ConfigureAwait(false);
  179. var cachedVersions = sources.Where(i => i.Protocol == MediaProtocol.File).ToList();
  180. if (cachedVersions.Count > 0)
  181. {
  182. await RefreshMediaSourceItems(cachedVersions, cancellationToken).ConfigureAwait(false);
  183. return;
  184. }
  185. var limit = GetDownloadLimit(channelOptions);
  186. if (limit.HasValue)
  187. {
  188. if (IsSizeLimitReached(path, limit.Value))
  189. {
  190. return;
  191. }
  192. }
  193. var channelItem = (IChannelMediaItem)item;
  194. var destination = Path.Combine(path, channelItem.ChannelId, itemId);
  195. await _manager.DownloadChannelItem(channelItem, destination, new Progress<double>(), cancellationToken)
  196. .ConfigureAwait(false);
  197. await RefreshMediaSourceItem(destination, cancellationToken).ConfigureAwait(false);
  198. }
  199. private async Task RefreshMediaSourceItems(IEnumerable<MediaSourceInfo> items, CancellationToken cancellationToken)
  200. {
  201. foreach (var item in items)
  202. {
  203. await RefreshMediaSourceItem(item.Path, cancellationToken).ConfigureAwait(false);
  204. }
  205. }
  206. private async Task RefreshMediaSourceItem(string path, CancellationToken cancellationToken)
  207. {
  208. var item = _libraryManager.ResolvePath(new FileInfo(path));
  209. if (item != null)
  210. {
  211. var forceSave = false;
  212. // Get the version from the database
  213. var dbItem = _libraryManager.GetItemById(item.Id);
  214. if (dbItem == null)
  215. {
  216. forceSave = true;
  217. }
  218. else
  219. {
  220. item = dbItem;
  221. }
  222. await item.RefreshMetadata(new MetadataRefreshOptions
  223. {
  224. ForceSave = forceSave
  225. }, cancellationToken).ConfigureAwait(false);
  226. }
  227. }
  228. private bool IsSizeLimitReached(string path, double gbLimit)
  229. {
  230. try
  231. {
  232. var byteLimit = gbLimit * 1000000000;
  233. long total = 0;
  234. foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories))
  235. {
  236. total += file.Length;
  237. if (total >= byteLimit)
  238. {
  239. return true;
  240. }
  241. }
  242. return false;
  243. }
  244. catch (DirectoryNotFoundException)
  245. {
  246. return false;
  247. }
  248. }
  249. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  250. {
  251. return new ITaskTrigger[]
  252. {
  253. new IntervalTrigger{ Interval = TimeSpan.FromHours(3)},
  254. };
  255. }
  256. private void CleanChannelContent(CancellationToken cancellationToken)
  257. {
  258. var options = _config.GetChannelsConfiguration();
  259. if (!options.MaxDownloadAge.HasValue)
  260. {
  261. return;
  262. }
  263. var minDateModified = DateTime.UtcNow.AddDays(0 - options.MaxDownloadAge.Value);
  264. var path = _manager.ChannelDownloadPath;
  265. try
  266. {
  267. DeleteCacheFilesFromDirectory(cancellationToken, path, minDateModified, new Progress<double>());
  268. }
  269. catch (DirectoryNotFoundException)
  270. {
  271. // No biggie here. Nothing to delete
  272. }
  273. }
  274. /// <summary>
  275. /// Deletes the cache files from directory with a last write time less than a given date
  276. /// </summary>
  277. /// <param name="cancellationToken">The task cancellation token.</param>
  278. /// <param name="directory">The directory.</param>
  279. /// <param name="minDateModified">The min date modified.</param>
  280. /// <param name="progress">The progress.</param>
  281. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  282. {
  283. var filesToDelete = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories)
  284. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  285. .ToList();
  286. var index = 0;
  287. foreach (var file in filesToDelete)
  288. {
  289. double percent = index;
  290. percent /= filesToDelete.Count;
  291. progress.Report(100 * percent);
  292. cancellationToken.ThrowIfCancellationRequested();
  293. DeleteFile(file.FullName);
  294. index++;
  295. }
  296. progress.Report(100);
  297. }
  298. /// <summary>
  299. /// Deletes the file.
  300. /// </summary>
  301. /// <param name="path">The path.</param>
  302. private void DeleteFile(string path)
  303. {
  304. try
  305. {
  306. _fileSystem.DeleteFile(path);
  307. }
  308. catch (IOException ex)
  309. {
  310. _logger.ErrorException("Error deleting file {0}", ex, path);
  311. }
  312. }
  313. /// <summary>
  314. /// Gets a value indicating whether this instance is hidden.
  315. /// </summary>
  316. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  317. public bool IsHidden
  318. {
  319. get
  320. {
  321. return !_manager.GetAllChannelFeatures().Any();
  322. }
  323. }
  324. /// <summary>
  325. /// Gets a value indicating whether this instance is enabled.
  326. /// </summary>
  327. /// <value><c>true</c> if this instance is enabled; otherwise, <c>false</c>.</value>
  328. public bool IsEnabled
  329. {
  330. get
  331. {
  332. return true;
  333. }
  334. }
  335. }
  336. }