DtoService.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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. ItemByNameCounts counts;
  116. if (user == null)
  117. {
  118. //counts = item.ItemCounts;
  119. return;
  120. }
  121. if (!item.UserItemCounts.TryGetValue(user.Id, out counts))
  122. {
  123. counts = new ItemByNameCounts();
  124. }
  125. dto.ChildCount = counts.TotalCount;
  126. dto.AdultVideoCount = counts.AdultVideoCount;
  127. dto.AlbumCount = counts.AlbumCount;
  128. dto.EpisodeCount = counts.EpisodeCount;
  129. dto.GameCount = counts.GameCount;
  130. dto.MovieCount = counts.MovieCount;
  131. dto.MusicVideoCount = counts.MusicVideoCount;
  132. dto.SeriesCount = counts.SeriesCount;
  133. dto.SongCount = counts.SongCount;
  134. dto.TrailerCount = counts.TrailerCount;
  135. }
  136. /// <summary>
  137. /// Attaches the user specific info.
  138. /// </summary>
  139. /// <param name="dto">The dto.</param>
  140. /// <param name="item">The item.</param>
  141. /// <param name="user">The user.</param>
  142. /// <param name="fields">The fields.</param>
  143. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  144. {
  145. if (item.IsFolder)
  146. {
  147. var folder = (Folder)item;
  148. dto.ChildCount = folder.GetChildren(user, true)
  149. .Count();
  150. if (!(folder is UserRootFolder))
  151. {
  152. SetSpecialCounts(folder, user, dto, fields);
  153. }
  154. }
  155. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  156. dto.UserData = GetUserItemDataDto(userData);
  157. if (item.IsFolder)
  158. {
  159. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  160. }
  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 = _imageProcessor.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. };
  214. if (session.NowPlayingItem != null)
  215. {
  216. dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
  217. }
  218. if (session.User != null)
  219. {
  220. dto.UserId = session.User.Id.ToString("N");
  221. dto.UserName = session.User.Name;
  222. }
  223. return dto;
  224. }
  225. /// <summary>
  226. /// Converts a BaseItem to a BaseItemInfo
  227. /// </summary>
  228. /// <param name="item">The item.</param>
  229. /// <returns>BaseItemInfo.</returns>
  230. /// <exception cref="System.ArgumentNullException">item</exception>
  231. public BaseItemInfo GetBaseItemInfo(BaseItem item)
  232. {
  233. if (item == null)
  234. {
  235. throw new ArgumentNullException("item");
  236. }
  237. var info = new BaseItemInfo
  238. {
  239. Id = GetDtoId(item),
  240. Name = item.Name,
  241. MediaType = item.MediaType,
  242. Type = item.GetClientTypeName(),
  243. RunTimeTicks = item.RunTimeTicks
  244. };
  245. var imagePath = item.PrimaryImagePath;
  246. if (!string.IsNullOrEmpty(imagePath))
  247. {
  248. try
  249. {
  250. info.PrimaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary, imagePath);
  251. }
  252. catch (IOException)
  253. {
  254. }
  255. }
  256. return info;
  257. }
  258. const string IndexFolderDelimeter = "-index-";
  259. /// <summary>
  260. /// Gets client-side Id of a server-side BaseItem
  261. /// </summary>
  262. /// <param name="item">The item.</param>
  263. /// <returns>System.String.</returns>
  264. /// <exception cref="System.ArgumentNullException">item</exception>
  265. public string GetDtoId(BaseItem item)
  266. {
  267. if (item == null)
  268. {
  269. throw new ArgumentNullException("item");
  270. }
  271. var indexFolder = item as IndexFolder;
  272. if (indexFolder != null)
  273. {
  274. return GetDtoId(indexFolder.Parent) + IndexFolderDelimeter + (indexFolder.IndexName ?? string.Empty) + IndexFolderDelimeter + indexFolder.Id;
  275. }
  276. return item.Id.ToString("N");
  277. }
  278. /// <summary>
  279. /// Converts a UserItemData to a DTOUserItemData
  280. /// </summary>
  281. /// <param name="data">The data.</param>
  282. /// <returns>DtoUserItemData.</returns>
  283. /// <exception cref="System.ArgumentNullException"></exception>
  284. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  285. {
  286. if (data == null)
  287. {
  288. throw new ArgumentNullException("data");
  289. }
  290. return new UserItemDataDto
  291. {
  292. IsFavorite = data.IsFavorite,
  293. Likes = data.Likes,
  294. PlaybackPositionTicks = data.PlaybackPositionTicks,
  295. PlayCount = data.PlayCount,
  296. Rating = data.Rating,
  297. Played = data.Played,
  298. LastPlayedDate = data.LastPlayedDate,
  299. Key = data.Key
  300. };
  301. }
  302. private void SetBookProperties(BaseItemDto dto, Book item)
  303. {
  304. dto.SeriesName = item.SeriesName;
  305. }
  306. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  307. {
  308. if (!string.IsNullOrEmpty(item.Album))
  309. {
  310. var parentAlbum = _libraryManager.RootFolder
  311. .GetRecursiveChildren(i => i is MusicAlbum)
  312. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  313. if (parentAlbum != null)
  314. {
  315. dto.AlbumId = GetDtoId(parentAlbum);
  316. }
  317. }
  318. dto.Album = item.Album;
  319. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  320. }
  321. private void SetGameProperties(BaseItemDto dto, Game item)
  322. {
  323. dto.Players = item.PlayersSupported;
  324. dto.GameSystem = item.GameSystem;
  325. }
  326. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  327. {
  328. dto.GameSystem = item.GameSystemName;
  329. }
  330. /// <summary>
  331. /// Gets the backdrop image tags.
  332. /// </summary>
  333. /// <param name="item">The item.</param>
  334. /// <returns>List{System.String}.</returns>
  335. private List<Guid> GetBackdropImageTags(BaseItem item)
  336. {
  337. return item.BackdropImagePaths
  338. .Select(p => GetImageCacheTag(item, ImageType.Backdrop, p))
  339. .Where(i => i.HasValue)
  340. .Select(i => i.Value)
  341. .ToList();
  342. }
  343. /// <summary>
  344. /// Gets the screenshot image tags.
  345. /// </summary>
  346. /// <param name="item">The item.</param>
  347. /// <returns>List{Guid}.</returns>
  348. private List<Guid> GetScreenshotImageTags(BaseItem item)
  349. {
  350. return item.ScreenshotImagePaths
  351. .Select(p => GetImageCacheTag(item, ImageType.Screenshot, p))
  352. .Where(i => i.HasValue)
  353. .Select(i => i.Value)
  354. .ToList();
  355. }
  356. private Guid? GetImageCacheTag(BaseItem item, ImageType type, string path)
  357. {
  358. try
  359. {
  360. return _imageProcessor.GetImageCacheTag(item, type, path);
  361. }
  362. catch (IOException ex)
  363. {
  364. _logger.ErrorException("Error getting {0} image info for {1}", ex, type, path);
  365. return null;
  366. }
  367. }
  368. /// <summary>
  369. /// Attaches People DTO's to a DTOBaseItem
  370. /// </summary>
  371. /// <param name="dto">The dto.</param>
  372. /// <param name="item">The item.</param>
  373. /// <returns>Task.</returns>
  374. private void AttachPeople(BaseItemDto dto, BaseItem item)
  375. {
  376. // Ordering by person type to ensure actors and artists are at the front.
  377. // This is taking advantage of the fact that they both begin with A
  378. // This should be improved in the future
  379. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue).ThenBy(i => i.Type).ToList();
  380. // Attach People by transforming them into BaseItemPerson (DTO)
  381. dto.People = new BaseItemPerson[people.Count];
  382. var dictionary = people.Select(p => p.Name)
  383. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  384. {
  385. try
  386. {
  387. return _libraryManager.GetPerson(c);
  388. }
  389. catch (IOException ex)
  390. {
  391. _logger.ErrorException("Error getting person {0}", ex, c);
  392. return null;
  393. }
  394. }).Where(i => i != null)
  395. .DistinctBy(i => i.Name)
  396. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  397. for (var i = 0; i < people.Count; i++)
  398. {
  399. var person = people[i];
  400. var baseItemPerson = new BaseItemPerson
  401. {
  402. Name = person.Name,
  403. Role = person.Role,
  404. Type = person.Type
  405. };
  406. Person entity;
  407. if (dictionary.TryGetValue(person.Name, out entity))
  408. {
  409. var primaryImagePath = entity.PrimaryImagePath;
  410. if (!string.IsNullOrEmpty(primaryImagePath))
  411. {
  412. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
  413. }
  414. }
  415. dto.People[i] = baseItemPerson;
  416. }
  417. }
  418. /// <summary>
  419. /// Attaches the studios.
  420. /// </summary>
  421. /// <param name="dto">The dto.</param>
  422. /// <param name="item">The item.</param>
  423. /// <returns>Task.</returns>
  424. private void AttachStudios(BaseItemDto dto, BaseItem item)
  425. {
  426. var studios = item.Studios.ToList();
  427. dto.Studios = new StudioDto[studios.Count];
  428. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  429. {
  430. try
  431. {
  432. return _libraryManager.GetStudio(name);
  433. }
  434. catch (IOException ex)
  435. {
  436. _logger.ErrorException("Error getting studio {0}", ex, name);
  437. return null;
  438. }
  439. })
  440. .Where(i => i != null)
  441. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  442. for (var i = 0; i < studios.Count; i++)
  443. {
  444. var studio = studios[i];
  445. var studioDto = new StudioDto
  446. {
  447. Name = studio
  448. };
  449. Studio entity;
  450. if (dictionary.TryGetValue(studio, out entity))
  451. {
  452. var primaryImagePath = entity.PrimaryImagePath;
  453. if (!string.IsNullOrEmpty(primaryImagePath))
  454. {
  455. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
  456. }
  457. }
  458. dto.Studios[i] = studioDto;
  459. }
  460. }
  461. /// <summary>
  462. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  463. /// </summary>
  464. /// <param name="item">The item.</param>
  465. /// <param name="owner">The owner.</param>
  466. /// <returns>BaseItem.</returns>
  467. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  468. {
  469. var parent = item.Parent ?? owner;
  470. while (parent != null)
  471. {
  472. if (parent.BackdropImagePaths != null && parent.BackdropImagePaths.Count > 0)
  473. {
  474. return parent;
  475. }
  476. parent = parent.Parent;
  477. }
  478. return null;
  479. }
  480. /// <summary>
  481. /// If an item does not have a logo, this can be used to find the first parent that does have one
  482. /// </summary>
  483. /// <param name="item">The item.</param>
  484. /// <param name="type">The type.</param>
  485. /// <param name="owner">The owner.</param>
  486. /// <returns>BaseItem.</returns>
  487. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  488. {
  489. var parent = item.Parent ?? owner;
  490. while (parent != null)
  491. {
  492. if (parent.HasImage(type))
  493. {
  494. return parent;
  495. }
  496. parent = parent.Parent;
  497. }
  498. return null;
  499. }
  500. /// <summary>
  501. /// Gets the chapter info dto.
  502. /// </summary>
  503. /// <param name="chapterInfo">The chapter info.</param>
  504. /// <param name="item">The item.</param>
  505. /// <returns>ChapterInfoDto.</returns>
  506. private ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  507. {
  508. var dto = new ChapterInfoDto
  509. {
  510. Name = chapterInfo.Name,
  511. StartPositionTicks = chapterInfo.StartPositionTicks
  512. };
  513. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  514. {
  515. dto.ImageTag = GetImageCacheTag(item, ImageType.Chapter, chapterInfo.ImagePath);
  516. }
  517. return dto;
  518. }
  519. /// <summary>
  520. /// Gets a BaseItem based upon it's client-side item id
  521. /// </summary>
  522. /// <param name="id">The id.</param>
  523. /// <param name="userId">The user id.</param>
  524. /// <returns>BaseItem.</returns>
  525. public BaseItem GetItemByDtoId(string id, Guid? userId = null)
  526. {
  527. if (string.IsNullOrEmpty(id))
  528. {
  529. throw new ArgumentNullException("id");
  530. }
  531. // If the item is an indexed folder we have to do a special routine to get it
  532. var isIndexFolder = id.IndexOf(IndexFolderDelimeter, StringComparison.OrdinalIgnoreCase) != -1;
  533. if (isIndexFolder)
  534. {
  535. if (userId.HasValue)
  536. {
  537. return GetIndexFolder(id, userId.Value);
  538. }
  539. }
  540. BaseItem item = null;
  541. if (userId.HasValue || !isIndexFolder)
  542. {
  543. item = _libraryManager.GetItemById(new Guid(id));
  544. }
  545. // If we still don't find it, look within individual user views
  546. if (item == null && !userId.HasValue && isIndexFolder)
  547. {
  548. foreach (var user in _userManager.Users)
  549. {
  550. item = GetItemByDtoId(id, user.Id);
  551. if (item != null)
  552. {
  553. break;
  554. }
  555. }
  556. }
  557. return item;
  558. }
  559. /// <summary>
  560. /// Finds an index folder based on an Id and userId
  561. /// </summary>
  562. /// <param name="id">The id.</param>
  563. /// <param name="userId">The user id.</param>
  564. /// <returns>BaseItem.</returns>
  565. private BaseItem GetIndexFolder(string id, Guid userId)
  566. {
  567. var user = _userManager.GetUserById(userId);
  568. var stringSeparators = new[] { IndexFolderDelimeter };
  569. // Split using the delimeter
  570. var values = id.Split(stringSeparators, StringSplitOptions.None).ToList();
  571. // Get the top folder normally using the first id
  572. var folder = GetItemByDtoId(values[0], userId) as Folder;
  573. values.RemoveAt(0);
  574. // Get indexed folders using the remaining values in the id string
  575. return GetIndexFolder(values, folder, user);
  576. }
  577. /// <summary>
  578. /// Gets indexed folders based on a list of index names and folder id's
  579. /// </summary>
  580. /// <param name="values">The values.</param>
  581. /// <param name="parentFolder">The parent folder.</param>
  582. /// <param name="user">The user.</param>
  583. /// <returns>BaseItem.</returns>
  584. private BaseItem GetIndexFolder(List<string> values, Folder parentFolder, User user)
  585. {
  586. // The index name is first
  587. var indexBy = values[0];
  588. // The index folder id is next
  589. var indexFolderId = new Guid(values[1]);
  590. // Remove them from the lst
  591. values.RemoveRange(0, 2);
  592. // Get the IndexFolder
  593. var indexFolder = parentFolder.GetChildren(user, false, indexBy).FirstOrDefault(i => i.Id == indexFolderId) as Folder;
  594. // Nested index folder
  595. if (values.Count > 0)
  596. {
  597. return GetIndexFolder(values, indexFolder, user);
  598. }
  599. return indexFolder;
  600. }
  601. /// <summary>
  602. /// Sets simple property values on a DTOBaseItem
  603. /// </summary>
  604. /// <param name="dto">The dto.</param>
  605. /// <param name="item">The item.</param>
  606. /// <param name="owner">The owner.</param>
  607. /// <param name="fields">The fields.</param>
  608. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  609. {
  610. if (fields.Contains(ItemFields.DateCreated))
  611. {
  612. dto.DateCreated = item.DateCreated;
  613. }
  614. if (fields.Contains(ItemFields.OriginalRunTimeTicks))
  615. {
  616. dto.OriginalRunTimeTicks = item.OriginalRunTimeTicks;
  617. }
  618. dto.DisplayMediaType = item.DisplayMediaType;
  619. if (fields.Contains(ItemFields.MetadataSettings))
  620. {
  621. dto.LockedFields = item.LockedFields;
  622. dto.EnableInternetProviders = !item.DontFetchMeta;
  623. }
  624. if (fields.Contains(ItemFields.Budget))
  625. {
  626. dto.Budget = item.Budget;
  627. }
  628. if (fields.Contains(ItemFields.Revenue))
  629. {
  630. dto.Revenue = item.Revenue;
  631. }
  632. dto.EndDate = item.EndDate;
  633. if (fields.Contains(ItemFields.HomePageUrl))
  634. {
  635. dto.HomePageUrl = item.HomePageUrl;
  636. }
  637. if (fields.Contains(ItemFields.Tags))
  638. {
  639. dto.Tags = item.Tags;
  640. }
  641. if (fields.Contains(ItemFields.ProductionLocations))
  642. {
  643. dto.ProductionLocations = item.ProductionLocations;
  644. }
  645. var hasAspectRatio = item as IHasAspectRatio;
  646. if (hasAspectRatio != null)
  647. {
  648. dto.AspectRatio = hasAspectRatio.AspectRatio;
  649. }
  650. dto.BackdropImageTags = GetBackdropImageTags(item);
  651. if (fields.Contains(ItemFields.ScreenshotImageTags))
  652. {
  653. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  654. }
  655. if (fields.Contains(ItemFields.Genres))
  656. {
  657. dto.Genres = item.Genres;
  658. }
  659. dto.ImageTags = new Dictionary<ImageType, Guid>();
  660. foreach (var image in item.Images)
  661. {
  662. var type = image.Key;
  663. var tag = GetImageCacheTag(item, type, image.Value);
  664. if (tag.HasValue)
  665. {
  666. dto.ImageTags[type] = tag.Value;
  667. }
  668. }
  669. dto.Id = GetDtoId(item);
  670. dto.IndexNumber = item.IndexNumber;
  671. dto.IsFolder = item.IsFolder;
  672. dto.Language = item.Language;
  673. dto.MediaType = item.MediaType;
  674. dto.LocationType = item.LocationType;
  675. var hasCriticRating = item as IHasCriticRating;
  676. if (hasCriticRating != null)
  677. {
  678. dto.CriticRating = hasCriticRating.CriticRating;
  679. if (fields.Contains(ItemFields.CriticRatingSummary))
  680. {
  681. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  682. }
  683. }
  684. var localTrailerCount = item.LocalTrailerIds.Count;
  685. if (localTrailerCount > 0)
  686. {
  687. dto.LocalTrailerCount = localTrailerCount;
  688. }
  689. dto.Name = item.Name;
  690. dto.OfficialRating = item.OfficialRating;
  691. var hasOverview = fields.Contains(ItemFields.Overview);
  692. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  693. if (hasOverview || hasHtmlOverview)
  694. {
  695. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  696. if (hasOverview)
  697. {
  698. dto.Overview = strippedOverview;
  699. }
  700. // Only supply the html version if there was actually html content
  701. if (hasHtmlOverview)
  702. {
  703. dto.OverviewHtml = item.Overview;
  704. }
  705. }
  706. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  707. if (dto.BackdropImageTags.Count == 0)
  708. {
  709. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  710. if (parentWithBackdrop != null)
  711. {
  712. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  713. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  714. }
  715. }
  716. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  717. {
  718. dto.ParentId = GetDtoId(item.Parent);
  719. }
  720. dto.ParentIndexNumber = item.ParentIndexNumber;
  721. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  722. if (!dto.HasLogo)
  723. {
  724. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  725. if (parentWithLogo != null)
  726. {
  727. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  728. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImage(ImageType.Logo));
  729. }
  730. }
  731. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  732. if (!dto.HasArtImage)
  733. {
  734. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  735. if (parentWithImage != null)
  736. {
  737. dto.ParentArtItemId = GetDtoId(parentWithImage);
  738. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImage(ImageType.Art));
  739. }
  740. }
  741. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  742. if (!dto.HasThumb)
  743. {
  744. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  745. if (parentWithImage != null)
  746. {
  747. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  748. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb, parentWithImage.GetImage(ImageType.Thumb));
  749. }
  750. }
  751. if (fields.Contains(ItemFields.Path))
  752. {
  753. dto.Path = item.Path;
  754. }
  755. dto.PremiereDate = item.PremiereDate;
  756. dto.ProductionYear = item.ProductionYear;
  757. if (fields.Contains(ItemFields.ProviderIds))
  758. {
  759. dto.ProviderIds = item.ProviderIds;
  760. }
  761. dto.RunTimeTicks = item.RunTimeTicks;
  762. if (fields.Contains(ItemFields.SortName))
  763. {
  764. dto.SortName = item.SortName;
  765. }
  766. if (fields.Contains(ItemFields.CustomRating))
  767. {
  768. dto.CustomRating = item.CustomRating;
  769. }
  770. if (fields.Contains(ItemFields.Taglines))
  771. {
  772. dto.Taglines = item.Taglines;
  773. }
  774. if (fields.Contains(ItemFields.RemoteTrailers))
  775. {
  776. dto.RemoteTrailers = item.RemoteTrailers;
  777. }
  778. dto.Type = item.GetClientTypeName();
  779. dto.CommunityRating = item.CommunityRating;
  780. dto.VoteCount = item.VoteCount;
  781. if (item.IsFolder)
  782. {
  783. var folder = (Folder)item;
  784. if (fields.Contains(ItemFields.IndexOptions))
  785. {
  786. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  787. }
  788. }
  789. // Add audio info
  790. var audio = item as Audio;
  791. if (audio != null)
  792. {
  793. dto.Album = audio.Album;
  794. dto.Artists = audio.Artists;
  795. var albumParent = audio.FindParent<MusicAlbum>();
  796. if (albumParent != null)
  797. {
  798. dto.AlbumId = GetDtoId(albumParent);
  799. var imagePath = albumParent.PrimaryImagePath;
  800. if (!string.IsNullOrEmpty(imagePath))
  801. {
  802. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  803. }
  804. }
  805. }
  806. var album = item as MusicAlbum;
  807. if (album != null)
  808. {
  809. dto.Artists = album.Artists;
  810. dto.SoundtrackIds = album.SoundtrackIds
  811. .Select(i => i.ToString("N"))
  812. .ToArray();
  813. }
  814. var hasAlbumArtist = item as IHasAlbumArtist;
  815. if (hasAlbumArtist != null)
  816. {
  817. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  818. }
  819. // Add video info
  820. var video = item as Video;
  821. if (video != null)
  822. {
  823. dto.VideoType = video.VideoType;
  824. dto.Video3DFormat = video.Video3DFormat;
  825. dto.IsoType = video.IsoType;
  826. dto.IsHD = video.IsHD;
  827. dto.PartCount = video.AdditionalPartIds.Count + 1;
  828. if (fields.Contains(ItemFields.Chapters))
  829. {
  830. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  831. }
  832. }
  833. if (fields.Contains(ItemFields.MediaStreams))
  834. {
  835. // Add VideoInfo
  836. var iHasMediaStreams = item as IHasMediaStreams;
  837. if (iHasMediaStreams != null)
  838. {
  839. dto.MediaStreams = iHasMediaStreams.MediaStreams;
  840. }
  841. }
  842. // Add MovieInfo
  843. var movie = item as Movie;
  844. if (movie != null)
  845. {
  846. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  847. if (specialFeatureCount > 0)
  848. {
  849. dto.SpecialFeatureCount = specialFeatureCount;
  850. }
  851. }
  852. // Add EpisodeInfo
  853. var episode = item as Episode;
  854. if (episode != null)
  855. {
  856. dto.IndexNumberEnd = episode.IndexNumberEnd;
  857. dto.SpecialSeasonNumber = episode.AirsAfterSeasonNumber ?? episode.AirsBeforeSeasonNumber;
  858. }
  859. // Add SeriesInfo
  860. var series = item as Series;
  861. if (series != null)
  862. {
  863. dto.AirDays = series.AirDays;
  864. dto.AirTime = series.AirTime;
  865. dto.Status = series.Status;
  866. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  867. dto.SeasonCount = series.SeasonCount;
  868. }
  869. if (episode != null)
  870. {
  871. series = item.FindParent<Series>();
  872. dto.SeriesId = GetDtoId(series);
  873. dto.SeriesName = series.Name;
  874. dto.AirTime = series.AirTime;
  875. dto.SeriesStudio = series.Studios.FirstOrDefault();
  876. if (series.HasImage(ImageType.Thumb))
  877. {
  878. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb, series.GetImage(ImageType.Thumb));
  879. }
  880. var imagePath = series.PrimaryImagePath;
  881. if (!string.IsNullOrEmpty(imagePath))
  882. {
  883. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  884. }
  885. }
  886. // Add SeasonInfo
  887. var season = item as Season;
  888. if (season != null)
  889. {
  890. series = item.FindParent<Series>();
  891. dto.SeriesId = GetDtoId(series);
  892. dto.SeriesName = series.Name;
  893. dto.AirTime = series.AirTime;
  894. dto.SeriesStudio = series.Studios.FirstOrDefault();
  895. var imagePath = series.PrimaryImagePath;
  896. if (!string.IsNullOrEmpty(imagePath))
  897. {
  898. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  899. }
  900. }
  901. var game = item as Game;
  902. if (game != null)
  903. {
  904. SetGameProperties(dto, game);
  905. }
  906. var gameSystem = item as GameSystem;
  907. if (gameSystem != null)
  908. {
  909. SetGameSystemProperties(dto, gameSystem);
  910. }
  911. var musicVideo = item as MusicVideo;
  912. if (musicVideo != null)
  913. {
  914. SetMusicVideoProperties(dto, musicVideo);
  915. }
  916. var book = item as Book;
  917. if (book != null)
  918. {
  919. SetBookProperties(dto, book);
  920. }
  921. }
  922. /// <summary>
  923. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  924. /// </summary>
  925. /// <param name="folder">The folder.</param>
  926. /// <param name="user">The user.</param>
  927. /// <param name="dto">The dto.</param>
  928. /// <param name="fields">The fields.</param>
  929. /// <returns>Task.</returns>
  930. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  931. {
  932. var rcentlyAddedItemCount = 0;
  933. var recursiveItemCount = 0;
  934. var unplayed = 0;
  935. long runtime = 0;
  936. double totalPercentPlayed = 0;
  937. // Loop through each recursive child
  938. foreach (var child in folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual))
  939. {
  940. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  941. recursiveItemCount++;
  942. // Check is recently added
  943. if (child.IsRecentlyAdded())
  944. {
  945. rcentlyAddedItemCount++;
  946. }
  947. var isUnplayed = true;
  948. // Incrememt totalPercentPlayed
  949. if (userdata != null)
  950. {
  951. if (userdata.Played)
  952. {
  953. totalPercentPlayed += 100;
  954. isUnplayed = false;
  955. }
  956. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  957. {
  958. double itemPercent = userdata.PlaybackPositionTicks;
  959. itemPercent /= child.RunTimeTicks.Value;
  960. totalPercentPlayed += itemPercent;
  961. }
  962. }
  963. if (isUnplayed)
  964. {
  965. unplayed++;
  966. }
  967. runtime += child.RunTimeTicks ?? 0;
  968. }
  969. dto.RecursiveItemCount = recursiveItemCount;
  970. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  971. dto.RecursiveUnplayedItemCount = unplayed;
  972. if (recursiveItemCount > 0)
  973. {
  974. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  975. }
  976. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  977. {
  978. dto.CumulativeRunTimeTicks = runtime;
  979. }
  980. }
  981. /// <summary>
  982. /// Attaches the primary image aspect ratio.
  983. /// </summary>
  984. /// <param name="dto">The dto.</param>
  985. /// <param name="item">The item.</param>
  986. /// <returns>Task.</returns>
  987. private void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  988. {
  989. var path = item.PrimaryImagePath;
  990. if (string.IsNullOrEmpty(path))
  991. {
  992. return;
  993. }
  994. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  995. var dateModified = item.GetImageDateModified(path);
  996. ImageSize size;
  997. try
  998. {
  999. size = _imageProcessor.GetImageSize(path, dateModified);
  1000. }
  1001. catch (FileNotFoundException)
  1002. {
  1003. _logger.Error("Image file does not exist: {0}", path);
  1004. return;
  1005. }
  1006. catch (Exception ex)
  1007. {
  1008. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1009. return;
  1010. }
  1011. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1012. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1013. foreach (var enhancer in supportedEnhancers)
  1014. {
  1015. try
  1016. {
  1017. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1022. }
  1023. }
  1024. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1025. }
  1026. }
  1027. }