DtoService.cs 57 KB

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