DtoService.cs 63 KB

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