DtoService.cs 57 KB

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