DtoService.cs 58 KB

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