DtoService.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. dto.SoundtrackIds = item.SoundtrackIds
  93. .Select(i => i.ToString("N"))
  94. .ToArray();
  95. }
  96. var itemByName = item as IItemByName;
  97. if (itemByName != null)
  98. {
  99. AttachItemByNameCounts(dto, itemByName, user);
  100. }
  101. return dto;
  102. }
  103. /// <summary>
  104. /// Attaches the item by name counts.
  105. /// </summary>
  106. /// <param name="dto">The dto.</param>
  107. /// <param name="item">The item.</param>
  108. /// <param name="user">The user.</param>
  109. private void AttachItemByNameCounts(BaseItemDto dto, IItemByName item, User user)
  110. {
  111. ItemByNameCounts counts;
  112. if (user == null)
  113. {
  114. //counts = item.ItemCounts;
  115. return;
  116. }
  117. else
  118. {
  119. if (!item.UserItemCounts.TryGetValue(user.Id, out counts))
  120. {
  121. counts = new ItemByNameCounts();
  122. }
  123. }
  124. dto.ChildCount = counts.TotalCount;
  125. dto.AdultVideoCount = counts.AdultVideoCount;
  126. dto.AlbumCount = counts.AlbumCount;
  127. dto.EpisodeCount = counts.EpisodeCount;
  128. dto.GameCount = counts.GameCount;
  129. dto.MovieCount = counts.MovieCount;
  130. dto.MusicVideoCount = counts.MusicVideoCount;
  131. dto.SeriesCount = counts.SeriesCount;
  132. dto.SongCount = counts.SongCount;
  133. dto.TrailerCount = counts.TrailerCount;
  134. }
  135. /// <summary>
  136. /// Attaches the user specific info.
  137. /// </summary>
  138. /// <param name="dto">The dto.</param>
  139. /// <param name="item">The item.</param>
  140. /// <param name="user">The user.</param>
  141. /// <param name="fields">The fields.</param>
  142. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  143. {
  144. if (item.IsFolder)
  145. {
  146. var folder = (Folder)item;
  147. dto.ChildCount = folder.GetChildren(user, true)
  148. .Count();
  149. if (!(folder is UserRootFolder))
  150. {
  151. SetSpecialCounts(folder, user, dto, fields);
  152. }
  153. }
  154. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  155. dto.UserData = GetUserItemDataDto(userData);
  156. if (item.IsFolder)
  157. {
  158. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  159. }
  160. }
  161. public UserDto GetUserDto(User user)
  162. {
  163. if (user == null)
  164. {
  165. throw new ArgumentNullException("user");
  166. }
  167. var dto = new UserDto
  168. {
  169. Id = user.Id.ToString("N"),
  170. Name = user.Name,
  171. HasPassword = !String.IsNullOrEmpty(user.Password),
  172. LastActivityDate = user.LastActivityDate,
  173. LastLoginDate = user.LastLoginDate,
  174. Configuration = user.Configuration
  175. };
  176. var image = user.PrimaryImagePath;
  177. if (!string.IsNullOrEmpty(image))
  178. {
  179. dto.PrimaryImageTag = _imageProcessor.GetImageCacheTag(user, ImageType.Primary, image);
  180. try
  181. {
  182. AttachPrimaryImageAspectRatio(dto, user);
  183. }
  184. catch (Exception ex)
  185. {
  186. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  187. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  188. }
  189. }
  190. return dto;
  191. }
  192. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  193. {
  194. var dto = new SessionInfoDto
  195. {
  196. Client = session.Client,
  197. DeviceId = session.DeviceId,
  198. DeviceName = session.DeviceName,
  199. Id = session.Id.ToString("N"),
  200. LastActivityDate = session.LastActivityDate,
  201. NowPlayingPositionTicks = session.NowPlayingPositionTicks,
  202. SupportsRemoteControl = session.SupportsRemoteControl,
  203. IsPaused = session.IsPaused,
  204. IsMuted = session.IsMuted,
  205. NowViewingContext = session.NowViewingContext,
  206. NowViewingItemId = session.NowViewingItemId,
  207. NowViewingItemName = session.NowViewingItemName,
  208. NowViewingItemType = session.NowViewingItemType,
  209. ApplicationVersion = session.ApplicationVersion,
  210. CanSeek = session.CanSeek,
  211. QueueableMediaTypes = session.QueueableMediaTypes
  212. };
  213. if (session.NowPlayingItem != null)
  214. {
  215. dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
  216. }
  217. if (session.User != null)
  218. {
  219. dto.UserId = session.User.Id.ToString("N");
  220. dto.UserName = session.User.Name;
  221. }
  222. return dto;
  223. }
  224. /// <summary>
  225. /// Converts a BaseItem to a BaseItemInfo
  226. /// </summary>
  227. /// <param name="item">The item.</param>
  228. /// <returns>BaseItemInfo.</returns>
  229. /// <exception cref="System.ArgumentNullException">item</exception>
  230. public BaseItemInfo GetBaseItemInfo(BaseItem item)
  231. {
  232. if (item == null)
  233. {
  234. throw new ArgumentNullException("item");
  235. }
  236. var info = new BaseItemInfo
  237. {
  238. Id = GetDtoId(item),
  239. Name = item.Name,
  240. MediaType = item.MediaType,
  241. Type = item.GetType().Name,
  242. RunTimeTicks = item.RunTimeTicks
  243. };
  244. var imagePath = item.PrimaryImagePath;
  245. if (!string.IsNullOrEmpty(imagePath))
  246. {
  247. try
  248. {
  249. info.PrimaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary, imagePath);
  250. }
  251. catch (IOException)
  252. {
  253. }
  254. }
  255. return info;
  256. }
  257. const string IndexFolderDelimeter = "-index-";
  258. /// <summary>
  259. /// Gets client-side Id of a server-side BaseItem
  260. /// </summary>
  261. /// <param name="item">The item.</param>
  262. /// <returns>System.String.</returns>
  263. /// <exception cref="System.ArgumentNullException">item</exception>
  264. public string GetDtoId(BaseItem item)
  265. {
  266. if (item == null)
  267. {
  268. throw new ArgumentNullException("item");
  269. }
  270. var indexFolder = item as IndexFolder;
  271. if (indexFolder != null)
  272. {
  273. return GetDtoId(indexFolder.Parent) + IndexFolderDelimeter + (indexFolder.IndexName ?? string.Empty) + IndexFolderDelimeter + indexFolder.Id;
  274. }
  275. return item.Id.ToString("N");
  276. }
  277. /// <summary>
  278. /// Converts a UserItemData to a DTOUserItemData
  279. /// </summary>
  280. /// <param name="data">The data.</param>
  281. /// <returns>DtoUserItemData.</returns>
  282. /// <exception cref="System.ArgumentNullException"></exception>
  283. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  284. {
  285. if (data == null)
  286. {
  287. throw new ArgumentNullException("data");
  288. }
  289. return new UserItemDataDto
  290. {
  291. IsFavorite = data.IsFavorite,
  292. Likes = data.Likes,
  293. PlaybackPositionTicks = data.PlaybackPositionTicks,
  294. PlayCount = data.PlayCount,
  295. Rating = data.Rating,
  296. Played = data.Played,
  297. LastPlayedDate = data.LastPlayedDate,
  298. Key = data.Key
  299. };
  300. }
  301. private void SetBookProperties(BaseItemDto dto, Book item)
  302. {
  303. dto.SeriesName = item.SeriesName;
  304. }
  305. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  306. {
  307. if (!string.IsNullOrEmpty(item.Album))
  308. {
  309. var parentAlbum = _libraryManager.RootFolder
  310. .GetRecursiveChildren(i => i is MusicAlbum)
  311. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  312. if (parentAlbum != null)
  313. {
  314. dto.AlbumId = GetDtoId(parentAlbum);
  315. }
  316. }
  317. dto.Album = item.Album;
  318. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  319. }
  320. private void SetGameProperties(BaseItemDto dto, Game item)
  321. {
  322. dto.Players = item.PlayersSupported;
  323. dto.GameSystem = item.GameSystem;
  324. }
  325. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  326. {
  327. dto.GameSystem = item.GameSystemName;
  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 _imageProcessor.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. if (fields.Contains(ItemFields.ScreenshotImageTags))
  647. {
  648. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  649. }
  650. if (fields.Contains(ItemFields.Genres))
  651. {
  652. dto.Genres = item.Genres;
  653. }
  654. dto.ImageTags = new Dictionary<ImageType, Guid>();
  655. foreach (var image in item.Images)
  656. {
  657. var type = image.Key;
  658. var tag = GetImageCacheTag(item, type, image.Value);
  659. if (tag.HasValue)
  660. {
  661. dto.ImageTags[type] = tag.Value;
  662. }
  663. }
  664. dto.Id = GetDtoId(item);
  665. dto.IndexNumber = item.IndexNumber;
  666. dto.IsFolder = item.IsFolder;
  667. dto.Language = item.Language;
  668. dto.MediaType = item.MediaType;
  669. dto.LocationType = item.LocationType;
  670. var hasCriticRating = item as IHasCriticRating;
  671. if (hasCriticRating != null)
  672. {
  673. dto.CriticRating = hasCriticRating.CriticRating;
  674. if (fields.Contains(ItemFields.CriticRatingSummary))
  675. {
  676. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  677. }
  678. }
  679. var localTrailerCount = item.LocalTrailerIds.Count;
  680. if (localTrailerCount > 0)
  681. {
  682. dto.LocalTrailerCount = localTrailerCount;
  683. }
  684. dto.Name = item.Name;
  685. dto.OfficialRating = item.OfficialRating;
  686. var hasOverview = fields.Contains(ItemFields.Overview);
  687. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  688. if (hasOverview || hasHtmlOverview)
  689. {
  690. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  691. if (hasOverview)
  692. {
  693. dto.Overview = strippedOverview;
  694. }
  695. // Only supply the html version if there was actually html content
  696. if (hasHtmlOverview)
  697. {
  698. dto.OverviewHtml = item.Overview;
  699. }
  700. }
  701. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  702. if (dto.BackdropImageTags.Count == 0)
  703. {
  704. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  705. if (parentWithBackdrop != null)
  706. {
  707. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  708. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  709. }
  710. }
  711. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  712. {
  713. dto.ParentId = GetDtoId(item.Parent);
  714. }
  715. dto.ParentIndexNumber = item.ParentIndexNumber;
  716. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  717. if (!dto.HasLogo)
  718. {
  719. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  720. if (parentWithLogo != null)
  721. {
  722. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  723. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImage(ImageType.Logo));
  724. }
  725. }
  726. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  727. if (!dto.HasArtImage)
  728. {
  729. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  730. if (parentWithImage != null)
  731. {
  732. dto.ParentArtItemId = GetDtoId(parentWithImage);
  733. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImage(ImageType.Art));
  734. }
  735. }
  736. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  737. if (!dto.HasThumb)
  738. {
  739. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  740. if (parentWithImage != null)
  741. {
  742. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  743. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb, parentWithImage.GetImage(ImageType.Thumb));
  744. }
  745. }
  746. if (fields.Contains(ItemFields.Path))
  747. {
  748. dto.Path = item.Path;
  749. }
  750. dto.PremiereDate = item.PremiereDate;
  751. dto.ProductionYear = item.ProductionYear;
  752. if (fields.Contains(ItemFields.ProviderIds))
  753. {
  754. dto.ProviderIds = item.ProviderIds;
  755. }
  756. dto.RunTimeTicks = item.RunTimeTicks;
  757. if (fields.Contains(ItemFields.SortName))
  758. {
  759. dto.SortName = item.SortName;
  760. }
  761. if (fields.Contains(ItemFields.CustomRating))
  762. {
  763. dto.CustomRating = item.CustomRating;
  764. }
  765. if (fields.Contains(ItemFields.Taglines))
  766. {
  767. dto.Taglines = item.Taglines;
  768. }
  769. if (fields.Contains(ItemFields.RemoteTrailers))
  770. {
  771. dto.RemoteTrailers = item.RemoteTrailers;
  772. }
  773. dto.Type = item.GetType().Name;
  774. dto.CommunityRating = item.CommunityRating;
  775. dto.VoteCount = item.VoteCount;
  776. if (item.IsFolder)
  777. {
  778. var folder = (Folder)item;
  779. if (fields.Contains(ItemFields.IndexOptions))
  780. {
  781. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  782. }
  783. }
  784. // Add audio info
  785. var audio = item as Audio;
  786. if (audio != null)
  787. {
  788. dto.Album = audio.Album;
  789. dto.Artists = audio.Artists;
  790. var albumParent = audio.FindParent<MusicAlbum>();
  791. if (albumParent != null)
  792. {
  793. dto.AlbumId = GetDtoId(albumParent);
  794. var imagePath = albumParent.PrimaryImagePath;
  795. if (!string.IsNullOrEmpty(imagePath))
  796. {
  797. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  798. }
  799. }
  800. }
  801. var album = item as MusicAlbum;
  802. if (album != null)
  803. {
  804. dto.Artists = album.Artists;
  805. }
  806. var hasAlbumArtist = item as IHasAlbumArtist;
  807. if (hasAlbumArtist != null)
  808. {
  809. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  810. }
  811. // Add video info
  812. var video = item as Video;
  813. if (video != null)
  814. {
  815. dto.VideoType = video.VideoType;
  816. dto.Video3DFormat = video.Video3DFormat;
  817. dto.IsoType = video.IsoType;
  818. dto.IsHD = video.IsHD;
  819. dto.PartCount = video.AdditionalPartIds.Count + 1;
  820. if (fields.Contains(ItemFields.Chapters))
  821. {
  822. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  823. }
  824. }
  825. if (fields.Contains(ItemFields.MediaStreams))
  826. {
  827. // Add VideoInfo
  828. var iHasMediaStreams = item as IHasMediaStreams;
  829. if (iHasMediaStreams != null)
  830. {
  831. dto.MediaStreams = iHasMediaStreams.MediaStreams;
  832. }
  833. }
  834. // Add MovieInfo
  835. var movie = item as Movie;
  836. if (movie != null)
  837. {
  838. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  839. if (specialFeatureCount > 0)
  840. {
  841. dto.SpecialFeatureCount = specialFeatureCount;
  842. }
  843. }
  844. // Add EpisodeInfo
  845. var episode = item as Episode;
  846. if (episode != null)
  847. {
  848. dto.IndexNumberEnd = episode.IndexNumberEnd;
  849. }
  850. // Add SeriesInfo
  851. var series = item as Series;
  852. if (series != null)
  853. {
  854. dto.AirDays = series.AirDays;
  855. dto.AirTime = series.AirTime;
  856. dto.Status = series.Status;
  857. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  858. dto.SeasonCount = series.SeasonCount;
  859. }
  860. if (episode != null)
  861. {
  862. series = item.FindParent<Series>();
  863. dto.SeriesId = GetDtoId(series);
  864. dto.SeriesName = series.Name;
  865. dto.AirTime = series.AirTime;
  866. dto.SeriesStudio = series.Studios.FirstOrDefault();
  867. if (series.HasImage(ImageType.Thumb))
  868. {
  869. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb, series.GetImage(ImageType.Thumb));
  870. }
  871. var imagePath = series.PrimaryImagePath;
  872. if (!string.IsNullOrEmpty(imagePath))
  873. {
  874. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  875. }
  876. }
  877. // Add SeasonInfo
  878. var season = item as Season;
  879. if (season != null)
  880. {
  881. series = item.FindParent<Series>();
  882. dto.SeriesId = GetDtoId(series);
  883. dto.SeriesName = series.Name;
  884. dto.AirTime = series.AirTime;
  885. dto.SeriesStudio = series.Studios.FirstOrDefault();
  886. var imagePath = series.PrimaryImagePath;
  887. if (!string.IsNullOrEmpty(imagePath))
  888. {
  889. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  890. }
  891. }
  892. var game = item as Game;
  893. if (game != null)
  894. {
  895. SetGameProperties(dto, game);
  896. }
  897. var gameSystem = item as GameSystem;
  898. if (gameSystem != null)
  899. {
  900. SetGameSystemProperties(dto, gameSystem);
  901. }
  902. var musicVideo = item as MusicVideo;
  903. if (musicVideo != null)
  904. {
  905. SetMusicVideoProperties(dto, musicVideo);
  906. }
  907. var book = item as Book;
  908. if (book != null)
  909. {
  910. SetBookProperties(dto, book);
  911. }
  912. }
  913. /// <summary>
  914. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  915. /// </summary>
  916. /// <param name="folder">The folder.</param>
  917. /// <param name="user">The user.</param>
  918. /// <param name="dto">The dto.</param>
  919. /// <param name="fields">The fields.</param>
  920. /// <returns>Task.</returns>
  921. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  922. {
  923. var rcentlyAddedItemCount = 0;
  924. var recursiveItemCount = 0;
  925. var unplayed = 0;
  926. long runtime = 0;
  927. double totalPercentPlayed = 0;
  928. // Loop through each recursive child
  929. foreach (var child in folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual))
  930. {
  931. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  932. recursiveItemCount++;
  933. // Check is recently added
  934. if (child.IsRecentlyAdded())
  935. {
  936. rcentlyAddedItemCount++;
  937. }
  938. var isUnplayed = true;
  939. // Incrememt totalPercentPlayed
  940. if (userdata != null)
  941. {
  942. if (userdata.Played)
  943. {
  944. totalPercentPlayed += 100;
  945. isUnplayed = false;
  946. }
  947. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  948. {
  949. double itemPercent = userdata.PlaybackPositionTicks;
  950. itemPercent /= child.RunTimeTicks.Value;
  951. totalPercentPlayed += itemPercent;
  952. }
  953. }
  954. if (isUnplayed)
  955. {
  956. unplayed++;
  957. }
  958. runtime += child.RunTimeTicks ?? 0;
  959. }
  960. dto.RecursiveItemCount = recursiveItemCount;
  961. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  962. dto.RecursiveUnplayedItemCount = unplayed;
  963. if (recursiveItemCount > 0)
  964. {
  965. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  966. }
  967. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  968. {
  969. dto.CumulativeRunTimeTicks = runtime;
  970. }
  971. }
  972. /// <summary>
  973. /// Attaches the primary image aspect ratio.
  974. /// </summary>
  975. /// <param name="dto">The dto.</param>
  976. /// <param name="item">The item.</param>
  977. /// <returns>Task.</returns>
  978. private void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  979. {
  980. var path = item.PrimaryImagePath;
  981. if (string.IsNullOrEmpty(path))
  982. {
  983. return;
  984. }
  985. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  986. var dateModified = item.GetImageDateModified(path);
  987. ImageSize size;
  988. try
  989. {
  990. size = _imageProcessor.GetImageSize(path, dateModified);
  991. }
  992. catch (FileNotFoundException)
  993. {
  994. _logger.Error("Image file does not exist: {0}", path);
  995. return;
  996. }
  997. catch (Exception ex)
  998. {
  999. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1000. return;
  1001. }
  1002. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1003. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1004. foreach (var enhancer in supportedEnhancers)
  1005. {
  1006. try
  1007. {
  1008. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1009. }
  1010. catch (Exception ex)
  1011. {
  1012. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1013. }
  1014. }
  1015. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1016. }
  1017. }
  1018. }