DtoService.cs 42 KB

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