DtoService.cs 46 KB

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