DtoService.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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.Artists = audio.Artists.ToArray();
  743. var albumParent = audio.FindParent<MusicAlbum>();
  744. if (albumParent != null)
  745. {
  746. dto.AlbumId = GetDtoId(albumParent);
  747. var imagePath = albumParent.PrimaryImagePath;
  748. if (!string.IsNullOrEmpty(imagePath))
  749. {
  750. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  751. }
  752. }
  753. }
  754. var album = item as MusicAlbum;
  755. if (album != null)
  756. {
  757. var songs = album.RecursiveChildren.OfType<Audio>().ToList();
  758. dto.Artists =
  759. songs.SelectMany(i => i.Artists)
  760. .Distinct(StringComparer.OrdinalIgnoreCase)
  761. .ToArray();
  762. }
  763. var hasAlbumArtist = item as IHasAlbumArtist;
  764. if (hasAlbumArtist != null)
  765. {
  766. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  767. }
  768. // Add video info
  769. var video = item as Video;
  770. if (video != null)
  771. {
  772. dto.VideoType = video.VideoType;
  773. dto.Video3DFormat = video.Video3DFormat;
  774. dto.IsoType = video.IsoType;
  775. dto.MainFeaturePlaylistName = video.MainFeaturePlaylistName;
  776. dto.PartCount = video.AdditionalPartIds.Count + 1;
  777. if (fields.Contains(ItemFields.Chapters))
  778. {
  779. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  780. }
  781. }
  782. if (fields.Contains(ItemFields.MediaStreams))
  783. {
  784. // Add VideoInfo
  785. var iHasMediaStreams = item as IHasMediaStreams;
  786. if (iHasMediaStreams != null)
  787. {
  788. dto.MediaStreams = iHasMediaStreams.MediaStreams;
  789. }
  790. }
  791. // Add MovieInfo
  792. var movie = item as Movie;
  793. if (movie != null)
  794. {
  795. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  796. if (specialFeatureCount > 0)
  797. {
  798. dto.SpecialFeatureCount = specialFeatureCount;
  799. }
  800. }
  801. // Add EpisodeInfo
  802. var episode = item as Episode;
  803. if (episode != null)
  804. {
  805. dto.IndexNumberEnd = episode.IndexNumberEnd;
  806. }
  807. // Add SeriesInfo
  808. var series = item as Series;
  809. if (series != null)
  810. {
  811. dto.AirDays = series.AirDays;
  812. dto.AirTime = series.AirTime;
  813. dto.Status = series.Status;
  814. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  815. dto.SeasonCount = series.SeasonCount;
  816. }
  817. if (episode != null)
  818. {
  819. series = item.FindParent<Series>();
  820. dto.SeriesId = GetDtoId(series);
  821. dto.SeriesName = series.Name;
  822. }
  823. // Add SeasonInfo
  824. var season = item as Season;
  825. if (season != null)
  826. {
  827. series = item.FindParent<Series>();
  828. dto.SeriesId = GetDtoId(series);
  829. dto.SeriesName = series.Name;
  830. }
  831. var game = item as Game;
  832. if (game != null)
  833. {
  834. SetGameProperties(dto, game);
  835. }
  836. var musicVideo = item as MusicVideo;
  837. if (musicVideo != null)
  838. {
  839. SetMusicVideoProperties(dto, musicVideo);
  840. }
  841. var book = item as Book;
  842. if (book != null)
  843. {
  844. SetBookProperties(dto, book);
  845. }
  846. }
  847. /// <summary>
  848. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  849. /// </summary>
  850. /// <param name="folder">The folder.</param>
  851. /// <param name="user">The user.</param>
  852. /// <param name="dto">The dto.</param>
  853. /// <returns>Task.</returns>
  854. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto)
  855. {
  856. var rcentlyAddedItemCount = 0;
  857. var recursiveItemCount = 0;
  858. var unplayed = 0;
  859. long runtime = 0;
  860. double totalPercentPlayed = 0;
  861. // Loop through each recursive child
  862. foreach (var child in folder.GetRecursiveChildren(user, true).Where(i => !i.IsFolder).ToList())
  863. {
  864. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  865. recursiveItemCount++;
  866. // Check is recently added
  867. if (child.IsRecentlyAdded())
  868. {
  869. rcentlyAddedItemCount++;
  870. }
  871. var isUnplayed = true;
  872. // Incrememt totalPercentPlayed
  873. if (userdata != null)
  874. {
  875. if (userdata.Played)
  876. {
  877. totalPercentPlayed += 100;
  878. isUnplayed = false;
  879. }
  880. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  881. {
  882. double itemPercent = userdata.PlaybackPositionTicks;
  883. itemPercent /= child.RunTimeTicks.Value;
  884. totalPercentPlayed += itemPercent;
  885. }
  886. }
  887. if (isUnplayed)
  888. {
  889. unplayed++;
  890. }
  891. runtime += child.RunTimeTicks ?? 0;
  892. }
  893. dto.RecursiveItemCount = recursiveItemCount;
  894. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  895. dto.RecursiveUnplayedItemCount = unplayed;
  896. if (recursiveItemCount > 0)
  897. {
  898. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  899. }
  900. if (runtime > 0)
  901. {
  902. dto.CumulativeRunTimeTicks = runtime;
  903. }
  904. }
  905. /// <summary>
  906. /// Attaches the primary image aspect ratio.
  907. /// </summary>
  908. /// <param name="dto">The dto.</param>
  909. /// <param name="item">The item.</param>
  910. /// <param name="logger">The _logger.</param>
  911. /// <returns>Task.</returns>
  912. private async Task AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  913. {
  914. var path = item.PrimaryImagePath;
  915. if (string.IsNullOrEmpty(path))
  916. {
  917. return;
  918. }
  919. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(path);
  920. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  921. var dateModified = metaFileEntry == null ? File.GetLastWriteTimeUtc(path) : metaFileEntry.LastWriteTimeUtc;
  922. ImageSize size;
  923. try
  924. {
  925. size = await Kernel.Instance.ImageManager.GetImageSize(path, dateModified).ConfigureAwait(false);
  926. }
  927. catch (FileNotFoundException)
  928. {
  929. _logger.Error("Image file does not exist: {0}", path);
  930. return;
  931. }
  932. catch (Exception ex)
  933. {
  934. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  935. return;
  936. }
  937. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  938. var supportedEnhancers = Kernel.Instance.ImageManager.ImageEnhancers.Where(i =>
  939. {
  940. try
  941. {
  942. return i.Supports(item, ImageType.Primary);
  943. }
  944. catch (Exception ex)
  945. {
  946. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  947. return false;
  948. }
  949. }).ToList();
  950. foreach (var enhancer in supportedEnhancers)
  951. {
  952. try
  953. {
  954. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  955. }
  956. catch (Exception ex)
  957. {
  958. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  959. }
  960. }
  961. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  962. }
  963. }
  964. }