DtoService.cs 44 KB

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