DtoService.cs 62 KB

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