DtoService.cs 61 KB

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