DtoService.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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 = GetMediaSources(tvChannel);
  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. public List<MediaSourceInfo> GetMediaSources(BaseItem item)
  932. {
  933. var video = item as Video;
  934. if (video != null)
  935. {
  936. return video.GetMediaSources(true).ToList();
  937. }
  938. var audio = item as Audio;
  939. if (audio != null)
  940. {
  941. return audio.GetMediaSources(true).ToList();
  942. }
  943. var result = new List<MediaSourceInfo>
  944. {
  945. new MediaSourceInfo
  946. {
  947. Id = item.Id.ToString("N"),
  948. LocationType = item.LocationType,
  949. Name = item.Name,
  950. Path = GetMappedPath(item),
  951. MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  952. {
  953. ItemId = item.Id
  954. }).ToList(),
  955. RunTimeTicks = item.RunTimeTicks
  956. }
  957. };
  958. return result;
  959. }
  960. private string GetMappedPath(IHasMetadata item)
  961. {
  962. var path = item.Path;
  963. var locationType = item.LocationType;
  964. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  965. {
  966. foreach (var map in _config.Configuration.PathSubstitutions)
  967. {
  968. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  969. }
  970. }
  971. return path;
  972. }
  973. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  974. {
  975. var hasProductionLocations = item as IHasProductionLocations;
  976. if (hasProductionLocations != null)
  977. {
  978. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  979. }
  980. var person = item as Person;
  981. if (person != null)
  982. {
  983. dto.ProductionLocations = new List<string>();
  984. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  985. {
  986. dto.ProductionLocations.Add(person.PlaceOfBirth);
  987. }
  988. }
  989. if (dto.ProductionLocations == null)
  990. {
  991. dto.ProductionLocations = new List<string>();
  992. }
  993. }
  994. /// <summary>
  995. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  996. /// </summary>
  997. /// <param name="folder">The folder.</param>
  998. /// <param name="user">The user.</param>
  999. /// <param name="dto">The dto.</param>
  1000. /// <param name="fields">The fields.</param>
  1001. /// <returns>Task.</returns>
  1002. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1003. {
  1004. var recursiveItemCount = 0;
  1005. var unplayed = 0;
  1006. long runtime = 0;
  1007. DateTime? dateLastMediaAdded = null;
  1008. double totalPercentPlayed = 0;
  1009. IEnumerable<BaseItem> children;
  1010. var season = folder as Season;
  1011. if (season != null)
  1012. {
  1013. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1014. }
  1015. else
  1016. {
  1017. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1018. }
  1019. // Loop through each recursive child
  1020. foreach (var child in children)
  1021. {
  1022. if (!dateLastMediaAdded.HasValue)
  1023. {
  1024. dateLastMediaAdded = child.DateCreated;
  1025. }
  1026. else
  1027. {
  1028. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1029. }
  1030. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1031. recursiveItemCount++;
  1032. var isUnplayed = true;
  1033. // Incrememt totalPercentPlayed
  1034. if (userdata != null)
  1035. {
  1036. if (userdata.Played)
  1037. {
  1038. totalPercentPlayed += 100;
  1039. isUnplayed = false;
  1040. }
  1041. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1042. {
  1043. double itemPercent = userdata.PlaybackPositionTicks;
  1044. itemPercent /= child.RunTimeTicks.Value;
  1045. totalPercentPlayed += itemPercent;
  1046. }
  1047. }
  1048. if (isUnplayed)
  1049. {
  1050. unplayed++;
  1051. }
  1052. runtime += child.RunTimeTicks ?? 0;
  1053. }
  1054. dto.RecursiveItemCount = recursiveItemCount;
  1055. dto.RecursiveUnplayedItemCount = unplayed;
  1056. if (recursiveItemCount > 0)
  1057. {
  1058. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1059. }
  1060. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1061. {
  1062. dto.CumulativeRunTimeTicks = runtime;
  1063. }
  1064. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1065. {
  1066. dto.DateLastMediaAdded = dateLastMediaAdded;
  1067. }
  1068. }
  1069. /// <summary>
  1070. /// Attaches the primary image aspect ratio.
  1071. /// </summary>
  1072. /// <param name="dto">The dto.</param>
  1073. /// <param name="item">The item.</param>
  1074. /// <returns>Task.</returns>
  1075. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1076. {
  1077. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1078. if (imageInfo == null)
  1079. {
  1080. return;
  1081. }
  1082. var path = imageInfo.Path;
  1083. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1084. var dateModified = imageInfo.DateModified;
  1085. ImageSize size;
  1086. try
  1087. {
  1088. size = _imageProcessor.GetImageSize(path, dateModified);
  1089. }
  1090. catch (FileNotFoundException)
  1091. {
  1092. _logger.Error("Image file does not exist: {0}", path);
  1093. return;
  1094. }
  1095. catch (Exception ex)
  1096. {
  1097. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1098. return;
  1099. }
  1100. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1101. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1102. foreach (var enhancer in supportedEnhancers)
  1103. {
  1104. try
  1105. {
  1106. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1111. }
  1112. }
  1113. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1114. }
  1115. }
  1116. }