DtoService.cs 61 KB

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