2
0

DtoService.cs 38 KB

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