DtoService.cs 61 KB

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