DtoService.cs 52 KB

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