DtoService.cs 59 KB

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