DtoService.cs 52 KB

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