DtoService.cs 38 KB

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