DtoService.cs 51 KB

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