2
0

DtoService.cs 42 KB

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