DtoService.cs 45 KB

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