DtoService.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Entities.Movies;
  10. using MediaBrowser.Controller.Entities.TV;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Sync;
  16. using MediaBrowser.Model.Drawing;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Querying;
  21. using MoreLinq;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.IO;
  25. using System.Linq;
  26. namespace MediaBrowser.Server.Implementations.Dto
  27. {
  28. public class DtoService : IDtoService
  29. {
  30. private readonly ILogger _logger;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly IUserDataManager _userDataRepository;
  33. private readonly IItemRepository _itemRepo;
  34. private readonly IImageProcessor _imageProcessor;
  35. private readonly IServerConfigurationManager _config;
  36. private readonly IFileSystem _fileSystem;
  37. private readonly IProviderManager _providerManager;
  38. private readonly Func<IChannelManager> _channelManagerFactory;
  39. private readonly ISyncManager _syncManager;
  40. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func<IChannelManager> channelManagerFactory, ISyncManager syncManager)
  41. {
  42. _logger = logger;
  43. _libraryManager = libraryManager;
  44. _userDataRepository = userDataRepository;
  45. _itemRepo = itemRepo;
  46. _imageProcessor = imageProcessor;
  47. _config = config;
  48. _fileSystem = fileSystem;
  49. _providerManager = providerManager;
  50. _channelManagerFactory = channelManagerFactory;
  51. _syncManager = syncManager;
  52. }
  53. /// <summary>
  54. /// Converts a BaseItem to a DTOBaseItem
  55. /// </summary>
  56. /// <param name="item">The item.</param>
  57. /// <param name="fields">The fields.</param>
  58. /// <param name="user">The user.</param>
  59. /// <param name="owner">The owner.</param>
  60. /// <returns>Task{DtoBaseItem}.</returns>
  61. /// <exception cref="System.ArgumentNullException">item</exception>
  62. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  63. {
  64. var dto = GetBaseItemDtoInternal(item, fields, user, owner);
  65. var byName = item as IItemByName;
  66. if (byName != null && !(item is LiveTvChannel))
  67. {
  68. IEnumerable<BaseItem> libraryItems;
  69. var artist = item as MusicArtist;
  70. if (artist == null || artist.IsAccessedByName)
  71. {
  72. libraryItems = user != null ?
  73. user.RootFolder.GetRecursiveChildren(user) :
  74. _libraryManager.RootFolder.RecursiveChildren;
  75. }
  76. else
  77. {
  78. libraryItems = user != null ?
  79. artist.GetRecursiveChildren(user) :
  80. artist.RecursiveChildren;
  81. }
  82. SetItemByNameInfo(item, dto, byName.GetTaggedItems(libraryItems).ToList(), user);
  83. return dto;
  84. }
  85. return dto;
  86. }
  87. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  88. {
  89. if (item == null)
  90. {
  91. throw new ArgumentNullException("item");
  92. }
  93. if (fields == null)
  94. {
  95. throw new ArgumentNullException("fields");
  96. }
  97. var dto = new BaseItemDto();
  98. if (fields.Contains(ItemFields.People))
  99. {
  100. AttachPeople(dto, item);
  101. }
  102. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  103. {
  104. try
  105. {
  106. AttachPrimaryImageAspectRatio(dto, item);
  107. }
  108. catch (Exception ex)
  109. {
  110. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  111. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  112. }
  113. }
  114. if (fields.Contains(ItemFields.DisplayPreferencesId))
  115. {
  116. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  117. }
  118. if (user != null)
  119. {
  120. AttachUserSpecificInfo(dto, item, user, fields);
  121. }
  122. var hasMediaSources = item as IHasMediaSources;
  123. if (hasMediaSources != null)
  124. {
  125. if (fields.Contains(ItemFields.MediaSources))
  126. {
  127. if (user == null)
  128. {
  129. dto.MediaSources = hasMediaSources.GetMediaSources(true).ToList();
  130. }
  131. else
  132. {
  133. dto.MediaSources = hasMediaSources.GetMediaSources(true, user).ToList();
  134. }
  135. }
  136. }
  137. if (fields.Contains(ItemFields.Studios))
  138. {
  139. AttachStudios(dto, item);
  140. }
  141. AttachBasicFields(dto, item, owner, fields);
  142. if (fields.Contains(ItemFields.SyncInfo))
  143. {
  144. dto.SupportsSync = _syncManager.SupportsSync(item);
  145. }
  146. if (fields.Contains(ItemFields.SoundtrackIds))
  147. {
  148. var hasSoundtracks = item as IHasSoundtracks;
  149. if (hasSoundtracks != null)
  150. {
  151. dto.SoundtrackIds = hasSoundtracks.SoundtrackIds
  152. .Select(i => i.ToString("N"))
  153. .ToArray();
  154. }
  155. }
  156. return dto;
  157. }
  158. public BaseItemDto GetItemByNameDto<T>(T item, List<ItemFields> fields, List<BaseItem> taggedItems, User user = null)
  159. where T : BaseItem, IItemByName
  160. {
  161. var dto = GetBaseItemDtoInternal(item, fields, user);
  162. SetItemByNameInfo(item, dto, taggedItems, user);
  163. return dto;
  164. }
  165. private void SetItemByNameInfo(BaseItem item, BaseItemDto dto, List<BaseItem> taggedItems, User user = null)
  166. {
  167. if (item is MusicArtist || item is MusicGenre)
  168. {
  169. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  170. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  171. dto.SongCount = taggedItems.Count(i => i is Audio);
  172. }
  173. else if (item is GameGenre)
  174. {
  175. dto.GameCount = taggedItems.Count(i => i is Game);
  176. }
  177. else
  178. {
  179. // This populates them all and covers Genre, Person, Studio, Year
  180. dto.AdultVideoCount = taggedItems.Count(i => i is AdultVideo);
  181. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  182. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  183. dto.GameCount = taggedItems.Count(i => i is Game);
  184. dto.MovieCount = taggedItems.Count(i => i is Movie);
  185. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  186. dto.SeriesCount = taggedItems.Count(i => i is Series);
  187. dto.SongCount = taggedItems.Count(i => i is Audio);
  188. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  189. }
  190. dto.ChildCount = taggedItems.Count;
  191. }
  192. /// <summary>
  193. /// Attaches the user specific info.
  194. /// </summary>
  195. /// <param name="dto">The dto.</param>
  196. /// <param name="item">The item.</param>
  197. /// <param name="user">The user.</param>
  198. /// <param name="fields">The fields.</param>
  199. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  200. {
  201. if (item.IsFolder)
  202. {
  203. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  204. // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice
  205. // TODO: Improve in future
  206. dto.UserData = GetUserItemDataDto(userData);
  207. var folder = (Folder)item;
  208. dto.ChildCount = GetChildCount(folder, user);
  209. if (!(folder is UserRootFolder))
  210. {
  211. SetSpecialCounts(folder, user, dto, fields);
  212. }
  213. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  214. dto.UserData.PlayedPercentage = dto.PlayedPercentage;
  215. dto.UserData.UnplayedItemCount = dto.RecursiveUnplayedItemCount;
  216. }
  217. else
  218. {
  219. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  220. }
  221. dto.PlayAccess = item.GetPlayAccess(user);
  222. }
  223. private int GetChildCount(Folder folder, User user)
  224. {
  225. return folder.GetChildren(user, true)
  226. .Count();
  227. }
  228. public UserDto GetUserDto(User user)
  229. {
  230. if (user == null)
  231. {
  232. throw new ArgumentNullException("user");
  233. }
  234. var dto = new UserDto
  235. {
  236. Id = user.Id.ToString("N"),
  237. Name = user.Name,
  238. HasPassword = !String.IsNullOrEmpty(user.Password),
  239. LastActivityDate = user.LastActivityDate,
  240. LastLoginDate = user.LastLoginDate,
  241. Configuration = user.Configuration
  242. };
  243. var image = user.GetImageInfo(ImageType.Primary, 0);
  244. if (image != null)
  245. {
  246. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  247. try
  248. {
  249. AttachPrimaryImageAspectRatio(dto, user);
  250. }
  251. catch (Exception ex)
  252. {
  253. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  254. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  255. }
  256. }
  257. return dto;
  258. }
  259. /// <summary>
  260. /// Gets client-side Id of a server-side BaseItem
  261. /// </summary>
  262. /// <param name="item">The item.</param>
  263. /// <returns>System.String.</returns>
  264. /// <exception cref="System.ArgumentNullException">item</exception>
  265. public string GetDtoId(BaseItem item)
  266. {
  267. if (item == null)
  268. {
  269. throw new ArgumentNullException("item");
  270. }
  271. return item.Id.ToString("N");
  272. }
  273. /// <summary>
  274. /// Converts a UserItemData to a DTOUserItemData
  275. /// </summary>
  276. /// <param name="data">The data.</param>
  277. /// <returns>DtoUserItemData.</returns>
  278. /// <exception cref="System.ArgumentNullException"></exception>
  279. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  280. {
  281. if (data == null)
  282. {
  283. throw new ArgumentNullException("data");
  284. }
  285. return new UserItemDataDto
  286. {
  287. IsFavorite = data.IsFavorite,
  288. Likes = data.Likes,
  289. PlaybackPositionTicks = data.PlaybackPositionTicks,
  290. PlayCount = data.PlayCount,
  291. Rating = data.Rating,
  292. Played = data.Played,
  293. LastPlayedDate = data.LastPlayedDate,
  294. Key = data.Key
  295. };
  296. }
  297. private void SetBookProperties(BaseItemDto dto, Book item)
  298. {
  299. dto.SeriesName = item.SeriesName;
  300. }
  301. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  302. {
  303. if (!string.IsNullOrEmpty(item.Album))
  304. {
  305. var parentAlbum = _libraryManager.RootFolder
  306. .GetRecursiveChildren()
  307. .Where(i => i is MusicAlbum)
  308. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  309. if (parentAlbum != null)
  310. {
  311. dto.AlbumId = GetDtoId(parentAlbum);
  312. }
  313. }
  314. dto.Album = item.Album;
  315. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  316. }
  317. private void SetGameProperties(BaseItemDto dto, Game item)
  318. {
  319. dto.Players = item.PlayersSupported;
  320. dto.GameSystem = item.GameSystem;
  321. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  322. }
  323. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  324. {
  325. dto.GameSystem = item.GameSystemName;
  326. }
  327. /// <summary>
  328. /// Gets the backdrop image tags.
  329. /// </summary>
  330. /// <param name="item">The item.</param>
  331. /// <returns>List{System.String}.</returns>
  332. private List<string> GetBackdropImageTags(BaseItem item)
  333. {
  334. return GetCacheTags(item, ImageType.Backdrop).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<string> GetScreenshotImageTags(BaseItem item)
  342. {
  343. var hasScreenshots = item as IHasScreenshots;
  344. if (hasScreenshots == null)
  345. {
  346. return new List<string>();
  347. }
  348. return GetCacheTags(item, ImageType.Screenshot).ToList();
  349. }
  350. private IEnumerable<string> GetCacheTags(BaseItem item, ImageType type)
  351. {
  352. return item.GetImages(type)
  353. .Select(p => GetImageCacheTag(item, p))
  354. .Where(i => i != null)
  355. .ToList();
  356. }
  357. private string GetImageCacheTag(BaseItem item, ImageType type)
  358. {
  359. try
  360. {
  361. return _imageProcessor.GetImageCacheTag(item, type);
  362. }
  363. catch (Exception ex)
  364. {
  365. _logger.ErrorException("Error getting {0} image info", ex, type);
  366. return null;
  367. }
  368. }
  369. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  370. {
  371. try
  372. {
  373. return _imageProcessor.GetImageCacheTag(item, image);
  374. }
  375. catch (Exception ex)
  376. {
  377. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  378. return null;
  379. }
  380. }
  381. /// <summary>
  382. /// Attaches People DTO's to a DTOBaseItem
  383. /// </summary>
  384. /// <param name="dto">The dto.</param>
  385. /// <param name="item">The item.</param>
  386. /// <returns>Task.</returns>
  387. private void AttachPeople(BaseItemDto dto, BaseItem item)
  388. {
  389. // Ordering by person type to ensure actors and artists are at the front.
  390. // This is taking advantage of the fact that they both begin with A
  391. // This should be improved in the future
  392. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue)
  393. .ThenBy(i =>
  394. {
  395. if (i.IsType(PersonType.Actor))
  396. {
  397. return 0;
  398. }
  399. if (i.IsType(PersonType.GuestStar))
  400. {
  401. return 1;
  402. }
  403. if (i.IsType(PersonType.Director))
  404. {
  405. return 2;
  406. }
  407. if (i.IsType(PersonType.Writer))
  408. {
  409. return 3;
  410. }
  411. if (i.IsType(PersonType.Producer))
  412. {
  413. return 4;
  414. }
  415. if (i.IsType(PersonType.Composer))
  416. {
  417. return 4;
  418. }
  419. return 10;
  420. })
  421. .ToList();
  422. // Attach People by transforming them into BaseItemPerson (DTO)
  423. dto.People = new BaseItemPerson[people.Count];
  424. var dictionary = people.Select(p => p.Name)
  425. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  426. {
  427. try
  428. {
  429. return _libraryManager.GetPerson(c);
  430. }
  431. catch (IOException ex)
  432. {
  433. _logger.ErrorException("Error getting person {0}", ex, c);
  434. return null;
  435. }
  436. }).Where(i => i != null)
  437. .DistinctBy(i => i.Name)
  438. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  439. for (var i = 0; i < people.Count; i++)
  440. {
  441. var person = people[i];
  442. var baseItemPerson = new BaseItemPerson
  443. {
  444. Name = person.Name,
  445. Role = person.Role,
  446. Type = person.Type
  447. };
  448. Person entity;
  449. if (dictionary.TryGetValue(person.Name, out entity))
  450. {
  451. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  452. baseItemPerson.Id = entity.Id.ToString("N");
  453. }
  454. dto.People[i] = baseItemPerson;
  455. }
  456. }
  457. /// <summary>
  458. /// Attaches the studios.
  459. /// </summary>
  460. /// <param name="dto">The dto.</param>
  461. /// <param name="item">The item.</param>
  462. /// <returns>Task.</returns>
  463. private void AttachStudios(BaseItemDto dto, BaseItem item)
  464. {
  465. var studios = item.Studios.ToList();
  466. dto.Studios = new StudioDto[studios.Count];
  467. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  468. {
  469. try
  470. {
  471. return _libraryManager.GetStudio(name);
  472. }
  473. catch (IOException ex)
  474. {
  475. _logger.ErrorException("Error getting studio {0}", ex, name);
  476. return null;
  477. }
  478. })
  479. .Where(i => i != null)
  480. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  481. for (var i = 0; i < studios.Count; i++)
  482. {
  483. var studio = studios[i];
  484. var studioDto = new StudioDto
  485. {
  486. Name = studio
  487. };
  488. Studio entity;
  489. if (dictionary.TryGetValue(studio, out entity))
  490. {
  491. studioDto.Id = entity.Id.ToString("N");
  492. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  493. }
  494. dto.Studios[i] = studioDto;
  495. }
  496. }
  497. /// <summary>
  498. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  499. /// </summary>
  500. /// <param name="item">The item.</param>
  501. /// <param name="owner">The owner.</param>
  502. /// <returns>BaseItem.</returns>
  503. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  504. {
  505. var parent = item.Parent ?? owner;
  506. while (parent != null)
  507. {
  508. if (parent.GetImages(ImageType.Backdrop).Any())
  509. {
  510. return parent;
  511. }
  512. parent = parent.Parent;
  513. }
  514. return null;
  515. }
  516. /// <summary>
  517. /// If an item does not have a logo, this can be used to find the first parent that does have one
  518. /// </summary>
  519. /// <param name="item">The item.</param>
  520. /// <param name="type">The type.</param>
  521. /// <param name="owner">The owner.</param>
  522. /// <returns>BaseItem.</returns>
  523. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  524. {
  525. var parent = item.Parent ?? owner;
  526. while (parent != null)
  527. {
  528. if (parent.HasImage(type))
  529. {
  530. return parent;
  531. }
  532. parent = parent.Parent;
  533. }
  534. return null;
  535. }
  536. /// <summary>
  537. /// Gets the chapter info dto.
  538. /// </summary>
  539. /// <param name="chapterInfo">The chapter info.</param>
  540. /// <param name="item">The item.</param>
  541. /// <returns>ChapterInfoDto.</returns>
  542. public ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  543. {
  544. var dto = new ChapterInfoDto
  545. {
  546. Name = chapterInfo.Name,
  547. StartPositionTicks = chapterInfo.StartPositionTicks
  548. };
  549. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  550. {
  551. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  552. {
  553. Path = chapterInfo.ImagePath,
  554. Type = ImageType.Chapter,
  555. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  556. });
  557. }
  558. return dto;
  559. }
  560. /// <summary>
  561. /// Sets simple property values on a DTOBaseItem
  562. /// </summary>
  563. /// <param name="dto">The dto.</param>
  564. /// <param name="item">The item.</param>
  565. /// <param name="owner">The owner.</param>
  566. /// <param name="fields">The fields.</param>
  567. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  568. {
  569. if (fields.Contains(ItemFields.DateCreated))
  570. {
  571. dto.DateCreated = item.DateCreated;
  572. }
  573. if (fields.Contains(ItemFields.DisplayMediaType))
  574. {
  575. dto.DisplayMediaType = item.DisplayMediaType;
  576. }
  577. dto.IsUnidentified = item.IsUnidentified;
  578. if (fields.Contains(ItemFields.Settings))
  579. {
  580. dto.LockedFields = item.LockedFields;
  581. dto.LockData = item.IsLocked;
  582. dto.ForcedSortName = item.ForcedSortName;
  583. }
  584. var hasBudget = item as IHasBudget;
  585. if (hasBudget != null)
  586. {
  587. if (fields.Contains(ItemFields.Budget))
  588. {
  589. dto.Budget = hasBudget.Budget;
  590. }
  591. if (fields.Contains(ItemFields.Revenue))
  592. {
  593. dto.Revenue = hasBudget.Revenue;
  594. }
  595. }
  596. dto.EndDate = item.EndDate;
  597. if (fields.Contains(ItemFields.HomePageUrl))
  598. {
  599. dto.HomePageUrl = item.HomePageUrl;
  600. }
  601. if (fields.Contains(ItemFields.ExternalUrls))
  602. {
  603. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  604. }
  605. if (fields.Contains(ItemFields.Tags))
  606. {
  607. var hasTags = item as IHasTags;
  608. if (hasTags != null)
  609. {
  610. dto.Tags = hasTags.Tags;
  611. }
  612. if (dto.Tags == null)
  613. {
  614. dto.Tags = new List<string>();
  615. }
  616. }
  617. if (fields.Contains(ItemFields.Keywords))
  618. {
  619. var hasTags = item as IHasKeywords;
  620. if (hasTags != null)
  621. {
  622. dto.Keywords = hasTags.Keywords;
  623. }
  624. if (dto.Keywords == null)
  625. {
  626. dto.Keywords = new List<string>();
  627. }
  628. }
  629. if (fields.Contains(ItemFields.ProductionLocations))
  630. {
  631. SetProductionLocations(item, dto);
  632. }
  633. var hasAspectRatio = item as IHasAspectRatio;
  634. if (hasAspectRatio != null)
  635. {
  636. dto.AspectRatio = hasAspectRatio.AspectRatio;
  637. }
  638. var hasMetascore = item as IHasMetascore;
  639. if (hasMetascore != null)
  640. {
  641. dto.Metascore = hasMetascore.Metascore;
  642. }
  643. if (fields.Contains(ItemFields.AwardSummary))
  644. {
  645. var hasAwards = item as IHasAwards;
  646. if (hasAwards != null)
  647. {
  648. dto.AwardSummary = hasAwards.AwardSummary;
  649. }
  650. }
  651. dto.BackdropImageTags = GetBackdropImageTags(item);
  652. if (fields.Contains(ItemFields.ScreenshotImageTags))
  653. {
  654. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  655. }
  656. if (fields.Contains(ItemFields.Genres))
  657. {
  658. dto.Genres = item.Genres;
  659. }
  660. dto.ImageTags = new Dictionary<ImageType, string>();
  661. // Prevent implicitly captured closure
  662. var currentItem = item;
  663. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  664. {
  665. var tag = GetImageCacheTag(item, image);
  666. if (tag != null)
  667. {
  668. dto.ImageTags[image.Type] = tag;
  669. }
  670. }
  671. dto.Id = GetDtoId(item);
  672. dto.IndexNumber = item.IndexNumber;
  673. dto.IsFolder = item.IsFolder;
  674. dto.MediaType = item.MediaType;
  675. dto.LocationType = item.LocationType;
  676. var hasLang = item as IHasPreferredMetadataLanguage;
  677. if (hasLang != null)
  678. {
  679. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  680. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  681. }
  682. var hasCriticRating = item as IHasCriticRating;
  683. if (hasCriticRating != null)
  684. {
  685. dto.CriticRating = hasCriticRating.CriticRating;
  686. if (fields.Contains(ItemFields.CriticRatingSummary))
  687. {
  688. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  689. }
  690. }
  691. var hasTrailers = item as IHasTrailers;
  692. if (hasTrailers != null)
  693. {
  694. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  695. }
  696. var hasDisplayOrder = item as IHasDisplayOrder;
  697. if (hasDisplayOrder != null)
  698. {
  699. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  700. }
  701. var collectionFolder = item as CollectionFolder;
  702. if (collectionFolder != null)
  703. {
  704. dto.CollectionType = collectionFolder.CollectionType;
  705. }
  706. var userView = item as UserView;
  707. if (userView != null)
  708. {
  709. dto.CollectionType = userView.ViewType;
  710. }
  711. if (fields.Contains(ItemFields.RemoteTrailers))
  712. {
  713. dto.RemoteTrailers = hasTrailers != null ?
  714. hasTrailers.RemoteTrailers :
  715. new List<MediaUrl>();
  716. }
  717. dto.Name = item.Name;
  718. dto.OfficialRating = item.OfficialRating;
  719. if (fields.Contains(ItemFields.Overview))
  720. {
  721. // TODO: Remove this after a while, since it's been moved to the providers
  722. if (item is MusicArtist)
  723. {
  724. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  725. dto.Overview = strippedOverview;
  726. }
  727. else
  728. {
  729. dto.Overview = item.Overview;
  730. }
  731. }
  732. if (fields.Contains(ItemFields.ShortOverview))
  733. {
  734. var hasShortOverview = item as IHasShortOverview;
  735. if (hasShortOverview != null)
  736. {
  737. dto.ShortOverview = hasShortOverview.ShortOverview;
  738. }
  739. }
  740. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  741. if (dto.BackdropImageTags.Count == 0)
  742. {
  743. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  744. if (parentWithBackdrop != null)
  745. {
  746. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  747. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  748. }
  749. }
  750. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  751. {
  752. dto.ParentId = GetDtoId(item.Parent);
  753. }
  754. dto.ParentIndexNumber = item.ParentIndexNumber;
  755. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  756. if (!dto.HasLogo)
  757. {
  758. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  759. if (parentWithLogo != null)
  760. {
  761. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  762. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  763. }
  764. }
  765. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  766. if (!dto.HasArtImage)
  767. {
  768. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  769. if (parentWithImage != null)
  770. {
  771. dto.ParentArtItemId = GetDtoId(parentWithImage);
  772. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  773. }
  774. }
  775. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  776. if (!dto.HasThumb)
  777. {
  778. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  779. if (parentWithImage != null)
  780. {
  781. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  782. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  783. }
  784. }
  785. if (fields.Contains(ItemFields.Path))
  786. {
  787. dto.Path = GetMappedPath(item);
  788. }
  789. dto.PremiereDate = item.PremiereDate;
  790. dto.ProductionYear = item.ProductionYear;
  791. if (fields.Contains(ItemFields.ProviderIds))
  792. {
  793. dto.ProviderIds = item.ProviderIds;
  794. }
  795. dto.RunTimeTicks = item.RunTimeTicks;
  796. if (fields.Contains(ItemFields.SortName))
  797. {
  798. dto.SortName = item.SortName;
  799. }
  800. if (fields.Contains(ItemFields.CustomRating))
  801. {
  802. dto.CustomRating = item.CustomRating;
  803. }
  804. if (fields.Contains(ItemFields.Taglines))
  805. {
  806. var hasTagline = item as IHasTaglines;
  807. if (hasTagline != null)
  808. {
  809. dto.Taglines = hasTagline.Taglines;
  810. }
  811. if (dto.Taglines == null)
  812. {
  813. dto.Taglines = new List<string>();
  814. }
  815. }
  816. dto.Type = item.GetClientTypeName();
  817. dto.CommunityRating = item.CommunityRating;
  818. dto.VoteCount = item.VoteCount;
  819. if (item.IsFolder)
  820. {
  821. var folder = (Folder)item;
  822. if (fields.Contains(ItemFields.IndexOptions))
  823. {
  824. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  825. }
  826. }
  827. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  828. if (supportsPlaceHolders != null)
  829. {
  830. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  831. }
  832. // Add audio info
  833. var audio = item as Audio;
  834. if (audio != null)
  835. {
  836. dto.Album = audio.Album;
  837. dto.Artists = audio.Artists;
  838. var albumParent = audio.FindParent<MusicAlbum>();
  839. if (albumParent != null)
  840. {
  841. dto.AlbumId = GetDtoId(albumParent);
  842. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  843. }
  844. dto.MediaSourceCount = 1;
  845. }
  846. var album = item as MusicAlbum;
  847. if (album != null)
  848. {
  849. dto.Artists = album.Artists;
  850. dto.SoundtrackIds = album.SoundtrackIds
  851. .Select(i => i.ToString("N"))
  852. .ToArray();
  853. }
  854. var hasAlbumArtist = item as IHasAlbumArtist;
  855. if (hasAlbumArtist != null)
  856. {
  857. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  858. }
  859. // Add video info
  860. var video = item as Video;
  861. if (video != null)
  862. {
  863. dto.VideoType = video.VideoType;
  864. dto.Video3DFormat = video.Video3DFormat;
  865. dto.IsoType = video.IsoType;
  866. dto.IsHD = video.IsHD;
  867. dto.PartCount = video.AdditionalPartIds.Count + 1;
  868. dto.MediaSourceCount = video.MediaSourceCount;
  869. if (fields.Contains(ItemFields.Chapters))
  870. {
  871. List<ChapterInfoDto> chapters;
  872. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  873. {
  874. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  875. }
  876. else
  877. {
  878. chapters = _itemRepo.GetChapters(video.Id)
  879. .Select(c => GetChapterInfoDto(c, item))
  880. .ToList();
  881. }
  882. dto.Chapters = chapters;
  883. }
  884. }
  885. if (fields.Contains(ItemFields.MediaStreams))
  886. {
  887. // Add VideoInfo
  888. var iHasMediaSources = item as IHasMediaSources;
  889. if (iHasMediaSources != null)
  890. {
  891. List<MediaStream> mediaStreams;
  892. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  893. {
  894. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  895. .SelectMany(i => i.MediaStreams)
  896. .ToList();
  897. }
  898. else
  899. {
  900. mediaStreams = iHasMediaSources.GetMediaSources(true).First().MediaStreams;
  901. }
  902. dto.MediaStreams = mediaStreams;
  903. }
  904. }
  905. // Add MovieInfo
  906. var movie = item as Movie;
  907. if (movie != null)
  908. {
  909. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  910. if (specialFeatureCount > 0)
  911. {
  912. dto.SpecialFeatureCount = specialFeatureCount;
  913. }
  914. if (fields.Contains(ItemFields.TmdbCollectionName))
  915. {
  916. dto.TmdbCollectionName = movie.TmdbCollectionName;
  917. }
  918. }
  919. // Add EpisodeInfo
  920. var episode = item as Episode;
  921. if (episode != null)
  922. {
  923. dto.IndexNumberEnd = episode.IndexNumberEnd;
  924. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  925. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  926. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  927. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  928. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  929. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  930. var seasonId = episode.SeasonId;
  931. if (seasonId.HasValue)
  932. {
  933. dto.SeasonId = seasonId.Value.ToString("N");
  934. }
  935. }
  936. // Add SeriesInfo
  937. var series = item as Series;
  938. if (series != null)
  939. {
  940. dto.AirDays = series.AirDays;
  941. dto.AirTime = series.AirTime;
  942. dto.Status = series.Status;
  943. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  944. dto.SeasonCount = series.SeasonCount;
  945. if (fields.Contains(ItemFields.Settings))
  946. {
  947. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  948. }
  949. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  950. }
  951. if (episode != null)
  952. {
  953. series = episode.Series;
  954. if (series != null)
  955. {
  956. dto.SeriesId = GetDtoId(series);
  957. dto.SeriesName = series.Name;
  958. dto.AirTime = series.AirTime;
  959. dto.SeriesStudio = series.Studios.FirstOrDefault();
  960. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  961. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  962. }
  963. }
  964. // Add SeasonInfo
  965. var season = item as Season;
  966. if (season != null)
  967. {
  968. series = season.Series;
  969. if (series != null)
  970. {
  971. dto.SeriesId = GetDtoId(series);
  972. dto.SeriesName = series.Name;
  973. dto.AirTime = series.AirTime;
  974. dto.SeriesStudio = series.Studios.FirstOrDefault();
  975. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  976. }
  977. }
  978. var game = item as Game;
  979. if (game != null)
  980. {
  981. SetGameProperties(dto, game);
  982. }
  983. var gameSystem = item as GameSystem;
  984. if (gameSystem != null)
  985. {
  986. SetGameSystemProperties(dto, gameSystem);
  987. }
  988. var musicVideo = item as MusicVideo;
  989. if (musicVideo != null)
  990. {
  991. SetMusicVideoProperties(dto, musicVideo);
  992. }
  993. var book = item as Book;
  994. if (book != null)
  995. {
  996. SetBookProperties(dto, book);
  997. }
  998. var tvChannel = item as LiveTvChannel;
  999. if (tvChannel != null)
  1000. {
  1001. dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
  1002. }
  1003. var channelItem = item as IChannelItem;
  1004. if (channelItem != null)
  1005. {
  1006. dto.ChannelId = channelItem.ChannelId;
  1007. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1008. }
  1009. }
  1010. private string GetMappedPath(IHasMetadata item)
  1011. {
  1012. var path = item.Path;
  1013. var locationType = item.LocationType;
  1014. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1015. {
  1016. foreach (var map in _config.Configuration.PathSubstitutions)
  1017. {
  1018. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1019. }
  1020. }
  1021. return path;
  1022. }
  1023. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1024. {
  1025. var hasProductionLocations = item as IHasProductionLocations;
  1026. if (hasProductionLocations != null)
  1027. {
  1028. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1029. }
  1030. var person = item as Person;
  1031. if (person != null)
  1032. {
  1033. dto.ProductionLocations = new List<string>();
  1034. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1035. {
  1036. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1037. }
  1038. }
  1039. if (dto.ProductionLocations == null)
  1040. {
  1041. dto.ProductionLocations = new List<string>();
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1046. /// </summary>
  1047. /// <param name="folder">The folder.</param>
  1048. /// <param name="user">The user.</param>
  1049. /// <param name="dto">The dto.</param>
  1050. /// <param name="fields">The fields.</param>
  1051. /// <returns>Task.</returns>
  1052. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1053. {
  1054. var recursiveItemCount = 0;
  1055. var unplayed = 0;
  1056. long runtime = 0;
  1057. DateTime? dateLastMediaAdded = null;
  1058. double totalPercentPlayed = 0;
  1059. IEnumerable<BaseItem> children;
  1060. var season = folder as Season;
  1061. if (season != null)
  1062. {
  1063. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1064. }
  1065. else
  1066. {
  1067. children = folder.GetRecursiveChildren(user)
  1068. .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1069. }
  1070. // Loop through each recursive child
  1071. foreach (var child in children)
  1072. {
  1073. if (!dateLastMediaAdded.HasValue)
  1074. {
  1075. dateLastMediaAdded = child.DateCreated;
  1076. }
  1077. else
  1078. {
  1079. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1080. }
  1081. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1082. recursiveItemCount++;
  1083. var isUnplayed = true;
  1084. // Incrememt totalPercentPlayed
  1085. if (userdata != null)
  1086. {
  1087. if (userdata.Played)
  1088. {
  1089. totalPercentPlayed += 100;
  1090. isUnplayed = false;
  1091. }
  1092. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1093. {
  1094. double itemPercent = userdata.PlaybackPositionTicks;
  1095. itemPercent /= child.RunTimeTicks.Value;
  1096. totalPercentPlayed += itemPercent;
  1097. }
  1098. }
  1099. if (isUnplayed)
  1100. {
  1101. unplayed++;
  1102. }
  1103. runtime += child.RunTimeTicks ?? 0;
  1104. }
  1105. dto.RecursiveItemCount = recursiveItemCount;
  1106. dto.RecursiveUnplayedItemCount = unplayed;
  1107. if (recursiveItemCount > 0)
  1108. {
  1109. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1110. }
  1111. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1112. {
  1113. dto.CumulativeRunTimeTicks = runtime;
  1114. }
  1115. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1116. {
  1117. dto.DateLastMediaAdded = dateLastMediaAdded;
  1118. }
  1119. }
  1120. /// <summary>
  1121. /// Attaches the primary image aspect ratio.
  1122. /// </summary>
  1123. /// <param name="dto">The dto.</param>
  1124. /// <param name="item">The item.</param>
  1125. /// <returns>Task.</returns>
  1126. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1127. {
  1128. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1129. if (imageInfo == null)
  1130. {
  1131. return;
  1132. }
  1133. var path = imageInfo.Path;
  1134. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1135. var dateModified = imageInfo.DateModified;
  1136. ImageSize size;
  1137. try
  1138. {
  1139. size = _imageProcessor.GetImageSize(path, dateModified);
  1140. }
  1141. catch (FileNotFoundException)
  1142. {
  1143. _logger.Error("Image file does not exist: {0}", path);
  1144. return;
  1145. }
  1146. catch (Exception ex)
  1147. {
  1148. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1149. return;
  1150. }
  1151. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1152. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1153. foreach (var enhancer in supportedEnhancers)
  1154. {
  1155. try
  1156. {
  1157. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1158. }
  1159. catch (Exception ex)
  1160. {
  1161. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1162. }
  1163. }
  1164. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1165. }
  1166. }
  1167. }