DtoService.cs 57 KB

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