ChannelDownloadScheduledTask.cs 14 KB

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