DtoService.cs 59 KB

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