DtoService.cs 55 KB

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