DtoService.cs 60 KB

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