DtoService.cs 45 KB

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