DtoService.cs 59 KB

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