DtoService.cs 39 KB

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