DtoService.cs 57 KB

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