DtoService.cs 51 KB

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