DtoService.cs 51 KB

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