DtoService.cs 42 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. return;
  118. }
  119. var counts = item.GetItemByNameCounts(user.Id) ?? new ItemByNameCounts();
  120. dto.ChildCount = counts.TotalCount;
  121. dto.AdultVideoCount = counts.AdultVideoCount;
  122. dto.AlbumCount = counts.AlbumCount;
  123. dto.EpisodeCount = counts.EpisodeCount;
  124. dto.GameCount = counts.GameCount;
  125. dto.MovieCount = counts.MovieCount;
  126. dto.MusicVideoCount = counts.MusicVideoCount;
  127. dto.SeriesCount = counts.SeriesCount;
  128. dto.SongCount = counts.SongCount;
  129. dto.TrailerCount = counts.TrailerCount;
  130. }
  131. /// <summary>
  132. /// Attaches the user specific info.
  133. /// </summary>
  134. /// <param name="dto">The dto.</param>
  135. /// <param name="item">The item.</param>
  136. /// <param name="user">The user.</param>
  137. /// <param name="fields">The fields.</param>
  138. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  139. {
  140. if (item.IsFolder)
  141. {
  142. var folder = (Folder)item;
  143. dto.ChildCount = GetChildCount(folder, user);
  144. if (!(folder is UserRootFolder))
  145. {
  146. SetSpecialCounts(folder, user, dto, fields);
  147. }
  148. }
  149. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  150. dto.UserData = GetUserItemDataDto(userData);
  151. if (item.IsFolder)
  152. {
  153. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  154. }
  155. }
  156. private int GetChildCount(Folder folder, User user)
  157. {
  158. return folder.GetChildren(user, true)
  159. .Count();
  160. }
  161. public UserDto GetUserDto(User user)
  162. {
  163. if (user == null)
  164. {
  165. throw new ArgumentNullException("user");
  166. }
  167. var dto = new UserDto
  168. {
  169. Id = user.Id.ToString("N"),
  170. Name = user.Name,
  171. HasPassword = !String.IsNullOrEmpty(user.Password),
  172. LastActivityDate = user.LastActivityDate,
  173. LastLoginDate = user.LastLoginDate,
  174. Configuration = user.Configuration
  175. };
  176. var image = user.PrimaryImagePath;
  177. if (!string.IsNullOrEmpty(image))
  178. {
  179. dto.PrimaryImageTag = GetImageCacheTag(user, ImageType.Primary, image);
  180. try
  181. {
  182. AttachPrimaryImageAspectRatio(dto, user);
  183. }
  184. catch (Exception ex)
  185. {
  186. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  187. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  188. }
  189. }
  190. return dto;
  191. }
  192. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  193. {
  194. var dto = new SessionInfoDto
  195. {
  196. Client = session.Client,
  197. DeviceId = session.DeviceId,
  198. DeviceName = session.DeviceName,
  199. Id = session.Id.ToString("N"),
  200. LastActivityDate = session.LastActivityDate,
  201. NowPlayingPositionTicks = session.NowPlayingPositionTicks,
  202. SupportsRemoteControl = session.SupportsRemoteControl,
  203. IsPaused = session.IsPaused,
  204. IsMuted = session.IsMuted,
  205. NowViewingContext = session.NowViewingContext,
  206. NowViewingItemId = session.NowViewingItemId,
  207. NowViewingItemName = session.NowViewingItemName,
  208. NowViewingItemType = session.NowViewingItemType,
  209. ApplicationVersion = session.ApplicationVersion,
  210. CanSeek = session.CanSeek,
  211. QueueableMediaTypes = session.QueueableMediaTypes,
  212. PlayableMediaTypes = session.PlayableMediaTypes,
  213. RemoteEndPoint = session.RemoteEndPoint,
  214. AdditionalUsers = session.AdditionalUsers
  215. };
  216. if (session.NowPlayingItem != null)
  217. {
  218. dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
  219. }
  220. if (session.UserId.HasValue)
  221. {
  222. dto.UserId = session.UserId.Value.ToString("N");
  223. }
  224. dto.UserName = session.UserName;
  225. return dto;
  226. }
  227. /// <summary>
  228. /// Converts a BaseItem to a BaseItemInfo
  229. /// </summary>
  230. /// <param name="item">The item.</param>
  231. /// <returns>BaseItemInfo.</returns>
  232. /// <exception cref="System.ArgumentNullException">item</exception>
  233. public BaseItemInfo GetBaseItemInfo(BaseItem item)
  234. {
  235. if (item == null)
  236. {
  237. throw new ArgumentNullException("item");
  238. }
  239. var info = new BaseItemInfo
  240. {
  241. Id = GetDtoId(item),
  242. Name = item.Name,
  243. MediaType = item.MediaType,
  244. Type = item.GetClientTypeName(),
  245. RunTimeTicks = item.RunTimeTicks
  246. };
  247. var imagePath = item.PrimaryImagePath;
  248. if (!string.IsNullOrEmpty(imagePath))
  249. {
  250. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary, imagePath);
  251. }
  252. return info;
  253. }
  254. /// <summary>
  255. /// Gets client-side Id of a server-side BaseItem
  256. /// </summary>
  257. /// <param name="item">The item.</param>
  258. /// <returns>System.String.</returns>
  259. /// <exception cref="System.ArgumentNullException">item</exception>
  260. public string GetDtoId(BaseItem item)
  261. {
  262. if (item == null)
  263. {
  264. throw new ArgumentNullException("item");
  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. BaseItem item = null;
  527. if (userId.HasValue)
  528. {
  529. item = _libraryManager.GetItemById(new Guid(id));
  530. }
  531. // If we still don't find it, look within individual user views
  532. if (item == null && !userId.HasValue)
  533. {
  534. foreach (var user in _userManager.Users)
  535. {
  536. item = GetItemByDtoId(id, user.Id);
  537. if (item != null)
  538. {
  539. break;
  540. }
  541. }
  542. }
  543. return item;
  544. }
  545. /// <summary>
  546. /// Sets simple property values on a DTOBaseItem
  547. /// </summary>
  548. /// <param name="dto">The dto.</param>
  549. /// <param name="item">The item.</param>
  550. /// <param name="owner">The owner.</param>
  551. /// <param name="fields">The fields.</param>
  552. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  553. {
  554. if (fields.Contains(ItemFields.DateCreated))
  555. {
  556. dto.DateCreated = item.DateCreated;
  557. }
  558. if (fields.Contains(ItemFields.OriginalRunTimeTicks))
  559. {
  560. dto.OriginalRunTimeTicks = item.OriginalRunTimeTicks;
  561. }
  562. dto.DisplayMediaType = item.DisplayMediaType;
  563. if (fields.Contains(ItemFields.Settings))
  564. {
  565. dto.LockedFields = item.LockedFields;
  566. dto.EnableInternetProviders = !item.DontFetchMeta;
  567. }
  568. var hasBudget = item as IHasBudget;
  569. if (hasBudget != null)
  570. {
  571. if (fields.Contains(ItemFields.Budget))
  572. {
  573. dto.Budget = hasBudget.Budget;
  574. }
  575. if (fields.Contains(ItemFields.Revenue))
  576. {
  577. dto.Revenue = hasBudget.Revenue;
  578. }
  579. }
  580. dto.EndDate = item.EndDate;
  581. if (fields.Contains(ItemFields.HomePageUrl))
  582. {
  583. dto.HomePageUrl = item.HomePageUrl;
  584. }
  585. if (fields.Contains(ItemFields.Tags))
  586. {
  587. var hasTags = item as IHasTags;
  588. if (hasTags != null)
  589. {
  590. dto.Tags = hasTags.Tags;
  591. }
  592. if (dto.Tags == null)
  593. {
  594. dto.Tags = new List<string>();
  595. }
  596. }
  597. if (fields.Contains(ItemFields.Keywords))
  598. {
  599. var hasTags = item as IHasKeywords;
  600. if (hasTags != null)
  601. {
  602. dto.Keywords = hasTags.Keywords;
  603. }
  604. if (dto.Keywords == null)
  605. {
  606. dto.Keywords = new List<string>();
  607. }
  608. }
  609. if (fields.Contains(ItemFields.ProductionLocations))
  610. {
  611. SetProductionLocations(item, dto);
  612. }
  613. var hasAspectRatio = item as IHasAspectRatio;
  614. if (hasAspectRatio != null)
  615. {
  616. dto.AspectRatio = hasAspectRatio.AspectRatio;
  617. }
  618. var hasMetascore = item as IHasMetascore;
  619. if (hasMetascore != null)
  620. {
  621. dto.Metascore = hasMetascore.Metascore;
  622. }
  623. if (fields.Contains(ItemFields.AwardSummary))
  624. {
  625. var hasAwards = item as IHasAwards;
  626. if (hasAwards != null)
  627. {
  628. dto.AwardSummary = hasAwards.AwardSummary;
  629. }
  630. }
  631. dto.BackdropImageTags = GetBackdropImageTags(item);
  632. if (fields.Contains(ItemFields.ScreenshotImageTags))
  633. {
  634. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  635. }
  636. if (fields.Contains(ItemFields.Genres))
  637. {
  638. dto.Genres = item.Genres;
  639. }
  640. dto.ImageTags = new Dictionary<ImageType, Guid>();
  641. foreach (var image in item.Images)
  642. {
  643. var type = image.Key;
  644. var tag = GetImageCacheTag(item, type, image.Value);
  645. if (tag.HasValue)
  646. {
  647. dto.ImageTags[type] = tag.Value;
  648. }
  649. }
  650. dto.Id = GetDtoId(item);
  651. dto.IndexNumber = item.IndexNumber;
  652. dto.IsFolder = item.IsFolder;
  653. dto.MediaType = item.MediaType;
  654. dto.LocationType = item.LocationType;
  655. var hasLang = item as IHasPreferredMetadataLanguage;
  656. if (hasLang != null)
  657. {
  658. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  659. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  660. }
  661. var hasCriticRating = item as IHasCriticRating;
  662. if (hasCriticRating != null)
  663. {
  664. dto.CriticRating = hasCriticRating.CriticRating;
  665. if (fields.Contains(ItemFields.CriticRatingSummary))
  666. {
  667. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  668. }
  669. }
  670. var hasTrailers = item as IHasTrailers;
  671. if (hasTrailers != null)
  672. {
  673. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  674. }
  675. var hasDisplayOrder = item as IHasDisplayOrder;
  676. if (hasDisplayOrder != null)
  677. {
  678. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  679. }
  680. var collectionFolder = item as CollectionFolder;
  681. if (collectionFolder != null)
  682. {
  683. dto.CollectionType = collectionFolder.CollectionType;
  684. }
  685. if (fields.Contains(ItemFields.RemoteTrailers))
  686. {
  687. dto.RemoteTrailers = hasTrailers != null ?
  688. hasTrailers.RemoteTrailers :
  689. new List<MediaUrl>();
  690. }
  691. dto.Name = item.Name;
  692. dto.OfficialRating = item.OfficialRating;
  693. var hasOverview = fields.Contains(ItemFields.Overview);
  694. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  695. if (hasOverview || hasHtmlOverview)
  696. {
  697. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  698. if (hasOverview)
  699. {
  700. dto.Overview = strippedOverview;
  701. }
  702. // Only supply the html version if there was actually html content
  703. if (hasHtmlOverview)
  704. {
  705. dto.OverviewHtml = item.Overview;
  706. }
  707. }
  708. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  709. if (dto.BackdropImageTags.Count == 0)
  710. {
  711. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  712. if (parentWithBackdrop != null)
  713. {
  714. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  715. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  716. }
  717. }
  718. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  719. {
  720. dto.ParentId = GetDtoId(item.Parent);
  721. }
  722. dto.ParentIndexNumber = item.ParentIndexNumber;
  723. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  724. if (!dto.HasLogo)
  725. {
  726. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  727. if (parentWithLogo != null)
  728. {
  729. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  730. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImagePath(ImageType.Logo));
  731. }
  732. }
  733. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  734. if (!dto.HasArtImage)
  735. {
  736. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  737. if (parentWithImage != null)
  738. {
  739. dto.ParentArtItemId = GetDtoId(parentWithImage);
  740. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImagePath(ImageType.Art));
  741. }
  742. }
  743. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  744. if (!dto.HasThumb)
  745. {
  746. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  747. if (parentWithImage != null)
  748. {
  749. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  750. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb, parentWithImage.GetImagePath(ImageType.Thumb));
  751. }
  752. }
  753. if (fields.Contains(ItemFields.Path))
  754. {
  755. dto.Path = item.Path;
  756. }
  757. dto.PremiereDate = item.PremiereDate;
  758. dto.ProductionYear = item.ProductionYear;
  759. if (fields.Contains(ItemFields.ProviderIds))
  760. {
  761. dto.ProviderIds = item.ProviderIds;
  762. }
  763. dto.RunTimeTicks = item.RunTimeTicks;
  764. if (fields.Contains(ItemFields.SortName))
  765. {
  766. dto.SortName = item.SortName;
  767. }
  768. if (fields.Contains(ItemFields.CustomRating))
  769. {
  770. dto.CustomRating = item.CustomRating;
  771. }
  772. if (fields.Contains(ItemFields.Taglines))
  773. {
  774. var hasTagline = item as IHasTaglines;
  775. if (hasTagline != null)
  776. {
  777. dto.Taglines = hasTagline.Taglines;
  778. }
  779. if (dto.Taglines == null)
  780. {
  781. dto.Taglines = new List<string>();
  782. }
  783. }
  784. dto.Type = item.GetClientTypeName();
  785. dto.CommunityRating = item.CommunityRating;
  786. dto.VoteCount = item.VoteCount;
  787. if (item.IsFolder)
  788. {
  789. var folder = (Folder)item;
  790. if (fields.Contains(ItemFields.IndexOptions))
  791. {
  792. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  793. }
  794. }
  795. // Add audio info
  796. var audio = item as Audio;
  797. if (audio != null)
  798. {
  799. dto.Album = audio.Album;
  800. dto.Artists = audio.Artists;
  801. var albumParent = audio.FindParent<MusicAlbum>();
  802. if (albumParent != null)
  803. {
  804. dto.AlbumId = GetDtoId(albumParent);
  805. var imagePath = albumParent.PrimaryImagePath;
  806. if (!string.IsNullOrEmpty(imagePath))
  807. {
  808. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  809. }
  810. }
  811. }
  812. var album = item as MusicAlbum;
  813. if (album != null)
  814. {
  815. dto.Artists = album.Artists;
  816. dto.SoundtrackIds = album.SoundtrackIds
  817. .Select(i => i.ToString("N"))
  818. .ToArray();
  819. }
  820. var hasAlbumArtist = item as IHasAlbumArtist;
  821. if (hasAlbumArtist != null)
  822. {
  823. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  824. }
  825. // Add video info
  826. var video = item as Video;
  827. if (video != null)
  828. {
  829. dto.VideoType = video.VideoType;
  830. dto.Video3DFormat = video.Video3DFormat;
  831. dto.IsoType = video.IsoType;
  832. dto.IsHD = video.IsHD;
  833. dto.PartCount = video.AdditionalPartIds.Count + 1;
  834. if (fields.Contains(ItemFields.Chapters))
  835. {
  836. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  837. }
  838. }
  839. if (fields.Contains(ItemFields.MediaStreams))
  840. {
  841. // Add VideoInfo
  842. var iHasMediaStreams = item as IHasMediaStreams;
  843. if (iHasMediaStreams != null)
  844. {
  845. dto.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  846. {
  847. ItemId = item.Id
  848. }).ToList();
  849. }
  850. }
  851. // Add MovieInfo
  852. var movie = item as Movie;
  853. if (movie != null)
  854. {
  855. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  856. if (specialFeatureCount > 0)
  857. {
  858. dto.SpecialFeatureCount = specialFeatureCount;
  859. }
  860. }
  861. // Add EpisodeInfo
  862. var episode = item as Episode;
  863. if (episode != null)
  864. {
  865. dto.IndexNumberEnd = episode.IndexNumberEnd;
  866. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  867. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  868. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  869. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  870. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  871. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  872. var seasonId = episode.SeasonId;
  873. if (seasonId.HasValue)
  874. {
  875. dto.SeasonId = seasonId.Value.ToString("N");
  876. }
  877. }
  878. // Add SeriesInfo
  879. var series = item as Series;
  880. if (series != null)
  881. {
  882. dto.AirDays = series.AirDays;
  883. dto.AirTime = series.AirTime;
  884. dto.Status = series.Status;
  885. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  886. dto.SeasonCount = series.SeasonCount;
  887. if (fields.Contains(ItemFields.Settings))
  888. {
  889. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  890. }
  891. }
  892. if (episode != null)
  893. {
  894. series = item.FindParent<Series>();
  895. dto.SeriesId = GetDtoId(series);
  896. dto.SeriesName = series.Name;
  897. dto.AirTime = series.AirTime;
  898. dto.SeriesStudio = series.Studios.FirstOrDefault();
  899. if (series.HasImage(ImageType.Thumb))
  900. {
  901. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb, series.GetImagePath(ImageType.Thumb));
  902. }
  903. var imagePath = series.PrimaryImagePath;
  904. if (!string.IsNullOrEmpty(imagePath))
  905. {
  906. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  907. }
  908. }
  909. // Add SeasonInfo
  910. var season = item as Season;
  911. if (season != null)
  912. {
  913. series = item.FindParent<Series>();
  914. dto.SeriesId = GetDtoId(series);
  915. dto.SeriesName = series.Name;
  916. dto.AirTime = series.AirTime;
  917. dto.SeriesStudio = series.Studios.FirstOrDefault();
  918. var imagePath = series.PrimaryImagePath;
  919. if (!string.IsNullOrEmpty(imagePath))
  920. {
  921. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  922. }
  923. }
  924. var game = item as Game;
  925. if (game != null)
  926. {
  927. SetGameProperties(dto, game);
  928. }
  929. var gameSystem = item as GameSystem;
  930. if (gameSystem != null)
  931. {
  932. SetGameSystemProperties(dto, gameSystem);
  933. }
  934. var musicVideo = item as MusicVideo;
  935. if (musicVideo != null)
  936. {
  937. SetMusicVideoProperties(dto, musicVideo);
  938. }
  939. var book = item as Book;
  940. if (book != null)
  941. {
  942. SetBookProperties(dto, book);
  943. }
  944. }
  945. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  946. {
  947. var hasProductionLocations = item as IHasProductionLocations;
  948. if (hasProductionLocations != null)
  949. {
  950. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  951. }
  952. var person = item as Person;
  953. if (person != null)
  954. {
  955. dto.ProductionLocations = new List<string>();
  956. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  957. {
  958. dto.ProductionLocations.Add(person.PlaceOfBirth);
  959. }
  960. }
  961. if (dto.ProductionLocations == null)
  962. {
  963. dto.ProductionLocations = new List<string>();
  964. }
  965. }
  966. /// <summary>
  967. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  968. /// </summary>
  969. /// <param name="folder">The folder.</param>
  970. /// <param name="user">The user.</param>
  971. /// <param name="dto">The dto.</param>
  972. /// <param name="fields">The fields.</param>
  973. /// <returns>Task.</returns>
  974. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  975. {
  976. var rcentlyAddedItemCount = 0;
  977. var recursiveItemCount = 0;
  978. var unplayed = 0;
  979. long runtime = 0;
  980. double totalPercentPlayed = 0;
  981. IEnumerable<BaseItem> children;
  982. var season = folder as Season;
  983. if (season != null)
  984. {
  985. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  986. }
  987. else
  988. {
  989. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  990. }
  991. // Loop through each recursive child
  992. foreach (var child in children)
  993. {
  994. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  995. recursiveItemCount++;
  996. // Check is recently added
  997. if (child.IsRecentlyAdded())
  998. {
  999. rcentlyAddedItemCount++;
  1000. }
  1001. var isUnplayed = true;
  1002. // Incrememt totalPercentPlayed
  1003. if (userdata != null)
  1004. {
  1005. if (userdata.Played)
  1006. {
  1007. totalPercentPlayed += 100;
  1008. isUnplayed = false;
  1009. }
  1010. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1011. {
  1012. double itemPercent = userdata.PlaybackPositionTicks;
  1013. itemPercent /= child.RunTimeTicks.Value;
  1014. totalPercentPlayed += itemPercent;
  1015. }
  1016. }
  1017. if (isUnplayed)
  1018. {
  1019. unplayed++;
  1020. }
  1021. runtime += child.RunTimeTicks ?? 0;
  1022. }
  1023. dto.RecursiveItemCount = recursiveItemCount;
  1024. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  1025. dto.RecursiveUnplayedItemCount = unplayed;
  1026. if (recursiveItemCount > 0)
  1027. {
  1028. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1029. }
  1030. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1031. {
  1032. dto.CumulativeRunTimeTicks = runtime;
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// Attaches the primary image aspect ratio.
  1037. /// </summary>
  1038. /// <param name="dto">The dto.</param>
  1039. /// <param name="item">The item.</param>
  1040. /// <returns>Task.</returns>
  1041. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1042. {
  1043. var path = item.PrimaryImagePath;
  1044. if (string.IsNullOrEmpty(path))
  1045. {
  1046. return;
  1047. }
  1048. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1049. var dateModified = item.GetImageDateModified(path);
  1050. ImageSize size;
  1051. try
  1052. {
  1053. size = _imageProcessor.GetImageSize(path, dateModified);
  1054. }
  1055. catch (FileNotFoundException)
  1056. {
  1057. _logger.Error("Image file does not exist: {0}", path);
  1058. return;
  1059. }
  1060. catch (Exception ex)
  1061. {
  1062. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1063. return;
  1064. }
  1065. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1066. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1067. foreach (var enhancer in supportedEnhancers)
  1068. {
  1069. try
  1070. {
  1071. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1072. }
  1073. catch (Exception ex)
  1074. {
  1075. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1076. }
  1077. }
  1078. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1079. }
  1080. }
  1081. }