DtoService.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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. private readonly Func<ILiveTvManager> _livetvManager;
  47. 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, Func<ILiveTvManager> livetvManager)
  48. {
  49. _logger = logger;
  50. _libraryManager = libraryManager;
  51. _userDataRepository = userDataRepository;
  52. _itemRepo = itemRepo;
  53. _imageProcessor = imageProcessor;
  54. _config = config;
  55. _fileSystem = fileSystem;
  56. _providerManager = providerManager;
  57. _channelManagerFactory = channelManagerFactory;
  58. _syncManager = syncManager;
  59. _appHost = appHost;
  60. _deviceManager = deviceManager;
  61. _mediaSourceManager = mediaSourceManager;
  62. _livetvManager = livetvManager;
  63. }
  64. /// <summary>
  65. /// Converts a BaseItem to a DTOBaseItem
  66. /// </summary>
  67. /// <param name="item">The item.</param>
  68. /// <param name="fields">The fields.</param>
  69. /// <param name="user">The user.</param>
  70. /// <param name="owner">The owner.</param>
  71. /// <returns>Task{DtoBaseItem}.</returns>
  72. /// <exception cref="System.ArgumentNullException">item</exception>
  73. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  74. {
  75. var options = new DtoOptions
  76. {
  77. Fields = fields
  78. };
  79. return GetBaseItemDto(item, options, user, owner);
  80. }
  81. public IEnumerable<BaseItemDto> GetBaseItemDtos(IEnumerable<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
  82. {
  83. var tuple = GetItemIdsWithSyncJobs(options);
  84. var list = new List<BaseItemDto>();
  85. foreach (var item in items)
  86. {
  87. var dto = GetBaseItemDtoInternal(item, options, user, owner);
  88. var byName = item as IItemByName;
  89. if (byName != null && !(item is LiveTvChannel))
  90. {
  91. if (options.Fields.Contains(ItemFields.ItemCounts))
  92. {
  93. var itemFilter = byName.GetItemFilter();
  94. var libraryItems = user != null ?
  95. user.RootFolder.GetRecursiveChildren(user, itemFilter) :
  96. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter);
  97. SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
  98. }
  99. }
  100. FillSyncInfo(dto, item, tuple.Item1, tuple.Item2, options, user);
  101. list.Add(dto);
  102. }
  103. return list;
  104. }
  105. public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
  106. {
  107. var dto = GetBaseItemDtoInternal(item, options, user, owner);
  108. var byName = item as IItemByName;
  109. if (byName != null && !(item is LiveTvChannel))
  110. {
  111. if (options.Fields.Contains(ItemFields.ItemCounts))
  112. {
  113. var itemFilter = byName.GetItemFilter();
  114. var libraryItems = user != null ?
  115. user.RootFolder.GetRecursiveChildren(user, itemFilter) :
  116. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter);
  117. SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
  118. }
  119. FillSyncInfo(dto, item, options, user);
  120. return dto;
  121. }
  122. FillSyncInfo(dto, item, options, user);
  123. return dto;
  124. }
  125. private Tuple<IEnumerable<string>, IEnumerable<string>> GetItemIdsWithSyncJobs(DtoOptions options)
  126. {
  127. if (!options.Fields.Contains(ItemFields.SyncInfo))
  128. {
  129. return new Tuple<IEnumerable<string>, IEnumerable<string>>(new List<string>(), new List<string>());
  130. }
  131. var deviceId = options.DeviceId;
  132. if (string.IsNullOrWhiteSpace(deviceId))
  133. {
  134. return new Tuple<IEnumerable<string>, IEnumerable<string>>(new List<string>(), new List<string>());
  135. }
  136. var caps = _deviceManager().GetCapabilities(deviceId);
  137. if (caps == null || !caps.SupportsSync)
  138. {
  139. return new Tuple<IEnumerable<string>, IEnumerable<string>>(new List<string>(), new List<string>());
  140. }
  141. var result1 = _syncManager.GetLibraryItemIds(new SyncJobItemQuery
  142. {
  143. TargetId = deviceId,
  144. Statuses = new[]
  145. {
  146. SyncJobItemStatus.Converting,
  147. SyncJobItemStatus.Queued,
  148. SyncJobItemStatus.Transferring,
  149. SyncJobItemStatus.ReadyToTransfer
  150. }
  151. });
  152. var result2 = _syncManager.GetLibraryItemIds(new SyncJobItemQuery
  153. {
  154. TargetId = deviceId,
  155. Statuses = new[]
  156. {
  157. SyncJobItemStatus.Synced
  158. }
  159. });
  160. return new Tuple<IEnumerable<string>, IEnumerable<string>>(result1.Items, result2.Items);
  161. }
  162. public void FillSyncInfo(IEnumerable<IHasSyncInfo> dtos, DtoOptions options, User user)
  163. {
  164. if (options.Fields.Contains(ItemFields.SyncInfo))
  165. {
  166. var tuple = GetItemIdsWithSyncJobs(options);
  167. foreach (var dto in dtos)
  168. {
  169. var item = _libraryManager.GetItemById(dto.Id);
  170. FillSyncInfo(dto, item, tuple.Item1, tuple.Item2, options, user);
  171. }
  172. }
  173. }
  174. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, DtoOptions options, User user)
  175. {
  176. if (options.Fields.Contains(ItemFields.SyncInfo))
  177. {
  178. var userCanSync = user != null && user.Policy.EnableSync;
  179. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  180. }
  181. if (dto.SupportsSync ?? false)
  182. {
  183. var tuple = GetItemIdsWithSyncJobs(options);
  184. dto.HasSyncJob = tuple.Item1.Contains(dto.Id, StringComparer.OrdinalIgnoreCase);
  185. dto.IsSynced = tuple.Item2.Contains(dto.Id, StringComparer.OrdinalIgnoreCase);
  186. if (dto.IsSynced.Value)
  187. {
  188. dto.SyncStatus = SyncJobItemStatus.Synced;
  189. }
  190. else if (dto.HasSyncJob.Value)
  191. {
  192. dto.SyncStatus = SyncJobItemStatus.Queued;
  193. }
  194. }
  195. }
  196. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, IEnumerable<string> itemIdsWithPendingSyncJobs, IEnumerable<string> syncedItemIds, DtoOptions options, User user)
  197. {
  198. if (options.Fields.Contains(ItemFields.SyncInfo))
  199. {
  200. var userCanSync = user != null && user.Policy.EnableSync;
  201. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  202. }
  203. if (dto.SupportsSync ?? false)
  204. {
  205. dto.HasSyncJob = itemIdsWithPendingSyncJobs.Contains(dto.Id, StringComparer.OrdinalIgnoreCase);
  206. dto.IsSynced = syncedItemIds.Contains(dto.Id, StringComparer.OrdinalIgnoreCase);
  207. if (dto.IsSynced.Value)
  208. {
  209. dto.SyncStatus = SyncJobItemStatus.Synced;
  210. }
  211. else if (dto.HasSyncJob.Value)
  212. {
  213. dto.SyncStatus = SyncJobItemStatus.Queued;
  214. }
  215. }
  216. }
  217. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
  218. {
  219. var fields = options.Fields;
  220. if (item == null)
  221. {
  222. throw new ArgumentNullException("item");
  223. }
  224. if (fields == null)
  225. {
  226. throw new ArgumentNullException("fields");
  227. }
  228. var dto = new BaseItemDto
  229. {
  230. ServerId = _appHost.SystemId
  231. };
  232. if (fields.Contains(ItemFields.People))
  233. {
  234. AttachPeople(dto, item);
  235. }
  236. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  237. {
  238. try
  239. {
  240. AttachPrimaryImageAspectRatio(dto, item, fields);
  241. }
  242. catch (Exception ex)
  243. {
  244. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  245. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  246. }
  247. }
  248. if (fields.Contains(ItemFields.DisplayPreferencesId))
  249. {
  250. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  251. }
  252. if (user != null)
  253. {
  254. AttachUserSpecificInfo(dto, item, user, fields);
  255. }
  256. var hasMediaSources = item as IHasMediaSources;
  257. if (hasMediaSources != null)
  258. {
  259. if (fields.Contains(ItemFields.MediaSources))
  260. {
  261. if (user == null)
  262. {
  263. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true).ToList();
  264. }
  265. else
  266. {
  267. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true, user).ToList();
  268. }
  269. }
  270. }
  271. if (fields.Contains(ItemFields.Studios))
  272. {
  273. AttachStudios(dto, item);
  274. }
  275. AttachBasicFields(dto, item, owner, options);
  276. var playlist = item as Playlist;
  277. if (playlist != null)
  278. {
  279. AttachLinkedChildImages(dto, playlist, user, options);
  280. }
  281. if (fields.Contains(ItemFields.CanDelete))
  282. {
  283. dto.CanDelete = user == null
  284. ? item.CanDelete()
  285. : item.CanDelete(user);
  286. }
  287. if (fields.Contains(ItemFields.CanDownload))
  288. {
  289. dto.CanDownload = user == null
  290. ? item.CanDownload()
  291. : item.CanDownload(user);
  292. }
  293. if (fields.Contains(ItemFields.Etag))
  294. {
  295. dto.Etag = item.GetEtag(user);
  296. }
  297. if (item is ILiveTvRecording)
  298. {
  299. _livetvManager().AddInfoToRecordingDto(item, dto, user);
  300. }
  301. else if (item is LiveTvProgram)
  302. {
  303. _livetvManager().AddInfoToProgramDto(item, dto, 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. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  706. {
  707. Path = chapterInfo.ImagePath,
  708. Type = ImageType.Chapter,
  709. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  710. });
  711. }
  712. return dto;
  713. }
  714. public List<ChapterInfoDto> GetChapterInfoDtos(BaseItem item)
  715. {
  716. return _itemRepo.GetChapters(item.Id)
  717. .Select(c => GetChapterInfoDto(c, item))
  718. .ToList();
  719. }
  720. /// <summary>
  721. /// Sets simple property values on a DTOBaseItem
  722. /// </summary>
  723. /// <param name="dto">The dto.</param>
  724. /// <param name="item">The item.</param>
  725. /// <param name="owner">The owner.</param>
  726. /// <param name="options">The options.</param>
  727. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  728. {
  729. var fields = options.Fields;
  730. if (fields.Contains(ItemFields.DateCreated))
  731. {
  732. dto.DateCreated = item.DateCreated;
  733. }
  734. if (fields.Contains(ItemFields.DisplayMediaType))
  735. {
  736. dto.DisplayMediaType = item.DisplayMediaType;
  737. }
  738. // Leave null if false
  739. if (item.IsUnidentified)
  740. {
  741. dto.IsUnidentified = item.IsUnidentified;
  742. }
  743. if (fields.Contains(ItemFields.Settings))
  744. {
  745. dto.LockedFields = item.LockedFields;
  746. dto.LockData = item.IsLocked;
  747. dto.ForcedSortName = item.ForcedSortName;
  748. }
  749. var hasBudget = item as IHasBudget;
  750. if (hasBudget != null)
  751. {
  752. if (fields.Contains(ItemFields.Budget))
  753. {
  754. dto.Budget = hasBudget.Budget;
  755. }
  756. if (fields.Contains(ItemFields.Revenue))
  757. {
  758. dto.Revenue = hasBudget.Revenue;
  759. }
  760. }
  761. dto.EndDate = item.EndDate;
  762. if (fields.Contains(ItemFields.HomePageUrl))
  763. {
  764. dto.HomePageUrl = item.HomePageUrl;
  765. }
  766. if (fields.Contains(ItemFields.ExternalUrls))
  767. {
  768. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  769. }
  770. if (fields.Contains(ItemFields.Tags))
  771. {
  772. var hasTags = item as IHasTags;
  773. if (hasTags != null)
  774. {
  775. dto.Tags = hasTags.Tags;
  776. }
  777. if (dto.Tags == null)
  778. {
  779. dto.Tags = new List<string>();
  780. }
  781. }
  782. if (fields.Contains(ItemFields.Keywords))
  783. {
  784. var hasTags = item as IHasKeywords;
  785. if (hasTags != null)
  786. {
  787. dto.Keywords = hasTags.Keywords;
  788. }
  789. if (dto.Keywords == null)
  790. {
  791. dto.Keywords = new List<string>();
  792. }
  793. }
  794. if (fields.Contains(ItemFields.ProductionLocations))
  795. {
  796. SetProductionLocations(item, dto);
  797. }
  798. var hasAspectRatio = item as IHasAspectRatio;
  799. if (hasAspectRatio != null)
  800. {
  801. dto.AspectRatio = hasAspectRatio.AspectRatio;
  802. }
  803. if (fields.Contains(ItemFields.Metascore))
  804. {
  805. var hasMetascore = item as IHasMetascore;
  806. if (hasMetascore != null)
  807. {
  808. dto.Metascore = hasMetascore.Metascore;
  809. }
  810. }
  811. if (fields.Contains(ItemFields.AwardSummary))
  812. {
  813. var hasAwards = item as IHasAwards;
  814. if (hasAwards != null)
  815. {
  816. dto.AwardSummary = hasAwards.AwardSummary;
  817. }
  818. }
  819. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  820. if (backdropLimit > 0)
  821. {
  822. dto.BackdropImageTags = GetBackdropImageTags(item, backdropLimit);
  823. }
  824. if (fields.Contains(ItemFields.ScreenshotImageTags))
  825. {
  826. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  827. if (screenshotLimit > 0)
  828. {
  829. dto.ScreenshotImageTags = GetScreenshotImageTags(item, screenshotLimit);
  830. }
  831. }
  832. if (fields.Contains(ItemFields.Genres))
  833. {
  834. dto.Genres = item.Genres;
  835. }
  836. dto.ImageTags = new Dictionary<ImageType, string>();
  837. // Prevent implicitly captured closure
  838. var currentItem = item;
  839. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  840. .ToList())
  841. {
  842. if (options.GetImageLimit(image.Type) > 0)
  843. {
  844. var tag = GetImageCacheTag(item, image);
  845. if (tag != null)
  846. {
  847. dto.ImageTags[image.Type] = tag;
  848. }
  849. }
  850. }
  851. dto.Id = GetDtoId(item);
  852. dto.IndexNumber = item.IndexNumber;
  853. dto.IsFolder = item.IsFolder;
  854. dto.MediaType = item.MediaType;
  855. dto.LocationType = item.LocationType;
  856. var hasLang = item as IHasPreferredMetadataLanguage;
  857. if (hasLang != null)
  858. {
  859. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  860. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  861. }
  862. var hasCriticRating = item as IHasCriticRating;
  863. if (hasCriticRating != null)
  864. {
  865. dto.CriticRating = hasCriticRating.CriticRating;
  866. if (fields.Contains(ItemFields.CriticRatingSummary))
  867. {
  868. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  869. }
  870. }
  871. var hasTrailers = item as IHasTrailers;
  872. if (hasTrailers != null)
  873. {
  874. dto.LocalTrailerCount = hasTrailers.GetTrailerIds().Count;
  875. }
  876. var hasDisplayOrder = item as IHasDisplayOrder;
  877. if (hasDisplayOrder != null)
  878. {
  879. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  880. }
  881. var collectionFolder = item as ICollectionFolder;
  882. if (collectionFolder != null)
  883. {
  884. dto.CollectionType = collectionFolder.CollectionType;
  885. }
  886. var userView = item as UserView;
  887. if (userView != null)
  888. {
  889. dto.CollectionType = userView.ViewType;
  890. }
  891. if (fields.Contains(ItemFields.RemoteTrailers))
  892. {
  893. dto.RemoteTrailers = hasTrailers != null ?
  894. hasTrailers.RemoteTrailers :
  895. new List<MediaUrl>();
  896. }
  897. dto.Name = item.Name;
  898. dto.OfficialRating = item.OfficialRating;
  899. if (fields.Contains(ItemFields.Overview))
  900. {
  901. dto.Overview = item.Overview;
  902. }
  903. if (fields.Contains(ItemFields.ShortOverview))
  904. {
  905. var hasShortOverview = item as IHasShortOverview;
  906. if (hasShortOverview != null)
  907. {
  908. dto.ShortOverview = hasShortOverview.ShortOverview;
  909. }
  910. }
  911. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  912. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  913. {
  914. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  915. if (parentWithBackdrop != null)
  916. {
  917. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  918. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  919. }
  920. }
  921. if (fields.Contains(ItemFields.ParentId))
  922. {
  923. var displayParent = item.DisplayParent;
  924. if (displayParent != null)
  925. {
  926. dto.ParentId = GetDtoId(displayParent);
  927. }
  928. }
  929. dto.ParentIndexNumber = item.ParentIndexNumber;
  930. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  931. if (!dto.HasLogo && options.GetImageLimit(ImageType.Logo) > 0)
  932. {
  933. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  934. if (parentWithLogo != null)
  935. {
  936. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  937. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  938. }
  939. }
  940. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  941. if (!dto.HasArtImage && options.GetImageLimit(ImageType.Art) > 0)
  942. {
  943. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  944. if (parentWithImage != null)
  945. {
  946. dto.ParentArtItemId = GetDtoId(parentWithImage);
  947. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  948. }
  949. }
  950. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  951. if (!dto.HasThumb && options.GetImageLimit(ImageType.Thumb) > 0)
  952. {
  953. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  954. if (parentWithImage != null)
  955. {
  956. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  957. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  958. }
  959. }
  960. if (fields.Contains(ItemFields.Path))
  961. {
  962. dto.Path = GetMappedPath(item);
  963. }
  964. dto.PremiereDate = item.PremiereDate;
  965. dto.ProductionYear = item.ProductionYear;
  966. if (fields.Contains(ItemFields.ProviderIds))
  967. {
  968. dto.ProviderIds = item.ProviderIds;
  969. }
  970. dto.RunTimeTicks = item.RunTimeTicks;
  971. if (fields.Contains(ItemFields.SortName))
  972. {
  973. dto.SortName = item.SortName;
  974. }
  975. if (fields.Contains(ItemFields.CustomRating))
  976. {
  977. dto.CustomRating = item.CustomRating;
  978. }
  979. if (fields.Contains(ItemFields.Taglines))
  980. {
  981. var hasTagline = item as IHasTaglines;
  982. if (hasTagline != null)
  983. {
  984. dto.Taglines = hasTagline.Taglines;
  985. }
  986. if (dto.Taglines == null)
  987. {
  988. dto.Taglines = new List<string>();
  989. }
  990. }
  991. dto.Type = item.GetClientTypeName();
  992. dto.CommunityRating = item.CommunityRating;
  993. if (fields.Contains(ItemFields.VoteCount))
  994. {
  995. dto.VoteCount = item.VoteCount;
  996. }
  997. if (item.IsFolder)
  998. {
  999. var folder = (Folder)item;
  1000. if (fields.Contains(ItemFields.IndexOptions))
  1001. {
  1002. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  1003. }
  1004. }
  1005. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  1006. if (supportsPlaceHolders != null)
  1007. {
  1008. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  1009. }
  1010. // Add audio info
  1011. var audio = item as Audio;
  1012. if (audio != null)
  1013. {
  1014. dto.Album = audio.Album;
  1015. var albumParent = audio.AlbumEntity;
  1016. if (albumParent != null)
  1017. {
  1018. dto.AlbumId = GetDtoId(albumParent);
  1019. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  1020. }
  1021. //if (fields.Contains(ItemFields.MediaSourceCount))
  1022. //{
  1023. // Songs always have one
  1024. //}
  1025. }
  1026. var hasArtist = item as IHasArtist;
  1027. if (hasArtist != null)
  1028. {
  1029. dto.Artists = hasArtist.Artists;
  1030. dto.ArtistItems = hasArtist
  1031. .Artists
  1032. .Select(i =>
  1033. {
  1034. try
  1035. {
  1036. var artist = _libraryManager.GetArtist(i);
  1037. return new NameIdPair
  1038. {
  1039. Name = artist.Name,
  1040. Id = artist.Id.ToString("N")
  1041. };
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. _logger.ErrorException("Error getting artist", ex);
  1046. return null;
  1047. }
  1048. })
  1049. .Where(i => i != null)
  1050. .ToList();
  1051. }
  1052. var hasAlbumArtist = item as IHasAlbumArtist;
  1053. if (hasAlbumArtist != null)
  1054. {
  1055. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  1056. dto.AlbumArtists = hasAlbumArtist
  1057. .AlbumArtists
  1058. .Select(i =>
  1059. {
  1060. try
  1061. {
  1062. var artist = _libraryManager.GetArtist(i);
  1063. return new NameIdPair
  1064. {
  1065. Name = artist.Name,
  1066. Id = artist.Id.ToString("N")
  1067. };
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. _logger.ErrorException("Error getting album artist", ex);
  1072. return null;
  1073. }
  1074. })
  1075. .Where(i => i != null)
  1076. .ToList();
  1077. }
  1078. // Add video info
  1079. var video = item as Video;
  1080. if (video != null)
  1081. {
  1082. dto.VideoType = video.VideoType;
  1083. dto.Video3DFormat = video.Video3DFormat;
  1084. dto.IsoType = video.IsoType;
  1085. dto.IsHD = video.IsHD;
  1086. if (video.AdditionalParts.Count != 0)
  1087. {
  1088. dto.PartCount = video.AdditionalParts.Count + 1;
  1089. }
  1090. if (fields.Contains(ItemFields.MediaSourceCount))
  1091. {
  1092. if (video.MediaSourceCount != 1)
  1093. {
  1094. dto.MediaSourceCount = video.MediaSourceCount;
  1095. }
  1096. }
  1097. if (fields.Contains(ItemFields.Chapters))
  1098. {
  1099. dto.Chapters = GetChapterInfoDtos(item);
  1100. }
  1101. }
  1102. if (fields.Contains(ItemFields.MediaStreams))
  1103. {
  1104. // Add VideoInfo
  1105. var iHasMediaSources = item as IHasMediaSources;
  1106. if (iHasMediaSources != null)
  1107. {
  1108. List<MediaStream> mediaStreams;
  1109. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  1110. {
  1111. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  1112. .SelectMany(i => i.MediaStreams)
  1113. .ToList();
  1114. }
  1115. else
  1116. {
  1117. mediaStreams = _mediaSourceManager().GetStaticMediaSources(iHasMediaSources, true).First().MediaStreams;
  1118. }
  1119. dto.MediaStreams = mediaStreams;
  1120. }
  1121. }
  1122. // Add MovieInfo
  1123. var movie = item as Movie;
  1124. if (movie != null)
  1125. {
  1126. if (fields.Contains(ItemFields.TmdbCollectionName))
  1127. {
  1128. dto.TmdbCollectionName = movie.TmdbCollectionName;
  1129. }
  1130. }
  1131. var hasSpecialFeatures = item as IHasSpecialFeatures;
  1132. if (hasSpecialFeatures != null)
  1133. {
  1134. var specialFeatureCount = hasSpecialFeatures.SpecialFeatureIds.Count;
  1135. if (specialFeatureCount > 0)
  1136. {
  1137. dto.SpecialFeatureCount = specialFeatureCount;
  1138. }
  1139. }
  1140. // Add EpisodeInfo
  1141. var episode = item as Episode;
  1142. if (episode != null)
  1143. {
  1144. dto.IndexNumberEnd = episode.IndexNumberEnd;
  1145. if (fields.Contains(ItemFields.AlternateEpisodeNumbers))
  1146. {
  1147. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  1148. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  1149. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  1150. }
  1151. if (fields.Contains(ItemFields.SpecialEpisodeNumbers))
  1152. {
  1153. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  1154. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  1155. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  1156. }
  1157. var episodeSeason = episode.Season;
  1158. if (episodeSeason != null)
  1159. {
  1160. dto.SeasonId = episodeSeason.Id.ToString("N");
  1161. if (fields.Contains(ItemFields.SeasonName))
  1162. {
  1163. dto.SeasonName = episodeSeason.Name;
  1164. }
  1165. }
  1166. if (fields.Contains(ItemFields.SeriesGenres))
  1167. {
  1168. var episodeseries = episode.Series;
  1169. if (episodeseries != null)
  1170. {
  1171. dto.SeriesGenres = episodeseries.Genres.ToList();
  1172. }
  1173. }
  1174. }
  1175. // Add SeriesInfo
  1176. var series = item as Series;
  1177. if (series != null)
  1178. {
  1179. dto.AirDays = series.AirDays;
  1180. dto.AirTime = series.AirTime;
  1181. dto.SeriesStatus = series.Status;
  1182. dto.SeasonCount = series.SeasonCount;
  1183. if (fields.Contains(ItemFields.Settings))
  1184. {
  1185. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  1186. }
  1187. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  1188. }
  1189. if (episode != null)
  1190. {
  1191. series = episode.Series;
  1192. if (series != null)
  1193. {
  1194. dto.SeriesId = GetDtoId(series);
  1195. dto.SeriesName = series.Name;
  1196. if (fields.Contains(ItemFields.AirTime))
  1197. {
  1198. dto.AirTime = series.AirTime;
  1199. }
  1200. if (options.GetImageLimit(ImageType.Thumb) > 0)
  1201. {
  1202. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  1203. }
  1204. if (options.GetImageLimit(ImageType.Primary) > 0)
  1205. {
  1206. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1207. }
  1208. if (fields.Contains(ItemFields.SeriesStudio))
  1209. {
  1210. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1211. }
  1212. }
  1213. }
  1214. // Add SeasonInfo
  1215. var season = item as Season;
  1216. if (season != null)
  1217. {
  1218. series = season.Series;
  1219. if (series != null)
  1220. {
  1221. dto.SeriesId = GetDtoId(series);
  1222. dto.SeriesName = series.Name;
  1223. dto.AirTime = series.AirTime;
  1224. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1225. if (options.GetImageLimit(ImageType.Primary) > 0)
  1226. {
  1227. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1228. }
  1229. }
  1230. }
  1231. var game = item as Game;
  1232. if (game != null)
  1233. {
  1234. SetGameProperties(dto, game);
  1235. }
  1236. var gameSystem = item as GameSystem;
  1237. if (gameSystem != null)
  1238. {
  1239. SetGameSystemProperties(dto, gameSystem);
  1240. }
  1241. var musicVideo = item as MusicVideo;
  1242. if (musicVideo != null)
  1243. {
  1244. SetMusicVideoProperties(dto, musicVideo);
  1245. }
  1246. var book = item as Book;
  1247. if (book != null)
  1248. {
  1249. SetBookProperties(dto, book);
  1250. }
  1251. var photo = item as Photo;
  1252. if (photo != null)
  1253. {
  1254. SetPhotoProperties(dto, photo);
  1255. }
  1256. var tvChannel = item as LiveTvChannel;
  1257. if (tvChannel != null)
  1258. {
  1259. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(tvChannel, true).ToList();
  1260. }
  1261. var channelItem = item as IChannelItem;
  1262. if (channelItem != null)
  1263. {
  1264. dto.ChannelId = channelItem.ChannelId;
  1265. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1266. }
  1267. var channelMediaItem = item as IChannelMediaItem;
  1268. if (channelMediaItem != null)
  1269. {
  1270. dto.ExtraType = channelMediaItem.ExtraType;
  1271. }
  1272. }
  1273. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user, DtoOptions options)
  1274. {
  1275. List<BaseItem> linkedChildren = null;
  1276. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1277. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  1278. {
  1279. linkedChildren = user == null
  1280. ? folder.GetRecursiveChildren().ToList()
  1281. : folder.GetRecursiveChildren(user).ToList();
  1282. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1283. if (parentWithBackdrop != null)
  1284. {
  1285. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1286. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  1287. }
  1288. }
  1289. if (!dto.ImageTags.ContainsKey(ImageType.Primary) && options.GetImageLimit(ImageType.Primary) > 0)
  1290. {
  1291. if (linkedChildren == null)
  1292. {
  1293. linkedChildren = user == null
  1294. ? folder.GetRecursiveChildren().ToList()
  1295. : folder.GetRecursiveChildren(user).ToList();
  1296. }
  1297. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1298. if (parentWithImage != null)
  1299. {
  1300. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1301. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1302. }
  1303. }
  1304. }
  1305. private string GetMappedPath(IHasMetadata item)
  1306. {
  1307. var path = item.Path;
  1308. var locationType = item.LocationType;
  1309. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1310. {
  1311. foreach (var map in _config.Configuration.PathSubstitutions)
  1312. {
  1313. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1314. }
  1315. }
  1316. return path;
  1317. }
  1318. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1319. {
  1320. var hasProductionLocations = item as IHasProductionLocations;
  1321. if (hasProductionLocations != null)
  1322. {
  1323. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1324. }
  1325. var person = item as Person;
  1326. if (person != null)
  1327. {
  1328. dto.ProductionLocations = new List<string>();
  1329. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1330. {
  1331. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1332. }
  1333. }
  1334. if (dto.ProductionLocations == null)
  1335. {
  1336. dto.ProductionLocations = new List<string>();
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1341. /// </summary>
  1342. /// <param name="folder">The folder.</param>
  1343. /// <param name="user">The user.</param>
  1344. /// <param name="dto">The dto.</param>
  1345. /// <param name="fields">The fields.</param>
  1346. /// <returns>Task.</returns>
  1347. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1348. {
  1349. var recursiveItemCount = 0;
  1350. var unplayed = 0;
  1351. long runtime = 0;
  1352. DateTime? dateLastMediaAdded = null;
  1353. double totalPercentPlayed = 0;
  1354. IEnumerable<BaseItem> children;
  1355. var season = folder as Season;
  1356. if (season != null)
  1357. {
  1358. children = season
  1359. .GetEpisodes(user)
  1360. .Where(i => i.LocationType != LocationType.Virtual);
  1361. }
  1362. else
  1363. {
  1364. children = folder
  1365. .GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1366. }
  1367. // Loop through each recursive child
  1368. foreach (var child in children)
  1369. {
  1370. if (!dateLastMediaAdded.HasValue)
  1371. {
  1372. dateLastMediaAdded = child.DateCreated;
  1373. }
  1374. else
  1375. {
  1376. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1377. }
  1378. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1379. recursiveItemCount++;
  1380. var isUnplayed = true;
  1381. // Incrememt totalPercentPlayed
  1382. if (userdata != null)
  1383. {
  1384. if (userdata.Played)
  1385. {
  1386. totalPercentPlayed += 100;
  1387. isUnplayed = false;
  1388. }
  1389. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1390. {
  1391. double itemPercent = userdata.PlaybackPositionTicks;
  1392. itemPercent /= child.RunTimeTicks.Value;
  1393. totalPercentPlayed += itemPercent;
  1394. }
  1395. }
  1396. if (isUnplayed)
  1397. {
  1398. unplayed++;
  1399. }
  1400. runtime += child.RunTimeTicks ?? 0;
  1401. }
  1402. dto.RecursiveItemCount = recursiveItemCount;
  1403. dto.UserData.UnplayedItemCount = unplayed;
  1404. if (recursiveItemCount > 0)
  1405. {
  1406. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1407. }
  1408. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1409. {
  1410. dto.CumulativeRunTimeTicks = runtime;
  1411. }
  1412. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1413. {
  1414. dto.DateLastMediaAdded = dateLastMediaAdded;
  1415. }
  1416. }
  1417. /// <summary>
  1418. /// Attaches the primary image aspect ratio.
  1419. /// </summary>
  1420. /// <param name="dto">The dto.</param>
  1421. /// <param name="item">The item.</param>
  1422. /// <param name="fields">The fields.</param>
  1423. /// <returns>Task.</returns>
  1424. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item, List<ItemFields> fields)
  1425. {
  1426. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1427. if (imageInfo == null)
  1428. {
  1429. return;
  1430. }
  1431. var path = imageInfo.Path;
  1432. ImageSize size;
  1433. try
  1434. {
  1435. size = _imageProcessor.GetImageSize(imageInfo);
  1436. }
  1437. catch (FileNotFoundException)
  1438. {
  1439. _logger.Error("Image file does not exist: {0}", path);
  1440. return;
  1441. }
  1442. catch (Exception ex)
  1443. {
  1444. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1445. return;
  1446. }
  1447. if (fields.Contains(ItemFields.OriginalPrimaryImageAspectRatio))
  1448. {
  1449. if (size.Width > 0 && size.Height > 0)
  1450. {
  1451. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1452. }
  1453. }
  1454. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1455. foreach (var enhancer in supportedEnhancers)
  1456. {
  1457. try
  1458. {
  1459. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1460. }
  1461. catch (Exception ex)
  1462. {
  1463. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1464. }
  1465. }
  1466. if (size.Width > 0 && size.Height > 0)
  1467. {
  1468. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1469. }
  1470. }
  1471. }
  1472. }