DtoService.cs 41 KB

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