DtoBuilder.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Querying;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Dto
  19. {
  20. /// <summary>
  21. /// Generates DTO's from domain entities
  22. /// </summary>
  23. public class DtoBuilder
  24. {
  25. /// <summary>
  26. /// The index folder delimeter
  27. /// </summary>
  28. const string IndexFolderDelimeter = "-index-";
  29. private readonly ILogger _logger;
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly IUserDataRepository _userDataRepository;
  32. public DtoBuilder(ILogger logger, ILibraryManager libraryManager, IUserDataRepository userDataRepository)
  33. {
  34. _logger = logger;
  35. _libraryManager = libraryManager;
  36. _userDataRepository = userDataRepository;
  37. }
  38. /// <summary>
  39. /// Gets the dto base item.
  40. /// </summary>
  41. /// <param name="item">The item.</param>
  42. /// <param name="fields">The fields.</param>
  43. /// <returns>Task{DtoBaseItem}.</returns>
  44. /// <exception cref="System.ArgumentNullException">item</exception>
  45. public async Task<BaseItemDto> GetBaseItemDto(BaseItem item, List<ItemFields> fields)
  46. {
  47. if (item == null)
  48. {
  49. throw new ArgumentNullException("item");
  50. }
  51. if (fields == null)
  52. {
  53. throw new ArgumentNullException("fields");
  54. }
  55. var dto = new BaseItemDto();
  56. var tasks = new List<Task>();
  57. if (fields.Contains(ItemFields.Studios))
  58. {
  59. tasks.Add(AttachStudios(dto, item));
  60. }
  61. if (fields.Contains(ItemFields.People))
  62. {
  63. tasks.Add(AttachPeople(dto, item));
  64. }
  65. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  66. {
  67. try
  68. {
  69. await AttachPrimaryImageAspectRatio(dto, item, _logger).ConfigureAwait(false);
  70. }
  71. catch (Exception ex)
  72. {
  73. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  74. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  75. }
  76. }
  77. AttachBasicFields(dto, item, fields);
  78. // Make sure all the tasks we kicked off have completed.
  79. if (tasks.Count > 0)
  80. {
  81. await Task.WhenAll(tasks).ConfigureAwait(false);
  82. }
  83. return dto;
  84. }
  85. /// <summary>
  86. /// Converts a BaseItem to a DTOBaseItem
  87. /// </summary>
  88. /// <param name="item">The item.</param>
  89. /// <param name="user">The user.</param>
  90. /// <param name="fields">The fields.</param>
  91. /// <returns>Task{DtoBaseItem}.</returns>
  92. /// <exception cref="System.ArgumentNullException">item</exception>
  93. public async Task<BaseItemDto> GetBaseItemDto(BaseItem item, User user, List<ItemFields> fields)
  94. {
  95. if (item == null)
  96. {
  97. throw new ArgumentNullException("item");
  98. }
  99. if (user == null)
  100. {
  101. throw new ArgumentNullException("user");
  102. }
  103. if (fields == null)
  104. {
  105. throw new ArgumentNullException("fields");
  106. }
  107. var dto = new BaseItemDto();
  108. var tasks = new List<Task>();
  109. if (fields.Contains(ItemFields.Studios))
  110. {
  111. tasks.Add(AttachStudios(dto, item));
  112. }
  113. if (fields.Contains(ItemFields.People))
  114. {
  115. tasks.Add(AttachPeople(dto, item));
  116. }
  117. tasks.Add(AttachUserSpecificInfo(dto, item, user, fields));
  118. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  119. {
  120. try
  121. {
  122. await AttachPrimaryImageAspectRatio(dto, item, _logger).ConfigureAwait(false);
  123. }
  124. catch (Exception ex)
  125. {
  126. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  127. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  128. }
  129. }
  130. AttachBasicFields(dto, item, fields);
  131. // Make sure all the tasks we kicked off have completed.
  132. if (tasks.Count > 0)
  133. {
  134. await Task.WhenAll(tasks).ConfigureAwait(false);
  135. }
  136. return dto;
  137. }
  138. /// <summary>
  139. /// Attaches the user specific info.
  140. /// </summary>
  141. /// <param name="dto">The dto.</param>
  142. /// <param name="item">The item.</param>
  143. /// <param name="user">The user.</param>
  144. /// <param name="fields">The fields.</param>
  145. private async Task AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  146. {
  147. if (fields.Contains(ItemFields.UserData))
  148. {
  149. var userData = await _userDataRepository.GetUserData(user.Id, item.GetUserDataKey()).ConfigureAwait(false);
  150. dto.UserData = GetUserItemDataDto(userData);
  151. }
  152. if (item.IsFolder && fields.Contains(ItemFields.DisplayPreferencesId))
  153. {
  154. dto.DisplayPreferencesId = ((Folder)item).GetDisplayPreferencesId(user.Id).ToString();
  155. }
  156. if (item.IsFolder)
  157. {
  158. if (fields.Contains(ItemFields.ItemCounts))
  159. {
  160. var folder = (Folder)item;
  161. // Skip sorting since all we want is a count
  162. dto.ChildCount = folder.GetChildren(user).Count();
  163. await SetSpecialCounts(folder, user, dto, _userDataRepository).ConfigureAwait(false);
  164. }
  165. }
  166. }
  167. /// <summary>
  168. /// Attaches the primary image aspect ratio.
  169. /// </summary>
  170. /// <param name="dto">The dto.</param>
  171. /// <param name="item">The item.</param>
  172. /// <param name="logger">The _logger.</param>
  173. /// <returns>Task.</returns>
  174. internal static async Task AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item, ILogger logger)
  175. {
  176. var path = item.PrimaryImagePath;
  177. if (string.IsNullOrEmpty(path))
  178. {
  179. return;
  180. }
  181. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(path);
  182. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  183. var dateModified = metaFileEntry == null ? File.GetLastWriteTimeUtc(path) : metaFileEntry.LastWriteTimeUtc;
  184. ImageSize size;
  185. try
  186. {
  187. size = await Kernel.Instance.ImageManager.GetImageSize(path, dateModified).ConfigureAwait(false);
  188. }
  189. catch (FileNotFoundException)
  190. {
  191. logger.Error("Image file does not exist: {0}", path);
  192. return;
  193. }
  194. catch (Exception ex)
  195. {
  196. logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  197. return;
  198. }
  199. foreach (var enhancer in Kernel.Instance.ImageEnhancers
  200. .Where(i => i.Supports(item, ImageType.Primary)))
  201. {
  202. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  203. }
  204. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  205. }
  206. /// <summary>
  207. /// Sets simple property values on a DTOBaseItem
  208. /// </summary>
  209. /// <param name="dto">The dto.</param>
  210. /// <param name="item">The item.</param>
  211. /// <param name="fields">The fields.</param>
  212. private void AttachBasicFields(BaseItemDto dto, BaseItem item, List<ItemFields> fields)
  213. {
  214. if (fields.Contains(ItemFields.DateCreated))
  215. {
  216. dto.DateCreated = item.DateCreated;
  217. }
  218. if (fields.Contains(ItemFields.DisplayMediaType))
  219. {
  220. dto.DisplayMediaType = item.DisplayMediaType;
  221. }
  222. if (fields.Contains(ItemFields.Budget))
  223. {
  224. dto.Budget = item.Budget;
  225. }
  226. if (fields.Contains(ItemFields.Revenue))
  227. {
  228. dto.Revenue = item.Revenue;
  229. }
  230. if (fields.Contains(ItemFields.EndDate))
  231. {
  232. dto.EndDate = item.EndDate;
  233. }
  234. if (fields.Contains(ItemFields.HomePageUrl))
  235. {
  236. dto.HomePageUrl = item.HomePageUrl;
  237. }
  238. if (fields.Contains(ItemFields.ProductionLocations))
  239. {
  240. dto.ProductionLocations = item.ProductionLocations;
  241. }
  242. dto.AspectRatio = item.AspectRatio;
  243. dto.BackdropImageTags = GetBackdropImageTags(item);
  244. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  245. if (fields.Contains(ItemFields.Genres))
  246. {
  247. dto.Genres = item.Genres;
  248. }
  249. if (item.Images != null)
  250. {
  251. dto.ImageTags = new Dictionary<ImageType, Guid>();
  252. foreach (var image in item.Images)
  253. {
  254. var type = image.Key;
  255. dto.ImageTags[type] = Kernel.Instance.ImageManager.GetImageCacheTag(item, type, image.Value);
  256. }
  257. }
  258. dto.Id = GetClientItemId(item);
  259. dto.IndexNumber = item.IndexNumber;
  260. dto.IsFolder = item.IsFolder;
  261. dto.Language = item.Language;
  262. dto.MediaType = item.MediaType;
  263. dto.LocationType = item.LocationType;
  264. var localTrailerCount = item.LocalTrailers == null ? 0 : item.LocalTrailers.Count;
  265. if (localTrailerCount > 0)
  266. {
  267. dto.LocalTrailerCount = localTrailerCount;
  268. }
  269. dto.Name = item.Name;
  270. dto.OfficialRating = item.OfficialRating;
  271. var hasOverview = fields.Contains(ItemFields.Overview);
  272. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  273. if (hasOverview || hasHtmlOverview)
  274. {
  275. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  276. if (hasOverview)
  277. {
  278. dto.Overview = strippedOverview;
  279. }
  280. // Only supply the html version if there was actually html content
  281. if (hasHtmlOverview)
  282. {
  283. dto.OverviewHtml = item.Overview;
  284. }
  285. }
  286. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  287. if (dto.BackdropImageTags.Count == 0)
  288. {
  289. var parentWithBackdrop = GetParentBackdropItem(item);
  290. if (parentWithBackdrop != null)
  291. {
  292. dto.ParentBackdropItemId = GetClientItemId(parentWithBackdrop);
  293. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  294. }
  295. }
  296. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  297. {
  298. dto.ParentId = GetClientItemId(item.Parent);
  299. }
  300. dto.ParentIndexNumber = item.ParentIndexNumber;
  301. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  302. if (!dto.HasLogo)
  303. {
  304. var parentWithLogo = GetParentLogoItem(item);
  305. if (parentWithLogo != null)
  306. {
  307. dto.ParentLogoItemId = GetClientItemId(parentWithLogo);
  308. dto.ParentLogoImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImage(ImageType.Logo));
  309. }
  310. }
  311. if (fields.Contains(ItemFields.Path))
  312. {
  313. dto.Path = item.Path;
  314. }
  315. dto.PremiereDate = item.PremiereDate;
  316. dto.ProductionYear = item.ProductionYear;
  317. if (fields.Contains(ItemFields.ProviderIds))
  318. {
  319. dto.ProviderIds = item.ProviderIds;
  320. }
  321. dto.RunTimeTicks = item.RunTimeTicks;
  322. if (fields.Contains(ItemFields.SortName))
  323. {
  324. dto.SortName = item.SortName;
  325. }
  326. if (fields.Contains(ItemFields.Taglines))
  327. {
  328. dto.Taglines = item.Taglines;
  329. }
  330. if (fields.Contains(ItemFields.TrailerUrls))
  331. {
  332. dto.TrailerUrls = item.TrailerUrls;
  333. }
  334. dto.Type = item.GetType().Name;
  335. dto.CommunityRating = item.CommunityRating;
  336. if (item.IsFolder)
  337. {
  338. var folder = (Folder)item;
  339. if (fields.Contains(ItemFields.IndexOptions))
  340. {
  341. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  342. }
  343. }
  344. // Add audio info
  345. if (fields.Contains(ItemFields.AudioInfo))
  346. {
  347. var audio = item as Audio;
  348. if (audio != null)
  349. {
  350. dto.Album = audio.Album;
  351. dto.AlbumArtist = audio.AlbumArtist;
  352. dto.Artists = new[] { audio.Artist };
  353. }
  354. var album = item as MusicAlbum;
  355. if (album != null)
  356. {
  357. var songs = album.RecursiveChildren.OfType<Audio>().ToList();
  358. dto.AlbumArtist = songs.Select(i => i.AlbumArtist).FirstOrDefault(i => !string.IsNullOrEmpty(i));
  359. dto.Artists =
  360. songs.Select(i => i.Artist ?? string.Empty)
  361. .Where(i => !string.IsNullOrEmpty(i))
  362. .Distinct(StringComparer.OrdinalIgnoreCase)
  363. .ToArray();
  364. }
  365. }
  366. // Add video info
  367. var video = item as Video;
  368. if (video != null)
  369. {
  370. dto.VideoType = video.VideoType;
  371. dto.VideoFormat = video.VideoFormat;
  372. dto.IsoType = video.IsoType;
  373. if (fields.Contains(ItemFields.Chapters) && video.Chapters != null)
  374. {
  375. dto.Chapters = video.Chapters.Select(c => GetChapterInfoDto(c, item)).ToList();
  376. }
  377. }
  378. if (fields.Contains(ItemFields.MediaStreams))
  379. {
  380. // Add VideoInfo
  381. var iHasMediaStreams = item as IHasMediaStreams;
  382. if (iHasMediaStreams != null)
  383. {
  384. dto.MediaStreams = iHasMediaStreams.MediaStreams;
  385. }
  386. }
  387. // Add MovieInfo
  388. var movie = item as Movie;
  389. if (movie != null)
  390. {
  391. var specialFeatureCount = movie.SpecialFeatures == null ? 0 : movie.SpecialFeatures.Count;
  392. if (specialFeatureCount > 0)
  393. {
  394. dto.SpecialFeatureCount = specialFeatureCount;
  395. }
  396. }
  397. if (fields.Contains(ItemFields.SeriesInfo))
  398. {
  399. // Add SeriesInfo
  400. var series = item as Series;
  401. if (series != null)
  402. {
  403. dto.AirDays = series.AirDays;
  404. dto.AirTime = series.AirTime;
  405. dto.Status = series.Status;
  406. }
  407. // Add EpisodeInfo
  408. var episode = item as Episode;
  409. if (episode != null)
  410. {
  411. series = item.FindParent<Series>();
  412. dto.SeriesId = GetClientItemId(series);
  413. dto.SeriesName = series.Name;
  414. }
  415. // Add SeasonInfo
  416. var season = item as Season;
  417. if (season != null)
  418. {
  419. series = item.FindParent<Series>();
  420. dto.SeriesId = GetClientItemId(series);
  421. dto.SeriesName = series.Name;
  422. }
  423. }
  424. var game = item as BaseGame;
  425. if (game != null)
  426. {
  427. dto.Players = game.PlayersSupported;
  428. }
  429. }
  430. /// <summary>
  431. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  432. /// </summary>
  433. /// <param name="folder">The folder.</param>
  434. /// <param name="user">The user.</param>
  435. /// <param name="dto">The dto.</param>
  436. /// <param name="userDataRepository">The user data repository.</param>
  437. /// <returns>Task.</returns>
  438. private static async Task SetSpecialCounts(Folder folder, User user, BaseItemDto dto, IUserDataRepository userDataRepository)
  439. {
  440. var rcentlyAddedItemCount = 0;
  441. var recursiveItemCount = 0;
  442. double totalPercentPlayed = 0;
  443. // Loop through each recursive child
  444. foreach (var child in folder.GetRecursiveChildren(user).Where(i => !i.IsFolder).ToList())
  445. {
  446. var userdata = await userDataRepository.GetUserData(user.Id, child.GetUserDataKey()).ConfigureAwait(false);
  447. recursiveItemCount++;
  448. // Check is recently added
  449. if (child.IsRecentlyAdded())
  450. {
  451. rcentlyAddedItemCount++;
  452. }
  453. // Incrememt totalPercentPlayed
  454. if (userdata != null)
  455. {
  456. if (userdata.PlayCount > 0)
  457. {
  458. totalPercentPlayed += 100;
  459. }
  460. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  461. {
  462. double itemPercent = userdata.PlaybackPositionTicks;
  463. itemPercent /= child.RunTimeTicks.Value;
  464. totalPercentPlayed += itemPercent;
  465. }
  466. }
  467. }
  468. dto.RecursiveItemCount = recursiveItemCount;
  469. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  470. if (recursiveItemCount > 0)
  471. {
  472. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  473. }
  474. }
  475. /// <summary>
  476. /// Attaches People DTO's to a DTOBaseItem
  477. /// </summary>
  478. /// <param name="dto">The dto.</param>
  479. /// <param name="item">The item.</param>
  480. /// <returns>Task.</returns>
  481. private async Task AttachPeople(BaseItemDto dto, BaseItem item)
  482. {
  483. if (item.People == null)
  484. {
  485. return;
  486. }
  487. // Ordering by person type to ensure actors and artists are at the front.
  488. // This is taking advantage of the fact that they both begin with A
  489. // This should be improved in the future
  490. var people = item.People.OrderBy(i => i.Type).ToList();
  491. // Attach People by transforming them into BaseItemPerson (DTO)
  492. dto.People = new BaseItemPerson[people.Count];
  493. var entities = await Task.WhenAll(people.Select(p => p.Name).Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  494. Task.Run(async () =>
  495. {
  496. try
  497. {
  498. return await _libraryManager.GetPerson(c).ConfigureAwait(false);
  499. }
  500. catch (IOException ex)
  501. {
  502. _logger.ErrorException("Error getting person {0}", ex, c);
  503. return null;
  504. }
  505. })
  506. )).ConfigureAwait(false);
  507. var dictionary = entities.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  508. for (var i = 0; i < people.Count; i++)
  509. {
  510. var person = people[i];
  511. var baseItemPerson = new BaseItemPerson
  512. {
  513. Name = person.Name,
  514. Role = person.Role,
  515. Type = person.Type
  516. };
  517. Person entity;
  518. if (dictionary.TryGetValue(person.Name, out entity))
  519. {
  520. var primaryImagePath = entity.PrimaryImagePath;
  521. if (!string.IsNullOrEmpty(primaryImagePath))
  522. {
  523. baseItemPerson.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
  524. }
  525. }
  526. dto.People[i] = baseItemPerson;
  527. }
  528. }
  529. /// <summary>
  530. /// Attaches the studios.
  531. /// </summary>
  532. /// <param name="dto">The dto.</param>
  533. /// <param name="item">The item.</param>
  534. /// <returns>Task.</returns>
  535. private async Task AttachStudios(BaseItemDto dto, BaseItem item)
  536. {
  537. if (item.Studios == null)
  538. {
  539. return;
  540. }
  541. var studios = item.Studios.ToList();
  542. dto.Studios = new StudioDto[studios.Count];
  543. var entities = await Task.WhenAll(studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  544. Task.Run(async () =>
  545. {
  546. try
  547. {
  548. return await _libraryManager.GetStudio(c).ConfigureAwait(false);
  549. }
  550. catch (IOException ex)
  551. {
  552. _logger.ErrorException("Error getting studio {0}", ex, c);
  553. return null;
  554. }
  555. })
  556. )).ConfigureAwait(false);
  557. var dictionary = entities.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  558. for (var i = 0; i < studios.Count; i++)
  559. {
  560. var studio = studios[i];
  561. var studioDto = new StudioDto
  562. {
  563. Name = studio
  564. };
  565. Studio entity;
  566. if (dictionary.TryGetValue(studio, out entity))
  567. {
  568. var primaryImagePath = entity.PrimaryImagePath;
  569. if (!string.IsNullOrEmpty(primaryImagePath))
  570. {
  571. studioDto.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
  572. }
  573. }
  574. dto.Studios[i] = studioDto;
  575. }
  576. }
  577. /// <summary>
  578. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  579. /// </summary>
  580. /// <param name="item">The item.</param>
  581. /// <returns>BaseItem.</returns>
  582. private BaseItem GetParentBackdropItem(BaseItem item)
  583. {
  584. var parent = item.Parent;
  585. while (parent != null)
  586. {
  587. if (parent.BackdropImagePaths != null && parent.BackdropImagePaths.Count > 0)
  588. {
  589. return parent;
  590. }
  591. parent = parent.Parent;
  592. }
  593. return null;
  594. }
  595. /// <summary>
  596. /// If an item does not have a logo, this can be used to find the first parent that does have one
  597. /// </summary>
  598. /// <param name="item">The item.</param>
  599. /// <returns>BaseItem.</returns>
  600. private BaseItem GetParentLogoItem(BaseItem item)
  601. {
  602. var parent = item.Parent;
  603. while (parent != null)
  604. {
  605. if (parent.HasImage(ImageType.Logo))
  606. {
  607. return parent;
  608. }
  609. parent = parent.Parent;
  610. }
  611. return null;
  612. }
  613. /// <summary>
  614. /// Converts a UserItemData to a DTOUserItemData
  615. /// </summary>
  616. /// <param name="data">The data.</param>
  617. /// <returns>DtoUserItemData.</returns>
  618. /// <exception cref="System.ArgumentNullException"></exception>
  619. public static UserItemDataDto GetUserItemDataDto(UserItemData data)
  620. {
  621. if (data == null)
  622. {
  623. throw new ArgumentNullException();
  624. }
  625. return new UserItemDataDto
  626. {
  627. IsFavorite = data.IsFavorite,
  628. Likes = data.Likes,
  629. PlaybackPositionTicks = data.PlaybackPositionTicks,
  630. PlayCount = data.PlayCount,
  631. Rating = data.Rating,
  632. Played = data.Played,
  633. LastPlayedDate = data.LastPlayedDate
  634. };
  635. }
  636. /// <summary>
  637. /// Gets the chapter info dto.
  638. /// </summary>
  639. /// <param name="chapterInfo">The chapter info.</param>
  640. /// <param name="item">The item.</param>
  641. /// <returns>ChapterInfoDto.</returns>
  642. private ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  643. {
  644. var dto = new ChapterInfoDto
  645. {
  646. Name = chapterInfo.Name,
  647. StartPositionTicks = chapterInfo.StartPositionTicks
  648. };
  649. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  650. {
  651. dto.ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Chapter, chapterInfo.ImagePath);
  652. }
  653. return dto;
  654. }
  655. /// <summary>
  656. /// Converts a BaseItem to a BaseItemInfo
  657. /// </summary>
  658. /// <param name="item">The item.</param>
  659. /// <returns>BaseItemInfo.</returns>
  660. /// <exception cref="System.ArgumentNullException">item</exception>
  661. public static BaseItemInfo GetBaseItemInfo(BaseItem item)
  662. {
  663. if (item == null)
  664. {
  665. throw new ArgumentNullException("item");
  666. }
  667. var info = new BaseItemInfo
  668. {
  669. Id = GetClientItemId(item),
  670. Name = item.Name,
  671. Type = item.GetType().Name,
  672. IsFolder = item.IsFolder,
  673. RunTimeTicks = item.RunTimeTicks
  674. };
  675. var imagePath = item.PrimaryImagePath;
  676. if (!string.IsNullOrEmpty(imagePath))
  677. {
  678. info.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Primary, imagePath);
  679. }
  680. if (item.BackdropImagePaths != null && item.BackdropImagePaths.Count > 0)
  681. {
  682. imagePath = item.BackdropImagePaths[0];
  683. if (!string.IsNullOrEmpty(imagePath))
  684. {
  685. info.BackdropImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Backdrop, imagePath);
  686. }
  687. }
  688. return info;
  689. }
  690. /// <summary>
  691. /// Gets client-side Id of a server-side BaseItem
  692. /// </summary>
  693. /// <param name="item">The item.</param>
  694. /// <returns>System.String.</returns>
  695. /// <exception cref="System.ArgumentNullException">item</exception>
  696. public static string GetClientItemId(BaseItem item)
  697. {
  698. if (item == null)
  699. {
  700. throw new ArgumentNullException("item");
  701. }
  702. var indexFolder = item as IndexFolder;
  703. if (indexFolder != null)
  704. {
  705. return GetClientItemId(indexFolder.Parent) + IndexFolderDelimeter + (indexFolder.IndexName ?? string.Empty) + IndexFolderDelimeter + indexFolder.Id;
  706. }
  707. return item.Id.ToString();
  708. }
  709. /// <summary>
  710. /// Gets a BaseItem based upon it's client-side item id
  711. /// </summary>
  712. /// <param name="id">The id.</param>
  713. /// <param name="userManager">The user manager.</param>
  714. /// <param name="libraryManager">The library manager.</param>
  715. /// <param name="userId">The user id.</param>
  716. /// <returns>BaseItem.</returns>
  717. public static BaseItem GetItemByClientId(string id, IUserManager userManager, ILibraryManager libraryManager, Guid? userId = null)
  718. {
  719. if (string.IsNullOrEmpty(id))
  720. {
  721. throw new ArgumentNullException("id");
  722. }
  723. // If the item is an indexed folder we have to do a special routine to get it
  724. var isIndexFolder = id.IndexOf(IndexFolderDelimeter, StringComparison.OrdinalIgnoreCase) != -1;
  725. if (isIndexFolder)
  726. {
  727. if (userId.HasValue)
  728. {
  729. return GetIndexFolder(id, userId.Value, userManager, libraryManager);
  730. }
  731. }
  732. BaseItem item = null;
  733. if (userId.HasValue || !isIndexFolder)
  734. {
  735. item = libraryManager.GetItemById(new Guid(id));
  736. }
  737. // If we still don't find it, look within individual user views
  738. if (item == null && !userId.HasValue && isIndexFolder)
  739. {
  740. foreach (var user in userManager.Users)
  741. {
  742. item = GetItemByClientId(id, userManager, libraryManager, user.Id);
  743. if (item != null)
  744. {
  745. break;
  746. }
  747. }
  748. }
  749. return item;
  750. }
  751. /// <summary>
  752. /// Finds an index folder based on an Id and userId
  753. /// </summary>
  754. /// <param name="id">The id.</param>
  755. /// <param name="userId">The user id.</param>
  756. /// <param name="userManager">The user manager.</param>
  757. /// <param name="libraryManager">The library manager.</param>
  758. /// <returns>BaseItem.</returns>
  759. private static BaseItem GetIndexFolder(string id, Guid userId, IUserManager userManager, ILibraryManager libraryManager)
  760. {
  761. var user = userManager.GetUserById(userId);
  762. var stringSeparators = new[] { IndexFolderDelimeter };
  763. // Split using the delimeter
  764. var values = id.Split(stringSeparators, StringSplitOptions.None).ToList();
  765. // Get the top folder normally using the first id
  766. var folder = GetItemByClientId(values[0], userManager, libraryManager, userId) as Folder;
  767. values.RemoveAt(0);
  768. // Get indexed folders using the remaining values in the id string
  769. return GetIndexFolder(values, folder, user);
  770. }
  771. /// <summary>
  772. /// Gets indexed folders based on a list of index names and folder id's
  773. /// </summary>
  774. /// <param name="values">The values.</param>
  775. /// <param name="parentFolder">The parent folder.</param>
  776. /// <param name="user">The user.</param>
  777. /// <returns>BaseItem.</returns>
  778. private static BaseItem GetIndexFolder(List<string> values, Folder parentFolder, User user)
  779. {
  780. // The index name is first
  781. var indexBy = values[0];
  782. // The index folder id is next
  783. var indexFolderId = new Guid(values[1]);
  784. // Remove them from the lst
  785. values.RemoveRange(0, 2);
  786. // Get the IndexFolder
  787. var indexFolder = parentFolder.GetChildren(user, indexBy).FirstOrDefault(i => i.Id == indexFolderId) as Folder;
  788. // Nested index folder
  789. if (values.Count > 0)
  790. {
  791. return GetIndexFolder(values, indexFolder, user);
  792. }
  793. return indexFolder;
  794. }
  795. /// <summary>
  796. /// Gets the backdrop image tags.
  797. /// </summary>
  798. /// <param name="item">The item.</param>
  799. /// <returns>List{System.String}.</returns>
  800. private List<Guid> GetBackdropImageTags(BaseItem item)
  801. {
  802. if (item.BackdropImagePaths == null)
  803. {
  804. return new List<Guid>();
  805. }
  806. return item.BackdropImagePaths.Select(p => Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Backdrop, p)).ToList();
  807. }
  808. /// <summary>
  809. /// Gets the screenshot image tags.
  810. /// </summary>
  811. /// <param name="item">The item.</param>
  812. /// <returns>List{Guid}.</returns>
  813. private List<Guid> GetScreenshotImageTags(BaseItem item)
  814. {
  815. if (item.ScreenshotImagePaths == null)
  816. {
  817. return new List<Guid>();
  818. }
  819. return item.ScreenshotImagePaths.Select(p => Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Screenshot, p)).ToList();
  820. }
  821. }
  822. }