2
0

DtoService.cs 60 KB

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