DtoService.cs 44 KB

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