BaseDynamicImageProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Playlists;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Model.Entities;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using CommonIO;
  17. namespace MediaBrowser.Server.Implementations.Photos
  18. {
  19. public abstract class BaseDynamicImageProvider<T> : IHasChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
  20. where T : IHasMetadata
  21. {
  22. protected IFileSystem FileSystem { get; private set; }
  23. protected IProviderManager ProviderManager { get; private set; }
  24. protected IApplicationPaths ApplicationPaths { get; private set; }
  25. protected IImageProcessor ImageProcessor { get; set; }
  26. protected BaseDynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor)
  27. {
  28. ApplicationPaths = applicationPaths;
  29. ProviderManager = providerManager;
  30. FileSystem = fileSystem;
  31. ImageProcessor = imageProcessor;
  32. }
  33. protected virtual bool Supports(IHasImages item)
  34. {
  35. return true;
  36. }
  37. public virtual IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  38. {
  39. return new List<ImageType>
  40. {
  41. ImageType.Primary,
  42. ImageType.Thumb
  43. };
  44. }
  45. public async Task<ItemUpdateType> FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  46. {
  47. if (!Supports(item))
  48. {
  49. return ItemUpdateType.None;
  50. }
  51. var updateType = ItemUpdateType.None;
  52. var supportedImages = GetSupportedImages(item).ToList();
  53. if (supportedImages.Contains(ImageType.Primary))
  54. {
  55. var primaryResult = await FetchAsync(item, ImageType.Primary, options, cancellationToken).ConfigureAwait(false);
  56. updateType = updateType | primaryResult;
  57. }
  58. if (supportedImages.Contains(ImageType.Thumb))
  59. {
  60. var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
  61. updateType = updateType | thumbResult;
  62. }
  63. return updateType;
  64. }
  65. protected async Task<ItemUpdateType> FetchAsync(IHasImages item, ImageType imageType, MetadataRefreshOptions options, CancellationToken cancellationToken)
  66. {
  67. var items = await GetItemsWithImages(item).ConfigureAwait(false);
  68. var cacheKey = GetConfigurationCacheKey(items, item.Name);
  69. if (!HasChanged(item, imageType, cacheKey))
  70. {
  71. return ItemUpdateType.None;
  72. }
  73. return await FetchToFileInternal(item, items, imageType, cacheKey, cancellationToken).ConfigureAwait(false);
  74. }
  75. protected async Task<ItemUpdateType> FetchToFileInternal(IHasImages item,
  76. List<BaseItem> itemsWithImages,
  77. ImageType imageType,
  78. string cacheKey,
  79. CancellationToken cancellationToken)
  80. {
  81. var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N"));
  82. FileSystem.CreateDirectory(Path.GetDirectoryName(outputPathWithoutExtension));
  83. string outputPath = await CreateImage(item, itemsWithImages, outputPathWithoutExtension, imageType, 0).ConfigureAwait(false);
  84. if (string.IsNullOrWhiteSpace(outputPath))
  85. {
  86. return ItemUpdateType.None;
  87. }
  88. await ProviderManager.SaveImage(item, outputPath, "image/png", imageType, null, cacheKey, cancellationToken).ConfigureAwait(false);
  89. return ItemUpdateType.ImageUpdate;
  90. }
  91. protected abstract Task<List<BaseItem>> GetItemsWithImages(IHasImages item);
  92. private const string Version = "32";
  93. protected string GetConfigurationCacheKey(List<BaseItem> items, string itemName)
  94. {
  95. var parts = Version + "_" + (itemName ?? string.Empty) + "_" +
  96. string.Join(",", items.Select(i => i.Id.ToString("N")).ToArray());
  97. return parts.GetMD5().ToString("N");
  98. }
  99. protected Task<string> CreateThumbCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath)
  100. {
  101. return CreateCollage(primaryItem, items, outputPath, 640, 360);
  102. }
  103. protected virtual IEnumerable<string> GetStripCollageImagePaths(IHasImages primaryItem, IEnumerable<BaseItem> items)
  104. {
  105. return items
  106. .Select(i =>
  107. {
  108. var image = i.GetImageInfo(ImageType.Primary, 0);
  109. if (image != null && image.IsLocalFile)
  110. {
  111. return image.Path;
  112. }
  113. image = i.GetImageInfo(ImageType.Thumb, 0);
  114. if (image != null && image.IsLocalFile)
  115. {
  116. return image.Path;
  117. }
  118. return null;
  119. })
  120. .Where(i => !string.IsNullOrWhiteSpace(i));
  121. }
  122. protected Task<string> CreatePosterCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath)
  123. {
  124. return CreateCollage(primaryItem, items, outputPath, 400, 600);
  125. }
  126. protected Task<string> CreateSquareCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath)
  127. {
  128. return CreateCollage(primaryItem, items, outputPath, 600, 600);
  129. }
  130. protected Task<string> CreateThumbCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath, int width, int height)
  131. {
  132. return CreateCollage(primaryItem, items, outputPath, width, height);
  133. }
  134. private async Task<string> CreateCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath, int width, int height)
  135. {
  136. FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  137. var options = new ImageCollageOptions
  138. {
  139. Height = height,
  140. Width = width,
  141. OutputPath = outputPath,
  142. InputPaths = GetStripCollageImagePaths(primaryItem, items).ToArray()
  143. };
  144. if (options.InputPaths.Length == 0)
  145. {
  146. return null;
  147. }
  148. if (!ImageProcessor.SupportsImageCollageCreation)
  149. {
  150. return null;
  151. }
  152. await ImageProcessor.CreateImageCollage(options).ConfigureAwait(false);
  153. return outputPath;
  154. }
  155. public string Name
  156. {
  157. get { return "Dynamic Image Provider"; }
  158. }
  159. protected virtual async Task<string> CreateImage(IHasImages item,
  160. List<BaseItem> itemsWithImages,
  161. string outputPathWithoutExtension,
  162. ImageType imageType,
  163. int imageIndex)
  164. {
  165. if (itemsWithImages.Count == 0)
  166. {
  167. return null;
  168. }
  169. string outputPath = Path.ChangeExtension(outputPathWithoutExtension, ".png");
  170. if (imageType == ImageType.Thumb)
  171. {
  172. return await CreateThumbCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  173. }
  174. if (imageType == ImageType.Primary)
  175. {
  176. if (item is UserView)
  177. {
  178. return await CreateSquareCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  179. }
  180. if (item is Playlist)
  181. {
  182. return await CreateSquareCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  183. }
  184. return await CreatePosterCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  185. }
  186. throw new ArgumentException("Unexpected image type");
  187. }
  188. private const int MaxImageAgeDays = 7;
  189. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  190. {
  191. if (!Supports(item))
  192. {
  193. return false;
  194. }
  195. var supportedImages = GetSupportedImages(item).ToList();
  196. if (item is UserView || item is ICollectionFolder)
  197. {
  198. if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
  199. {
  200. return true;
  201. }
  202. if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
  203. {
  204. return true;
  205. }
  206. return false;
  207. }
  208. var items = GetItemsWithImages(item).Result;
  209. var cacheKey = GetConfigurationCacheKey(items, item.Name);
  210. if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary, cacheKey))
  211. {
  212. return true;
  213. }
  214. if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb, cacheKey))
  215. {
  216. return true;
  217. }
  218. return false;
  219. }
  220. protected bool HasChanged(IHasImages item, ImageType type, string cacheKey)
  221. {
  222. var image = item.GetImageInfo(type, 0);
  223. if (image != null)
  224. {
  225. if (!image.IsLocalFile)
  226. {
  227. return false;
  228. }
  229. if (!FileSystem.ContainsSubPath(item.GetInternalMetadataPath(), image.Path))
  230. {
  231. return false;
  232. }
  233. var currentPathCacheKey = (Path.GetFileNameWithoutExtension(image.Path) ?? string.Empty).Split('_').LastOrDefault();
  234. if (string.Equals(cacheKey, currentPathCacheKey, StringComparison.OrdinalIgnoreCase))
  235. {
  236. return false;
  237. }
  238. }
  239. return true;
  240. }
  241. protected bool HasChanged(IHasImages item, ImageType type)
  242. {
  243. var image = item.GetImageInfo(type, 0);
  244. if (image != null)
  245. {
  246. if (!image.IsLocalFile)
  247. {
  248. return false;
  249. }
  250. if (!FileSystem.ContainsSubPath(item.GetInternalMetadataPath(), image.Path))
  251. {
  252. return false;
  253. }
  254. var age = DateTime.UtcNow - image.DateModified;
  255. if (age.TotalDays <= MaxImageAgeDays)
  256. {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. protected List<BaseItem> GetFinalItems(List<BaseItem> items)
  263. {
  264. return GetFinalItems(items, 4);
  265. }
  266. protected virtual List<BaseItem> GetFinalItems(List<BaseItem> items, int limit)
  267. {
  268. // Rotate the images once every x days
  269. var random = DateTime.Now.DayOfYear % MaxImageAgeDays;
  270. return items
  271. .OrderBy(i => (random + string.Empty + items.IndexOf(i)).GetMD5())
  272. .Take(limit)
  273. .OrderBy(i => i.Name)
  274. .ToList();
  275. }
  276. public int Order
  277. {
  278. get
  279. {
  280. // Run before the default image provider which will download placeholders
  281. return 0;
  282. }
  283. }
  284. }
  285. }