ChannelDownloadScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. return channelOptions.DownloadSizeLimit;
  157. }
  158. private async Task DownloadChannelItem(BaseItem item,
  159. ChannelOptions channelOptions,
  160. CancellationToken cancellationToken,
  161. string path)
  162. {
  163. var limit = GetDownloadLimit(channelOptions);
  164. if (limit.HasValue)
  165. {
  166. if (IsSizeLimitReached(path, limit.Value))
  167. {
  168. return;
  169. }
  170. }
  171. var itemId = item.Id.ToString("N");
  172. var sources = await _manager.GetChannelItemMediaSources(itemId, false, cancellationToken)
  173. .ConfigureAwait(false);
  174. var cachedVersions = sources.Where(i => i.Protocol == MediaProtocol.File).ToList();
  175. if (cachedVersions.Count > 0)
  176. {
  177. await RefreshMediaSourceItems(cachedVersions, cancellationToken).ConfigureAwait(false);
  178. return;
  179. }
  180. var channelItem = (IChannelMediaItem)item;
  181. var destination = Path.Combine(path, channelItem.ChannelId, itemId);
  182. await _manager.DownloadChannelItem(channelItem, destination, new Progress<double>(), cancellationToken)
  183. .ConfigureAwait(false);
  184. await RefreshMediaSourceItem(destination, cancellationToken).ConfigureAwait(false);
  185. }
  186. private async Task RefreshMediaSourceItems(IEnumerable<MediaSourceInfo> items, CancellationToken cancellationToken)
  187. {
  188. foreach (var item in items)
  189. {
  190. await RefreshMediaSourceItem(item.Path, cancellationToken).ConfigureAwait(false);
  191. }
  192. }
  193. private async Task RefreshMediaSourceItem(string path, CancellationToken cancellationToken)
  194. {
  195. var item = _libraryManager.ResolvePath(new FileInfo(path));
  196. if (item != null)
  197. {
  198. // Get the version from the database
  199. item = _libraryManager.GetItemById(item.Id) ?? item;
  200. await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  201. }
  202. }
  203. private bool IsSizeLimitReached(string path, double gbLimit)
  204. {
  205. try
  206. {
  207. var byteLimit = gbLimit * 1000000000;
  208. long total = 0;
  209. foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories))
  210. {
  211. total += file.Length;
  212. if (total >= byteLimit)
  213. {
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. catch (DirectoryNotFoundException)
  220. {
  221. return false;
  222. }
  223. }
  224. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  225. {
  226. return new ITaskTrigger[]
  227. {
  228. new IntervalTrigger{ Interval = TimeSpan.FromHours(3)},
  229. };
  230. }
  231. private void CleanChannelContent(CancellationToken cancellationToken)
  232. {
  233. var options = _config.GetChannelsConfiguration();
  234. if (!options.MaxDownloadAge.HasValue)
  235. {
  236. return;
  237. }
  238. var minDateModified = DateTime.UtcNow.AddDays(0 - options.MaxDownloadAge.Value);
  239. var path = _manager.ChannelDownloadPath;
  240. try
  241. {
  242. DeleteCacheFilesFromDirectory(cancellationToken, path, minDateModified, new Progress<double>());
  243. }
  244. catch (DirectoryNotFoundException)
  245. {
  246. // No biggie here. Nothing to delete
  247. }
  248. }
  249. /// <summary>
  250. /// Deletes the cache files from directory with a last write time less than a given date
  251. /// </summary>
  252. /// <param name="cancellationToken">The task cancellation token.</param>
  253. /// <param name="directory">The directory.</param>
  254. /// <param name="minDateModified">The min date modified.</param>
  255. /// <param name="progress">The progress.</param>
  256. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  257. {
  258. var filesToDelete = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories)
  259. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  260. .ToList();
  261. var index = 0;
  262. foreach (var file in filesToDelete)
  263. {
  264. double percent = index;
  265. percent /= filesToDelete.Count;
  266. progress.Report(100 * percent);
  267. cancellationToken.ThrowIfCancellationRequested();
  268. DeleteFile(file.FullName);
  269. index++;
  270. }
  271. progress.Report(100);
  272. }
  273. /// <summary>
  274. /// Deletes the file.
  275. /// </summary>
  276. /// <param name="path">The path.</param>
  277. private void DeleteFile(string path)
  278. {
  279. try
  280. {
  281. File.Delete(path);
  282. }
  283. catch (IOException ex)
  284. {
  285. _logger.ErrorException("Error deleting file {0}", ex, path);
  286. }
  287. }
  288. /// <summary>
  289. /// Gets a value indicating whether this instance is hidden.
  290. /// </summary>
  291. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  292. public bool IsHidden
  293. {
  294. get
  295. {
  296. return !_manager.GetAllChannelFeatures().Any();
  297. }
  298. }
  299. /// <summary>
  300. /// Gets a value indicating whether this instance is enabled.
  301. /// </summary>
  302. /// <value><c>true</c> if this instance is enabled; otherwise, <c>false</c>.</value>
  303. public bool IsEnabled
  304. {
  305. get
  306. {
  307. return true;
  308. }
  309. }
  310. }
  311. }