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