2
0

BaseDynamicImageProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 outputPath = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid() + ".png");
  82. FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  83. var imageCreated = await CreateImage(item, itemsWithImages, outputPath, imageType, 0).ConfigureAwait(false);
  84. if (!imageCreated)
  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<bool> 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<bool> CreatePosterCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath)
  123. {
  124. return CreateCollage(primaryItem, items, outputPath, 400, 600);
  125. }
  126. protected Task<bool> CreateSquareCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath)
  127. {
  128. return CreateCollage(primaryItem, items, outputPath, 600, 600);
  129. }
  130. protected Task<bool> CreateThumbCollage(IHasImages primaryItem, List<BaseItem> items, string outputPath, int width, int height)
  131. {
  132. return CreateCollage(primaryItem, items, outputPath, width, height);
  133. }
  134. private Task<bool> 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 Task.FromResult(false);
  147. }
  148. ImageProcessor.CreateImageCollage(options);
  149. return Task.FromResult(true);
  150. }
  151. public string Name
  152. {
  153. get { return "Dynamic Image Provider"; }
  154. }
  155. protected virtual async Task<bool> CreateImage(IHasImages item,
  156. List<BaseItem> itemsWithImages,
  157. string outputPath,
  158. ImageType imageType,
  159. int imageIndex)
  160. {
  161. if (itemsWithImages.Count == 0)
  162. {
  163. return false;
  164. }
  165. if (imageType == ImageType.Thumb)
  166. {
  167. return await CreateThumbCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  168. }
  169. if (imageType == ImageType.Primary)
  170. {
  171. if (item is UserView)
  172. {
  173. return await CreateSquareCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  174. }
  175. if (item is PhotoAlbum || item is Playlist)
  176. {
  177. return await CreateSquareCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  178. }
  179. return await CreatePosterCollage(item, itemsWithImages, outputPath).ConfigureAwait(false);
  180. }
  181. throw new ArgumentException("Unexpected image type");
  182. }
  183. private const int MaxImageAgeDays = 7;
  184. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  185. {
  186. if (!Supports(item))
  187. {
  188. return false;
  189. }
  190. var supportedImages = GetSupportedImages(item).ToList();
  191. if (item is UserView || item is ICollectionFolder)
  192. {
  193. if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
  194. {
  195. return true;
  196. }
  197. if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
  198. {
  199. return true;
  200. }
  201. return false;
  202. }
  203. var items = GetItemsWithImages(item).Result;
  204. var cacheKey = GetConfigurationCacheKey(items, item.Name);
  205. if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary, cacheKey))
  206. {
  207. return true;
  208. }
  209. if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb, cacheKey))
  210. {
  211. return true;
  212. }
  213. return false;
  214. }
  215. protected bool HasChanged(IHasImages item, ImageType type, string cacheKey)
  216. {
  217. var image = item.GetImageInfo(type, 0);
  218. if (image != null)
  219. {
  220. if (!image.IsLocalFile)
  221. {
  222. return false;
  223. }
  224. if (!FileSystem.ContainsSubPath(item.GetInternalMetadataPath(), image.Path))
  225. {
  226. return false;
  227. }
  228. var currentPathCacheKey = (Path.GetFileNameWithoutExtension(image.Path) ?? string.Empty).Split('_').LastOrDefault();
  229. if (string.Equals(cacheKey, currentPathCacheKey, StringComparison.OrdinalIgnoreCase))
  230. {
  231. return false;
  232. }
  233. }
  234. return true;
  235. }
  236. protected bool HasChanged(IHasImages item, ImageType type)
  237. {
  238. var image = item.GetImageInfo(type, 0);
  239. if (image != null)
  240. {
  241. if (!image.IsLocalFile)
  242. {
  243. return false;
  244. }
  245. if (!FileSystem.ContainsSubPath(item.GetInternalMetadataPath(), image.Path))
  246. {
  247. return false;
  248. }
  249. var age = DateTime.UtcNow - image.DateModified;
  250. if (age.TotalDays <= MaxImageAgeDays)
  251. {
  252. return false;
  253. }
  254. }
  255. return true;
  256. }
  257. protected List<BaseItem> GetFinalItems(List<BaseItem> items)
  258. {
  259. return GetFinalItems(items, 4);
  260. }
  261. protected virtual List<BaseItem> GetFinalItems(List<BaseItem> items, int limit)
  262. {
  263. // Rotate the images once every x days
  264. var random = DateTime.Now.DayOfYear % MaxImageAgeDays;
  265. return items
  266. .OrderBy(i => (random + "" + items.IndexOf(i)).GetMD5())
  267. .Take(limit)
  268. .OrderBy(i => i.Name)
  269. .ToList();
  270. }
  271. public int Order
  272. {
  273. get
  274. {
  275. // Run before the default image provider which will download placeholders
  276. return 0;
  277. }
  278. }
  279. }
  280. }