ChannelDownloadScheduledTask.cs 12 KB

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