DtoService.cs 61 KB

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