DtoService.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Entities.Movies;
  10. using MediaBrowser.Controller.Entities.TV;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Drawing;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Querying;
  20. using 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. private readonly Func<IChannelManager> _channelManagerFactory;
  39. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func<IChannelManager> channelManagerFactory)
  40. {
  41. _logger = logger;
  42. _libraryManager = libraryManager;
  43. _userManager = userManager;
  44. _userDataRepository = userDataRepository;
  45. _itemRepo = itemRepo;
  46. _imageProcessor = imageProcessor;
  47. _config = config;
  48. _fileSystem = fileSystem;
  49. _providerManager = providerManager;
  50. _channelManagerFactory = channelManagerFactory;
  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. if (fields.Contains(ItemFields.Overview))
  657. {
  658. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  659. dto.Overview = strippedOverview;
  660. }
  661. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  662. if (dto.BackdropImageTags.Count == 0)
  663. {
  664. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  665. if (parentWithBackdrop != null)
  666. {
  667. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  668. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  669. }
  670. }
  671. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  672. {
  673. dto.ParentId = GetDtoId(item.Parent);
  674. }
  675. dto.ParentIndexNumber = item.ParentIndexNumber;
  676. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  677. if (!dto.HasLogo)
  678. {
  679. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  680. if (parentWithLogo != null)
  681. {
  682. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  683. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  684. }
  685. }
  686. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  687. if (!dto.HasArtImage)
  688. {
  689. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  690. if (parentWithImage != null)
  691. {
  692. dto.ParentArtItemId = GetDtoId(parentWithImage);
  693. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  694. }
  695. }
  696. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  697. if (!dto.HasThumb)
  698. {
  699. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  700. if (parentWithImage != null)
  701. {
  702. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  703. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  704. }
  705. }
  706. if (fields.Contains(ItemFields.Path))
  707. {
  708. var locationType = item.LocationType;
  709. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  710. {
  711. dto.Path = GetMappedPath(item.Path);
  712. }
  713. else
  714. {
  715. dto.Path = item.Path;
  716. }
  717. }
  718. dto.PremiereDate = item.PremiereDate;
  719. dto.ProductionYear = item.ProductionYear;
  720. if (fields.Contains(ItemFields.ProviderIds))
  721. {
  722. dto.ProviderIds = item.ProviderIds;
  723. }
  724. dto.RunTimeTicks = item.RunTimeTicks;
  725. if (fields.Contains(ItemFields.SortName))
  726. {
  727. dto.SortName = item.SortName;
  728. }
  729. if (fields.Contains(ItemFields.CustomRating))
  730. {
  731. dto.CustomRating = item.CustomRating;
  732. }
  733. if (fields.Contains(ItemFields.Taglines))
  734. {
  735. var hasTagline = item as IHasTaglines;
  736. if (hasTagline != null)
  737. {
  738. dto.Taglines = hasTagline.Taglines;
  739. }
  740. if (dto.Taglines == null)
  741. {
  742. dto.Taglines = new List<string>();
  743. }
  744. }
  745. dto.Type = item.GetClientTypeName();
  746. dto.CommunityRating = item.CommunityRating;
  747. dto.VoteCount = item.VoteCount;
  748. if (item.IsFolder)
  749. {
  750. var folder = (Folder)item;
  751. if (fields.Contains(ItemFields.IndexOptions))
  752. {
  753. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  754. }
  755. }
  756. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  757. if (supportsPlaceHolders != null)
  758. {
  759. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  760. }
  761. // Add audio info
  762. var audio = item as Audio;
  763. if (audio != null)
  764. {
  765. dto.Album = audio.Album;
  766. dto.Artists = audio.Artists;
  767. var albumParent = audio.FindParent<MusicAlbum>();
  768. if (albumParent != null)
  769. {
  770. dto.AlbumId = GetDtoId(albumParent);
  771. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  772. }
  773. dto.MediaSources = GetAudioMediaSources(audio);
  774. dto.MediaSourceCount = 1;
  775. }
  776. var album = item as MusicAlbum;
  777. if (album != null)
  778. {
  779. dto.Artists = album.Artists;
  780. dto.SoundtrackIds = album.SoundtrackIds
  781. .Select(i => i.ToString("N"))
  782. .ToArray();
  783. }
  784. var hasAlbumArtist = item as IHasAlbumArtist;
  785. if (hasAlbumArtist != null)
  786. {
  787. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  788. }
  789. // Add video info
  790. var video = item as Video;
  791. if (video != null)
  792. {
  793. dto.VideoType = video.VideoType;
  794. dto.Video3DFormat = video.Video3DFormat;
  795. dto.IsoType = video.IsoType;
  796. dto.IsHD = video.IsHD;
  797. dto.PartCount = video.AdditionalPartIds.Count + 1;
  798. dto.MediaSourceCount = video.MediaSourceCount;
  799. if (fields.Contains(ItemFields.MediaSources))
  800. {
  801. dto.MediaSources = GetVideoMediaSources(video);
  802. }
  803. if (fields.Contains(ItemFields.Chapters))
  804. {
  805. List<ChapterInfoDto> chapters;
  806. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  807. {
  808. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  809. }
  810. else
  811. {
  812. chapters = _itemRepo.GetChapters(video.Id)
  813. .Select(c => GetChapterInfoDto(c, item))
  814. .ToList();
  815. }
  816. dto.Chapters = chapters;
  817. }
  818. }
  819. if (fields.Contains(ItemFields.MediaStreams))
  820. {
  821. // Add VideoInfo
  822. var iHasMediaStreams = item as IHasMediaStreams;
  823. if (iHasMediaStreams != null)
  824. {
  825. List<MediaStream> mediaStreams;
  826. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  827. {
  828. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  829. .SelectMany(i => i.MediaStreams)
  830. .ToList();
  831. }
  832. else
  833. {
  834. mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  835. {
  836. ItemId = item.Id
  837. }).ToList();
  838. }
  839. dto.MediaStreams = mediaStreams;
  840. }
  841. }
  842. // Add MovieInfo
  843. var movie = item as Movie;
  844. if (movie != null)
  845. {
  846. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  847. if (specialFeatureCount > 0)
  848. {
  849. dto.SpecialFeatureCount = specialFeatureCount;
  850. }
  851. if (fields.Contains(ItemFields.TmdbCollectionName))
  852. {
  853. dto.TmdbCollectionName = movie.TmdbCollectionName;
  854. }
  855. }
  856. // Add EpisodeInfo
  857. var episode = item as Episode;
  858. if (episode != null)
  859. {
  860. dto.IndexNumberEnd = episode.IndexNumberEnd;
  861. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  862. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  863. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  864. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  865. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  866. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  867. var seasonId = episode.SeasonId;
  868. if (seasonId.HasValue)
  869. {
  870. dto.SeasonId = seasonId.Value.ToString("N");
  871. }
  872. }
  873. // Add SeriesInfo
  874. var series = item as Series;
  875. if (series != null)
  876. {
  877. dto.AirDays = series.AirDays;
  878. dto.AirTime = series.AirTime;
  879. dto.Status = series.Status;
  880. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  881. dto.SeasonCount = series.SeasonCount;
  882. if (fields.Contains(ItemFields.Settings))
  883. {
  884. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  885. }
  886. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  887. }
  888. if (episode != null)
  889. {
  890. series = item.FindParent<Series>();
  891. dto.SeriesId = GetDtoId(series);
  892. dto.SeriesName = series.Name;
  893. dto.AirTime = series.AirTime;
  894. dto.SeriesStudio = series.Studios.FirstOrDefault();
  895. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  896. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  897. }
  898. // Add SeasonInfo
  899. var season = item as Season;
  900. if (season != null)
  901. {
  902. series = item.FindParent<Series>();
  903. dto.SeriesId = GetDtoId(series);
  904. dto.SeriesName = series.Name;
  905. dto.AirTime = series.AirTime;
  906. dto.SeriesStudio = series.Studios.FirstOrDefault();
  907. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  908. }
  909. var game = item as Game;
  910. if (game != null)
  911. {
  912. SetGameProperties(dto, game);
  913. }
  914. var gameSystem = item as GameSystem;
  915. if (gameSystem != null)
  916. {
  917. SetGameSystemProperties(dto, gameSystem);
  918. }
  919. var musicVideo = item as MusicVideo;
  920. if (musicVideo != null)
  921. {
  922. SetMusicVideoProperties(dto, musicVideo);
  923. }
  924. var book = item as Book;
  925. if (book != null)
  926. {
  927. SetBookProperties(dto, book);
  928. }
  929. var tvChannel = item as LiveTvChannel;
  930. if (tvChannel != null)
  931. {
  932. dto.MediaSources = GetMediaSources(tvChannel);
  933. }
  934. var channelItem = item as IChannelItem;
  935. if (channelItem != null)
  936. {
  937. dto.ChannelId = channelItem.ChannelId;
  938. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  939. }
  940. }
  941. public List<MediaSourceInfo> GetMediaSources(BaseItem item)
  942. {
  943. var video = item as Video;
  944. if (video != null)
  945. {
  946. return GetVideoMediaSources(video);
  947. }
  948. var audio = item as Audio;
  949. if (audio != null)
  950. {
  951. return GetAudioMediaSources(audio);
  952. }
  953. var result = new List<MediaSourceInfo>
  954. {
  955. new MediaSourceInfo
  956. {
  957. Id = item.Id.ToString("N"),
  958. LocationType = item.LocationType,
  959. Name = item.Name,
  960. Path = GetMappedPath(item),
  961. MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery { ItemId = item.Id }).ToList(),
  962. RunTimeTicks = item.RunTimeTicks
  963. }
  964. };
  965. return result;
  966. }
  967. private List<MediaSourceInfo> GetVideoMediaSources(Video item)
  968. {
  969. var result = item.GetAlternateVersions().Select(GetVersionInfo).ToList();
  970. result.Add(GetVersionInfo(item));
  971. return result.OrderBy(i =>
  972. {
  973. if (item.VideoType == VideoType.VideoFile)
  974. {
  975. return 0;
  976. }
  977. return 1;
  978. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  979. .ThenByDescending(i =>
  980. {
  981. var stream = i.VideoStream;
  982. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  983. })
  984. .ToList();
  985. }
  986. private List<MediaSourceInfo> GetAudioMediaSources(Audio item)
  987. {
  988. var result = new List<MediaSourceInfo>
  989. {
  990. GetVersionInfo(item)
  991. };
  992. return result;
  993. }
  994. private MediaSourceInfo GetVersionInfo(Video i)
  995. {
  996. var mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery { ItemId = i.Id }).ToList();
  997. var info = new MediaSourceInfo
  998. {
  999. Id = i.Id.ToString("N"),
  1000. IsoType = i.IsoType,
  1001. LocationType = i.LocationType,
  1002. MediaStreams = mediaStreams,
  1003. Name = GetMediaSourceName(i, mediaStreams),
  1004. Path = GetMappedPath(i),
  1005. RunTimeTicks = i.RunTimeTicks,
  1006. Video3DFormat = i.Video3DFormat,
  1007. VideoType = i.VideoType,
  1008. Container = i.Container,
  1009. Size = i.Size,
  1010. Formats = (i.FormatName ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  1011. Timestamp = i.Timestamp
  1012. };
  1013. if (string.IsNullOrEmpty(info.Container))
  1014. {
  1015. if (i.VideoType == VideoType.VideoFile || i.VideoType == VideoType.Iso)
  1016. {
  1017. var locationType = i.LocationType;
  1018. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1019. {
  1020. info.Container = Path.GetExtension(i.Path).TrimStart('.');
  1021. }
  1022. }
  1023. }
  1024. try
  1025. {
  1026. var bitrate = i.TotalBitrate ??
  1027. info.MediaStreams.Where(m => m.Type != MediaStreamType.Subtitle && !string.Equals(m.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  1028. .Select(m => m.BitRate ?? 0)
  1029. .Sum();
  1030. if (bitrate > 0)
  1031. {
  1032. info.Bitrate = bitrate;
  1033. }
  1034. }
  1035. catch (OverflowException ex)
  1036. {
  1037. _logger.ErrorException("Error calculating total bitrate", ex);
  1038. }
  1039. return info;
  1040. }
  1041. private MediaSourceInfo GetVersionInfo(Audio i)
  1042. {
  1043. var info = new MediaSourceInfo
  1044. {
  1045. Id = i.Id.ToString("N"),
  1046. LocationType = i.LocationType,
  1047. MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery { ItemId = i.Id }).ToList(),
  1048. Name = i.Name,
  1049. Path = GetMappedPath(i),
  1050. RunTimeTicks = i.RunTimeTicks,
  1051. Container = i.Container,
  1052. Size = i.Size,
  1053. Formats = (i.FormatName ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList()
  1054. };
  1055. if (string.IsNullOrEmpty(info.Container))
  1056. {
  1057. var locationType = i.LocationType;
  1058. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1059. {
  1060. info.Container = Path.GetExtension(i.Path).TrimStart('.');
  1061. }
  1062. }
  1063. var bitrate = i.TotalBitrate ??
  1064. info.MediaStreams.Where(m => m.Type == MediaStreamType.Audio)
  1065. .Select(m => m.BitRate ?? 0)
  1066. .Sum();
  1067. if (bitrate > 0)
  1068. {
  1069. info.Bitrate = bitrate;
  1070. }
  1071. return info;
  1072. }
  1073. private string GetMappedPath(IHasMetadata item)
  1074. {
  1075. var path = item.Path;
  1076. var locationType = item.LocationType;
  1077. if (locationType != LocationType.FileSystem && locationType != LocationType.Offline)
  1078. {
  1079. return path;
  1080. }
  1081. foreach (var map in _config.Configuration.PathSubstitutions)
  1082. {
  1083. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1084. }
  1085. return path;
  1086. }
  1087. private string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  1088. {
  1089. var terms = new List<string>();
  1090. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  1091. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  1092. if (video.Video3DFormat.HasValue)
  1093. {
  1094. terms.Add("3D");
  1095. }
  1096. if (video.VideoType == VideoType.BluRay)
  1097. {
  1098. terms.Add("Bluray");
  1099. }
  1100. else if (video.VideoType == VideoType.Dvd)
  1101. {
  1102. terms.Add("DVD");
  1103. }
  1104. else if (video.VideoType == VideoType.HdDvd)
  1105. {
  1106. terms.Add("HD-DVD");
  1107. }
  1108. else if (video.VideoType == VideoType.Iso)
  1109. {
  1110. if (video.IsoType.HasValue)
  1111. {
  1112. if (video.IsoType.Value == IsoType.BluRay)
  1113. {
  1114. terms.Add("Bluray");
  1115. }
  1116. else if (video.IsoType.Value == IsoType.Dvd)
  1117. {
  1118. terms.Add("DVD");
  1119. }
  1120. }
  1121. else
  1122. {
  1123. terms.Add("ISO");
  1124. }
  1125. }
  1126. if (videoStream != null)
  1127. {
  1128. if (videoStream.Width.HasValue)
  1129. {
  1130. if (videoStream.Width.Value >= 3800)
  1131. {
  1132. terms.Add("4K");
  1133. }
  1134. else if (videoStream.Width.Value >= 1900)
  1135. {
  1136. terms.Add("1080P");
  1137. }
  1138. else if (videoStream.Width.Value >= 1270)
  1139. {
  1140. terms.Add("720P");
  1141. }
  1142. else if (videoStream.Width.Value >= 700)
  1143. {
  1144. terms.Add("480P");
  1145. }
  1146. else
  1147. {
  1148. terms.Add("SD");
  1149. }
  1150. }
  1151. }
  1152. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  1153. {
  1154. terms.Add(videoStream.Codec.ToUpper());
  1155. }
  1156. if (audioStream != null)
  1157. {
  1158. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  1159. ? audioStream.Profile
  1160. : audioStream.Codec;
  1161. if (!string.IsNullOrEmpty(audioCodec))
  1162. {
  1163. terms.Add(audioCodec.ToUpper());
  1164. }
  1165. }
  1166. return string.Join("/", terms.ToArray());
  1167. }
  1168. private string GetMappedPath(string path)
  1169. {
  1170. foreach (var map in _config.Configuration.PathSubstitutions)
  1171. {
  1172. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1173. }
  1174. return path;
  1175. }
  1176. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1177. {
  1178. var hasProductionLocations = item as IHasProductionLocations;
  1179. if (hasProductionLocations != null)
  1180. {
  1181. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1182. }
  1183. var person = item as Person;
  1184. if (person != null)
  1185. {
  1186. dto.ProductionLocations = new List<string>();
  1187. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1188. {
  1189. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1190. }
  1191. }
  1192. if (dto.ProductionLocations == null)
  1193. {
  1194. dto.ProductionLocations = new List<string>();
  1195. }
  1196. }
  1197. /// <summary>
  1198. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1199. /// </summary>
  1200. /// <param name="folder">The folder.</param>
  1201. /// <param name="user">The user.</param>
  1202. /// <param name="dto">The dto.</param>
  1203. /// <param name="fields">The fields.</param>
  1204. /// <returns>Task.</returns>
  1205. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1206. {
  1207. var recursiveItemCount = 0;
  1208. var unplayed = 0;
  1209. long runtime = 0;
  1210. DateTime? dateLastMediaAdded = null;
  1211. double totalPercentPlayed = 0;
  1212. IEnumerable<BaseItem> children;
  1213. var season = folder as Season;
  1214. if (season != null)
  1215. {
  1216. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1217. }
  1218. else
  1219. {
  1220. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1221. }
  1222. // Loop through each recursive child
  1223. foreach (var child in children)
  1224. {
  1225. if (!dateLastMediaAdded.HasValue)
  1226. {
  1227. dateLastMediaAdded = child.DateCreated;
  1228. }
  1229. else
  1230. {
  1231. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1232. }
  1233. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1234. recursiveItemCount++;
  1235. var isUnplayed = true;
  1236. // Incrememt totalPercentPlayed
  1237. if (userdata != null)
  1238. {
  1239. if (userdata.Played)
  1240. {
  1241. totalPercentPlayed += 100;
  1242. isUnplayed = false;
  1243. }
  1244. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1245. {
  1246. double itemPercent = userdata.PlaybackPositionTicks;
  1247. itemPercent /= child.RunTimeTicks.Value;
  1248. totalPercentPlayed += itemPercent;
  1249. }
  1250. }
  1251. if (isUnplayed)
  1252. {
  1253. unplayed++;
  1254. }
  1255. runtime += child.RunTimeTicks ?? 0;
  1256. }
  1257. dto.RecursiveItemCount = recursiveItemCount;
  1258. dto.RecursiveUnplayedItemCount = unplayed;
  1259. if (recursiveItemCount > 0)
  1260. {
  1261. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1262. }
  1263. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1264. {
  1265. dto.CumulativeRunTimeTicks = runtime;
  1266. }
  1267. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1268. {
  1269. dto.DateLastMediaAdded = dateLastMediaAdded;
  1270. }
  1271. }
  1272. /// <summary>
  1273. /// Attaches the primary image aspect ratio.
  1274. /// </summary>
  1275. /// <param name="dto">The dto.</param>
  1276. /// <param name="item">The item.</param>
  1277. /// <returns>Task.</returns>
  1278. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1279. {
  1280. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1281. if (imageInfo == null)
  1282. {
  1283. return;
  1284. }
  1285. var path = imageInfo.Path;
  1286. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1287. var dateModified = imageInfo.DateModified;
  1288. ImageSize size;
  1289. try
  1290. {
  1291. size = _imageProcessor.GetImageSize(path, dateModified);
  1292. }
  1293. catch (FileNotFoundException)
  1294. {
  1295. _logger.Error("Image file does not exist: {0}", path);
  1296. return;
  1297. }
  1298. catch (Exception ex)
  1299. {
  1300. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1301. return;
  1302. }
  1303. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1304. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1305. foreach (var enhancer in supportedEnhancers)
  1306. {
  1307. try
  1308. {
  1309. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1310. }
  1311. catch (Exception ex)
  1312. {
  1313. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1314. }
  1315. }
  1316. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1317. }
  1318. }
  1319. }