DtoService.cs 53 KB

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