ChannelDownloadScheduledTask.cs 14 KB

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