ImageService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using ServiceStack.ServiceHost;
  15. using ServiceStack.Text.Controller;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Drawing;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Api.Images
  24. {
  25. /// <summary>
  26. /// Class GetItemImage
  27. /// </summary>
  28. [Route("/Items/{Id}/Images", "GET")]
  29. [Api(Description = "Gets information about an item's images")]
  30. public class GetItemImageInfos : IReturn<List<ImageInfo>>
  31. {
  32. /// <summary>
  33. /// Gets or sets the id.
  34. /// </summary>
  35. /// <value>The id.</value>
  36. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  37. public string Id { get; set; }
  38. }
  39. [Route("/Items/{Id}/Images/{Type}", "GET")]
  40. [Route("/Items/{Id}/Images/{Type}/{Index}", "GET")]
  41. [Api(Description = "Gets an item image")]
  42. public class GetItemImage : ImageRequest
  43. {
  44. /// <summary>
  45. /// Gets or sets the id.
  46. /// </summary>
  47. /// <value>The id.</value>
  48. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  49. public string Id { get; set; }
  50. }
  51. /// <summary>
  52. /// Class UpdateItemImageIndex
  53. /// </summary>
  54. [Route("/Items/{Id}/Images/{Type}/{Index}/Index", "POST")]
  55. [Api(Description = "Updates the index for an item image")]
  56. public class UpdateItemImageIndex : IReturnVoid
  57. {
  58. /// <summary>
  59. /// Gets or sets the id.
  60. /// </summary>
  61. /// <value>The id.</value>
  62. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  63. public Guid Id { get; set; }
  64. /// <summary>
  65. /// Gets or sets the type of the image.
  66. /// </summary>
  67. /// <value>The type of the image.</value>
  68. [ApiMember(Name = "Type", Description = "Image Type", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  69. public ImageType Type { get; set; }
  70. /// <summary>
  71. /// Gets or sets the index.
  72. /// </summary>
  73. /// <value>The index.</value>
  74. [ApiMember(Name = "Index", Description = "Image Index", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  75. public int Index { get; set; }
  76. /// <summary>
  77. /// Gets or sets the new index.
  78. /// </summary>
  79. /// <value>The new index.</value>
  80. [ApiMember(Name = "NewIndex", Description = "The new image index", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  81. public int NewIndex { get; set; }
  82. }
  83. /// <summary>
  84. /// Class DeleteItemImage
  85. /// </summary>
  86. [Route("/Items/{Id}/Images/{Type}", "DELETE")]
  87. [Route("/Items/{Id}/Images/{Type}/{Index}", "DELETE")]
  88. [Api(Description = "Deletes an item image")]
  89. public class DeleteItemImage : DeleteImageRequest, IReturnVoid
  90. {
  91. /// <summary>
  92. /// Gets or sets the id.
  93. /// </summary>
  94. /// <value>The id.</value>
  95. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  96. public Guid Id { get; set; }
  97. }
  98. /// <summary>
  99. /// Class GetPersonImage
  100. /// </summary>
  101. [Route("/Persons/{Name}/Images/{Type}", "GET")]
  102. [Route("/Persons/{Name}/Images/{Type}/{Index}", "GET")]
  103. [Api(Description = "Gets a person image")]
  104. public class GetPersonImage : ImageRequest
  105. {
  106. /// <summary>
  107. /// Gets or sets the name.
  108. /// </summary>
  109. /// <value>The name.</value>
  110. [ApiMember(Name = "Name", Description = "Person name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  111. public string Name { get; set; }
  112. }
  113. /// <summary>
  114. /// Class GetArtistImage
  115. /// </summary>
  116. [Route("/Artists/{Name}/Images/{Type}", "GET")]
  117. [Route("/Artists/{Name}/Images/{Type}/{Index}", "GET")]
  118. [Api(Description = "Gets an artist image")]
  119. public class GetArtistImage : ImageRequest
  120. {
  121. /// <summary>
  122. /// Gets or sets the name.
  123. /// </summary>
  124. /// <value>The name.</value>
  125. [ApiMember(Name = "Name", Description = "Artist name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  126. public string Name { get; set; }
  127. }
  128. /// <summary>
  129. /// Class GetStudioImage
  130. /// </summary>
  131. [Route("/Studios/{Name}/Images/{Type}", "GET")]
  132. [Route("/Studios/{Name}/Images/{Type}/{Index}", "GET")]
  133. [Api(Description = "Gets a studio image")]
  134. public class GetStudioImage : ImageRequest
  135. {
  136. /// <summary>
  137. /// Gets or sets the name.
  138. /// </summary>
  139. /// <value>The name.</value>
  140. [ApiMember(Name = "Name", Description = "Studio name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  141. public string Name { get; set; }
  142. }
  143. /// <summary>
  144. /// Class GetGenreImage
  145. /// </summary>
  146. [Route("/Genres/{Name}/Images/{Type}", "GET")]
  147. [Route("/Genres/{Name}/Images/{Type}/{Index}", "GET")]
  148. [Api(Description = "Gets a genre image")]
  149. public class GetGenreImage : ImageRequest
  150. {
  151. /// <summary>
  152. /// Gets or sets the name.
  153. /// </summary>
  154. /// <value>The name.</value>
  155. [ApiMember(Name = "Name", Description = "Genre name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  156. public string Name { get; set; }
  157. }
  158. [Route("/MusicGenres/{Name}/Images/{Type}", "GET")]
  159. [Route("/MusicGenres/{Name}/Images/{Type}/{Index}", "GET")]
  160. [Api(Description = "Gets a genre image")]
  161. public class GetMusicGenreImage : ImageRequest
  162. {
  163. /// <summary>
  164. /// Gets or sets the name.
  165. /// </summary>
  166. /// <value>The name.</value>
  167. [ApiMember(Name = "Name", Description = "Genre name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  168. public string Name { get; set; }
  169. }
  170. /// <summary>
  171. /// Class GetYearImage
  172. /// </summary>
  173. [Route("/Years/{Year}/Images/{Type}", "GET")]
  174. [Route("/Years/{Year}/Images/{Type}/{Index}", "GET")]
  175. [Api(Description = "Gets a year image")]
  176. public class GetYearImage : ImageRequest
  177. {
  178. /// <summary>
  179. /// Gets or sets the year.
  180. /// </summary>
  181. /// <value>The year.</value>
  182. [ApiMember(Name = "Year", Description = "Year", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
  183. public int Year { get; set; }
  184. }
  185. /// <summary>
  186. /// Class GetUserImage
  187. /// </summary>
  188. [Route("/Users/{Id}/Images/{Type}", "GET")]
  189. [Route("/Users/{Id}/Images/{Type}/{Index}", "GET")]
  190. [Api(Description = "Gets a user image")]
  191. public class GetUserImage : ImageRequest
  192. {
  193. /// <summary>
  194. /// Gets or sets the id.
  195. /// </summary>
  196. /// <value>The id.</value>
  197. [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  198. public Guid Id { get; set; }
  199. }
  200. /// <summary>
  201. /// Class DeleteUserImage
  202. /// </summary>
  203. [Route("/Users/{Id}/Images/{Type}", "DELETE")]
  204. [Route("/Users/{Id}/Images/{Type}/{Index}", "DELETE")]
  205. [Api(Description = "Deletes a user image")]
  206. public class DeleteUserImage : DeleteImageRequest, IReturnVoid
  207. {
  208. /// <summary>
  209. /// Gets or sets the id.
  210. /// </summary>
  211. /// <value>The id.</value>
  212. [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
  213. public Guid Id { get; set; }
  214. }
  215. /// <summary>
  216. /// Class PostUserImage
  217. /// </summary>
  218. [Route("/Users/{Id}/Images/{Type}", "POST")]
  219. [Route("/Users/{Id}/Images/{Type}/{Index}", "POST")]
  220. [Api(Description = "Posts a user image")]
  221. public class PostUserImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
  222. {
  223. /// <summary>
  224. /// Gets or sets the id.
  225. /// </summary>
  226. /// <value>The id.</value>
  227. [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  228. public Guid Id { get; set; }
  229. /// <summary>
  230. /// The raw Http Request Input Stream
  231. /// </summary>
  232. /// <value>The request stream.</value>
  233. public Stream RequestStream { get; set; }
  234. }
  235. /// <summary>
  236. /// Class PostItemImage
  237. /// </summary>
  238. [Route("/Items/{Id}/Images/{Type}", "POST")]
  239. [Route("/Items/{Id}/Images/{Type}/{Index}", "POST")]
  240. [Api(Description = "Posts an item image")]
  241. public class PostItemImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
  242. {
  243. /// <summary>
  244. /// Gets or sets the id.
  245. /// </summary>
  246. /// <value>The id.</value>
  247. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  248. public string Id { get; set; }
  249. /// <summary>
  250. /// The raw Http Request Input Stream
  251. /// </summary>
  252. /// <value>The request stream.</value>
  253. public Stream RequestStream { get; set; }
  254. }
  255. /// <summary>
  256. /// Class ImageService
  257. /// </summary>
  258. public class ImageService : BaseApiService
  259. {
  260. /// <summary>
  261. /// The _user manager
  262. /// </summary>
  263. private readonly IUserManager _userManager;
  264. /// <summary>
  265. /// The _library manager
  266. /// </summary>
  267. private readonly ILibraryManager _libraryManager;
  268. private readonly IApplicationPaths _appPaths;
  269. private readonly IProviderManager _providerManager;
  270. /// <summary>
  271. /// Initializes a new instance of the <see cref="ImageService" /> class.
  272. /// </summary>
  273. /// <param name="userManager">The user manager.</param>
  274. /// <param name="libraryManager">The library manager.</param>
  275. /// <param name="appPaths">The app paths.</param>
  276. /// <param name="providerManager">The provider manager.</param>
  277. public ImageService(IUserManager userManager, ILibraryManager libraryManager, IApplicationPaths appPaths, IProviderManager providerManager)
  278. {
  279. _userManager = userManager;
  280. _libraryManager = libraryManager;
  281. _appPaths = appPaths;
  282. _providerManager = providerManager;
  283. }
  284. /// <summary>
  285. /// Gets the specified request.
  286. /// </summary>
  287. /// <param name="request">The request.</param>
  288. /// <returns>System.Object.</returns>
  289. public object Get(GetItemImageInfos request)
  290. {
  291. var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);
  292. var result = GetItemImageInfos(item).Result;
  293. return ToOptimizedResult(result);
  294. }
  295. /// <summary>
  296. /// Gets the item image infos.
  297. /// </summary>
  298. /// <param name="item">The item.</param>
  299. /// <returns>Task{List{ImageInfo}}.</returns>
  300. public async Task<List<ImageInfo>> GetItemImageInfos(BaseItem item)
  301. {
  302. var list = new List<ImageInfo>();
  303. foreach (var image in item.Images)
  304. {
  305. var path = image.Value;
  306. var fileInfo = new FileInfo(path);
  307. var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, path);
  308. var size = await Kernel.Instance.ImageManager.GetImageSize(path, dateModified).ConfigureAwait(false);
  309. list.Add(new ImageInfo
  310. {
  311. Path = path,
  312. ImageType = image.Key,
  313. ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, image.Key, path),
  314. Size = fileInfo.Length,
  315. Width = Convert.ToInt32(size.Width),
  316. Height = Convert.ToInt32(size.Height)
  317. });
  318. }
  319. var index = 0;
  320. foreach (var image in item.BackdropImagePaths)
  321. {
  322. var fileInfo = new FileInfo(image);
  323. var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image);
  324. var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false);
  325. list.Add(new ImageInfo
  326. {
  327. Path = image,
  328. ImageIndex = index,
  329. ImageType = ImageType.Backdrop,
  330. ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Backdrop, image),
  331. Size = fileInfo.Length,
  332. Width = Convert.ToInt32(size.Width),
  333. Height = Convert.ToInt32(size.Height)
  334. });
  335. index++;
  336. }
  337. index = 0;
  338. foreach (var image in item.ScreenshotImagePaths)
  339. {
  340. var fileInfo = new FileInfo(image);
  341. var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image);
  342. var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false);
  343. list.Add(new ImageInfo
  344. {
  345. Path = image,
  346. ImageIndex = index,
  347. ImageType = ImageType.Screenshot,
  348. ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Screenshot, image),
  349. Size = fileInfo.Length,
  350. Width = Convert.ToInt32(size.Width),
  351. Height = Convert.ToInt32(size.Height)
  352. });
  353. index++;
  354. }
  355. var video = item as Video;
  356. if (video != null)
  357. {
  358. index = 0;
  359. foreach (var chapter in video.Chapters)
  360. {
  361. if (!string.IsNullOrEmpty(chapter.ImagePath))
  362. {
  363. var image = chapter.ImagePath;
  364. var fileInfo = new FileInfo(image);
  365. var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image);
  366. var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false);
  367. list.Add(new ImageInfo
  368. {
  369. Path = image,
  370. ImageIndex = index,
  371. ImageType = ImageType.Chapter,
  372. ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Chapter, image),
  373. Size = fileInfo.Length,
  374. Width = Convert.ToInt32(size.Width),
  375. Height = Convert.ToInt32(size.Height)
  376. });
  377. }
  378. index++;
  379. }
  380. }
  381. return list;
  382. }
  383. /// <summary>
  384. /// Gets the specified request.
  385. /// </summary>
  386. /// <param name="request">The request.</param>
  387. /// <returns>System.Object.</returns>
  388. public object Get(GetItemImage request)
  389. {
  390. var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);
  391. return GetImage(request, item);
  392. }
  393. /// <summary>
  394. /// Gets the specified request.
  395. /// </summary>
  396. /// <param name="request">The request.</param>
  397. /// <returns>System.Object.</returns>
  398. public object Get(GetUserImage request)
  399. {
  400. var item = _userManager.Users.First(i => i.Id == request.Id);
  401. return GetImage(request, item);
  402. }
  403. /// <summary>
  404. /// Gets the specified request.
  405. /// </summary>
  406. /// <param name="request">The request.</param>
  407. /// <returns>System.Object.</returns>
  408. public object Get(GetYearImage request)
  409. {
  410. var item = _libraryManager.GetYear(request.Year).Result;
  411. return GetImage(request, item);
  412. }
  413. /// <summary>
  414. /// Gets the specified request.
  415. /// </summary>
  416. /// <param name="request">The request.</param>
  417. /// <returns>System.Object.</returns>
  418. public object Get(GetStudioImage request)
  419. {
  420. var item = GetStudio(request.Name, _libraryManager).Result;
  421. return GetImage(request, item);
  422. }
  423. /// <summary>
  424. /// Gets the specified request.
  425. /// </summary>
  426. /// <param name="request">The request.</param>
  427. /// <returns>System.Object.</returns>
  428. public object Get(GetPersonImage request)
  429. {
  430. var item = GetPerson(request.Name, _libraryManager).Result;
  431. return GetImage(request, item);
  432. }
  433. /// <summary>
  434. /// Gets the specified request.
  435. /// </summary>
  436. /// <param name="request">The request.</param>
  437. /// <returns>System.Object.</returns>
  438. public object Get(GetArtistImage request)
  439. {
  440. var item = GetArtist(request.Name, _libraryManager).Result;
  441. return GetImage(request, item);
  442. }
  443. /// <summary>
  444. /// Gets the specified request.
  445. /// </summary>
  446. /// <param name="request">The request.</param>
  447. /// <returns>System.Object.</returns>
  448. public object Get(GetGenreImage request)
  449. {
  450. var item = GetGenre(request.Name, _libraryManager).Result;
  451. return GetImage(request, item);
  452. }
  453. public object Get(GetMusicGenreImage request)
  454. {
  455. var item = GetMusicGenre(request.Name, _libraryManager).Result;
  456. return GetImage(request, item);
  457. }
  458. /// <summary>
  459. /// Posts the specified request.
  460. /// </summary>
  461. /// <param name="request">The request.</param>
  462. public void Post(PostUserImage request)
  463. {
  464. var pathInfo = PathInfo.Parse(RequestContext.PathInfo);
  465. var id = new Guid(pathInfo.GetArgumentValue<string>(1));
  466. request.Type = (ImageType)Enum.Parse(typeof(ImageType), pathInfo.GetArgumentValue<string>(3), true);
  467. var item = _userManager.Users.First(i => i.Id == id);
  468. var task = PostImage(item, request.RequestStream, request.Type, RequestContext.ContentType);
  469. Task.WaitAll(task);
  470. }
  471. /// <summary>
  472. /// Posts the specified request.
  473. /// </summary>
  474. /// <param name="request">The request.</param>
  475. public void Post(PostItemImage request)
  476. {
  477. var pathInfo = PathInfo.Parse(RequestContext.PathInfo);
  478. var id = new Guid(pathInfo.GetArgumentValue<string>(1));
  479. request.Type = (ImageType)Enum.Parse(typeof(ImageType), pathInfo.GetArgumentValue<string>(3), true);
  480. var item = _libraryManager.GetItemById(id);
  481. var task = PostImage(item, request.RequestStream, request.Type, RequestContext.ContentType);
  482. Task.WaitAll(task);
  483. }
  484. /// <summary>
  485. /// Deletes the specified request.
  486. /// </summary>
  487. /// <param name="request">The request.</param>
  488. public void Delete(DeleteUserImage request)
  489. {
  490. var item = _userManager.Users.First(i => i.Id == request.Id);
  491. var task = item.DeleteImage(request.Type, request.Index);
  492. Task.WaitAll(task);
  493. }
  494. /// <summary>
  495. /// Deletes the specified request.
  496. /// </summary>
  497. /// <param name="request">The request.</param>
  498. public void Delete(DeleteItemImage request)
  499. {
  500. var item = _libraryManager.GetItemById(request.Id);
  501. var task = item.DeleteImage(request.Type, request.Index);
  502. Task.WaitAll(task);
  503. }
  504. /// <summary>
  505. /// Posts the specified request.
  506. /// </summary>
  507. /// <param name="request">The request.</param>
  508. public void Post(UpdateItemImageIndex request)
  509. {
  510. var item = _libraryManager.GetItemById(request.Id);
  511. var task = UpdateItemIndex(item, request.Type, request.Index, request.NewIndex);
  512. Task.WaitAll(task);
  513. }
  514. /// <summary>
  515. /// Updates the index of the item.
  516. /// </summary>
  517. /// <param name="item">The item.</param>
  518. /// <param name="type">The type.</param>
  519. /// <param name="currentIndex">Index of the current.</param>
  520. /// <param name="newIndex">The new index.</param>
  521. /// <returns>Task.</returns>
  522. /// <exception cref="System.ArgumentException">The change index operation is only applicable to backdrops and screenshots</exception>
  523. private Task UpdateItemIndex(BaseItem item, ImageType type, int currentIndex, int newIndex)
  524. {
  525. string file1;
  526. string file2;
  527. if (type == ImageType.Screenshot)
  528. {
  529. file1 = item.ScreenshotImagePaths[currentIndex];
  530. file2 = item.ScreenshotImagePaths[newIndex];
  531. }
  532. else if (type == ImageType.Backdrop)
  533. {
  534. file1 = item.BackdropImagePaths[currentIndex];
  535. file2 = item.BackdropImagePaths[newIndex];
  536. }
  537. else
  538. {
  539. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  540. }
  541. SwapFiles(file1, file2);
  542. // Directory watchers should repeat this, but do a quick refresh first
  543. return item.RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false);
  544. }
  545. /// <summary>
  546. /// Swaps the files.
  547. /// </summary>
  548. /// <param name="file1">The file1.</param>
  549. /// <param name="file2">The file2.</param>
  550. private void SwapFiles(string file1, string file2)
  551. {
  552. var temp1 = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  553. var temp2 = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  554. File.Copy(file1, temp1);
  555. File.Copy(file2, temp2);
  556. File.Copy(temp1, file2, true);
  557. File.Copy(temp2, file1, true);
  558. }
  559. /// <summary>
  560. /// Gets the image.
  561. /// </summary>
  562. /// <param name="request">The request.</param>
  563. /// <param name="item">The item.</param>
  564. /// <returns>System.Object.</returns>
  565. /// <exception cref="ResourceNotFoundException">
  566. /// </exception>
  567. private object GetImage(ImageRequest request, BaseItem item)
  568. {
  569. var kernel = Kernel.Instance;
  570. var index = request.Index ?? 0;
  571. var imagePath = GetImagePath(kernel, request, item);
  572. if (string.IsNullOrEmpty(imagePath))
  573. {
  574. throw new ResourceNotFoundException(string.Format("{0} does not have an image of type {1}", item.Name, request.Type));
  575. }
  576. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  577. var originalFileImageDateModified = kernel.ImageManager.GetImageDateModified(item, request.Type, index);
  578. var supportedImageEnhancers = request.EnableImageEnhancers ? kernel.ImageManager.ImageEnhancers.Where(i =>
  579. {
  580. try
  581. {
  582. return i.Supports(item, request.Type);
  583. }
  584. catch (Exception ex)
  585. {
  586. Logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  587. return false;
  588. }
  589. }).ToList() : new List<IImageEnhancer>();
  590. // If the file does not exist GetLastWriteTimeUtc will return jan 1, 1601 as opposed to throwing an exception
  591. // http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc.aspx
  592. if (originalFileImageDateModified.Year == 1601 && !File.Exists(imagePath))
  593. {
  594. throw new ResourceNotFoundException(string.Format("File not found: {0}", imagePath));
  595. }
  596. var contentType = MimeTypes.GetMimeType(imagePath);
  597. var cacheGuid = kernel.ImageManager.GetImageCacheTag(imagePath, originalFileImageDateModified, supportedImageEnhancers, item, request.Type);
  598. TimeSpan? cacheDuration = null;
  599. if (!string.IsNullOrEmpty(request.Tag) && cacheGuid == new Guid(request.Tag))
  600. {
  601. cacheDuration = TimeSpan.FromDays(365);
  602. }
  603. // Avoid implicitly captured closure
  604. var currentItem = item;
  605. var currentRequest = request;
  606. return ToCachedResult(cacheGuid, originalFileImageDateModified, cacheDuration, () => new ImageWriter
  607. {
  608. Item = currentItem,
  609. Request = currentRequest,
  610. OriginalImageDateModified = originalFileImageDateModified,
  611. Enhancers = supportedImageEnhancers
  612. }, contentType);
  613. }
  614. /// <summary>
  615. /// Gets the image path.
  616. /// </summary>
  617. /// <param name="kernel">The kernel.</param>
  618. /// <param name="request">The request.</param>
  619. /// <param name="item">The item.</param>
  620. /// <returns>System.String.</returns>
  621. private string GetImagePath(Kernel kernel, ImageRequest request, BaseItem item)
  622. {
  623. var index = request.Index ?? 0;
  624. return kernel.ImageManager.GetImagePath(item, request.Type, index);
  625. }
  626. /// <summary>
  627. /// Posts the image.
  628. /// </summary>
  629. /// <param name="entity">The entity.</param>
  630. /// <param name="inputStream">The input stream.</param>
  631. /// <param name="imageType">Type of the image.</param>
  632. /// <param name="mimeType">Type of the MIME.</param>
  633. /// <returns>Task.</returns>
  634. private async Task PostImage(BaseItem entity, Stream inputStream, ImageType imageType, string mimeType)
  635. {
  636. using (var reader = new StreamReader(inputStream))
  637. {
  638. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  639. var bytes = Convert.FromBase64String(text);
  640. // Validate first
  641. using (var memoryStream = new MemoryStream(bytes))
  642. {
  643. using (var image = Image.FromStream(memoryStream))
  644. {
  645. Logger.Info("New image is {0}x{1}", image.Width, image.Height);
  646. }
  647. }
  648. string filename;
  649. switch (imageType)
  650. {
  651. case ImageType.Art:
  652. filename = "clearart";
  653. break;
  654. case ImageType.Primary:
  655. filename = entity is Episode ? Path.GetFileNameWithoutExtension(entity.Path) : "folder";
  656. break;
  657. case ImageType.Backdrop:
  658. filename = GetBackdropFilenameToSave(entity);
  659. break;
  660. case ImageType.Screenshot:
  661. filename = GetScreenshotFilenameToSave(entity);
  662. break;
  663. default:
  664. filename = imageType.ToString().ToLower();
  665. break;
  666. }
  667. var extension = mimeType.Split(';').First().Split('/').Last();
  668. string oldImagePath;
  669. switch (imageType)
  670. {
  671. case ImageType.Backdrop:
  672. case ImageType.Screenshot:
  673. oldImagePath = null;
  674. break;
  675. default:
  676. oldImagePath = entity.GetImage(imageType);
  677. break;
  678. }
  679. // Don't save locally if there's no parent (special feature, trailer, etc)
  680. var saveLocally = !(entity is Audio) && entity.Parent != null && !string.IsNullOrEmpty(entity.MetaLocation) || entity is User;
  681. if (imageType != ImageType.Primary)
  682. {
  683. if (entity is Episode)
  684. {
  685. saveLocally = false;
  686. }
  687. }
  688. if (entity.LocationType != LocationType.FileSystem)
  689. {
  690. saveLocally = false;
  691. }
  692. var imagePath = _providerManager.GetSavePath(entity, filename + "." + extension, saveLocally);
  693. // Save to file system
  694. using (var fs = new FileStream(imagePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  695. {
  696. await fs.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  697. }
  698. if (imageType == ImageType.Screenshot)
  699. {
  700. entity.ScreenshotImagePaths.Add(imagePath);
  701. }
  702. else if (imageType == ImageType.Backdrop)
  703. {
  704. entity.BackdropImagePaths.Add(imagePath);
  705. }
  706. else
  707. {
  708. // Set the image
  709. entity.SetImage(imageType, imagePath);
  710. }
  711. // If the new and old paths are different, delete the old one
  712. if (!string.IsNullOrEmpty(oldImagePath) && !oldImagePath.Equals(imagePath, StringComparison.OrdinalIgnoreCase))
  713. {
  714. File.Delete(oldImagePath);
  715. }
  716. // Directory watchers should repeat this, but do a quick refresh first
  717. await entity.RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false).ConfigureAwait(false);
  718. }
  719. }
  720. /// <summary>
  721. /// Gets the backdrop filename to save.
  722. /// </summary>
  723. /// <param name="item">The item.</param>
  724. /// <returns>System.String.</returns>
  725. private string GetBackdropFilenameToSave(BaseItem item)
  726. {
  727. var paths = item.BackdropImagePaths.ToList();
  728. if (!paths.Any(i => string.Equals(Path.GetFileNameWithoutExtension(i), "backdrop", StringComparison.OrdinalIgnoreCase)))
  729. {
  730. return "screenshot";
  731. }
  732. var index = 1;
  733. while (paths.Any(i => string.Equals(Path.GetFileNameWithoutExtension(i), "backdrop" + index, StringComparison.OrdinalIgnoreCase)))
  734. {
  735. index++;
  736. }
  737. return "backdrop" + index;
  738. }
  739. /// <summary>
  740. /// Gets the screenshot filename to save.
  741. /// </summary>
  742. /// <param name="item">The item.</param>
  743. /// <returns>System.String.</returns>
  744. private string GetScreenshotFilenameToSave(BaseItem item)
  745. {
  746. var paths = item.ScreenshotImagePaths.ToList();
  747. if (!paths.Any(i => string.Equals(Path.GetFileNameWithoutExtension(i), "screenshot", StringComparison.OrdinalIgnoreCase)))
  748. {
  749. return "screenshot";
  750. }
  751. var index = 1;
  752. while (paths.Any(i => string.Equals(Path.GetFileNameWithoutExtension(i), "screenshot" + index, StringComparison.OrdinalIgnoreCase)))
  753. {
  754. index++;
  755. }
  756. return "screenshot" + index;
  757. }
  758. }
  759. }