DtoService.cs 39 KB

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