DtoService.cs 42 KB

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