DtoService.cs 60 KB

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