DtoService.cs 58 KB

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