DtoService.cs 46 KB

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