DtoService.cs 53 KB

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