CurrentTrailerDownloadTask.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Common.Serialization;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Model.Net;
  7. using MediaBrowser.Model.Tasks;
  8. using MediaBrowser.Plugins.Trailers.Entities;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.ComponentModel.Composition;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Plugins.Trailers.ScheduledTasks
  17. {
  18. /// <summary>
  19. /// Downloads trailers from the web at scheduled times
  20. /// </summary>
  21. [Export(typeof(IScheduledTask))]
  22. public class CurrentTrailerDownloadTask : BaseScheduledTask<Kernel>
  23. {
  24. /// <summary>
  25. /// Creates the triggers that define when the task will run
  26. /// </summary>
  27. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  28. protected override IEnumerable<BaseTaskTrigger> GetDefaultTriggers()
  29. {
  30. var trigger = new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) }; //2am
  31. return new[] { trigger };
  32. }
  33. /// <summary>
  34. /// Returns the task to be executed
  35. /// </summary>
  36. /// <param name="cancellationToken">The cancellation token.</param>
  37. /// <param name="progress">The progress.</param>
  38. /// <returns>Task.</returns>
  39. protected override async Task ExecuteInternal(CancellationToken cancellationToken, IProgress<TaskProgress> progress)
  40. {
  41. // Get the list of trailers
  42. var trailers = await AppleTrailerListingDownloader.GetTrailerList(cancellationToken).ConfigureAwait(false);
  43. progress.Report(new TaskProgress { PercentComplete = 1 });
  44. var trailersToDownload = trailers.Where(t => !IsOldTrailer(t.Video)).ToList();
  45. cancellationToken.ThrowIfCancellationRequested();
  46. var numComplete = 0;
  47. // Fetch them all in parallel
  48. var tasks = trailersToDownload.Select(t => Task.Run(async () =>
  49. {
  50. cancellationToken.ThrowIfCancellationRequested();
  51. try
  52. {
  53. await DownloadTrailer(t, cancellationToken).ConfigureAwait(false);
  54. }
  55. catch (Exception ex)
  56. {
  57. Logger.ErrorException("Error downloading {0}", ex, t.TrailerUrl);
  58. }
  59. // Update progress
  60. lock (progress)
  61. {
  62. numComplete++;
  63. double percent = numComplete;
  64. percent /= trailersToDownload.Count;
  65. // Leave 1% for DeleteOldTrailers
  66. progress.Report(new TaskProgress { PercentComplete = (99 * percent) + 1 });
  67. }
  68. }));
  69. cancellationToken.ThrowIfCancellationRequested();
  70. await Task.WhenAll(tasks).ConfigureAwait(false);
  71. cancellationToken.ThrowIfCancellationRequested();
  72. if (Plugin.Instance.Configuration.DeleteOldTrailers)
  73. {
  74. // Enforce MaxTrailerAge
  75. DeleteOldTrailers();
  76. }
  77. progress.Report(new TaskProgress { PercentComplete = 100 });
  78. }
  79. /// <summary>
  80. /// Downloads a single trailer into the trailers directory
  81. /// </summary>
  82. /// <param name="trailer">The trailer.</param>
  83. /// <param name="cancellationToken">The cancellation token.</param>
  84. /// <returns>Task.</returns>
  85. private async Task DownloadTrailer(TrailerInfo trailer, CancellationToken cancellationToken)
  86. {
  87. // Construct the trailer foldername
  88. var folderName = FileSystem.GetValidFilename(trailer.Video.Name);
  89. if (trailer.Video.ProductionYear.HasValue)
  90. {
  91. folderName += string.Format(" ({0})", trailer.Video.ProductionYear);
  92. }
  93. var folderPath = Path.Combine(Plugin.Instance.DownloadPath, folderName);
  94. // Figure out which image we're going to download
  95. var imageUrl = trailer.HdImageUrl ?? trailer.ImageUrl;
  96. // Construct the video filename (to match the folder name)
  97. var videoFileName = Path.ChangeExtension(folderName, Path.GetExtension(trailer.TrailerUrl));
  98. // Construct the image filename (folder + original extension)
  99. var imageFileName = Path.ChangeExtension("folder", Path.GetExtension(imageUrl));
  100. // Construct full paths
  101. var videoFilePath = Path.Combine(folderPath, videoFileName);
  102. var imageFilePath = Path.Combine(folderPath, imageFileName);
  103. // Create tasks to download each of them, if we don't already have them
  104. Task<string> videoTask = null;
  105. Task<MemoryStream> imageTask = null;
  106. var tasks = new List<Task>();
  107. if (!File.Exists(videoFilePath))
  108. {
  109. Logger.Info("Downloading trailer: " + trailer.TrailerUrl);
  110. // Fetch the video to a temp file because it's too big to put into a MemoryStream
  111. videoTask = Kernel.HttpManager.FetchToTempFile(trailer.TrailerUrl, Kernel.ResourcePools.AppleTrailerVideos, cancellationToken, new Progress<double> { }, "QuickTime/7.6.2");
  112. tasks.Add(videoTask);
  113. }
  114. if (!string.IsNullOrWhiteSpace(imageUrl) && !File.Exists(imageFilePath))
  115. {
  116. // Fetch the image to a memory stream
  117. Logger.Info("Downloading trailer image: " + imageUrl);
  118. imageTask = Kernel.HttpManager.FetchToMemoryStream(imageUrl, Kernel.ResourcePools.AppleTrailerImages, cancellationToken);
  119. tasks.Add(imageTask);
  120. }
  121. try
  122. {
  123. // Wait for both downloads to finish
  124. await Task.WhenAll(tasks).ConfigureAwait(false);
  125. }
  126. catch (HttpException ex)
  127. {
  128. Logger.ErrorException("Error downloading trailer file or image", ex);
  129. }
  130. var videoFailed = false;
  131. var directoryEnsured = false;
  132. // Proces the video file task result
  133. if (videoTask != null)
  134. {
  135. if (videoTask.Status == TaskStatus.RanToCompletion)
  136. {
  137. EnsureDirectory(folderPath);
  138. directoryEnsured = true;
  139. // Move the temp file to the final destination
  140. try
  141. {
  142. File.Move(videoTask.Result, videoFilePath);
  143. }
  144. catch (IOException ex)
  145. {
  146. Logger.ErrorException("Error moving temp file", ex);
  147. File.Delete(videoTask.Result);
  148. videoFailed = true;
  149. }
  150. }
  151. else
  152. {
  153. Logger.Info("Trailer download failed: " + trailer.TrailerUrl);
  154. // Don't bother with the image if the video download failed
  155. videoFailed = true;
  156. }
  157. }
  158. // Process the image file task result
  159. if (imageTask != null && !videoFailed && imageTask.Status == TaskStatus.RanToCompletion)
  160. {
  161. if (!directoryEnsured)
  162. {
  163. EnsureDirectory(folderPath);
  164. }
  165. try
  166. {
  167. // Save the image to the file system
  168. using (var fs = new FileStream(imageFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  169. {
  170. using (var sourceStream = imageTask.Result)
  171. {
  172. await sourceStream.CopyToAsync(fs).ConfigureAwait(false);
  173. }
  174. }
  175. }
  176. catch (IOException ex)
  177. {
  178. Logger.ErrorException("Error saving image to file system", ex);
  179. }
  180. }
  181. // Save metadata only if the video was downloaded
  182. if (!videoFailed && videoTask != null)
  183. {
  184. JsonSerializer.SerializeToFile(trailer.Video, Path.Combine(folderPath, "trailer.json"));
  185. }
  186. }
  187. /// <summary>
  188. /// Determines whether [is old trailer] [the specified trailer].
  189. /// </summary>
  190. /// <param name="trailer">The trailer.</param>
  191. /// <returns><c>true</c> if [is old trailer] [the specified trailer]; otherwise, <c>false</c>.</returns>
  192. private bool IsOldTrailer(Trailer trailer)
  193. {
  194. if (!Plugin.Instance.Configuration.MaxTrailerAge.HasValue)
  195. {
  196. return false;
  197. }
  198. if (!trailer.PremiereDate.HasValue)
  199. {
  200. return false;
  201. }
  202. var now = DateTime.UtcNow;
  203. // Not old if it still hasn't premiered.
  204. if (now < trailer.PremiereDate.Value)
  205. {
  206. return false;
  207. }
  208. return (DateTime.UtcNow - trailer.PremiereDate.Value).TotalDays >
  209. Plugin.Instance.Configuration.MaxTrailerAge.Value;
  210. }
  211. /// <summary>
  212. /// Deletes trailers that are older than the supplied date
  213. /// </summary>
  214. private void DeleteOldTrailers()
  215. {
  216. var collectionFolder = (Folder)Kernel.RootFolder.Children.First(c => c.GetType().Name.Equals(typeof(TrailerCollectionFolder).Name));
  217. foreach (var trailer in collectionFolder.RecursiveChildren.OfType<Trailer>().Where(IsOldTrailer))
  218. {
  219. Logger.Info("Deleting old trailer: " + trailer.Name);
  220. Directory.Delete(Path.GetDirectoryName(trailer.Path), true);
  221. }
  222. }
  223. /// <summary>
  224. /// Ensures the directory.
  225. /// </summary>
  226. /// <param name="path">The path.</param>
  227. private void EnsureDirectory(string path)
  228. {
  229. if (!Directory.Exists(path))
  230. {
  231. Directory.CreateDirectory(path);
  232. }
  233. }
  234. /// <summary>
  235. /// Gets the name of the task
  236. /// </summary>
  237. /// <value>The name.</value>
  238. public override string Name
  239. {
  240. get { return "Find current trailers"; }
  241. }
  242. /// <summary>
  243. /// Gets the category.
  244. /// </summary>
  245. /// <value>The category.</value>
  246. public override string Category
  247. {
  248. get
  249. {
  250. return "Trailers";
  251. }
  252. }
  253. /// <summary>
  254. /// Gets the description.
  255. /// </summary>
  256. /// <value>The description.</value>
  257. public override string Description
  258. {
  259. get { return "Searches the web for upcoming movie trailers, and downloads them based on your Trailer plugin settings."; }
  260. }
  261. }
  262. }