DtoService.cs 38 KB

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