DtoService.cs 52 KB

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