DtoService.cs 40 KB

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