DtoService.cs 43 KB

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