DtoService.cs 45 KB

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