DtoService.cs 61 KB

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