DtoService.cs 58 KB

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