DtoService.cs 54 KB

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