ChannelDownloadScheduledTask.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. try
  218. {
  219. var byteLimit = gbLimit * 1000000000;
  220. long total = 0;
  221. foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories))
  222. {
  223. total += file.Length;
  224. if (total >= byteLimit)
  225. {
  226. return true;
  227. }
  228. }
  229. return false;
  230. }
  231. catch (DirectoryNotFoundException)
  232. {
  233. return false;
  234. }
  235. }
  236. private async Task RefreshMediaSourceItems(IEnumerable<MediaSourceInfo> items, CancellationToken cancellationToken)
  237. {
  238. foreach (var item in items)
  239. {
  240. await RefreshMediaSourceItem(item.Path, cancellationToken).ConfigureAwait(false);
  241. }
  242. }
  243. private async Task RefreshMediaSourceItem(string path, CancellationToken cancellationToken)
  244. {
  245. var item = _libraryManager.ResolvePath(new FileInfo(path));
  246. if (item != null)
  247. {
  248. // Get the version from the database
  249. item = _libraryManager.GetItemById(item.Id) ?? item;
  250. await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  251. }
  252. }
  253. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  254. {
  255. return new ITaskTrigger[]
  256. {
  257. new IntervalTrigger{ Interval = TimeSpan.FromHours(6)},
  258. };
  259. }
  260. private void CleanChannelContent(CancellationToken cancellationToken)
  261. {
  262. var options = _config.GetChannelsConfiguration();
  263. if (!options.MaxDownloadAge.HasValue)
  264. {
  265. return;
  266. }
  267. var minDateModified = DateTime.UtcNow.AddDays(0 - options.MaxDownloadAge.Value);
  268. var path = _manager.ChannelDownloadPath;
  269. try
  270. {
  271. DeleteCacheFilesFromDirectory(cancellationToken, path, minDateModified, new Progress<double>());
  272. }
  273. catch (DirectoryNotFoundException)
  274. {
  275. // No biggie here. Nothing to delete
  276. }
  277. }
  278. /// <summary>
  279. /// Deletes the cache files from directory with a last write time less than a given date
  280. /// </summary>
  281. /// <param name="cancellationToken">The task cancellation token.</param>
  282. /// <param name="directory">The directory.</param>
  283. /// <param name="minDateModified">The min date modified.</param>
  284. /// <param name="progress">The progress.</param>
  285. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  286. {
  287. var filesToDelete = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories)
  288. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  289. .ToList();
  290. var index = 0;
  291. foreach (var file in filesToDelete)
  292. {
  293. double percent = index;
  294. percent /= filesToDelete.Count;
  295. progress.Report(100 * percent);
  296. cancellationToken.ThrowIfCancellationRequested();
  297. DeleteFile(file.FullName);
  298. index++;
  299. }
  300. progress.Report(100);
  301. }
  302. /// <summary>
  303. /// Deletes the file.
  304. /// </summary>
  305. /// <param name="path">The path.</param>
  306. private void DeleteFile(string path)
  307. {
  308. try
  309. {
  310. File.Delete(path);
  311. }
  312. catch (IOException ex)
  313. {
  314. _logger.ErrorException("Error deleting file {0}", ex, path);
  315. }
  316. }
  317. /// <summary>
  318. /// Gets a value indicating whether this instance is hidden.
  319. /// </summary>
  320. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  321. public bool IsHidden
  322. {
  323. get
  324. {
  325. return !_manager.GetAllChannelFeatures().Any();
  326. }
  327. }
  328. /// <summary>
  329. /// Gets a value indicating whether this instance is enabled.
  330. /// </summary>
  331. /// <value><c>true</c> if this instance is enabled; otherwise, <c>false</c>.</value>
  332. public bool IsEnabled
  333. {
  334. get
  335. {
  336. return true;
  337. }
  338. }
  339. }
  340. }