DtoService.cs 41 KB

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