ChannelDownloadScheduledTask.cs 13 KB

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