DtoService.cs 51 KB

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