DtoService.cs 60 KB

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