DtoService.cs 60 KB

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