DtoService.cs 60 KB

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