ChannelDownloadScheduledTask.cs 14 KB

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