DtoService.cs 59 KB

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