DtoService.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Entities.Movies;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Controller.Session;
  14. using MediaBrowser.Model.Drawing;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.Querying;
  19. using MediaBrowser.Model.Session;
  20. using MoreLinq;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.IO;
  24. using System.Linq;
  25. namespace MediaBrowser.Server.Implementations.Dto
  26. {
  27. public class DtoService : IDtoService
  28. {
  29. private readonly ILogger _logger;
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly IUserManager _userManager;
  32. private readonly IUserDataManager _userDataRepository;
  33. private readonly IItemRepository _itemRepo;
  34. private readonly IImageProcessor _imageProcessor;
  35. private readonly IServerConfigurationManager _config;
  36. private readonly IFileSystem _fileSystem;
  37. private readonly IProviderManager _providerManager;
  38. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager)
  39. {
  40. _logger = logger;
  41. _libraryManager = libraryManager;
  42. _userManager = userManager;
  43. _userDataRepository = userDataRepository;
  44. _itemRepo = itemRepo;
  45. _imageProcessor = imageProcessor;
  46. _config = config;
  47. _fileSystem = fileSystem;
  48. _providerManager = providerManager;
  49. }
  50. /// <summary>
  51. /// Converts a BaseItem to a DTOBaseItem
  52. /// </summary>
  53. /// <param name="item">The item.</param>
  54. /// <param name="fields">The fields.</param>
  55. /// <param name="user">The user.</param>
  56. /// <param name="owner">The owner.</param>
  57. /// <returns>Task{DtoBaseItem}.</returns>
  58. /// <exception cref="System.ArgumentNullException">item</exception>
  59. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  60. {
  61. if (item == null)
  62. {
  63. throw new ArgumentNullException("item");
  64. }
  65. if (fields == null)
  66. {
  67. throw new ArgumentNullException("fields");
  68. }
  69. var dto = new BaseItemDto();
  70. if (fields.Contains(ItemFields.People))
  71. {
  72. AttachPeople(dto, item);
  73. }
  74. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  75. {
  76. try
  77. {
  78. AttachPrimaryImageAspectRatio(dto, item);
  79. }
  80. catch (Exception ex)
  81. {
  82. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  83. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  84. }
  85. }
  86. if (fields.Contains(ItemFields.DisplayPreferencesId))
  87. {
  88. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  89. }
  90. if (user != null)
  91. {
  92. AttachUserSpecificInfo(dto, item, user, fields);
  93. }
  94. if (fields.Contains(ItemFields.Studios))
  95. {
  96. AttachStudios(dto, item);
  97. }
  98. AttachBasicFields(dto, item, owner, fields);
  99. if (fields.Contains(ItemFields.SoundtrackIds))
  100. {
  101. var hasSoundtracks = item as IHasSoundtracks;
  102. if (hasSoundtracks != null)
  103. {
  104. dto.SoundtrackIds = hasSoundtracks.SoundtrackIds
  105. .Select(i => i.ToString("N"))
  106. .ToArray();
  107. }
  108. }
  109. var itemByName = item as IItemByName;
  110. if (itemByName != null)
  111. {
  112. AttachItemByNameCounts(dto, itemByName, user);
  113. }
  114. return dto;
  115. }
  116. /// <summary>
  117. /// Attaches the item by name counts.
  118. /// </summary>
  119. /// <param name="dto">The dto.</param>
  120. /// <param name="item">The item.</param>
  121. /// <param name="user">The user.</param>
  122. private void AttachItemByNameCounts(BaseItemDto dto, IItemByName item, User user)
  123. {
  124. if (user == null)
  125. {
  126. return;
  127. }
  128. var counts = item.GetItemByNameCounts(user.Id) ?? new ItemByNameCounts();
  129. dto.ChildCount = counts.TotalCount;
  130. dto.AdultVideoCount = counts.AdultVideoCount;
  131. dto.AlbumCount = counts.AlbumCount;
  132. dto.EpisodeCount = counts.EpisodeCount;
  133. dto.GameCount = counts.GameCount;
  134. dto.MovieCount = counts.MovieCount;
  135. dto.MusicVideoCount = counts.MusicVideoCount;
  136. dto.SeriesCount = counts.SeriesCount;
  137. dto.SongCount = counts.SongCount;
  138. dto.TrailerCount = counts.TrailerCount;
  139. }
  140. /// <summary>
  141. /// Attaches the user specific info.
  142. /// </summary>
  143. /// <param name="dto">The dto.</param>
  144. /// <param name="item">The item.</param>
  145. /// <param name="user">The user.</param>
  146. /// <param name="fields">The fields.</param>
  147. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  148. {
  149. if (item.IsFolder)
  150. {
  151. var folder = (Folder)item;
  152. dto.ChildCount = GetChildCount(folder, user);
  153. if (!(folder is UserRootFolder))
  154. {
  155. SetSpecialCounts(folder, user, dto, fields);
  156. }
  157. }
  158. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  159. dto.UserData = GetUserItemDataDto(userData);
  160. if (item.IsFolder)
  161. {
  162. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  163. }
  164. dto.PlayAccess = item.GetPlayAccess(user);
  165. }
  166. private int GetChildCount(Folder folder, User user)
  167. {
  168. return folder.GetChildren(user, true)
  169. .Count();
  170. }
  171. public UserDto GetUserDto(User user)
  172. {
  173. if (user == null)
  174. {
  175. throw new ArgumentNullException("user");
  176. }
  177. var dto = new UserDto
  178. {
  179. Id = user.Id.ToString("N"),
  180. Name = user.Name,
  181. HasPassword = !String.IsNullOrEmpty(user.Password),
  182. LastActivityDate = user.LastActivityDate,
  183. LastLoginDate = user.LastLoginDate,
  184. Configuration = user.Configuration
  185. };
  186. var image = user.GetImageInfo(ImageType.Primary, 0);
  187. if (image != null)
  188. {
  189. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  190. try
  191. {
  192. AttachPrimaryImageAspectRatio(dto, user);
  193. }
  194. catch (Exception ex)
  195. {
  196. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  197. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  198. }
  199. }
  200. return dto;
  201. }
  202. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  203. {
  204. var dto = new SessionInfoDto
  205. {
  206. Client = session.Client,
  207. DeviceId = session.DeviceId,
  208. DeviceName = session.DeviceName,
  209. Id = session.Id.ToString("N"),
  210. LastActivityDate = session.LastActivityDate,
  211. NowPlayingPositionTicks = session.NowPlayingPositionTicks,
  212. SupportsRemoteControl = session.SupportsRemoteControl,
  213. IsPaused = session.IsPaused,
  214. IsMuted = session.IsMuted,
  215. NowViewingContext = session.NowViewingContext,
  216. NowViewingItemId = session.NowViewingItemId,
  217. NowViewingItemName = session.NowViewingItemName,
  218. NowViewingItemType = session.NowViewingItemType,
  219. ApplicationVersion = session.ApplicationVersion,
  220. CanSeek = session.CanSeek,
  221. QueueableMediaTypes = session.QueueableMediaTypes,
  222. PlayableMediaTypes = session.PlayableMediaTypes,
  223. RemoteEndPoint = session.RemoteEndPoint,
  224. AdditionalUsers = session.AdditionalUsers
  225. };
  226. if (session.NowPlayingItem != null)
  227. {
  228. dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
  229. }
  230. if (session.UserId.HasValue)
  231. {
  232. dto.UserId = session.UserId.Value.ToString("N");
  233. }
  234. dto.UserName = session.UserName;
  235. return dto;
  236. }
  237. /// <summary>
  238. /// Converts a BaseItem to a BaseItemInfo
  239. /// </summary>
  240. /// <param name="item">The item.</param>
  241. /// <returns>BaseItemInfo.</returns>
  242. /// <exception cref="System.ArgumentNullException">item</exception>
  243. public BaseItemInfo GetBaseItemInfo(BaseItem item)
  244. {
  245. if (item == null)
  246. {
  247. throw new ArgumentNullException("item");
  248. }
  249. var info = new BaseItemInfo
  250. {
  251. Id = GetDtoId(item),
  252. Name = item.Name,
  253. MediaType = item.MediaType,
  254. Type = item.GetClientTypeName(),
  255. RunTimeTicks = item.RunTimeTicks
  256. };
  257. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  258. return info;
  259. }
  260. /// <summary>
  261. /// Gets client-side Id of a server-side BaseItem
  262. /// </summary>
  263. /// <param name="item">The item.</param>
  264. /// <returns>System.String.</returns>
  265. /// <exception cref="System.ArgumentNullException">item</exception>
  266. public string GetDtoId(BaseItem item)
  267. {
  268. if (item == null)
  269. {
  270. throw new ArgumentNullException("item");
  271. }
  272. return item.Id.ToString("N");
  273. }
  274. /// <summary>
  275. /// Converts a UserItemData to a DTOUserItemData
  276. /// </summary>
  277. /// <param name="data">The data.</param>
  278. /// <returns>DtoUserItemData.</returns>
  279. /// <exception cref="System.ArgumentNullException"></exception>
  280. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  281. {
  282. if (data == null)
  283. {
  284. throw new ArgumentNullException("data");
  285. }
  286. return new UserItemDataDto
  287. {
  288. IsFavorite = data.IsFavorite,
  289. Likes = data.Likes,
  290. PlaybackPositionTicks = data.PlaybackPositionTicks,
  291. PlayCount = data.PlayCount,
  292. Rating = data.Rating,
  293. Played = data.Played,
  294. LastPlayedDate = data.LastPlayedDate,
  295. Key = data.Key
  296. };
  297. }
  298. private void SetBookProperties(BaseItemDto dto, Book item)
  299. {
  300. dto.SeriesName = item.SeriesName;
  301. }
  302. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  303. {
  304. if (!string.IsNullOrEmpty(item.Album))
  305. {
  306. var parentAlbum = _libraryManager.RootFolder
  307. .GetRecursiveChildren(i => i is MusicAlbum)
  308. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  309. if (parentAlbum != null)
  310. {
  311. dto.AlbumId = GetDtoId(parentAlbum);
  312. }
  313. }
  314. dto.Album = item.Album;
  315. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  316. }
  317. private void SetGameProperties(BaseItemDto dto, Game item)
  318. {
  319. dto.Players = item.PlayersSupported;
  320. dto.GameSystem = item.GameSystem;
  321. }
  322. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  323. {
  324. dto.GameSystem = item.GameSystemName;
  325. }
  326. /// <summary>
  327. /// Gets the backdrop image tags.
  328. /// </summary>
  329. /// <param name="item">The item.</param>
  330. /// <returns>List{System.String}.</returns>
  331. private List<Guid> GetBackdropImageTags(BaseItem item)
  332. {
  333. return GetCacheTags(item, ImageType.Backdrop).ToList();
  334. }
  335. /// <summary>
  336. /// Gets the screenshot image tags.
  337. /// </summary>
  338. /// <param name="item">The item.</param>
  339. /// <returns>List{Guid}.</returns>
  340. private List<Guid> GetScreenshotImageTags(BaseItem item)
  341. {
  342. var hasScreenshots = item as IHasScreenshots;
  343. if (hasScreenshots == null)
  344. {
  345. return new List<Guid>();
  346. }
  347. return GetCacheTags(item, ImageType.Screenshot).ToList();
  348. }
  349. private IEnumerable<Guid> GetCacheTags(BaseItem item, ImageType type)
  350. {
  351. return item.GetImages(type)
  352. .Select(p => GetImageCacheTag(item, p))
  353. .Where(i => i.HasValue)
  354. .Select(i => i.Value)
  355. .ToList();
  356. }
  357. private Guid? GetImageCacheTag(BaseItem item, ImageType type)
  358. {
  359. try
  360. {
  361. return _imageProcessor.GetImageCacheTag(item, type);
  362. }
  363. catch (IOException ex)
  364. {
  365. _logger.ErrorException("Error getting {0} image info", ex, type);
  366. return null;
  367. }
  368. }
  369. private Guid? GetImageCacheTag(BaseItem item, ItemImageInfo image)
  370. {
  371. try
  372. {
  373. return _imageProcessor.GetImageCacheTag(item, image);
  374. }
  375. catch (IOException ex)
  376. {
  377. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  378. return null;
  379. }
  380. }
  381. /// <summary>
  382. /// Attaches People DTO's to a DTOBaseItem
  383. /// </summary>
  384. /// <param name="dto">The dto.</param>
  385. /// <param name="item">The item.</param>
  386. /// <returns>Task.</returns>
  387. private void AttachPeople(BaseItemDto dto, BaseItem item)
  388. {
  389. // Ordering by person type to ensure actors and artists are at the front.
  390. // This is taking advantage of the fact that they both begin with A
  391. // This should be improved in the future
  392. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue).ThenBy(i => i.Type).ToList();
  393. // Attach People by transforming them into BaseItemPerson (DTO)
  394. dto.People = new BaseItemPerson[people.Count];
  395. var dictionary = people.Select(p => p.Name)
  396. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  397. {
  398. try
  399. {
  400. return _libraryManager.GetPerson(c);
  401. }
  402. catch (IOException ex)
  403. {
  404. _logger.ErrorException("Error getting person {0}", ex, c);
  405. return null;
  406. }
  407. }).Where(i => i != null)
  408. .DistinctBy(i => i.Name)
  409. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  410. for (var i = 0; i < people.Count; i++)
  411. {
  412. var person = people[i];
  413. var baseItemPerson = new BaseItemPerson
  414. {
  415. Name = person.Name,
  416. Role = person.Role,
  417. Type = person.Type
  418. };
  419. Person entity;
  420. if (dictionary.TryGetValue(person.Name, out entity))
  421. {
  422. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  423. }
  424. dto.People[i] = baseItemPerson;
  425. }
  426. }
  427. /// <summary>
  428. /// Attaches the studios.
  429. /// </summary>
  430. /// <param name="dto">The dto.</param>
  431. /// <param name="item">The item.</param>
  432. /// <returns>Task.</returns>
  433. private void AttachStudios(BaseItemDto dto, BaseItem item)
  434. {
  435. var studios = item.Studios.ToList();
  436. dto.Studios = new StudioDto[studios.Count];
  437. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  438. {
  439. try
  440. {
  441. return _libraryManager.GetStudio(name);
  442. }
  443. catch (IOException ex)
  444. {
  445. _logger.ErrorException("Error getting studio {0}", ex, name);
  446. return null;
  447. }
  448. })
  449. .Where(i => i != null)
  450. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  451. for (var i = 0; i < studios.Count; i++)
  452. {
  453. var studio = studios[i];
  454. var studioDto = new StudioDto
  455. {
  456. Name = studio
  457. };
  458. Studio entity;
  459. if (dictionary.TryGetValue(studio, out entity))
  460. {
  461. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  462. }
  463. dto.Studios[i] = studioDto;
  464. }
  465. }
  466. /// <summary>
  467. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  468. /// </summary>
  469. /// <param name="item">The item.</param>
  470. /// <param name="owner">The owner.</param>
  471. /// <returns>BaseItem.</returns>
  472. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  473. {
  474. var parent = item.Parent ?? owner;
  475. while (parent != null)
  476. {
  477. if (parent.GetImages(ImageType.Backdrop).Any())
  478. {
  479. return parent;
  480. }
  481. parent = parent.Parent;
  482. }
  483. return null;
  484. }
  485. /// <summary>
  486. /// If an item does not have a logo, this can be used to find the first parent that does have one
  487. /// </summary>
  488. /// <param name="item">The item.</param>
  489. /// <param name="type">The type.</param>
  490. /// <param name="owner">The owner.</param>
  491. /// <returns>BaseItem.</returns>
  492. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  493. {
  494. var parent = item.Parent ?? owner;
  495. while (parent != null)
  496. {
  497. if (parent.HasImage(type))
  498. {
  499. return parent;
  500. }
  501. parent = parent.Parent;
  502. }
  503. return null;
  504. }
  505. /// <summary>
  506. /// Gets the chapter info dto.
  507. /// </summary>
  508. /// <param name="chapterInfo">The chapter info.</param>
  509. /// <param name="item">The item.</param>
  510. /// <returns>ChapterInfoDto.</returns>
  511. private ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  512. {
  513. var dto = new ChapterInfoDto
  514. {
  515. Name = chapterInfo.Name,
  516. StartPositionTicks = chapterInfo.StartPositionTicks
  517. };
  518. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  519. {
  520. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  521. {
  522. Path = chapterInfo.ImagePath,
  523. Type = ImageType.Chapter,
  524. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  525. });
  526. }
  527. return dto;
  528. }
  529. /// <summary>
  530. /// Gets a BaseItem based upon it's client-side item id
  531. /// </summary>
  532. /// <param name="id">The id.</param>
  533. /// <param name="userId">The user id.</param>
  534. /// <returns>BaseItem.</returns>
  535. public BaseItem GetItemByDtoId(string id, Guid? userId = null)
  536. {
  537. if (string.IsNullOrEmpty(id))
  538. {
  539. throw new ArgumentNullException("id");
  540. }
  541. BaseItem item = null;
  542. if (userId.HasValue)
  543. {
  544. item = _libraryManager.GetItemById(new Guid(id));
  545. }
  546. // If we still don't find it, look within individual user views
  547. if (item == null && !userId.HasValue)
  548. {
  549. foreach (var user in _userManager.Users)
  550. {
  551. item = GetItemByDtoId(id, user.Id);
  552. if (item != null)
  553. {
  554. break;
  555. }
  556. }
  557. }
  558. return item;
  559. }
  560. /// <summary>
  561. /// Sets simple property values on a DTOBaseItem
  562. /// </summary>
  563. /// <param name="dto">The dto.</param>
  564. /// <param name="item">The item.</param>
  565. /// <param name="owner">The owner.</param>
  566. /// <param name="fields">The fields.</param>
  567. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  568. {
  569. if (fields.Contains(ItemFields.DateCreated))
  570. {
  571. dto.DateCreated = item.DateCreated;
  572. }
  573. dto.DisplayMediaType = item.DisplayMediaType;
  574. dto.IsUnidentified = item.IsUnidentified;
  575. if (fields.Contains(ItemFields.Settings))
  576. {
  577. dto.LockedFields = item.LockedFields;
  578. dto.LockData = item.DontFetchMeta;
  579. }
  580. var hasBudget = item as IHasBudget;
  581. if (hasBudget != null)
  582. {
  583. if (fields.Contains(ItemFields.Budget))
  584. {
  585. dto.Budget = hasBudget.Budget;
  586. }
  587. if (fields.Contains(ItemFields.Revenue))
  588. {
  589. dto.Revenue = hasBudget.Revenue;
  590. }
  591. }
  592. dto.EndDate = item.EndDate;
  593. if (fields.Contains(ItemFields.HomePageUrl))
  594. {
  595. dto.HomePageUrl = item.HomePageUrl;
  596. }
  597. if (fields.Contains(ItemFields.ExternalUrls))
  598. {
  599. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  600. }
  601. if (fields.Contains(ItemFields.Tags))
  602. {
  603. var hasTags = item as IHasTags;
  604. if (hasTags != null)
  605. {
  606. dto.Tags = hasTags.Tags;
  607. }
  608. if (dto.Tags == null)
  609. {
  610. dto.Tags = new List<string>();
  611. }
  612. }
  613. if (fields.Contains(ItemFields.Keywords))
  614. {
  615. var hasTags = item as IHasKeywords;
  616. if (hasTags != null)
  617. {
  618. dto.Keywords = hasTags.Keywords;
  619. }
  620. if (dto.Keywords == null)
  621. {
  622. dto.Keywords = new List<string>();
  623. }
  624. }
  625. if (fields.Contains(ItemFields.ProductionLocations))
  626. {
  627. SetProductionLocations(item, dto);
  628. }
  629. var hasAspectRatio = item as IHasAspectRatio;
  630. if (hasAspectRatio != null)
  631. {
  632. dto.AspectRatio = hasAspectRatio.AspectRatio;
  633. }
  634. var hasMetascore = item as IHasMetascore;
  635. if (hasMetascore != null)
  636. {
  637. dto.Metascore = hasMetascore.Metascore;
  638. }
  639. if (fields.Contains(ItemFields.AwardSummary))
  640. {
  641. var hasAwards = item as IHasAwards;
  642. if (hasAwards != null)
  643. {
  644. dto.AwardSummary = hasAwards.AwardSummary;
  645. }
  646. }
  647. dto.BackdropImageTags = GetBackdropImageTags(item);
  648. if (fields.Contains(ItemFields.ScreenshotImageTags))
  649. {
  650. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  651. }
  652. if (fields.Contains(ItemFields.Genres))
  653. {
  654. dto.Genres = item.Genres;
  655. }
  656. dto.ImageTags = new Dictionary<ImageType, Guid>();
  657. // Prevent implicitly captured closure
  658. var currentItem = item;
  659. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  660. {
  661. var tag = GetImageCacheTag(item, image);
  662. if (tag.HasValue)
  663. {
  664. dto.ImageTags[image.Type] = tag.Value;
  665. }
  666. }
  667. dto.Id = GetDtoId(item);
  668. dto.IndexNumber = item.IndexNumber;
  669. dto.IsFolder = item.IsFolder;
  670. dto.MediaType = item.MediaType;
  671. dto.LocationType = item.LocationType;
  672. var hasLang = item as IHasPreferredMetadataLanguage;
  673. if (hasLang != null)
  674. {
  675. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  676. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  677. }
  678. var hasCriticRating = item as IHasCriticRating;
  679. if (hasCriticRating != null)
  680. {
  681. dto.CriticRating = hasCriticRating.CriticRating;
  682. if (fields.Contains(ItemFields.CriticRatingSummary))
  683. {
  684. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  685. }
  686. }
  687. var hasTrailers = item as IHasTrailers;
  688. if (hasTrailers != null)
  689. {
  690. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  691. }
  692. var hasDisplayOrder = item as IHasDisplayOrder;
  693. if (hasDisplayOrder != null)
  694. {
  695. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  696. }
  697. var collectionFolder = item as CollectionFolder;
  698. if (collectionFolder != null)
  699. {
  700. dto.CollectionType = collectionFolder.CollectionType;
  701. }
  702. if (fields.Contains(ItemFields.RemoteTrailers))
  703. {
  704. dto.RemoteTrailers = hasTrailers != null ?
  705. hasTrailers.RemoteTrailers :
  706. new List<MediaUrl>();
  707. }
  708. dto.Name = item.Name;
  709. dto.OfficialRating = item.OfficialRating;
  710. var hasOverview = fields.Contains(ItemFields.Overview);
  711. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  712. if (hasOverview || hasHtmlOverview)
  713. {
  714. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  715. if (hasOverview)
  716. {
  717. dto.Overview = strippedOverview;
  718. }
  719. // Only supply the html version if there was actually html content
  720. if (hasHtmlOverview)
  721. {
  722. dto.OverviewHtml = item.Overview;
  723. }
  724. }
  725. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  726. if (dto.BackdropImageTags.Count == 0)
  727. {
  728. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  729. if (parentWithBackdrop != null)
  730. {
  731. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  732. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  733. }
  734. }
  735. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  736. {
  737. dto.ParentId = GetDtoId(item.Parent);
  738. }
  739. dto.ParentIndexNumber = item.ParentIndexNumber;
  740. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  741. if (!dto.HasLogo)
  742. {
  743. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  744. if (parentWithLogo != null)
  745. {
  746. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  747. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  748. }
  749. }
  750. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  751. if (!dto.HasArtImage)
  752. {
  753. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  754. if (parentWithImage != null)
  755. {
  756. dto.ParentArtItemId = GetDtoId(parentWithImage);
  757. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  758. }
  759. }
  760. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  761. if (!dto.HasThumb)
  762. {
  763. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  764. if (parentWithImage != null)
  765. {
  766. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  767. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  768. }
  769. }
  770. if (fields.Contains(ItemFields.Path))
  771. {
  772. var locationType = item.LocationType;
  773. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  774. {
  775. dto.Path = GetMappedPath(item.Path);
  776. }
  777. else
  778. {
  779. dto.Path = item.Path;
  780. }
  781. }
  782. dto.PremiereDate = item.PremiereDate;
  783. dto.ProductionYear = item.ProductionYear;
  784. if (fields.Contains(ItemFields.ProviderIds))
  785. {
  786. dto.ProviderIds = item.ProviderIds;
  787. }
  788. dto.RunTimeTicks = item.RunTimeTicks;
  789. if (fields.Contains(ItemFields.SortName))
  790. {
  791. dto.SortName = item.SortName;
  792. }
  793. if (fields.Contains(ItemFields.CustomRating))
  794. {
  795. dto.CustomRating = item.CustomRating;
  796. }
  797. if (fields.Contains(ItemFields.Taglines))
  798. {
  799. var hasTagline = item as IHasTaglines;
  800. if (hasTagline != null)
  801. {
  802. dto.Taglines = hasTagline.Taglines;
  803. }
  804. if (dto.Taglines == null)
  805. {
  806. dto.Taglines = new List<string>();
  807. }
  808. }
  809. dto.Type = item.GetClientTypeName();
  810. dto.CommunityRating = item.CommunityRating;
  811. dto.VoteCount = item.VoteCount;
  812. if (item.IsFolder)
  813. {
  814. var folder = (Folder)item;
  815. if (fields.Contains(ItemFields.IndexOptions))
  816. {
  817. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  818. }
  819. }
  820. // Add audio info
  821. var audio = item as Audio;
  822. if (audio != null)
  823. {
  824. dto.Album = audio.Album;
  825. dto.Artists = audio.Artists;
  826. var albumParent = audio.FindParent<MusicAlbum>();
  827. if (albumParent != null)
  828. {
  829. dto.AlbumId = GetDtoId(albumParent);
  830. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  831. }
  832. }
  833. var album = item as MusicAlbum;
  834. if (album != null)
  835. {
  836. dto.Artists = album.Artists;
  837. dto.SoundtrackIds = album.SoundtrackIds
  838. .Select(i => i.ToString("N"))
  839. .ToArray();
  840. }
  841. var hasAlbumArtist = item as IHasAlbumArtist;
  842. if (hasAlbumArtist != null)
  843. {
  844. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  845. }
  846. // Add video info
  847. var video = item as Video;
  848. if (video != null)
  849. {
  850. dto.VideoType = video.VideoType;
  851. dto.Video3DFormat = video.Video3DFormat;
  852. dto.IsoType = video.IsoType;
  853. dto.IsHD = video.IsHD;
  854. dto.PartCount = video.AdditionalPartIds.Count + 1;
  855. if (fields.Contains(ItemFields.Chapters))
  856. {
  857. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  858. }
  859. }
  860. if (fields.Contains(ItemFields.MediaStreams))
  861. {
  862. // Add VideoInfo
  863. var iHasMediaStreams = item as IHasMediaStreams;
  864. if (iHasMediaStreams != null)
  865. {
  866. dto.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  867. {
  868. ItemId = item.Id
  869. }).ToList();
  870. }
  871. }
  872. // Add MovieInfo
  873. var movie = item as Movie;
  874. if (movie != null)
  875. {
  876. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  877. if (specialFeatureCount > 0)
  878. {
  879. dto.SpecialFeatureCount = specialFeatureCount;
  880. }
  881. if (fields.Contains(ItemFields.TmdbCollectionName))
  882. {
  883. dto.TmdbCollectionName = movie.TmdbCollectionName;
  884. }
  885. }
  886. // Add EpisodeInfo
  887. var episode = item as Episode;
  888. if (episode != null)
  889. {
  890. dto.IndexNumberEnd = episode.IndexNumberEnd;
  891. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  892. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  893. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  894. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  895. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  896. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  897. var seasonId = episode.SeasonId;
  898. if (seasonId.HasValue)
  899. {
  900. dto.SeasonId = seasonId.Value.ToString("N");
  901. }
  902. }
  903. // Add SeriesInfo
  904. var series = item as Series;
  905. if (series != null)
  906. {
  907. dto.AirDays = series.AirDays;
  908. dto.AirTime = series.AirTime;
  909. dto.Status = series.Status;
  910. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  911. dto.SeasonCount = series.SeasonCount;
  912. if (fields.Contains(ItemFields.Settings))
  913. {
  914. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  915. }
  916. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  917. }
  918. if (episode != null)
  919. {
  920. series = item.FindParent<Series>();
  921. dto.SeriesId = GetDtoId(series);
  922. dto.SeriesName = series.Name;
  923. dto.AirTime = series.AirTime;
  924. dto.SeriesStudio = series.Studios.FirstOrDefault();
  925. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  926. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  927. }
  928. // Add SeasonInfo
  929. var season = item as Season;
  930. if (season != null)
  931. {
  932. series = item.FindParent<Series>();
  933. dto.SeriesId = GetDtoId(series);
  934. dto.SeriesName = series.Name;
  935. dto.AirTime = series.AirTime;
  936. dto.SeriesStudio = series.Studios.FirstOrDefault();
  937. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  938. }
  939. var game = item as Game;
  940. if (game != null)
  941. {
  942. SetGameProperties(dto, game);
  943. }
  944. var gameSystem = item as GameSystem;
  945. if (gameSystem != null)
  946. {
  947. SetGameSystemProperties(dto, gameSystem);
  948. }
  949. var musicVideo = item as MusicVideo;
  950. if (musicVideo != null)
  951. {
  952. SetMusicVideoProperties(dto, musicVideo);
  953. }
  954. var book = item as Book;
  955. if (book != null)
  956. {
  957. SetBookProperties(dto, book);
  958. }
  959. }
  960. private string GetMappedPath(string path)
  961. {
  962. foreach (var map in _config.Configuration.PathSubstitutions)
  963. {
  964. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  965. }
  966. return path;
  967. }
  968. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  969. {
  970. var hasProductionLocations = item as IHasProductionLocations;
  971. if (hasProductionLocations != null)
  972. {
  973. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  974. }
  975. var person = item as Person;
  976. if (person != null)
  977. {
  978. dto.ProductionLocations = new List<string>();
  979. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  980. {
  981. dto.ProductionLocations.Add(person.PlaceOfBirth);
  982. }
  983. }
  984. if (dto.ProductionLocations == null)
  985. {
  986. dto.ProductionLocations = new List<string>();
  987. }
  988. }
  989. /// <summary>
  990. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  991. /// </summary>
  992. /// <param name="folder">The folder.</param>
  993. /// <param name="user">The user.</param>
  994. /// <param name="dto">The dto.</param>
  995. /// <param name="fields">The fields.</param>
  996. /// <returns>Task.</returns>
  997. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  998. {
  999. var rcentlyAddedItemCount = 0;
  1000. var recursiveItemCount = 0;
  1001. var unplayed = 0;
  1002. long runtime = 0;
  1003. DateTime? dateLastMediaAdded = null;
  1004. double totalPercentPlayed = 0;
  1005. IEnumerable<BaseItem> children;
  1006. var season = folder as Season;
  1007. if (season != null)
  1008. {
  1009. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1010. }
  1011. else
  1012. {
  1013. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1014. }
  1015. // Loop through each recursive child
  1016. foreach (var child in children)
  1017. {
  1018. if (!dateLastMediaAdded.HasValue)
  1019. {
  1020. dateLastMediaAdded = child.DateCreated;
  1021. }
  1022. else
  1023. {
  1024. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1025. }
  1026. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1027. recursiveItemCount++;
  1028. // Check is recently added
  1029. if (child.IsRecentlyAdded())
  1030. {
  1031. rcentlyAddedItemCount++;
  1032. }
  1033. var isUnplayed = true;
  1034. // Incrememt totalPercentPlayed
  1035. if (userdata != null)
  1036. {
  1037. if (userdata.Played)
  1038. {
  1039. totalPercentPlayed += 100;
  1040. isUnplayed = false;
  1041. }
  1042. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1043. {
  1044. double itemPercent = userdata.PlaybackPositionTicks;
  1045. itemPercent /= child.RunTimeTicks.Value;
  1046. totalPercentPlayed += itemPercent;
  1047. }
  1048. }
  1049. if (isUnplayed)
  1050. {
  1051. unplayed++;
  1052. }
  1053. runtime += child.RunTimeTicks ?? 0;
  1054. }
  1055. dto.RecursiveItemCount = recursiveItemCount;
  1056. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  1057. dto.RecursiveUnplayedItemCount = unplayed;
  1058. if (recursiveItemCount > 0)
  1059. {
  1060. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1061. }
  1062. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1063. {
  1064. dto.CumulativeRunTimeTicks = runtime;
  1065. }
  1066. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1067. {
  1068. dto.DateLastMediaAdded = dateLastMediaAdded;
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// Attaches the primary image aspect ratio.
  1073. /// </summary>
  1074. /// <param name="dto">The dto.</param>
  1075. /// <param name="item">The item.</param>
  1076. /// <returns>Task.</returns>
  1077. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1078. {
  1079. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1080. if (imageInfo == null)
  1081. {
  1082. return;
  1083. }
  1084. var path = imageInfo.Path;
  1085. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1086. var dateModified = imageInfo.DateModified;
  1087. ImageSize size;
  1088. try
  1089. {
  1090. size = _imageProcessor.GetImageSize(path, dateModified);
  1091. }
  1092. catch (FileNotFoundException)
  1093. {
  1094. _logger.Error("Image file does not exist: {0}", path);
  1095. return;
  1096. }
  1097. catch (Exception ex)
  1098. {
  1099. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1100. return;
  1101. }
  1102. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1103. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1104. foreach (var enhancer in supportedEnhancers)
  1105. {
  1106. try
  1107. {
  1108. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1109. }
  1110. catch (Exception ex)
  1111. {
  1112. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1113. }
  1114. }
  1115. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1116. }
  1117. }
  1118. }