ChannelDownloadScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 + (percentPerUser * 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. var options = _config.GetChannelsConfiguration();
  121. foreach (var item in result.Items)
  122. {
  123. if (options.DownloadingChannels.Contains(item.ChannelId))
  124. {
  125. try
  126. {
  127. await DownloadChannelItem(item, cancellationToken, path);
  128. }
  129. catch (OperationCanceledException)
  130. {
  131. break;
  132. }
  133. catch (Exception ex)
  134. {
  135. _logger.ErrorException("Error downloading channel content for {0}", ex, item.Name);
  136. }
  137. }
  138. numComplete++;
  139. double percent = numComplete;
  140. percent /= result.Items.Length;
  141. progress.Report(percent * 100);
  142. }
  143. progress.Report(100);
  144. }
  145. private async Task DownloadChannelItem(BaseItemDto item,
  146. CancellationToken cancellationToken,
  147. string path)
  148. {
  149. var sources = await _manager.GetChannelItemMediaSources(item.Id, cancellationToken)
  150. .ConfigureAwait(false);
  151. var list = sources.ToList();
  152. var cachedVersions = list.Where(i => i.Protocol == MediaProtocol.File).ToList();
  153. if (cachedVersions.Count > 0)
  154. {
  155. await RefreshMediaSourceItems(cachedVersions, cancellationToken).ConfigureAwait(false);
  156. return;
  157. }
  158. var source = list.FirstOrDefault(i => i.Protocol == MediaProtocol.Http);
  159. if (source == null)
  160. {
  161. return;
  162. }
  163. var options = new HttpRequestOptions
  164. {
  165. CancellationToken = cancellationToken,
  166. Url = source.Path,
  167. Progress = new Progress<double>()
  168. };
  169. foreach (var header in source.RequiredHttpHeaders)
  170. {
  171. options.RequestHeaders[header.Key] = header.Value;
  172. }
  173. var destination = Path.Combine(path, item.ChannelId, item.Id);
  174. Directory.CreateDirectory(Path.GetDirectoryName(destination));
  175. // Determine output extension
  176. var response = await _httpClient.GetTempFileResponse(options).ConfigureAwait(false);
  177. if (item.IsVideo && response.ContentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  178. {
  179. var extension = response.ContentType.Split('/')
  180. .Last();
  181. destination += "." + extension;
  182. }
  183. else if (item.IsAudio && response.ContentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase))
  184. {
  185. var extension = response.ContentType.Replace("audio/mpeg", "audio/mp3", StringComparison.OrdinalIgnoreCase)
  186. .Split('/')
  187. .Last();
  188. destination += "." + extension;
  189. }
  190. else
  191. {
  192. File.Delete(response.TempFilePath);
  193. throw new ApplicationException("Unexpected response type encountered: " + response.ContentType);
  194. }
  195. File.Move(response.TempFilePath, destination);
  196. await RefreshMediaSourceItem(destination, cancellationToken).ConfigureAwait(false);
  197. try
  198. {
  199. File.Delete(response.TempFilePath);
  200. }
  201. catch
  202. {
  203. }
  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. // Get the version from the database
  218. item = _libraryManager.GetItemById(item.Id) ?? item;
  219. await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  220. }
  221. }
  222. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  223. {
  224. return new ITaskTrigger[]
  225. {
  226. new IntervalTrigger{ Interval = TimeSpan.FromHours(6)},
  227. };
  228. }
  229. private void CleanChannelContent(CancellationToken cancellationToken)
  230. {
  231. var options = _config.GetChannelsConfiguration();
  232. if (!options.MaxDownloadAge.HasValue)
  233. {
  234. return;
  235. }
  236. var minDateModified = DateTime.UtcNow.AddDays(0 - options.MaxDownloadAge.Value);
  237. var path = _manager.ChannelDownloadPath;
  238. try
  239. {
  240. DeleteCacheFilesFromDirectory(cancellationToken, path, minDateModified, new Progress<double>());
  241. }
  242. catch (DirectoryNotFoundException)
  243. {
  244. // No biggie here. Nothing to delete
  245. }
  246. }
  247. /// <summary>
  248. /// Deletes the cache files from directory with a last write time less than a given date
  249. /// </summary>
  250. /// <param name="cancellationToken">The task cancellation token.</param>
  251. /// <param name="directory">The directory.</param>
  252. /// <param name="minDateModified">The min date modified.</param>
  253. /// <param name="progress">The progress.</param>
  254. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  255. {
  256. var filesToDelete = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories)
  257. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  258. .ToList();
  259. var index = 0;
  260. foreach (var file in filesToDelete)
  261. {
  262. double percent = index;
  263. percent /= filesToDelete.Count;
  264. progress.Report(100 * percent);
  265. cancellationToken.ThrowIfCancellationRequested();
  266. DeleteFile(file.FullName);
  267. index++;
  268. }
  269. progress.Report(100);
  270. }
  271. /// <summary>
  272. /// Deletes the file.
  273. /// </summary>
  274. /// <param name="path">The path.</param>
  275. private void DeleteFile(string path)
  276. {
  277. try
  278. {
  279. File.Delete(path);
  280. }
  281. catch (IOException ex)
  282. {
  283. _logger.ErrorException("Error deleting file {0}", ex, path);
  284. }
  285. }
  286. /// <summary>
  287. /// Gets a value indicating whether this instance is hidden.
  288. /// </summary>
  289. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  290. public bool IsHidden
  291. {
  292. get
  293. {
  294. return !_manager.GetAllChannelFeatures().Any();
  295. }
  296. }
  297. /// <summary>
  298. /// Gets a value indicating whether this instance is enabled.
  299. /// </summary>
  300. /// <value><c>true</c> if this instance is enabled; otherwise, <c>false</c>.</value>
  301. public bool IsEnabled
  302. {
  303. get
  304. {
  305. return true;
  306. }
  307. }
  308. }
  309. }