DtoService.cs 60 KB

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