DtoService.cs 59 KB

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