DtoService.cs 39 KB

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