DtoService.cs 45 KB

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