DtoService.cs 53 KB

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