DtoService.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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 hasLanguage = item as IHasLanguage;
  630. if (hasLanguage != null)
  631. {
  632. dto.Language = hasLanguage.Language;
  633. }
  634. var hasCriticRating = item as IHasCriticRating;
  635. if (hasCriticRating != null)
  636. {
  637. dto.CriticRating = hasCriticRating.CriticRating;
  638. if (fields.Contains(ItemFields.CriticRatingSummary))
  639. {
  640. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  641. }
  642. }
  643. var hasTrailers = item as IHasTrailers;
  644. if (hasTrailers != null)
  645. {
  646. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  647. }
  648. if (fields.Contains(ItemFields.RemoteTrailers))
  649. {
  650. dto.RemoteTrailers = hasTrailers != null ?
  651. hasTrailers.RemoteTrailers :
  652. new List<MediaUrl>();
  653. }
  654. dto.Name = item.Name;
  655. dto.OfficialRating = item.OfficialRating;
  656. var hasOverview = fields.Contains(ItemFields.Overview);
  657. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  658. if (hasOverview || hasHtmlOverview)
  659. {
  660. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  661. if (hasOverview)
  662. {
  663. dto.Overview = strippedOverview;
  664. }
  665. // Only supply the html version if there was actually html content
  666. if (hasHtmlOverview)
  667. {
  668. dto.OverviewHtml = item.Overview;
  669. }
  670. }
  671. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  672. if (dto.BackdropImageTags.Count == 0)
  673. {
  674. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  675. if (parentWithBackdrop != null)
  676. {
  677. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  678. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  679. }
  680. }
  681. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  682. {
  683. dto.ParentId = GetDtoId(item.Parent);
  684. }
  685. dto.ParentIndexNumber = item.ParentIndexNumber;
  686. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  687. if (!dto.HasLogo)
  688. {
  689. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  690. if (parentWithLogo != null)
  691. {
  692. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  693. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImagePath(ImageType.Logo));
  694. }
  695. }
  696. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  697. if (!dto.HasArtImage)
  698. {
  699. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  700. if (parentWithImage != null)
  701. {
  702. dto.ParentArtItemId = GetDtoId(parentWithImage);
  703. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImagePath(ImageType.Art));
  704. }
  705. }
  706. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  707. if (!dto.HasThumb)
  708. {
  709. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  710. if (parentWithImage != null)
  711. {
  712. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  713. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb, parentWithImage.GetImagePath(ImageType.Thumb));
  714. }
  715. }
  716. if (fields.Contains(ItemFields.Path))
  717. {
  718. dto.Path = item.Path;
  719. }
  720. dto.PremiereDate = item.PremiereDate;
  721. dto.ProductionYear = item.ProductionYear;
  722. if (fields.Contains(ItemFields.ProviderIds))
  723. {
  724. dto.ProviderIds = item.ProviderIds;
  725. }
  726. dto.RunTimeTicks = item.RunTimeTicks;
  727. if (fields.Contains(ItemFields.SortName))
  728. {
  729. dto.SortName = item.SortName;
  730. }
  731. if (fields.Contains(ItemFields.CustomRating))
  732. {
  733. dto.CustomRating = item.CustomRating;
  734. }
  735. if (fields.Contains(ItemFields.Taglines))
  736. {
  737. var hasTagline = item as IHasTaglines;
  738. if (hasTagline != null)
  739. {
  740. dto.Taglines = hasTagline.Taglines;
  741. }
  742. if (dto.Taglines == null)
  743. {
  744. dto.Taglines = new List<string>();
  745. }
  746. }
  747. dto.Type = item.GetClientTypeName();
  748. dto.CommunityRating = item.CommunityRating;
  749. dto.VoteCount = item.VoteCount;
  750. if (item.IsFolder)
  751. {
  752. var folder = (Folder)item;
  753. if (fields.Contains(ItemFields.IndexOptions))
  754. {
  755. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  756. }
  757. }
  758. // Add audio info
  759. var audio = item as Audio;
  760. if (audio != null)
  761. {
  762. dto.Album = audio.Album;
  763. dto.Artists = audio.Artists;
  764. var albumParent = audio.FindParent<MusicAlbum>();
  765. if (albumParent != null)
  766. {
  767. dto.AlbumId = GetDtoId(albumParent);
  768. var imagePath = albumParent.PrimaryImagePath;
  769. if (!string.IsNullOrEmpty(imagePath))
  770. {
  771. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  772. }
  773. }
  774. }
  775. var album = item as MusicAlbum;
  776. if (album != null)
  777. {
  778. dto.Artists = album.Artists;
  779. dto.SoundtrackIds = album.SoundtrackIds
  780. .Select(i => i.ToString("N"))
  781. .ToArray();
  782. }
  783. var hasAlbumArtist = item as IHasAlbumArtist;
  784. if (hasAlbumArtist != null)
  785. {
  786. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  787. }
  788. // Add video info
  789. var video = item as Video;
  790. if (video != null)
  791. {
  792. dto.VideoType = video.VideoType;
  793. dto.Video3DFormat = video.Video3DFormat;
  794. dto.IsoType = video.IsoType;
  795. dto.IsHD = video.IsHD;
  796. dto.PartCount = video.AdditionalPartIds.Count + 1;
  797. if (fields.Contains(ItemFields.Chapters))
  798. {
  799. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  800. }
  801. }
  802. if (fields.Contains(ItemFields.MediaStreams))
  803. {
  804. // Add VideoInfo
  805. var iHasMediaStreams = item as IHasMediaStreams;
  806. if (iHasMediaStreams != null)
  807. {
  808. dto.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  809. {
  810. ItemId = item.Id
  811. }).ToList();
  812. }
  813. }
  814. // Add MovieInfo
  815. var movie = item as Movie;
  816. if (movie != null)
  817. {
  818. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  819. if (specialFeatureCount > 0)
  820. {
  821. dto.SpecialFeatureCount = specialFeatureCount;
  822. }
  823. }
  824. // Add EpisodeInfo
  825. var episode = item as Episode;
  826. if (episode != null)
  827. {
  828. dto.IndexNumberEnd = episode.IndexNumberEnd;
  829. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  830. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  831. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  832. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  833. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  834. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  835. var seasonId = episode.SeasonId;
  836. if (seasonId.HasValue)
  837. {
  838. dto.SeasonId = seasonId.Value.ToString("N");
  839. }
  840. }
  841. // Add SeriesInfo
  842. var series = item as Series;
  843. if (series != null)
  844. {
  845. dto.AirDays = series.AirDays;
  846. dto.AirTime = series.AirTime;
  847. dto.Status = series.Status;
  848. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  849. dto.SeasonCount = series.SeasonCount;
  850. if (fields.Contains(ItemFields.Settings))
  851. {
  852. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  853. }
  854. }
  855. if (episode != null)
  856. {
  857. series = item.FindParent<Series>();
  858. dto.SeriesId = GetDtoId(series);
  859. dto.SeriesName = series.Name;
  860. dto.AirTime = series.AirTime;
  861. dto.SeriesStudio = series.Studios.FirstOrDefault();
  862. if (series.HasImage(ImageType.Thumb))
  863. {
  864. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb, series.GetImagePath(ImageType.Thumb));
  865. }
  866. var imagePath = series.PrimaryImagePath;
  867. if (!string.IsNullOrEmpty(imagePath))
  868. {
  869. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  870. }
  871. }
  872. // Add SeasonInfo
  873. var season = item as Season;
  874. if (season != null)
  875. {
  876. series = item.FindParent<Series>();
  877. dto.SeriesId = GetDtoId(series);
  878. dto.SeriesName = series.Name;
  879. dto.AirTime = series.AirTime;
  880. dto.SeriesStudio = series.Studios.FirstOrDefault();
  881. var imagePath = series.PrimaryImagePath;
  882. if (!string.IsNullOrEmpty(imagePath))
  883. {
  884. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  885. }
  886. }
  887. var game = item as Game;
  888. if (game != null)
  889. {
  890. SetGameProperties(dto, game);
  891. }
  892. var gameSystem = item as GameSystem;
  893. if (gameSystem != null)
  894. {
  895. SetGameSystemProperties(dto, gameSystem);
  896. }
  897. var musicVideo = item as MusicVideo;
  898. if (musicVideo != null)
  899. {
  900. SetMusicVideoProperties(dto, musicVideo);
  901. }
  902. var book = item as Book;
  903. if (book != null)
  904. {
  905. SetBookProperties(dto, book);
  906. }
  907. }
  908. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  909. {
  910. var hasProductionLocations = item as IHasProductionLocations;
  911. if (hasProductionLocations != null)
  912. {
  913. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  914. }
  915. var person = item as Person;
  916. if (person != null)
  917. {
  918. dto.ProductionLocations = new List<string>();
  919. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  920. {
  921. dto.ProductionLocations.Add(person.PlaceOfBirth);
  922. }
  923. }
  924. if (dto.ProductionLocations == null)
  925. {
  926. dto.ProductionLocations = new List<string>();
  927. }
  928. }
  929. /// <summary>
  930. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  931. /// </summary>
  932. /// <param name="folder">The folder.</param>
  933. /// <param name="user">The user.</param>
  934. /// <param name="dto">The dto.</param>
  935. /// <param name="fields">The fields.</param>
  936. /// <returns>Task.</returns>
  937. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  938. {
  939. var rcentlyAddedItemCount = 0;
  940. var recursiveItemCount = 0;
  941. var unplayed = 0;
  942. long runtime = 0;
  943. double totalPercentPlayed = 0;
  944. IEnumerable<BaseItem> children;
  945. var season = folder as Season;
  946. if (season != null)
  947. {
  948. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  949. }
  950. else
  951. {
  952. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  953. }
  954. // Loop through each recursive child
  955. foreach (var child in children)
  956. {
  957. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  958. recursiveItemCount++;
  959. // Check is recently added
  960. if (child.IsRecentlyAdded())
  961. {
  962. rcentlyAddedItemCount++;
  963. }
  964. var isUnplayed = true;
  965. // Incrememt totalPercentPlayed
  966. if (userdata != null)
  967. {
  968. if (userdata.Played)
  969. {
  970. totalPercentPlayed += 100;
  971. isUnplayed = false;
  972. }
  973. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  974. {
  975. double itemPercent = userdata.PlaybackPositionTicks;
  976. itemPercent /= child.RunTimeTicks.Value;
  977. totalPercentPlayed += itemPercent;
  978. }
  979. }
  980. if (isUnplayed)
  981. {
  982. unplayed++;
  983. }
  984. runtime += child.RunTimeTicks ?? 0;
  985. }
  986. dto.RecursiveItemCount = recursiveItemCount;
  987. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  988. dto.RecursiveUnplayedItemCount = unplayed;
  989. if (recursiveItemCount > 0)
  990. {
  991. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  992. }
  993. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  994. {
  995. dto.CumulativeRunTimeTicks = runtime;
  996. }
  997. }
  998. /// <summary>
  999. /// Attaches the primary image aspect ratio.
  1000. /// </summary>
  1001. /// <param name="dto">The dto.</param>
  1002. /// <param name="item">The item.</param>
  1003. /// <returns>Task.</returns>
  1004. private void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1005. {
  1006. var path = item.PrimaryImagePath;
  1007. if (string.IsNullOrEmpty(path))
  1008. {
  1009. return;
  1010. }
  1011. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1012. var dateModified = item.GetImageDateModified(path);
  1013. ImageSize size;
  1014. try
  1015. {
  1016. size = _imageProcessor.GetImageSize(path, dateModified);
  1017. }
  1018. catch (FileNotFoundException)
  1019. {
  1020. _logger.Error("Image file does not exist: {0}", path);
  1021. return;
  1022. }
  1023. catch (Exception ex)
  1024. {
  1025. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1026. return;
  1027. }
  1028. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1029. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1030. foreach (var enhancer in supportedEnhancers)
  1031. {
  1032. try
  1033. {
  1034. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1039. }
  1040. }
  1041. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1042. }
  1043. }
  1044. }