DtoService.cs 38 KB

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