DtoBuilder.cs 34 KB

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