2
0

DtoService.cs 43 KB

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