DtoService.cs 60 KB

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