DtoService.cs 44 KB

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