DtoService.cs 55 KB

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