DtoService.cs 43 KB

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