ChannelDownloadScheduledTask.cs 13 KB

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