DtoService.cs 40 KB

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