DtoService.cs 55 KB

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