ImageSaver.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.IO;
  7. using MediaBrowser.Model.Entities;
  8. using System;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.Providers
  15. {
  16. /// <summary>
  17. /// Class ImageSaver
  18. /// </summary>
  19. public class ImageSaver
  20. {
  21. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  22. /// <summary>
  23. /// The _config
  24. /// </summary>
  25. private readonly IServerConfigurationManager _config;
  26. /// <summary>
  27. /// The remote image cache
  28. /// </summary>
  29. private readonly FileSystemRepository _remoteImageCache;
  30. /// <summary>
  31. /// The _directory watchers
  32. /// </summary>
  33. private readonly IDirectoryWatchers _directoryWatchers;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="ImageSaver"/> class.
  36. /// </summary>
  37. /// <param name="config">The config.</param>
  38. /// <param name="directoryWatchers">The directory watchers.</param>
  39. public ImageSaver(IServerConfigurationManager config, IDirectoryWatchers directoryWatchers)
  40. {
  41. _config = config;
  42. _directoryWatchers = directoryWatchers;
  43. _remoteImageCache = new FileSystemRepository(config.ApplicationPaths.DownloadedImagesDataPath);
  44. }
  45. /// <summary>
  46. /// Saves the image.
  47. /// </summary>
  48. /// <param name="item">The item.</param>
  49. /// <param name="source">The source.</param>
  50. /// <param name="mimeType">Type of the MIME.</param>
  51. /// <param name="type">The type.</param>
  52. /// <param name="imageIndex">Index of the image.</param>
  53. /// <param name="cancellationToken">The cancellation token.</param>
  54. /// <returns>Task.</returns>
  55. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  56. {
  57. if (string.IsNullOrEmpty(mimeType))
  58. {
  59. throw new ArgumentNullException("mimeType");
  60. }
  61. var saveLocally = _config.Configuration.SaveLocalMeta;
  62. if (item is IItemByName)
  63. {
  64. saveLocally = true;
  65. }
  66. else if (item is User)
  67. {
  68. saveLocally = true;
  69. }
  70. else if (item is Audio || item.Parent == null || string.IsNullOrEmpty(item.MetaLocation))
  71. {
  72. saveLocally = false;
  73. }
  74. if (type != ImageType.Primary)
  75. {
  76. if (item is Episode)
  77. {
  78. saveLocally = false;
  79. }
  80. }
  81. if (item.LocationType == LocationType.Remote || item.LocationType == LocationType.Virtual)
  82. {
  83. saveLocally = false;
  84. }
  85. var path = GetSavePath(item, type, imageIndex, mimeType, saveLocally);
  86. var currentPath = GetCurrentImagePath(item, type, imageIndex);
  87. try
  88. {
  89. _directoryWatchers.TemporarilyIgnore(path);
  90. using (source)
  91. {
  92. // If the file is currently hidden we'll have to remove that or the save will fail
  93. var file = new FileInfo(path);
  94. // This will fail if the file is hidden
  95. if (file.Exists)
  96. {
  97. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  98. {
  99. file.Attributes &= ~FileAttributes.Hidden;
  100. }
  101. }
  102. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  103. {
  104. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  105. }
  106. }
  107. SetImagePath(item, type, imageIndex, path);
  108. if (!string.IsNullOrEmpty(currentPath) && !string.Equals(path, currentPath, StringComparison.OrdinalIgnoreCase))
  109. {
  110. File.Delete(currentPath);
  111. }
  112. }
  113. finally
  114. {
  115. _directoryWatchers.RemoveTempIgnore(path);
  116. }
  117. }
  118. private string GetCurrentImagePath(BaseItem item, ImageType type, int? imageIndex)
  119. {
  120. switch (type)
  121. {
  122. case ImageType.Screenshot:
  123. if (!imageIndex.HasValue)
  124. {
  125. throw new ArgumentNullException("imageIndex");
  126. }
  127. return item.ScreenshotImagePaths.Count > imageIndex.Value ? item.ScreenshotImagePaths[imageIndex.Value] : null;
  128. case ImageType.Backdrop:
  129. if (!imageIndex.HasValue)
  130. {
  131. throw new ArgumentNullException("imageIndex");
  132. }
  133. return item.BackdropImagePaths.Count > imageIndex.Value ? item.BackdropImagePaths[imageIndex.Value] : null;
  134. default:
  135. return item.GetImage(type);
  136. }
  137. }
  138. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  139. {
  140. switch (type)
  141. {
  142. case ImageType.Screenshot:
  143. if (!imageIndex.HasValue)
  144. {
  145. throw new ArgumentNullException("imageIndex");
  146. }
  147. if (item.ScreenshotImagePaths.Count > imageIndex.Value)
  148. {
  149. item.ScreenshotImagePaths[imageIndex.Value] = path;
  150. }
  151. else
  152. {
  153. item.ScreenshotImagePaths.Add(path);
  154. }
  155. break;
  156. case ImageType.Backdrop:
  157. if (!imageIndex.HasValue)
  158. {
  159. throw new ArgumentNullException("imageIndex");
  160. }
  161. if (item.BackdropImagePaths.Count > imageIndex.Value)
  162. {
  163. item.BackdropImagePaths[imageIndex.Value] = path;
  164. }
  165. else
  166. {
  167. item.BackdropImagePaths.Add(path);
  168. }
  169. break;
  170. default:
  171. item.SetImage(type, path);
  172. break;
  173. }
  174. }
  175. /// <summary>
  176. /// Gets the save path.
  177. /// </summary>
  178. /// <param name="item">The item.</param>
  179. /// <param name="type">The type.</param>
  180. /// <param name="imageIndex">Index of the image.</param>
  181. /// <param name="mimeType">Type of the MIME.</param>
  182. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  183. /// <returns>System.String.</returns>
  184. /// <exception cref="System.ArgumentNullException">
  185. /// imageIndex
  186. /// or
  187. /// imageIndex
  188. /// </exception>
  189. private string GetSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  190. {
  191. string filename;
  192. switch (type)
  193. {
  194. case ImageType.Art:
  195. filename = "clearart";
  196. break;
  197. case ImageType.Primary:
  198. filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
  199. break;
  200. case ImageType.Backdrop:
  201. if (!imageIndex.HasValue)
  202. {
  203. throw new ArgumentNullException("imageIndex");
  204. }
  205. filename = imageIndex.Value == 0 ? "backdrop" : "backdrop" + imageIndex.Value.ToString(UsCulture);
  206. break;
  207. case ImageType.Screenshot:
  208. if (!imageIndex.HasValue)
  209. {
  210. throw new ArgumentNullException("imageIndex");
  211. }
  212. filename = imageIndex.Value == 0 ? "screenshot" : "screenshot" + imageIndex.Value.ToString(UsCulture);
  213. break;
  214. default:
  215. filename = type.ToString().ToLower();
  216. break;
  217. }
  218. var extension = mimeType.Split('/').Last();
  219. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  220. {
  221. extension = "jpg";
  222. }
  223. filename += "." + extension.ToLower();
  224. string path = null;
  225. if (saveLocally)
  226. {
  227. if (item.IsInMixedFolder && !(item is Episode))
  228. {
  229. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  230. }
  231. if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(item.MetaLocation))
  232. {
  233. path = Path.Combine(item.MetaLocation, filename);
  234. }
  235. }
  236. // None of the save local conditions passed, so store it in our internal folders
  237. if (string.IsNullOrEmpty(path))
  238. {
  239. path = _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id, filename);
  240. }
  241. var parentPath = Path.GetDirectoryName(path);
  242. Directory.CreateDirectory(parentPath);
  243. return path;
  244. }
  245. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  246. {
  247. if (type == ImageType.Primary)
  248. {
  249. return Path.ChangeExtension(item.Path, extension);
  250. }
  251. var folder = Path.GetDirectoryName(item.Path);
  252. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename);
  253. }
  254. }
  255. }