DtoService.cs 57 KB

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