DtoService.cs 61 KB

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