DtoService.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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 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. var file = new FileInfo(chapterInfo.ImagePath);
  654. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  655. {
  656. Path = chapterInfo.ImagePath,
  657. Type = ImageType.Chapter,
  658. DateModified = _fileSystem.GetLastWriteTimeUtc(file),
  659. Length = file.Length
  660. });
  661. }
  662. return dto;
  663. }
  664. public List<ChapterInfoDto> GetChapterInfoDtos(BaseItem item)
  665. {
  666. return _itemRepo.GetChapters(item.Id)
  667. .Select(c => GetChapterInfoDto(c, item))
  668. .ToList();
  669. }
  670. /// <summary>
  671. /// Sets simple property values on a DTOBaseItem
  672. /// </summary>
  673. /// <param name="dto">The dto.</param>
  674. /// <param name="item">The item.</param>
  675. /// <param name="owner">The owner.</param>
  676. /// <param name="options">The options.</param>
  677. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  678. {
  679. var fields = options.Fields;
  680. if (fields.Contains(ItemFields.DateCreated))
  681. {
  682. dto.DateCreated = item.DateCreated;
  683. }
  684. if (fields.Contains(ItemFields.DisplayMediaType))
  685. {
  686. dto.DisplayMediaType = item.DisplayMediaType;
  687. }
  688. // Leave null if false
  689. if (item.IsUnidentified)
  690. {
  691. dto.IsUnidentified = item.IsUnidentified;
  692. }
  693. if (fields.Contains(ItemFields.Settings))
  694. {
  695. dto.LockedFields = item.LockedFields;
  696. dto.LockData = item.IsLocked;
  697. dto.ForcedSortName = item.ForcedSortName;
  698. }
  699. var hasBudget = item as IHasBudget;
  700. if (hasBudget != null)
  701. {
  702. if (fields.Contains(ItemFields.Budget))
  703. {
  704. dto.Budget = hasBudget.Budget;
  705. }
  706. if (fields.Contains(ItemFields.Revenue))
  707. {
  708. dto.Revenue = hasBudget.Revenue;
  709. }
  710. }
  711. dto.EndDate = item.EndDate;
  712. if (fields.Contains(ItemFields.HomePageUrl))
  713. {
  714. dto.HomePageUrl = item.HomePageUrl;
  715. }
  716. if (fields.Contains(ItemFields.ExternalUrls))
  717. {
  718. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  719. }
  720. if (fields.Contains(ItemFields.Tags))
  721. {
  722. var hasTags = item as IHasTags;
  723. if (hasTags != null)
  724. {
  725. dto.Tags = hasTags.Tags;
  726. }
  727. if (dto.Tags == null)
  728. {
  729. dto.Tags = new List<string>();
  730. }
  731. }
  732. if (fields.Contains(ItemFields.Keywords))
  733. {
  734. var hasTags = item as IHasKeywords;
  735. if (hasTags != null)
  736. {
  737. dto.Keywords = hasTags.Keywords;
  738. }
  739. if (dto.Keywords == null)
  740. {
  741. dto.Keywords = new List<string>();
  742. }
  743. }
  744. if (fields.Contains(ItemFields.ProductionLocations))
  745. {
  746. SetProductionLocations(item, dto);
  747. }
  748. var hasAspectRatio = item as IHasAspectRatio;
  749. if (hasAspectRatio != null)
  750. {
  751. dto.AspectRatio = hasAspectRatio.AspectRatio;
  752. }
  753. if (fields.Contains(ItemFields.Metascore))
  754. {
  755. var hasMetascore = item as IHasMetascore;
  756. if (hasMetascore != null)
  757. {
  758. dto.Metascore = hasMetascore.Metascore;
  759. }
  760. }
  761. if (fields.Contains(ItemFields.AwardSummary))
  762. {
  763. var hasAwards = item as IHasAwards;
  764. if (hasAwards != null)
  765. {
  766. dto.AwardSummary = hasAwards.AwardSummary;
  767. }
  768. }
  769. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  770. if (backdropLimit > 0)
  771. {
  772. dto.BackdropImageTags = GetBackdropImageTags(item, backdropLimit);
  773. }
  774. if (fields.Contains(ItemFields.ScreenshotImageTags))
  775. {
  776. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  777. if (screenshotLimit > 0)
  778. {
  779. dto.ScreenshotImageTags = GetScreenshotImageTags(item, screenshotLimit);
  780. }
  781. }
  782. if (fields.Contains(ItemFields.Genres))
  783. {
  784. dto.Genres = item.Genres;
  785. }
  786. dto.ImageTags = new Dictionary<ImageType, string>();
  787. // Prevent implicitly captured closure
  788. var currentItem = item;
  789. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  790. .ToList())
  791. {
  792. if (options.GetImageLimit(image.Type) > 0)
  793. {
  794. var tag = GetImageCacheTag(item, image);
  795. if (tag != null)
  796. {
  797. dto.ImageTags[image.Type] = tag;
  798. }
  799. }
  800. }
  801. dto.Id = GetDtoId(item);
  802. dto.IndexNumber = item.IndexNumber;
  803. dto.IsFolder = item.IsFolder;
  804. dto.MediaType = item.MediaType;
  805. dto.LocationType = item.LocationType;
  806. var hasLang = item as IHasPreferredMetadataLanguage;
  807. if (hasLang != null)
  808. {
  809. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  810. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  811. }
  812. var hasCriticRating = item as IHasCriticRating;
  813. if (hasCriticRating != null)
  814. {
  815. dto.CriticRating = hasCriticRating.CriticRating;
  816. if (fields.Contains(ItemFields.CriticRatingSummary))
  817. {
  818. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  819. }
  820. }
  821. var hasTrailers = item as IHasTrailers;
  822. if (hasTrailers != null)
  823. {
  824. dto.LocalTrailerCount = hasTrailers.GetTrailerIds().Count;
  825. }
  826. var hasDisplayOrder = item as IHasDisplayOrder;
  827. if (hasDisplayOrder != null)
  828. {
  829. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  830. }
  831. var collectionFolder = item as ICollectionFolder;
  832. if (collectionFolder != null)
  833. {
  834. dto.CollectionType = collectionFolder.CollectionType;
  835. }
  836. var userView = item as UserView;
  837. if (userView != null)
  838. {
  839. dto.CollectionType = userView.ViewType;
  840. }
  841. if (fields.Contains(ItemFields.RemoteTrailers))
  842. {
  843. dto.RemoteTrailers = hasTrailers != null ?
  844. hasTrailers.RemoteTrailers :
  845. new List<MediaUrl>();
  846. }
  847. dto.Name = item.Name;
  848. dto.OfficialRating = item.OfficialRating;
  849. if (fields.Contains(ItemFields.Overview))
  850. {
  851. dto.Overview = item.Overview;
  852. }
  853. if (fields.Contains(ItemFields.ShortOverview))
  854. {
  855. var hasShortOverview = item as IHasShortOverview;
  856. if (hasShortOverview != null)
  857. {
  858. dto.ShortOverview = hasShortOverview.ShortOverview;
  859. }
  860. }
  861. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  862. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  863. {
  864. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  865. if (parentWithBackdrop != null)
  866. {
  867. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  868. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  869. }
  870. }
  871. if (fields.Contains(ItemFields.ParentId))
  872. {
  873. var displayParent = item.DisplayParent;
  874. if (displayParent != null)
  875. {
  876. dto.ParentId = GetDtoId(displayParent);
  877. }
  878. }
  879. dto.ParentIndexNumber = item.ParentIndexNumber;
  880. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  881. if (!dto.HasLogo && options.GetImageLimit(ImageType.Logo) > 0)
  882. {
  883. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  884. if (parentWithLogo != null)
  885. {
  886. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  887. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  888. }
  889. }
  890. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  891. if (!dto.HasArtImage && options.GetImageLimit(ImageType.Art) > 0)
  892. {
  893. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  894. if (parentWithImage != null)
  895. {
  896. dto.ParentArtItemId = GetDtoId(parentWithImage);
  897. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  898. }
  899. }
  900. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  901. if (!dto.HasThumb && options.GetImageLimit(ImageType.Thumb) > 0)
  902. {
  903. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  904. if (parentWithImage != null)
  905. {
  906. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  907. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  908. }
  909. }
  910. if (fields.Contains(ItemFields.Path))
  911. {
  912. dto.Path = GetMappedPath(item);
  913. }
  914. dto.PremiereDate = item.PremiereDate;
  915. dto.ProductionYear = item.ProductionYear;
  916. if (fields.Contains(ItemFields.ProviderIds))
  917. {
  918. dto.ProviderIds = item.ProviderIds;
  919. }
  920. dto.RunTimeTicks = item.RunTimeTicks;
  921. if (fields.Contains(ItemFields.SortName))
  922. {
  923. dto.SortName = item.SortName;
  924. }
  925. if (fields.Contains(ItemFields.CustomRating))
  926. {
  927. dto.CustomRating = item.CustomRating;
  928. }
  929. if (fields.Contains(ItemFields.Taglines))
  930. {
  931. var hasTagline = item as IHasTaglines;
  932. if (hasTagline != null)
  933. {
  934. dto.Taglines = hasTagline.Taglines;
  935. }
  936. if (dto.Taglines == null)
  937. {
  938. dto.Taglines = new List<string>();
  939. }
  940. }
  941. dto.Type = item.GetClientTypeName();
  942. dto.CommunityRating = item.CommunityRating;
  943. if (fields.Contains(ItemFields.VoteCount))
  944. {
  945. dto.VoteCount = item.VoteCount;
  946. }
  947. if (item.IsFolder)
  948. {
  949. var folder = (Folder)item;
  950. if (fields.Contains(ItemFields.IndexOptions))
  951. {
  952. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  953. }
  954. }
  955. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  956. if (supportsPlaceHolders != null)
  957. {
  958. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  959. }
  960. // Add audio info
  961. var audio = item as Audio;
  962. if (audio != null)
  963. {
  964. dto.Album = audio.Album;
  965. var albumParent = audio.FindParent<MusicAlbum>();
  966. if (albumParent != null)
  967. {
  968. dto.AlbumId = GetDtoId(albumParent);
  969. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  970. }
  971. //if (fields.Contains(ItemFields.MediaSourceCount))
  972. //{
  973. // Songs always have one
  974. //}
  975. }
  976. var album = item as MusicAlbum;
  977. if (album != null)
  978. {
  979. dto.SoundtrackIds = album.SoundtrackIds
  980. .Select(i => i.ToString("N"))
  981. .ToArray();
  982. }
  983. var hasArtist = item as IHasArtist;
  984. if (hasArtist != null)
  985. {
  986. dto.Artists = hasArtist.Artists;
  987. dto.ArtistItems = hasArtist
  988. .Artists
  989. .Select(i =>
  990. {
  991. try
  992. {
  993. var artist = _libraryManager.GetArtist(i);
  994. return new NameIdPair
  995. {
  996. Name = artist.Name,
  997. Id = artist.Id.ToString("N")
  998. };
  999. }
  1000. catch (Exception ex)
  1001. {
  1002. _logger.ErrorException("Error getting artist", ex);
  1003. return null;
  1004. }
  1005. })
  1006. .Where(i => i != null)
  1007. .ToList();
  1008. }
  1009. var hasAlbumArtist = item as IHasAlbumArtist;
  1010. if (hasAlbumArtist != null)
  1011. {
  1012. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  1013. dto.AlbumArtists = hasAlbumArtist
  1014. .AlbumArtists
  1015. .Select(i =>
  1016. {
  1017. try
  1018. {
  1019. var artist = _libraryManager.GetArtist(i);
  1020. return new NameIdPair
  1021. {
  1022. Name = artist.Name,
  1023. Id = artist.Id.ToString("N")
  1024. };
  1025. }
  1026. catch (Exception ex)
  1027. {
  1028. _logger.ErrorException("Error getting album artist", ex);
  1029. return null;
  1030. }
  1031. })
  1032. .Where(i => i != null)
  1033. .ToList();
  1034. }
  1035. // Add video info
  1036. var video = item as Video;
  1037. if (video != null)
  1038. {
  1039. dto.VideoType = video.VideoType;
  1040. dto.Video3DFormat = video.Video3DFormat;
  1041. dto.IsoType = video.IsoType;
  1042. dto.IsHD = video.IsHD;
  1043. if (video.AdditionalParts.Count != 0)
  1044. {
  1045. dto.PartCount = video.AdditionalParts.Count + 1;
  1046. }
  1047. if (fields.Contains(ItemFields.MediaSourceCount))
  1048. {
  1049. if (video.MediaSourceCount != 1)
  1050. {
  1051. dto.MediaSourceCount = video.MediaSourceCount;
  1052. }
  1053. }
  1054. if (fields.Contains(ItemFields.Chapters))
  1055. {
  1056. dto.Chapters = GetChapterInfoDtos(item);
  1057. }
  1058. }
  1059. if (fields.Contains(ItemFields.MediaStreams))
  1060. {
  1061. // Add VideoInfo
  1062. var iHasMediaSources = item as IHasMediaSources;
  1063. if (iHasMediaSources != null)
  1064. {
  1065. List<MediaStream> mediaStreams;
  1066. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  1067. {
  1068. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  1069. .SelectMany(i => i.MediaStreams)
  1070. .ToList();
  1071. }
  1072. else
  1073. {
  1074. mediaStreams = iHasMediaSources.GetMediaSources(true).First().MediaStreams;
  1075. }
  1076. dto.MediaStreams = mediaStreams;
  1077. }
  1078. }
  1079. // Add MovieInfo
  1080. var movie = item as Movie;
  1081. if (movie != null)
  1082. {
  1083. if (fields.Contains(ItemFields.TmdbCollectionName))
  1084. {
  1085. dto.TmdbCollectionName = movie.TmdbCollectionName;
  1086. }
  1087. }
  1088. var hasSpecialFeatures = item as IHasSpecialFeatures;
  1089. if (hasSpecialFeatures != null)
  1090. {
  1091. var specialFeatureCount = hasSpecialFeatures.SpecialFeatureIds.Count;
  1092. if (specialFeatureCount > 0)
  1093. {
  1094. dto.SpecialFeatureCount = specialFeatureCount;
  1095. }
  1096. }
  1097. // Add EpisodeInfo
  1098. var episode = item as Episode;
  1099. if (episode != null)
  1100. {
  1101. dto.IndexNumberEnd = episode.IndexNumberEnd;
  1102. if (fields.Contains(ItemFields.AlternateEpisodeNumbers))
  1103. {
  1104. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  1105. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  1106. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  1107. }
  1108. if (fields.Contains(ItemFields.SpecialEpisodeNumbers))
  1109. {
  1110. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  1111. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  1112. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  1113. }
  1114. var episodeSeason = episode.Season;
  1115. if (episodeSeason != null)
  1116. {
  1117. dto.SeasonId = episodeSeason.Id.ToString("N");
  1118. if (fields.Contains(ItemFields.SeasonName))
  1119. {
  1120. dto.SeasonName = episodeSeason.Name;
  1121. }
  1122. }
  1123. if (fields.Contains(ItemFields.SeriesGenres))
  1124. {
  1125. var episodeseries = episode.Series;
  1126. if (episodeseries != null)
  1127. {
  1128. dto.SeriesGenres = episodeseries.Genres.ToList();
  1129. }
  1130. }
  1131. }
  1132. // Add SeriesInfo
  1133. var series = item as Series;
  1134. if (series != null)
  1135. {
  1136. dto.AirDays = series.AirDays;
  1137. dto.AirTime = series.AirTime;
  1138. dto.Status = series.Status;
  1139. dto.SeasonCount = series.SeasonCount;
  1140. if (fields.Contains(ItemFields.Settings))
  1141. {
  1142. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  1143. }
  1144. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  1145. }
  1146. if (episode != null)
  1147. {
  1148. series = episode.Series;
  1149. if (series != null)
  1150. {
  1151. dto.SeriesId = GetDtoId(series);
  1152. dto.SeriesName = series.Name;
  1153. if (fields.Contains(ItemFields.AirTime))
  1154. {
  1155. dto.AirTime = series.AirTime;
  1156. }
  1157. if (options.GetImageLimit(ImageType.Thumb) > 0)
  1158. {
  1159. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  1160. }
  1161. if (options.GetImageLimit(ImageType.Primary) > 0)
  1162. {
  1163. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1164. }
  1165. if (fields.Contains(ItemFields.SeriesStudio))
  1166. {
  1167. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1168. }
  1169. }
  1170. }
  1171. // Add SeasonInfo
  1172. var season = item as Season;
  1173. if (season != null)
  1174. {
  1175. series = season.Series;
  1176. if (series != null)
  1177. {
  1178. dto.SeriesId = GetDtoId(series);
  1179. dto.SeriesName = series.Name;
  1180. dto.AirTime = series.AirTime;
  1181. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1182. if (options.GetImageLimit(ImageType.Primary) > 0)
  1183. {
  1184. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1185. }
  1186. }
  1187. }
  1188. var game = item as Game;
  1189. if (game != null)
  1190. {
  1191. SetGameProperties(dto, game);
  1192. }
  1193. var gameSystem = item as GameSystem;
  1194. if (gameSystem != null)
  1195. {
  1196. SetGameSystemProperties(dto, gameSystem);
  1197. }
  1198. var musicVideo = item as MusicVideo;
  1199. if (musicVideo != null)
  1200. {
  1201. SetMusicVideoProperties(dto, musicVideo);
  1202. }
  1203. var book = item as Book;
  1204. if (book != null)
  1205. {
  1206. SetBookProperties(dto, book);
  1207. }
  1208. var photo = item as Photo;
  1209. if (photo != null)
  1210. {
  1211. SetPhotoProperties(dto, photo);
  1212. }
  1213. var tvChannel = item as LiveTvChannel;
  1214. if (tvChannel != null)
  1215. {
  1216. dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
  1217. }
  1218. var channelItem = item as IChannelItem;
  1219. if (channelItem != null)
  1220. {
  1221. dto.ChannelId = channelItem.ChannelId;
  1222. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1223. }
  1224. var channelMediaItem = item as IChannelMediaItem;
  1225. if (channelMediaItem != null)
  1226. {
  1227. dto.ExtraType = channelMediaItem.ExtraType;
  1228. }
  1229. }
  1230. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user, DtoOptions options)
  1231. {
  1232. List<BaseItem> linkedChildren = null;
  1233. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1234. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  1235. {
  1236. linkedChildren = user == null
  1237. ? folder.GetRecursiveChildren().ToList()
  1238. : folder.GetRecursiveChildren(user).ToList();
  1239. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1240. if (parentWithBackdrop != null)
  1241. {
  1242. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1243. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  1244. }
  1245. }
  1246. if (!dto.ImageTags.ContainsKey(ImageType.Primary) && options.GetImageLimit(ImageType.Primary) > 0)
  1247. {
  1248. if (linkedChildren == null)
  1249. {
  1250. linkedChildren = user == null
  1251. ? folder.GetRecursiveChildren().ToList()
  1252. : folder.GetRecursiveChildren(user).ToList();
  1253. }
  1254. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1255. if (parentWithImage != null)
  1256. {
  1257. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1258. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1259. }
  1260. }
  1261. }
  1262. private string GetMappedPath(IHasMetadata item)
  1263. {
  1264. var path = item.Path;
  1265. var locationType = item.LocationType;
  1266. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1267. {
  1268. foreach (var map in _config.Configuration.PathSubstitutions)
  1269. {
  1270. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1271. }
  1272. }
  1273. return path;
  1274. }
  1275. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1276. {
  1277. var hasProductionLocations = item as IHasProductionLocations;
  1278. if (hasProductionLocations != null)
  1279. {
  1280. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1281. }
  1282. var person = item as Person;
  1283. if (person != null)
  1284. {
  1285. dto.ProductionLocations = new List<string>();
  1286. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1287. {
  1288. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1289. }
  1290. }
  1291. if (dto.ProductionLocations == null)
  1292. {
  1293. dto.ProductionLocations = new List<string>();
  1294. }
  1295. }
  1296. /// <summary>
  1297. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1298. /// </summary>
  1299. /// <param name="folder">The folder.</param>
  1300. /// <param name="user">The user.</param>
  1301. /// <param name="dto">The dto.</param>
  1302. /// <param name="fields">The fields.</param>
  1303. /// <returns>Task.</returns>
  1304. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1305. {
  1306. var recursiveItemCount = 0;
  1307. var unplayed = 0;
  1308. long runtime = 0;
  1309. DateTime? dateLastMediaAdded = null;
  1310. double totalPercentPlayed = 0;
  1311. IEnumerable<BaseItem> children;
  1312. var season = folder as Season;
  1313. if (season != null)
  1314. {
  1315. children = season
  1316. .GetEpisodes(user)
  1317. .Where(i => i.LocationType != LocationType.Virtual);
  1318. }
  1319. else
  1320. {
  1321. children = folder
  1322. .GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1323. }
  1324. // Loop through each recursive child
  1325. foreach (var child in children)
  1326. {
  1327. if (!dateLastMediaAdded.HasValue)
  1328. {
  1329. dateLastMediaAdded = child.DateCreated;
  1330. }
  1331. else
  1332. {
  1333. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1334. }
  1335. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1336. recursiveItemCount++;
  1337. var isUnplayed = true;
  1338. // Incrememt totalPercentPlayed
  1339. if (userdata != null)
  1340. {
  1341. if (userdata.Played)
  1342. {
  1343. totalPercentPlayed += 100;
  1344. isUnplayed = false;
  1345. }
  1346. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1347. {
  1348. double itemPercent = userdata.PlaybackPositionTicks;
  1349. itemPercent /= child.RunTimeTicks.Value;
  1350. totalPercentPlayed += itemPercent;
  1351. }
  1352. }
  1353. if (isUnplayed)
  1354. {
  1355. unplayed++;
  1356. }
  1357. runtime += child.RunTimeTicks ?? 0;
  1358. }
  1359. dto.RecursiveItemCount = recursiveItemCount;
  1360. dto.UserData.UnplayedItemCount = unplayed;
  1361. if (recursiveItemCount > 0)
  1362. {
  1363. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1364. }
  1365. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1366. {
  1367. dto.CumulativeRunTimeTicks = runtime;
  1368. }
  1369. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1370. {
  1371. dto.DateLastMediaAdded = dateLastMediaAdded;
  1372. }
  1373. }
  1374. /// <summary>
  1375. /// Attaches the primary image aspect ratio.
  1376. /// </summary>
  1377. /// <param name="dto">The dto.</param>
  1378. /// <param name="item">The item.</param>
  1379. /// <param name="fields">The fields.</param>
  1380. /// <returns>Task.</returns>
  1381. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item, List<ItemFields> fields)
  1382. {
  1383. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1384. if (imageInfo == null)
  1385. {
  1386. return;
  1387. }
  1388. var path = imageInfo.Path;
  1389. ImageSize size;
  1390. try
  1391. {
  1392. size = _imageProcessor.GetImageSize(imageInfo);
  1393. }
  1394. catch (FileNotFoundException)
  1395. {
  1396. _logger.Error("Image file does not exist: {0}", path);
  1397. return;
  1398. }
  1399. catch (Exception ex)
  1400. {
  1401. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1402. return;
  1403. }
  1404. if (fields.Contains(ItemFields.OriginalPrimaryImageAspectRatio))
  1405. {
  1406. if (size.Width > 0 && size.Height > 0)
  1407. {
  1408. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1409. }
  1410. }
  1411. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1412. foreach (var enhancer in supportedEnhancers)
  1413. {
  1414. try
  1415. {
  1416. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1417. }
  1418. catch (Exception ex)
  1419. {
  1420. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1421. }
  1422. }
  1423. if (size.Width > 0 && size.Height > 0)
  1424. {
  1425. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1426. }
  1427. }
  1428. }
  1429. }