DtoService.cs 63 KB

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