DtoService.cs 56 KB

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