DtoBuilder.cs 31 KB

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