DtoBuilder.cs 34 KB

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