DtoService.cs 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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. dto.ForcedSortName = item.ForcedSortName;
  637. }
  638. var hasBudget = item as IHasBudget;
  639. if (hasBudget != null)
  640. {
  641. if (fields.Contains(ItemFields.Budget))
  642. {
  643. dto.Budget = hasBudget.Budget;
  644. }
  645. if (fields.Contains(ItemFields.Revenue))
  646. {
  647. dto.Revenue = hasBudget.Revenue;
  648. }
  649. }
  650. dto.EndDate = item.EndDate;
  651. if (fields.Contains(ItemFields.HomePageUrl))
  652. {
  653. dto.HomePageUrl = item.HomePageUrl;
  654. }
  655. if (fields.Contains(ItemFields.ExternalUrls))
  656. {
  657. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  658. }
  659. if (fields.Contains(ItemFields.Tags))
  660. {
  661. var hasTags = item as IHasTags;
  662. if (hasTags != null)
  663. {
  664. dto.Tags = hasTags.Tags;
  665. }
  666. if (dto.Tags == null)
  667. {
  668. dto.Tags = new List<string>();
  669. }
  670. }
  671. if (fields.Contains(ItemFields.Keywords))
  672. {
  673. var hasTags = item as IHasKeywords;
  674. if (hasTags != null)
  675. {
  676. dto.Keywords = hasTags.Keywords;
  677. }
  678. if (dto.Keywords == null)
  679. {
  680. dto.Keywords = new List<string>();
  681. }
  682. }
  683. if (fields.Contains(ItemFields.ProductionLocations))
  684. {
  685. SetProductionLocations(item, dto);
  686. }
  687. var hasAspectRatio = item as IHasAspectRatio;
  688. if (hasAspectRatio != null)
  689. {
  690. dto.AspectRatio = hasAspectRatio.AspectRatio;
  691. }
  692. var hasMetascore = item as IHasMetascore;
  693. if (hasMetascore != null)
  694. {
  695. dto.Metascore = hasMetascore.Metascore;
  696. }
  697. if (fields.Contains(ItemFields.AwardSummary))
  698. {
  699. var hasAwards = item as IHasAwards;
  700. if (hasAwards != null)
  701. {
  702. dto.AwardSummary = hasAwards.AwardSummary;
  703. }
  704. }
  705. dto.BackdropImageTags = GetBackdropImageTags(item);
  706. if (fields.Contains(ItemFields.ScreenshotImageTags))
  707. {
  708. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  709. }
  710. if (fields.Contains(ItemFields.Genres))
  711. {
  712. dto.Genres = item.Genres;
  713. }
  714. dto.ImageTags = new Dictionary<ImageType, Guid>();
  715. // Prevent implicitly captured closure
  716. var currentItem = item;
  717. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  718. {
  719. var tag = GetImageCacheTag(item, image);
  720. if (tag.HasValue)
  721. {
  722. dto.ImageTags[image.Type] = tag.Value;
  723. }
  724. }
  725. dto.Id = GetDtoId(item);
  726. dto.IndexNumber = item.IndexNumber;
  727. dto.IsFolder = item.IsFolder;
  728. dto.MediaType = item.MediaType;
  729. dto.LocationType = item.LocationType;
  730. var hasLang = item as IHasPreferredMetadataLanguage;
  731. if (hasLang != null)
  732. {
  733. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  734. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  735. }
  736. var hasCriticRating = item as IHasCriticRating;
  737. if (hasCriticRating != null)
  738. {
  739. dto.CriticRating = hasCriticRating.CriticRating;
  740. if (fields.Contains(ItemFields.CriticRatingSummary))
  741. {
  742. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  743. }
  744. }
  745. var hasTrailers = item as IHasTrailers;
  746. if (hasTrailers != null)
  747. {
  748. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  749. }
  750. var hasDisplayOrder = item as IHasDisplayOrder;
  751. if (hasDisplayOrder != null)
  752. {
  753. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  754. }
  755. var collectionFolder = item as CollectionFolder;
  756. if (collectionFolder != null)
  757. {
  758. dto.CollectionType = collectionFolder.CollectionType;
  759. }
  760. if (fields.Contains(ItemFields.RemoteTrailers))
  761. {
  762. dto.RemoteTrailers = hasTrailers != null ?
  763. hasTrailers.RemoteTrailers :
  764. new List<MediaUrl>();
  765. }
  766. dto.Name = item.Name;
  767. dto.OfficialRating = item.OfficialRating;
  768. var hasOverview = fields.Contains(ItemFields.Overview);
  769. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  770. if (hasOverview || hasHtmlOverview)
  771. {
  772. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  773. if (hasOverview)
  774. {
  775. dto.Overview = strippedOverview;
  776. }
  777. // Only supply the html version if there was actually html content
  778. if (hasHtmlOverview)
  779. {
  780. dto.OverviewHtml = item.Overview;
  781. }
  782. }
  783. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  784. if (dto.BackdropImageTags.Count == 0)
  785. {
  786. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  787. if (parentWithBackdrop != null)
  788. {
  789. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  790. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  791. }
  792. }
  793. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  794. {
  795. dto.ParentId = GetDtoId(item.Parent);
  796. }
  797. dto.ParentIndexNumber = item.ParentIndexNumber;
  798. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  799. if (!dto.HasLogo)
  800. {
  801. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  802. if (parentWithLogo != null)
  803. {
  804. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  805. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  806. }
  807. }
  808. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  809. if (!dto.HasArtImage)
  810. {
  811. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  812. if (parentWithImage != null)
  813. {
  814. dto.ParentArtItemId = GetDtoId(parentWithImage);
  815. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  816. }
  817. }
  818. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  819. if (!dto.HasThumb)
  820. {
  821. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  822. if (parentWithImage != null)
  823. {
  824. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  825. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  826. }
  827. }
  828. if (fields.Contains(ItemFields.Path))
  829. {
  830. var locationType = item.LocationType;
  831. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  832. {
  833. dto.Path = GetMappedPath(item.Path);
  834. }
  835. else
  836. {
  837. dto.Path = item.Path;
  838. }
  839. }
  840. dto.PremiereDate = item.PremiereDate;
  841. dto.ProductionYear = item.ProductionYear;
  842. if (fields.Contains(ItemFields.ProviderIds))
  843. {
  844. dto.ProviderIds = item.ProviderIds;
  845. }
  846. dto.RunTimeTicks = item.RunTimeTicks;
  847. if (fields.Contains(ItemFields.SortName))
  848. {
  849. dto.SortName = item.SortName;
  850. }
  851. if (fields.Contains(ItemFields.CustomRating))
  852. {
  853. dto.CustomRating = item.CustomRating;
  854. }
  855. if (fields.Contains(ItemFields.Taglines))
  856. {
  857. var hasTagline = item as IHasTaglines;
  858. if (hasTagline != null)
  859. {
  860. dto.Taglines = hasTagline.Taglines;
  861. }
  862. if (dto.Taglines == null)
  863. {
  864. dto.Taglines = new List<string>();
  865. }
  866. }
  867. dto.Type = item.GetClientTypeName();
  868. dto.CommunityRating = item.CommunityRating;
  869. dto.VoteCount = item.VoteCount;
  870. if (item.IsFolder)
  871. {
  872. var folder = (Folder)item;
  873. if (fields.Contains(ItemFields.IndexOptions))
  874. {
  875. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  876. }
  877. }
  878. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  879. if (supportsPlaceHolders != null)
  880. {
  881. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  882. }
  883. // Add audio info
  884. var audio = item as Audio;
  885. if (audio != null)
  886. {
  887. dto.Album = audio.Album;
  888. dto.Artists = audio.Artists;
  889. var albumParent = audio.FindParent<MusicAlbum>();
  890. if (albumParent != null)
  891. {
  892. dto.AlbumId = GetDtoId(albumParent);
  893. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  894. }
  895. dto.MediaSources = GetMediaSources(audio);
  896. dto.MediaSourceCount = 1;
  897. }
  898. var album = item as MusicAlbum;
  899. if (album != null)
  900. {
  901. dto.Artists = album.Artists;
  902. dto.SoundtrackIds = album.SoundtrackIds
  903. .Select(i => i.ToString("N"))
  904. .ToArray();
  905. }
  906. var hasAlbumArtist = item as IHasAlbumArtist;
  907. if (hasAlbumArtist != null)
  908. {
  909. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  910. }
  911. // Add video info
  912. var video = item as Video;
  913. if (video != null)
  914. {
  915. dto.VideoType = video.VideoType;
  916. dto.Video3DFormat = video.Video3DFormat;
  917. dto.IsoType = video.IsoType;
  918. dto.IsHD = video.IsHD;
  919. dto.PartCount = video.AdditionalPartIds.Count + 1;
  920. dto.MediaSourceCount = video.MediaSourceCount;
  921. if (fields.Contains(ItemFields.MediaSources))
  922. {
  923. dto.MediaSources = GetMediaSources(video);
  924. }
  925. if (fields.Contains(ItemFields.Chapters))
  926. {
  927. List<ChapterInfoDto> chapters;
  928. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  929. {
  930. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  931. }
  932. else
  933. {
  934. chapters = _itemRepo.GetChapters(video.Id)
  935. .Select(c => GetChapterInfoDto(c, item))
  936. .ToList();
  937. }
  938. dto.Chapters = chapters;
  939. }
  940. }
  941. if (fields.Contains(ItemFields.MediaStreams))
  942. {
  943. // Add VideoInfo
  944. var iHasMediaStreams = item as IHasMediaStreams;
  945. if (iHasMediaStreams != null)
  946. {
  947. List<MediaStream> mediaStreams;
  948. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  949. {
  950. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  951. .SelectMany(i => i.MediaStreams)
  952. .ToList();
  953. }
  954. else
  955. {
  956. mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  957. {
  958. ItemId = item.Id
  959. }).ToList();
  960. }
  961. dto.MediaStreams = mediaStreams;
  962. }
  963. }
  964. // Add MovieInfo
  965. var movie = item as Movie;
  966. if (movie != null)
  967. {
  968. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  969. if (specialFeatureCount > 0)
  970. {
  971. dto.SpecialFeatureCount = specialFeatureCount;
  972. }
  973. if (fields.Contains(ItemFields.TmdbCollectionName))
  974. {
  975. dto.TmdbCollectionName = movie.TmdbCollectionName;
  976. }
  977. }
  978. // Add EpisodeInfo
  979. var episode = item as Episode;
  980. if (episode != null)
  981. {
  982. dto.IndexNumberEnd = episode.IndexNumberEnd;
  983. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  984. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  985. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  986. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  987. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  988. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  989. var seasonId = episode.SeasonId;
  990. if (seasonId.HasValue)
  991. {
  992. dto.SeasonId = seasonId.Value.ToString("N");
  993. }
  994. }
  995. // Add SeriesInfo
  996. var series = item as Series;
  997. if (series != null)
  998. {
  999. dto.AirDays = series.AirDays;
  1000. dto.AirTime = series.AirTime;
  1001. dto.Status = series.Status;
  1002. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  1003. dto.SeasonCount = series.SeasonCount;
  1004. if (fields.Contains(ItemFields.Settings))
  1005. {
  1006. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  1007. }
  1008. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  1009. }
  1010. if (episode != null)
  1011. {
  1012. series = item.FindParent<Series>();
  1013. dto.SeriesId = GetDtoId(series);
  1014. dto.SeriesName = series.Name;
  1015. dto.AirTime = series.AirTime;
  1016. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1017. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  1018. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1019. }
  1020. // Add SeasonInfo
  1021. var season = item as Season;
  1022. if (season != null)
  1023. {
  1024. series = item.FindParent<Series>();
  1025. dto.SeriesId = GetDtoId(series);
  1026. dto.SeriesName = series.Name;
  1027. dto.AirTime = series.AirTime;
  1028. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1029. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1030. }
  1031. var game = item as Game;
  1032. if (game != null)
  1033. {
  1034. SetGameProperties(dto, game);
  1035. }
  1036. var gameSystem = item as GameSystem;
  1037. if (gameSystem != null)
  1038. {
  1039. SetGameSystemProperties(dto, gameSystem);
  1040. }
  1041. var musicVideo = item as MusicVideo;
  1042. if (musicVideo != null)
  1043. {
  1044. SetMusicVideoProperties(dto, musicVideo);
  1045. }
  1046. var book = item as Book;
  1047. if (book != null)
  1048. {
  1049. SetBookProperties(dto, book);
  1050. }
  1051. }
  1052. private List<MediaSourceInfo> GetMediaSources(Video item)
  1053. {
  1054. var result = item.GetAlternateVersions().Select(GetVersionInfo).ToList();
  1055. result.Add(GetVersionInfo(item));
  1056. return result.OrderBy(i =>
  1057. {
  1058. if (item.VideoType == VideoType.VideoFile)
  1059. {
  1060. return 0;
  1061. }
  1062. return 1;
  1063. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  1064. .ThenByDescending(i =>
  1065. {
  1066. var stream = i.MediaStreams.FirstOrDefault(m => m.Type == MediaStreamType.Video);
  1067. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  1068. })
  1069. .ToList();
  1070. }
  1071. private List<MediaSourceInfo> GetMediaSources(Audio item)
  1072. {
  1073. var result = new List<MediaSourceInfo>
  1074. {
  1075. GetVersionInfo(item)
  1076. };
  1077. return result;
  1078. }
  1079. private MediaSourceInfo GetVersionInfo(Video i)
  1080. {
  1081. var mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery { ItemId = i.Id }).ToList();
  1082. return new MediaSourceInfo
  1083. {
  1084. Id = i.Id.ToString("N"),
  1085. IsoType = i.IsoType,
  1086. LocationType = i.LocationType,
  1087. MediaStreams = mediaStreams,
  1088. Name = GetMediaSourceName(i, mediaStreams),
  1089. Path = GetMappedPath(i),
  1090. RunTimeTicks = i.RunTimeTicks,
  1091. Video3DFormat = i.Video3DFormat,
  1092. VideoType = i.VideoType
  1093. };
  1094. }
  1095. private MediaSourceInfo GetVersionInfo(Audio i)
  1096. {
  1097. return new MediaSourceInfo
  1098. {
  1099. Id = i.Id.ToString("N"),
  1100. LocationType = i.LocationType,
  1101. MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery { ItemId = i.Id }).ToList(),
  1102. Name = i.Name,
  1103. Path = GetMappedPath(i),
  1104. RunTimeTicks = i.RunTimeTicks
  1105. };
  1106. }
  1107. private string GetMappedPath(IHasMetadata item)
  1108. {
  1109. var path = item.Path;
  1110. var locationType = item.LocationType;
  1111. if (locationType != LocationType.FileSystem && locationType != LocationType.Offline)
  1112. {
  1113. return path;
  1114. }
  1115. foreach (var map in _config.Configuration.PathSubstitutions)
  1116. {
  1117. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1118. }
  1119. return path;
  1120. }
  1121. private string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  1122. {
  1123. var terms = new List<string>();
  1124. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  1125. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  1126. if (video.Video3DFormat.HasValue)
  1127. {
  1128. terms.Add("3D");
  1129. }
  1130. if (video.VideoType == VideoType.BluRay)
  1131. {
  1132. terms.Add("Bluray");
  1133. }
  1134. else if (video.VideoType == VideoType.Dvd)
  1135. {
  1136. terms.Add("DVD");
  1137. }
  1138. else if (video.VideoType == VideoType.HdDvd)
  1139. {
  1140. terms.Add("HD-DVD");
  1141. }
  1142. else if (video.VideoType == VideoType.Iso)
  1143. {
  1144. if (video.IsoType.HasValue)
  1145. {
  1146. if (video.IsoType.Value == IsoType.BluRay)
  1147. {
  1148. terms.Add("Bluray");
  1149. }
  1150. else if (video.IsoType.Value == IsoType.Dvd)
  1151. {
  1152. terms.Add("DVD");
  1153. }
  1154. }
  1155. else
  1156. {
  1157. terms.Add("ISO");
  1158. }
  1159. }
  1160. if (videoStream != null)
  1161. {
  1162. if (videoStream.Width.HasValue)
  1163. {
  1164. if (videoStream.Width.Value >= 3800)
  1165. {
  1166. terms.Add("4K");
  1167. }
  1168. else if (videoStream.Width.Value >= 1900)
  1169. {
  1170. terms.Add("1080P");
  1171. }
  1172. else if (videoStream.Width.Value >= 1270)
  1173. {
  1174. terms.Add("720P");
  1175. }
  1176. else if (videoStream.Width.Value >= 700)
  1177. {
  1178. terms.Add("480P");
  1179. }
  1180. else
  1181. {
  1182. terms.Add("SD");
  1183. }
  1184. }
  1185. }
  1186. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  1187. {
  1188. terms.Add(videoStream.Codec.ToUpper());
  1189. }
  1190. if (audioStream != null)
  1191. {
  1192. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  1193. ? audioStream.Profile
  1194. : audioStream.Codec;
  1195. if (!string.IsNullOrEmpty(audioCodec))
  1196. {
  1197. terms.Add(audioCodec.ToUpper());
  1198. }
  1199. }
  1200. return string.Join("/", terms.ToArray());
  1201. }
  1202. private string GetMappedPath(string path)
  1203. {
  1204. foreach (var map in _config.Configuration.PathSubstitutions)
  1205. {
  1206. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1207. }
  1208. return path;
  1209. }
  1210. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1211. {
  1212. var hasProductionLocations = item as IHasProductionLocations;
  1213. if (hasProductionLocations != null)
  1214. {
  1215. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1216. }
  1217. var person = item as Person;
  1218. if (person != null)
  1219. {
  1220. dto.ProductionLocations = new List<string>();
  1221. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1222. {
  1223. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1224. }
  1225. }
  1226. if (dto.ProductionLocations == null)
  1227. {
  1228. dto.ProductionLocations = new List<string>();
  1229. }
  1230. }
  1231. /// <summary>
  1232. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1233. /// </summary>
  1234. /// <param name="folder">The folder.</param>
  1235. /// <param name="user">The user.</param>
  1236. /// <param name="dto">The dto.</param>
  1237. /// <param name="fields">The fields.</param>
  1238. /// <returns>Task.</returns>
  1239. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1240. {
  1241. var rcentlyAddedItemCount = 0;
  1242. var recursiveItemCount = 0;
  1243. var unplayed = 0;
  1244. long runtime = 0;
  1245. DateTime? dateLastMediaAdded = null;
  1246. double totalPercentPlayed = 0;
  1247. IEnumerable<BaseItem> children;
  1248. var season = folder as Season;
  1249. if (season != null)
  1250. {
  1251. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1252. }
  1253. else
  1254. {
  1255. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1256. }
  1257. // Loop through each recursive child
  1258. foreach (var child in children)
  1259. {
  1260. if (!dateLastMediaAdded.HasValue)
  1261. {
  1262. dateLastMediaAdded = child.DateCreated;
  1263. }
  1264. else
  1265. {
  1266. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1267. }
  1268. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1269. recursiveItemCount++;
  1270. // Check is recently added
  1271. if (child.IsRecentlyAdded())
  1272. {
  1273. rcentlyAddedItemCount++;
  1274. }
  1275. var isUnplayed = true;
  1276. // Incrememt totalPercentPlayed
  1277. if (userdata != null)
  1278. {
  1279. if (userdata.Played)
  1280. {
  1281. totalPercentPlayed += 100;
  1282. isUnplayed = false;
  1283. }
  1284. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1285. {
  1286. double itemPercent = userdata.PlaybackPositionTicks;
  1287. itemPercent /= child.RunTimeTicks.Value;
  1288. totalPercentPlayed += itemPercent;
  1289. }
  1290. }
  1291. if (isUnplayed)
  1292. {
  1293. unplayed++;
  1294. }
  1295. runtime += child.RunTimeTicks ?? 0;
  1296. }
  1297. dto.RecursiveItemCount = recursiveItemCount;
  1298. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  1299. dto.RecursiveUnplayedItemCount = unplayed;
  1300. if (recursiveItemCount > 0)
  1301. {
  1302. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1303. }
  1304. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1305. {
  1306. dto.CumulativeRunTimeTicks = runtime;
  1307. }
  1308. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1309. {
  1310. dto.DateLastMediaAdded = dateLastMediaAdded;
  1311. }
  1312. }
  1313. /// <summary>
  1314. /// Attaches the primary image aspect ratio.
  1315. /// </summary>
  1316. /// <param name="dto">The dto.</param>
  1317. /// <param name="item">The item.</param>
  1318. /// <returns>Task.</returns>
  1319. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1320. {
  1321. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1322. if (imageInfo == null)
  1323. {
  1324. return;
  1325. }
  1326. var path = imageInfo.Path;
  1327. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1328. var dateModified = imageInfo.DateModified;
  1329. ImageSize size;
  1330. try
  1331. {
  1332. size = _imageProcessor.GetImageSize(path, dateModified);
  1333. }
  1334. catch (FileNotFoundException)
  1335. {
  1336. _logger.Error("Image file does not exist: {0}", path);
  1337. return;
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1342. return;
  1343. }
  1344. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1345. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1346. foreach (var enhancer in supportedEnhancers)
  1347. {
  1348. try
  1349. {
  1350. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1351. }
  1352. catch (Exception ex)
  1353. {
  1354. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1355. }
  1356. }
  1357. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1358. }
  1359. }
  1360. }