ChannelDownloadScheduledTask.cs 14 KB

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