DtoService.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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. if (user == null)
  116. {
  117. //counts = item.ItemCounts;
  118. return;
  119. }
  120. ItemByNameCounts counts = item.GetItemByNameCounts(user.Id) ?? new ItemByNameCounts();
  121. dto.ChildCount = counts.TotalCount;
  122. dto.AdultVideoCount = counts.AdultVideoCount;
  123. dto.AlbumCount = counts.AlbumCount;
  124. dto.EpisodeCount = counts.EpisodeCount;
  125. dto.GameCount = counts.GameCount;
  126. dto.MovieCount = counts.MovieCount;
  127. dto.MusicVideoCount = counts.MusicVideoCount;
  128. dto.SeriesCount = counts.SeriesCount;
  129. dto.SongCount = counts.SongCount;
  130. dto.TrailerCount = counts.TrailerCount;
  131. }
  132. /// <summary>
  133. /// Attaches the user specific info.
  134. /// </summary>
  135. /// <param name="dto">The dto.</param>
  136. /// <param name="item">The item.</param>
  137. /// <param name="user">The user.</param>
  138. /// <param name="fields">The fields.</param>
  139. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  140. {
  141. if (item.IsFolder)
  142. {
  143. var folder = (Folder)item;
  144. dto.ChildCount = folder.GetChildren(user, true)
  145. .Count();
  146. if (!(folder is UserRootFolder))
  147. {
  148. SetSpecialCounts(folder, user, dto, fields);
  149. }
  150. }
  151. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  152. dto.UserData = GetUserItemDataDto(userData);
  153. if (item.IsFolder)
  154. {
  155. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  156. }
  157. }
  158. public UserDto GetUserDto(User user)
  159. {
  160. if (user == null)
  161. {
  162. throw new ArgumentNullException("user");
  163. }
  164. var dto = new UserDto
  165. {
  166. Id = user.Id.ToString("N"),
  167. Name = user.Name,
  168. HasPassword = !String.IsNullOrEmpty(user.Password),
  169. LastActivityDate = user.LastActivityDate,
  170. LastLoginDate = user.LastLoginDate,
  171. Configuration = user.Configuration
  172. };
  173. var image = user.PrimaryImagePath;
  174. if (!string.IsNullOrEmpty(image))
  175. {
  176. dto.PrimaryImageTag = GetImageCacheTag(user, ImageType.Primary, image);
  177. try
  178. {
  179. AttachPrimaryImageAspectRatio(dto, user);
  180. }
  181. catch (Exception ex)
  182. {
  183. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  184. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  185. }
  186. }
  187. return dto;
  188. }
  189. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  190. {
  191. var dto = new SessionInfoDto
  192. {
  193. Client = session.Client,
  194. DeviceId = session.DeviceId,
  195. DeviceName = session.DeviceName,
  196. Id = session.Id.ToString("N"),
  197. LastActivityDate = session.LastActivityDate,
  198. NowPlayingPositionTicks = session.NowPlayingPositionTicks,
  199. SupportsRemoteControl = session.SupportsRemoteControl,
  200. IsPaused = session.IsPaused,
  201. IsMuted = session.IsMuted,
  202. NowViewingContext = session.NowViewingContext,
  203. NowViewingItemId = session.NowViewingItemId,
  204. NowViewingItemName = session.NowViewingItemName,
  205. NowViewingItemType = session.NowViewingItemType,
  206. ApplicationVersion = session.ApplicationVersion,
  207. CanSeek = session.CanSeek,
  208. QueueableMediaTypes = session.QueueableMediaTypes
  209. };
  210. if (session.NowPlayingItem != null)
  211. {
  212. dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
  213. }
  214. if (session.User != null)
  215. {
  216. dto.UserId = session.User.Id.ToString("N");
  217. dto.UserName = session.User.Name;
  218. }
  219. return dto;
  220. }
  221. /// <summary>
  222. /// Converts a BaseItem to a BaseItemInfo
  223. /// </summary>
  224. /// <param name="item">The item.</param>
  225. /// <returns>BaseItemInfo.</returns>
  226. /// <exception cref="System.ArgumentNullException">item</exception>
  227. public BaseItemInfo GetBaseItemInfo(BaseItem item)
  228. {
  229. if (item == null)
  230. {
  231. throw new ArgumentNullException("item");
  232. }
  233. var info = new BaseItemInfo
  234. {
  235. Id = GetDtoId(item),
  236. Name = item.Name,
  237. MediaType = item.MediaType,
  238. Type = item.GetClientTypeName(),
  239. RunTimeTicks = item.RunTimeTicks
  240. };
  241. var imagePath = item.PrimaryImagePath;
  242. if (!string.IsNullOrEmpty(imagePath))
  243. {
  244. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary, imagePath);
  245. }
  246. return info;
  247. }
  248. const string IndexFolderDelimeter = "-index-";
  249. /// <summary>
  250. /// Gets client-side Id of a server-side BaseItem
  251. /// </summary>
  252. /// <param name="item">The item.</param>
  253. /// <returns>System.String.</returns>
  254. /// <exception cref="System.ArgumentNullException">item</exception>
  255. public string GetDtoId(BaseItem item)
  256. {
  257. if (item == null)
  258. {
  259. throw new ArgumentNullException("item");
  260. }
  261. var indexFolder = item as IndexFolder;
  262. if (indexFolder != null)
  263. {
  264. return GetDtoId(indexFolder.Parent) + IndexFolderDelimeter + (indexFolder.IndexName ?? string.Empty) + IndexFolderDelimeter + indexFolder.Id;
  265. }
  266. return item.Id.ToString("N");
  267. }
  268. /// <summary>
  269. /// Converts a UserItemData to a DTOUserItemData
  270. /// </summary>
  271. /// <param name="data">The data.</param>
  272. /// <returns>DtoUserItemData.</returns>
  273. /// <exception cref="System.ArgumentNullException"></exception>
  274. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  275. {
  276. if (data == null)
  277. {
  278. throw new ArgumentNullException("data");
  279. }
  280. return new UserItemDataDto
  281. {
  282. IsFavorite = data.IsFavorite,
  283. Likes = data.Likes,
  284. PlaybackPositionTicks = data.PlaybackPositionTicks,
  285. PlayCount = data.PlayCount,
  286. Rating = data.Rating,
  287. Played = data.Played,
  288. LastPlayedDate = data.LastPlayedDate,
  289. Key = data.Key
  290. };
  291. }
  292. private void SetBookProperties(BaseItemDto dto, Book item)
  293. {
  294. dto.SeriesName = item.SeriesName;
  295. }
  296. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  297. {
  298. if (!string.IsNullOrEmpty(item.Album))
  299. {
  300. var parentAlbum = _libraryManager.RootFolder
  301. .GetRecursiveChildren(i => i is MusicAlbum)
  302. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  303. if (parentAlbum != null)
  304. {
  305. dto.AlbumId = GetDtoId(parentAlbum);
  306. }
  307. }
  308. dto.Album = item.Album;
  309. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  310. }
  311. private void SetGameProperties(BaseItemDto dto, Game item)
  312. {
  313. dto.Players = item.PlayersSupported;
  314. dto.GameSystem = item.GameSystem;
  315. }
  316. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  317. {
  318. dto.GameSystem = item.GameSystemName;
  319. }
  320. /// <summary>
  321. /// Gets the backdrop image tags.
  322. /// </summary>
  323. /// <param name="item">The item.</param>
  324. /// <returns>List{System.String}.</returns>
  325. private List<Guid> GetBackdropImageTags(BaseItem item)
  326. {
  327. return item.BackdropImagePaths
  328. .Select(p => GetImageCacheTag(item, ImageType.Backdrop, p))
  329. .Where(i => i.HasValue)
  330. .Select(i => i.Value)
  331. .ToList();
  332. }
  333. /// <summary>
  334. /// Gets the screenshot image tags.
  335. /// </summary>
  336. /// <param name="item">The item.</param>
  337. /// <returns>List{Guid}.</returns>
  338. private List<Guid> GetScreenshotImageTags(BaseItem item)
  339. {
  340. var hasScreenshots = item as IHasScreenshots;
  341. if (hasScreenshots == null)
  342. {
  343. return new List<Guid>();
  344. }
  345. return hasScreenshots.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.SortOrder ?? int.MaxValue).ThenBy(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. var hasBudget = item as IHasBudget;
  620. if (hasBudget != null)
  621. {
  622. if (fields.Contains(ItemFields.Budget))
  623. {
  624. dto.Budget = hasBudget.Budget;
  625. }
  626. if (fields.Contains(ItemFields.Revenue))
  627. {
  628. dto.Revenue = hasBudget.Revenue;
  629. }
  630. }
  631. dto.EndDate = item.EndDate;
  632. if (fields.Contains(ItemFields.HomePageUrl))
  633. {
  634. dto.HomePageUrl = item.HomePageUrl;
  635. }
  636. if (fields.Contains(ItemFields.Tags))
  637. {
  638. var hasTags = item as IHasTags;
  639. if (hasTags != null)
  640. {
  641. dto.Tags = hasTags.Tags;
  642. }
  643. if (dto.Tags == null)
  644. {
  645. dto.Tags = new List<string>();
  646. }
  647. }
  648. if (fields.Contains(ItemFields.ProductionLocations))
  649. {
  650. SetProductionLocations(item, dto);
  651. }
  652. var hasAspectRatio = item as IHasAspectRatio;
  653. if (hasAspectRatio != null)
  654. {
  655. dto.AspectRatio = hasAspectRatio.AspectRatio;
  656. }
  657. dto.BackdropImageTags = GetBackdropImageTags(item);
  658. if (fields.Contains(ItemFields.ScreenshotImageTags))
  659. {
  660. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  661. }
  662. if (fields.Contains(ItemFields.Genres))
  663. {
  664. dto.Genres = item.Genres;
  665. }
  666. dto.ImageTags = new Dictionary<ImageType, Guid>();
  667. foreach (var image in item.Images)
  668. {
  669. var type = image.Key;
  670. var tag = GetImageCacheTag(item, type, image.Value);
  671. if (tag.HasValue)
  672. {
  673. dto.ImageTags[type] = tag.Value;
  674. }
  675. }
  676. dto.Id = GetDtoId(item);
  677. dto.IndexNumber = item.IndexNumber;
  678. dto.IsFolder = item.IsFolder;
  679. dto.MediaType = item.MediaType;
  680. dto.LocationType = item.LocationType;
  681. var hasLanguage = item as IHasLanguage;
  682. if (hasLanguage != null)
  683. {
  684. dto.Language = hasLanguage.Language;
  685. }
  686. var hasCriticRating = item as IHasCriticRating;
  687. if (hasCriticRating != null)
  688. {
  689. dto.CriticRating = hasCriticRating.CriticRating;
  690. if (fields.Contains(ItemFields.CriticRatingSummary))
  691. {
  692. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  693. }
  694. }
  695. var hasTrailers = item as IHasTrailers;
  696. if (hasTrailers != null)
  697. {
  698. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  699. }
  700. if (fields.Contains(ItemFields.RemoteTrailers))
  701. {
  702. dto.RemoteTrailers = hasTrailers != null ?
  703. hasTrailers.RemoteTrailers :
  704. new List<MediaUrl>();
  705. }
  706. dto.Name = item.Name;
  707. dto.OfficialRating = item.OfficialRating;
  708. var hasOverview = fields.Contains(ItemFields.Overview);
  709. var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
  710. if (hasOverview || hasHtmlOverview)
  711. {
  712. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  713. if (hasOverview)
  714. {
  715. dto.Overview = strippedOverview;
  716. }
  717. // Only supply the html version if there was actually html content
  718. if (hasHtmlOverview)
  719. {
  720. dto.OverviewHtml = item.Overview;
  721. }
  722. }
  723. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  724. if (dto.BackdropImageTags.Count == 0)
  725. {
  726. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  727. if (parentWithBackdrop != null)
  728. {
  729. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  730. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  731. }
  732. }
  733. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  734. {
  735. dto.ParentId = GetDtoId(item.Parent);
  736. }
  737. dto.ParentIndexNumber = item.ParentIndexNumber;
  738. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  739. if (!dto.HasLogo)
  740. {
  741. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  742. if (parentWithLogo != null)
  743. {
  744. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  745. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImage(ImageType.Logo));
  746. }
  747. }
  748. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  749. if (!dto.HasArtImage)
  750. {
  751. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  752. if (parentWithImage != null)
  753. {
  754. dto.ParentArtItemId = GetDtoId(parentWithImage);
  755. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImage(ImageType.Art));
  756. }
  757. }
  758. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  759. if (!dto.HasThumb)
  760. {
  761. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  762. if (parentWithImage != null)
  763. {
  764. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  765. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb, parentWithImage.GetImage(ImageType.Thumb));
  766. }
  767. }
  768. if (fields.Contains(ItemFields.Path))
  769. {
  770. dto.Path = item.Path;
  771. }
  772. dto.PremiereDate = item.PremiereDate;
  773. dto.ProductionYear = item.ProductionYear;
  774. if (fields.Contains(ItemFields.ProviderIds))
  775. {
  776. dto.ProviderIds = item.ProviderIds;
  777. }
  778. dto.RunTimeTicks = item.RunTimeTicks;
  779. if (fields.Contains(ItemFields.SortName))
  780. {
  781. dto.SortName = item.SortName;
  782. }
  783. if (fields.Contains(ItemFields.CustomRating))
  784. {
  785. dto.CustomRating = item.CustomRating;
  786. }
  787. if (fields.Contains(ItemFields.Taglines))
  788. {
  789. var hasTagline = item as IHasTaglines;
  790. if (hasTagline != null)
  791. {
  792. dto.Taglines = hasTagline.Taglines;
  793. }
  794. if (dto.Taglines == null)
  795. {
  796. dto.Taglines = new List<string>();
  797. }
  798. }
  799. dto.Type = item.GetClientTypeName();
  800. dto.CommunityRating = item.CommunityRating;
  801. dto.VoteCount = item.VoteCount;
  802. if (item.IsFolder)
  803. {
  804. var folder = (Folder)item;
  805. if (fields.Contains(ItemFields.IndexOptions))
  806. {
  807. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  808. }
  809. }
  810. // Add audio info
  811. var audio = item as Audio;
  812. if (audio != null)
  813. {
  814. dto.Album = audio.Album;
  815. dto.Artists = audio.Artists;
  816. var albumParent = audio.FindParent<MusicAlbum>();
  817. if (albumParent != null)
  818. {
  819. dto.AlbumId = GetDtoId(albumParent);
  820. var imagePath = albumParent.PrimaryImagePath;
  821. if (!string.IsNullOrEmpty(imagePath))
  822. {
  823. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
  824. }
  825. }
  826. }
  827. var album = item as MusicAlbum;
  828. if (album != null)
  829. {
  830. dto.Artists = album.Artists;
  831. dto.SoundtrackIds = album.SoundtrackIds
  832. .Select(i => i.ToString("N"))
  833. .ToArray();
  834. }
  835. var hasAlbumArtist = item as IHasAlbumArtist;
  836. if (hasAlbumArtist != null)
  837. {
  838. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  839. }
  840. // Add video info
  841. var video = item as Video;
  842. if (video != null)
  843. {
  844. dto.VideoType = video.VideoType;
  845. dto.Video3DFormat = video.Video3DFormat;
  846. dto.IsoType = video.IsoType;
  847. dto.IsHD = video.IsHD;
  848. dto.PartCount = video.AdditionalPartIds.Count + 1;
  849. if (fields.Contains(ItemFields.Chapters))
  850. {
  851. dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  852. }
  853. }
  854. if (fields.Contains(ItemFields.MediaStreams))
  855. {
  856. // Add VideoInfo
  857. var iHasMediaStreams = item as IHasMediaStreams;
  858. if (iHasMediaStreams != null)
  859. {
  860. dto.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  861. {
  862. ItemId = item.Id
  863. }).ToList();
  864. }
  865. }
  866. // Add MovieInfo
  867. var movie = item as Movie;
  868. if (movie != null)
  869. {
  870. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  871. if (specialFeatureCount > 0)
  872. {
  873. dto.SpecialFeatureCount = specialFeatureCount;
  874. }
  875. }
  876. // Add EpisodeInfo
  877. var episode = item as Episode;
  878. if (episode != null)
  879. {
  880. dto.IndexNumberEnd = episode.IndexNumberEnd;
  881. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  882. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  883. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  884. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  885. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  886. var seasonId = episode.SeasonId;
  887. if (seasonId.HasValue)
  888. {
  889. dto.SeasonId = seasonId.Value.ToString("N");
  890. }
  891. }
  892. // Add SeriesInfo
  893. var series = item as Series;
  894. if (series != null)
  895. {
  896. dto.AirDays = series.AirDays;
  897. dto.AirTime = series.AirTime;
  898. dto.Status = series.Status;
  899. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  900. dto.SeasonCount = series.SeasonCount;
  901. }
  902. if (episode != null)
  903. {
  904. series = item.FindParent<Series>();
  905. dto.SeriesId = GetDtoId(series);
  906. dto.SeriesName = series.Name;
  907. dto.AirTime = series.AirTime;
  908. dto.SeriesStudio = series.Studios.FirstOrDefault();
  909. if (series.HasImage(ImageType.Thumb))
  910. {
  911. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb, series.GetImage(ImageType.Thumb));
  912. }
  913. var imagePath = series.PrimaryImagePath;
  914. if (!string.IsNullOrEmpty(imagePath))
  915. {
  916. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  917. }
  918. }
  919. // Add SeasonInfo
  920. var season = item as Season;
  921. if (season != null)
  922. {
  923. series = item.FindParent<Series>();
  924. dto.SeriesId = GetDtoId(series);
  925. dto.SeriesName = series.Name;
  926. dto.AirTime = series.AirTime;
  927. dto.SeriesStudio = series.Studios.FirstOrDefault();
  928. var imagePath = series.PrimaryImagePath;
  929. if (!string.IsNullOrEmpty(imagePath))
  930. {
  931. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary, imagePath);
  932. }
  933. }
  934. var game = item as Game;
  935. if (game != null)
  936. {
  937. SetGameProperties(dto, game);
  938. }
  939. var gameSystem = item as GameSystem;
  940. if (gameSystem != null)
  941. {
  942. SetGameSystemProperties(dto, gameSystem);
  943. }
  944. var musicVideo = item as MusicVideo;
  945. if (musicVideo != null)
  946. {
  947. SetMusicVideoProperties(dto, musicVideo);
  948. }
  949. var book = item as Book;
  950. if (book != null)
  951. {
  952. SetBookProperties(dto, book);
  953. }
  954. }
  955. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  956. {
  957. var hasProductionLocations = item as IHasProductionLocations;
  958. if (hasProductionLocations != null)
  959. {
  960. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  961. }
  962. var person = item as Person;
  963. if (person != null)
  964. {
  965. dto.ProductionLocations = new List<string>();
  966. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  967. {
  968. dto.ProductionLocations.Add(person.PlaceOfBirth);
  969. }
  970. }
  971. if (dto.ProductionLocations == null)
  972. {
  973. dto.ProductionLocations = new List<string>();
  974. }
  975. }
  976. /// <summary>
  977. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  978. /// </summary>
  979. /// <param name="folder">The folder.</param>
  980. /// <param name="user">The user.</param>
  981. /// <param name="dto">The dto.</param>
  982. /// <param name="fields">The fields.</param>
  983. /// <returns>Task.</returns>
  984. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  985. {
  986. var rcentlyAddedItemCount = 0;
  987. var recursiveItemCount = 0;
  988. var unplayed = 0;
  989. long runtime = 0;
  990. double totalPercentPlayed = 0;
  991. // Loop through each recursive child
  992. foreach (var child in folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual))
  993. {
  994. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  995. recursiveItemCount++;
  996. // Check is recently added
  997. if (child.IsRecentlyAdded())
  998. {
  999. rcentlyAddedItemCount++;
  1000. }
  1001. var isUnplayed = true;
  1002. // Incrememt totalPercentPlayed
  1003. if (userdata != null)
  1004. {
  1005. if (userdata.Played)
  1006. {
  1007. totalPercentPlayed += 100;
  1008. isUnplayed = false;
  1009. }
  1010. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1011. {
  1012. double itemPercent = userdata.PlaybackPositionTicks;
  1013. itemPercent /= child.RunTimeTicks.Value;
  1014. totalPercentPlayed += itemPercent;
  1015. }
  1016. }
  1017. if (isUnplayed)
  1018. {
  1019. unplayed++;
  1020. }
  1021. runtime += child.RunTimeTicks ?? 0;
  1022. }
  1023. dto.RecursiveItemCount = recursiveItemCount;
  1024. dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
  1025. dto.RecursiveUnplayedItemCount = unplayed;
  1026. if (recursiveItemCount > 0)
  1027. {
  1028. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1029. }
  1030. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1031. {
  1032. dto.CumulativeRunTimeTicks = runtime;
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// Attaches the primary image aspect ratio.
  1037. /// </summary>
  1038. /// <param name="dto">The dto.</param>
  1039. /// <param name="item">The item.</param>
  1040. /// <returns>Task.</returns>
  1041. private void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1042. {
  1043. var path = item.PrimaryImagePath;
  1044. if (string.IsNullOrEmpty(path))
  1045. {
  1046. return;
  1047. }
  1048. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1049. var dateModified = item.GetImageDateModified(path);
  1050. ImageSize size;
  1051. try
  1052. {
  1053. size = _imageProcessor.GetImageSize(path, dateModified);
  1054. }
  1055. catch (FileNotFoundException)
  1056. {
  1057. _logger.Error("Image file does not exist: {0}", path);
  1058. return;
  1059. }
  1060. catch (Exception ex)
  1061. {
  1062. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1063. return;
  1064. }
  1065. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1066. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1067. foreach (var enhancer in supportedEnhancers)
  1068. {
  1069. try
  1070. {
  1071. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1072. }
  1073. catch (Exception ex)
  1074. {
  1075. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1076. }
  1077. }
  1078. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1079. }
  1080. }
  1081. }