DtoService.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Devices;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.Audio;
  10. using MediaBrowser.Controller.Entities.Movies;
  11. using MediaBrowser.Controller.Entities.TV;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Controller.Persistence;
  15. using MediaBrowser.Controller.Playlists;
  16. using MediaBrowser.Controller.Providers;
  17. using MediaBrowser.Controller.Sync;
  18. using MediaBrowser.Model.Drawing;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Querying;
  23. using MediaBrowser.Model.Sync;
  24. using MoreLinq;
  25. using System;
  26. using System.Collections.Generic;
  27. using System.IO;
  28. using System.Linq;
  29. using CommonIO;
  30. namespace MediaBrowser.Server.Implementations.Dto
  31. {
  32. public class DtoService : IDtoService
  33. {
  34. private readonly ILogger _logger;
  35. private readonly ILibraryManager _libraryManager;
  36. private readonly IUserDataManager _userDataRepository;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IImageProcessor _imageProcessor;
  39. private readonly IServerConfigurationManager _config;
  40. private readonly IFileSystem _fileSystem;
  41. private readonly IProviderManager _providerManager;
  42. private readonly Func<IChannelManager> _channelManagerFactory;
  43. private readonly ISyncManager _syncManager;
  44. private readonly IApplicationHost _appHost;
  45. private readonly Func<IDeviceManager> _deviceManager;
  46. private readonly Func<IMediaSourceManager> _mediaSourceManager;
  47. private readonly Func<ILiveTvManager> _livetvManager;
  48. 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)
  49. {
  50. _logger = logger;
  51. _libraryManager = libraryManager;
  52. _userDataRepository = userDataRepository;
  53. _itemRepo = itemRepo;
  54. _imageProcessor = imageProcessor;
  55. _config = config;
  56. _fileSystem = fileSystem;
  57. _providerManager = providerManager;
  58. _channelManagerFactory = channelManagerFactory;
  59. _syncManager = syncManager;
  60. _appHost = appHost;
  61. _deviceManager = deviceManager;
  62. _mediaSourceManager = mediaSourceManager;
  63. _livetvManager = livetvManager;
  64. }
  65. /// <summary>
  66. /// Converts a BaseItem to a DTOBaseItem
  67. /// </summary>
  68. /// <param name="item">The item.</param>
  69. /// <param name="fields">The fields.</param>
  70. /// <param name="user">The user.</param>
  71. /// <param name="owner">The owner.</param>
  72. /// <returns>Task{DtoBaseItem}.</returns>
  73. /// <exception cref="System.ArgumentNullException">item</exception>
  74. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  75. {
  76. var options = new DtoOptions
  77. {
  78. Fields = fields
  79. };
  80. return GetBaseItemDto(item, options, user, owner);
  81. }
  82. public IEnumerable<BaseItemDto> GetBaseItemDtos(IEnumerable<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
  83. {
  84. var syncJobItems = GetSyncedItemProgress(options);
  85. var syncDictionary = GetSyncedItemProgressDictionary(syncJobItems);
  86. var list = new List<BaseItemDto>();
  87. foreach (var item in items)
  88. {
  89. var dto = GetBaseItemDtoInternal(item, options, syncDictionary, user, owner);
  90. var byName = item as IItemByName;
  91. if (byName != null)
  92. {
  93. if (options.Fields.Contains(ItemFields.ItemCounts))
  94. {
  95. var itemFilter = byName.GetItemFilter();
  96. var libraryItems = user != null ?
  97. user.RootFolder.GetRecursiveChildren(user, itemFilter) :
  98. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter);
  99. SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
  100. }
  101. }
  102. FillSyncInfo(dto, item, syncJobItems, options, user);
  103. list.Add(dto);
  104. }
  105. return list;
  106. }
  107. private Dictionary<string, SyncedItemProgress> GetSyncedItemProgressDictionary(IEnumerable<SyncedItemProgress> items)
  108. {
  109. var dict = new Dictionary<string, SyncedItemProgress>();
  110. foreach (var item in items)
  111. {
  112. dict[item.ItemId] = item;
  113. }
  114. return dict;
  115. }
  116. public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
  117. {
  118. var syncProgress = GetSyncedItemProgress(options);
  119. var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user, owner);
  120. var byName = item as IItemByName;
  121. if (byName != null)
  122. {
  123. if (options.Fields.Contains(ItemFields.ItemCounts))
  124. {
  125. SetItemByNameInfo(item, dto, GetTaggedItems(byName, user), user);
  126. }
  127. FillSyncInfo(dto, item, options, user, syncProgress);
  128. return dto;
  129. }
  130. FillSyncInfo(dto, item, options, user, syncProgress);
  131. return dto;
  132. }
  133. private List<BaseItem> GetTaggedItems(IItemByName byName, User user)
  134. {
  135. var person = byName as Person;
  136. if (person != null)
  137. {
  138. var items = _libraryManager.GetItems(new InternalItemsQuery(user)
  139. {
  140. Person = byName.Name
  141. }, new string[] { });
  142. return items.ToList();
  143. }
  144. var itemFilter = byName.GetItemFilter();
  145. return user != null ?
  146. user.RootFolder.GetRecursiveChildren(user, itemFilter).ToList() :
  147. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter).ToList();
  148. }
  149. private SyncedItemProgress[] GetSyncedItemProgress(DtoOptions options)
  150. {
  151. if (!options.Fields.Contains(ItemFields.SyncInfo))
  152. {
  153. return new SyncedItemProgress[] { };
  154. }
  155. var deviceId = options.DeviceId;
  156. if (string.IsNullOrWhiteSpace(deviceId))
  157. {
  158. return new SyncedItemProgress[] { };
  159. }
  160. var caps = _deviceManager().GetCapabilities(deviceId);
  161. if (caps == null || !caps.SupportsSync)
  162. {
  163. return new SyncedItemProgress[] { };
  164. }
  165. return _syncManager.GetSyncedItemProgresses(new SyncJobItemQuery
  166. {
  167. TargetId = deviceId,
  168. Statuses = new[]
  169. {
  170. SyncJobItemStatus.Converting,
  171. SyncJobItemStatus.Queued,
  172. SyncJobItemStatus.Transferring,
  173. SyncJobItemStatus.ReadyToTransfer,
  174. SyncJobItemStatus.Synced
  175. }
  176. }).Items;
  177. }
  178. public void FillSyncInfo(IEnumerable<IHasSyncInfo> dtos, DtoOptions options, User user)
  179. {
  180. if (options.Fields.Contains(ItemFields.SyncInfo))
  181. {
  182. var syncProgress = GetSyncedItemProgress(options);
  183. foreach (var dto in dtos)
  184. {
  185. var item = _libraryManager.GetItemById(dto.Id);
  186. FillSyncInfo(dto, item, syncProgress, options, user);
  187. }
  188. }
  189. }
  190. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, DtoOptions options, User user, SyncedItemProgress[] syncProgress)
  191. {
  192. if (options.Fields.Contains(ItemFields.SyncInfo))
  193. {
  194. var userCanSync = user != null && user.Policy.EnableSync;
  195. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  196. }
  197. if (dto.SupportsSync ?? false)
  198. {
  199. dto.HasSyncJob = syncProgress.Any(i => i.Status != SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  200. dto.IsSynced = syncProgress.Any(i => i.Status == SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  201. if (dto.IsSynced.Value)
  202. {
  203. dto.SyncStatus = SyncJobItemStatus.Synced;
  204. }
  205. else if (dto.HasSyncJob.Value)
  206. {
  207. dto.SyncStatus = SyncJobItemStatus.Queued;
  208. }
  209. }
  210. }
  211. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, SyncedItemProgress[] syncProgress, DtoOptions options, User user)
  212. {
  213. if (options.Fields.Contains(ItemFields.SyncInfo))
  214. {
  215. var userCanSync = user != null && user.Policy.EnableSync;
  216. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  217. }
  218. if (dto.SupportsSync ?? false)
  219. {
  220. dto.HasSyncJob = syncProgress.Any(i => i.Status != SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  221. dto.IsSynced = syncProgress.Any(i => i.Status == SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  222. if (dto.IsSynced.Value)
  223. {
  224. dto.SyncStatus = SyncJobItemStatus.Synced;
  225. }
  226. else if (dto.HasSyncJob.Value)
  227. {
  228. dto.SyncStatus = SyncJobItemStatus.Queued;
  229. }
  230. }
  231. }
  232. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, Dictionary<string, SyncedItemProgress> syncProgress, User user = null, BaseItem owner = null)
  233. {
  234. var fields = options.Fields;
  235. if (item == null)
  236. {
  237. throw new ArgumentNullException("item");
  238. }
  239. if (fields == null)
  240. {
  241. throw new ArgumentNullException("fields");
  242. }
  243. var dto = new BaseItemDto
  244. {
  245. ServerId = _appHost.SystemId
  246. };
  247. if (fields.Contains(ItemFields.People))
  248. {
  249. AttachPeople(dto, item);
  250. }
  251. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  252. {
  253. try
  254. {
  255. AttachPrimaryImageAspectRatio(dto, item);
  256. }
  257. catch (Exception ex)
  258. {
  259. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  260. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  261. }
  262. }
  263. if (fields.Contains(ItemFields.DisplayPreferencesId))
  264. {
  265. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  266. }
  267. if (user != null)
  268. {
  269. AttachUserSpecificInfo(dto, item, user, fields, syncProgress);
  270. }
  271. var hasMediaSources = item as IHasMediaSources;
  272. if (hasMediaSources != null)
  273. {
  274. if (fields.Contains(ItemFields.MediaSources))
  275. {
  276. if (user == null)
  277. {
  278. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true).ToList();
  279. }
  280. else
  281. {
  282. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true, user).ToList();
  283. }
  284. }
  285. }
  286. if (fields.Contains(ItemFields.Studios))
  287. {
  288. AttachStudios(dto, item);
  289. }
  290. AttachBasicFields(dto, item, owner, options);
  291. var tvChannel = item as LiveTvChannel;
  292. if (tvChannel != null)
  293. {
  294. _livetvManager().AddChannelInfo(dto, tvChannel, options, user);
  295. }
  296. var collectionFolder = item as ICollectionFolder;
  297. if (collectionFolder != null)
  298. {
  299. dto.OriginalCollectionType = collectionFolder.CollectionType;
  300. dto.CollectionType = user == null ?
  301. collectionFolder.CollectionType :
  302. collectionFolder.GetViewType(user);
  303. }
  304. var playlist = item as Playlist;
  305. if (playlist != null)
  306. {
  307. AttachLinkedChildImages(dto, playlist, user, options);
  308. }
  309. if (fields.Contains(ItemFields.CanDelete))
  310. {
  311. dto.CanDelete = user == null
  312. ? item.CanDelete()
  313. : item.CanDelete(user);
  314. }
  315. if (fields.Contains(ItemFields.CanDownload))
  316. {
  317. dto.CanDownload = user == null
  318. ? item.CanDownload()
  319. : item.CanDownload(user);
  320. }
  321. if (fields.Contains(ItemFields.Etag))
  322. {
  323. dto.Etag = item.GetEtag(user);
  324. }
  325. if (item is ILiveTvRecording)
  326. {
  327. _livetvManager().AddInfoToRecordingDto(item, dto, user);
  328. }
  329. else if (item is LiveTvProgram)
  330. {
  331. _livetvManager().AddInfoToProgramDto(item, dto, fields.Contains(ItemFields.ChannelInfo), user);
  332. }
  333. return dto;
  334. }
  335. public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null)
  336. {
  337. var syncProgress = GetSyncedItemProgress(options);
  338. var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user);
  339. if (options.Fields.Contains(ItemFields.ItemCounts))
  340. {
  341. SetItemByNameInfo(item, dto, taggedItems, user);
  342. }
  343. FillSyncInfo(dto, item, options, user, syncProgress);
  344. return dto;
  345. }
  346. private void SetItemByNameInfo(BaseItem item, BaseItemDto dto, List<BaseItem> taggedItems, User user = null)
  347. {
  348. if (item is MusicArtist || item is MusicGenre)
  349. {
  350. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  351. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  352. dto.SongCount = taggedItems.Count(i => i is Audio);
  353. }
  354. else if (item is GameGenre)
  355. {
  356. dto.GameCount = taggedItems.Count(i => i is Game);
  357. }
  358. else
  359. {
  360. // This populates them all and covers Genre, Person, Studio, Year
  361. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  362. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  363. dto.GameCount = taggedItems.Count(i => i is Game);
  364. dto.MovieCount = taggedItems.Count(i => i is Movie);
  365. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  366. dto.SeriesCount = taggedItems.Count(i => i is Series);
  367. dto.SongCount = taggedItems.Count(i => i is Audio);
  368. }
  369. dto.ChildCount = taggedItems.Count;
  370. }
  371. /// <summary>
  372. /// Attaches the user specific info.
  373. /// </summary>
  374. /// <param name="dto">The dto.</param>
  375. /// <param name="item">The item.</param>
  376. /// <param name="user">The user.</param>
  377. /// <param name="fields">The fields.</param>
  378. /// <param name="syncProgress">The synchronize progress.</param>
  379. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields, Dictionary<string, SyncedItemProgress> syncProgress)
  380. {
  381. if (item.IsFolder)
  382. {
  383. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  384. // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice
  385. // TODO: Improve in future
  386. dto.UserData = GetUserItemDataDto(userData);
  387. var folder = (Folder)item;
  388. if (!(folder is IChannelItem) && !(folder is Channel))
  389. {
  390. dto.ChildCount = GetChildCount(folder, user);
  391. // These are just far too slow.
  392. if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is ICollectionFolder))
  393. {
  394. SetSpecialCounts(folder, user, dto, fields, syncProgress);
  395. }
  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.GetParent() ?? owner;
  692. while (parent != null)
  693. {
  694. if (parent.GetImages(ImageType.Backdrop).Any())
  695. {
  696. return parent;
  697. }
  698. parent = parent.GetParent();
  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.GetParent() ?? owner;
  712. while (parent != null)
  713. {
  714. if (parent.HasImage(type))
  715. {
  716. return parent;
  717. }
  718. parent = parent.GetParent();
  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. if (fields.Contains(ItemFields.Settings))
  771. {
  772. dto.LockedFields = item.LockedFields;
  773. dto.LockData = item.IsLocked;
  774. dto.ForcedSortName = item.ForcedSortName;
  775. }
  776. var hasBudget = item as IHasBudget;
  777. if (hasBudget != null)
  778. {
  779. if (fields.Contains(ItemFields.Budget))
  780. {
  781. dto.Budget = hasBudget.Budget;
  782. }
  783. if (fields.Contains(ItemFields.Revenue))
  784. {
  785. dto.Revenue = hasBudget.Revenue;
  786. }
  787. }
  788. dto.EndDate = item.EndDate;
  789. if (fields.Contains(ItemFields.HomePageUrl))
  790. {
  791. dto.HomePageUrl = item.HomePageUrl;
  792. }
  793. if (fields.Contains(ItemFields.ExternalUrls))
  794. {
  795. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  796. }
  797. if (fields.Contains(ItemFields.Tags))
  798. {
  799. var hasTags = item as IHasTags;
  800. if (hasTags != null)
  801. {
  802. dto.Tags = hasTags.Tags;
  803. }
  804. if (dto.Tags == null)
  805. {
  806. dto.Tags = new List<string>();
  807. }
  808. }
  809. if (fields.Contains(ItemFields.Keywords))
  810. {
  811. var hasTags = item as IHasKeywords;
  812. if (hasTags != null)
  813. {
  814. dto.Keywords = hasTags.Keywords;
  815. }
  816. if (dto.Keywords == null)
  817. {
  818. dto.Keywords = new List<string>();
  819. }
  820. }
  821. if (fields.Contains(ItemFields.ProductionLocations))
  822. {
  823. SetProductionLocations(item, dto);
  824. }
  825. var hasAspectRatio = item as IHasAspectRatio;
  826. if (hasAspectRatio != null)
  827. {
  828. dto.AspectRatio = hasAspectRatio.AspectRatio;
  829. }
  830. if (fields.Contains(ItemFields.Metascore))
  831. {
  832. var hasMetascore = item as IHasMetascore;
  833. if (hasMetascore != null)
  834. {
  835. dto.Metascore = hasMetascore.Metascore;
  836. }
  837. }
  838. if (fields.Contains(ItemFields.AwardSummary))
  839. {
  840. var hasAwards = item as IHasAwards;
  841. if (hasAwards != null)
  842. {
  843. dto.AwardSummary = hasAwards.AwardSummary;
  844. }
  845. }
  846. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  847. if (backdropLimit > 0)
  848. {
  849. dto.BackdropImageTags = GetBackdropImageTags(item, backdropLimit);
  850. }
  851. if (fields.Contains(ItemFields.ScreenshotImageTags))
  852. {
  853. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  854. if (screenshotLimit > 0)
  855. {
  856. dto.ScreenshotImageTags = GetScreenshotImageTags(item, screenshotLimit);
  857. }
  858. }
  859. if (fields.Contains(ItemFields.Genres))
  860. {
  861. dto.Genres = item.Genres;
  862. }
  863. dto.ImageTags = new Dictionary<ImageType, string>();
  864. // Prevent implicitly captured closure
  865. var currentItem = item;
  866. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  867. .ToList())
  868. {
  869. if (options.GetImageLimit(image.Type) > 0)
  870. {
  871. var tag = GetImageCacheTag(item, image);
  872. if (tag != null)
  873. {
  874. dto.ImageTags[image.Type] = tag;
  875. }
  876. }
  877. }
  878. dto.Id = GetDtoId(item);
  879. dto.IndexNumber = item.IndexNumber;
  880. dto.IsFolder = item.IsFolder;
  881. dto.MediaType = item.MediaType;
  882. dto.LocationType = item.LocationType;
  883. if (item.IsHD.HasValue && item.IsHD.Value)
  884. {
  885. dto.IsHD = item.IsHD;
  886. }
  887. dto.Audio = item.Audio;
  888. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  889. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  890. var hasCriticRating = item as IHasCriticRating;
  891. if (hasCriticRating != null)
  892. {
  893. dto.CriticRating = hasCriticRating.CriticRating;
  894. if (fields.Contains(ItemFields.CriticRatingSummary))
  895. {
  896. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  897. }
  898. }
  899. var hasTrailers = item as IHasTrailers;
  900. if (hasTrailers != null)
  901. {
  902. dto.LocalTrailerCount = hasTrailers.GetTrailerIds().Count;
  903. }
  904. var hasDisplayOrder = item as IHasDisplayOrder;
  905. if (hasDisplayOrder != null)
  906. {
  907. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  908. }
  909. var userView = item as UserView;
  910. if (userView != null)
  911. {
  912. dto.CollectionType = userView.ViewType;
  913. }
  914. if (fields.Contains(ItemFields.RemoteTrailers))
  915. {
  916. dto.RemoteTrailers = hasTrailers != null ?
  917. hasTrailers.RemoteTrailers :
  918. new List<MediaUrl>();
  919. }
  920. dto.Name = item.Name;
  921. dto.OfficialRating = item.OfficialRating;
  922. if (fields.Contains(ItemFields.Overview))
  923. {
  924. dto.Overview = item.Overview;
  925. }
  926. if (fields.Contains(ItemFields.ShortOverview))
  927. {
  928. var hasShortOverview = item as IHasShortOverview;
  929. if (hasShortOverview != null)
  930. {
  931. dto.ShortOverview = hasShortOverview.ShortOverview;
  932. }
  933. }
  934. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  935. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  936. {
  937. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  938. if (parentWithBackdrop != null)
  939. {
  940. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  941. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  942. }
  943. }
  944. if (fields.Contains(ItemFields.ParentId))
  945. {
  946. var displayParent = item.DisplayParent;
  947. if (displayParent != null)
  948. {
  949. dto.ParentId = GetDtoId(displayParent);
  950. }
  951. }
  952. dto.ParentIndexNumber = item.ParentIndexNumber;
  953. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  954. if (!dto.HasLogo && options.GetImageLimit(ImageType.Logo) > 0)
  955. {
  956. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  957. if (parentWithLogo != null)
  958. {
  959. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  960. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  961. }
  962. }
  963. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  964. if (!dto.HasArtImage && options.GetImageLimit(ImageType.Art) > 0)
  965. {
  966. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  967. if (parentWithImage != null)
  968. {
  969. dto.ParentArtItemId = GetDtoId(parentWithImage);
  970. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  971. }
  972. }
  973. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  974. if (!dto.HasThumb && options.GetImageLimit(ImageType.Thumb) > 0)
  975. {
  976. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  977. if (parentWithImage != null)
  978. {
  979. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  980. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  981. }
  982. }
  983. if (fields.Contains(ItemFields.Path))
  984. {
  985. dto.Path = GetMappedPath(item);
  986. }
  987. dto.PremiereDate = item.PremiereDate;
  988. dto.ProductionYear = item.ProductionYear;
  989. if (fields.Contains(ItemFields.ProviderIds))
  990. {
  991. dto.ProviderIds = item.ProviderIds;
  992. }
  993. dto.RunTimeTicks = item.RunTimeTicks;
  994. if (fields.Contains(ItemFields.SortName))
  995. {
  996. dto.SortName = item.SortName;
  997. }
  998. if (fields.Contains(ItemFields.CustomRating))
  999. {
  1000. dto.CustomRating = item.CustomRating;
  1001. }
  1002. if (fields.Contains(ItemFields.Taglines))
  1003. {
  1004. var hasTagline = item as IHasTaglines;
  1005. if (hasTagline != null)
  1006. {
  1007. dto.Taglines = hasTagline.Taglines;
  1008. }
  1009. if (dto.Taglines == null)
  1010. {
  1011. dto.Taglines = new List<string>();
  1012. }
  1013. }
  1014. dto.Type = item.GetClientTypeName();
  1015. dto.CommunityRating = item.CommunityRating;
  1016. if (fields.Contains(ItemFields.VoteCount))
  1017. {
  1018. dto.VoteCount = item.VoteCount;
  1019. }
  1020. //if (item.IsFolder)
  1021. //{
  1022. // var folder = (Folder)item;
  1023. // if (fields.Contains(ItemFields.IndexOptions))
  1024. // {
  1025. // dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  1026. // }
  1027. //}
  1028. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  1029. if (supportsPlaceHolders != null)
  1030. {
  1031. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  1032. }
  1033. // Add audio info
  1034. var audio = item as Audio;
  1035. if (audio != null)
  1036. {
  1037. dto.Album = audio.Album;
  1038. var albumParent = audio.AlbumEntity;
  1039. if (albumParent != null)
  1040. {
  1041. dto.AlbumId = GetDtoId(albumParent);
  1042. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  1043. }
  1044. //if (fields.Contains(ItemFields.MediaSourceCount))
  1045. //{
  1046. // Songs always have one
  1047. //}
  1048. }
  1049. var hasArtist = item as IHasArtist;
  1050. if (hasArtist != null)
  1051. {
  1052. dto.Artists = hasArtist.Artists;
  1053. dto.ArtistItems = hasArtist
  1054. .Artists
  1055. .Select(i =>
  1056. {
  1057. try
  1058. {
  1059. var artist = _libraryManager.GetArtist(i);
  1060. return new NameIdPair
  1061. {
  1062. Name = artist.Name,
  1063. Id = artist.Id.ToString("N")
  1064. };
  1065. }
  1066. catch (Exception ex)
  1067. {
  1068. _logger.ErrorException("Error getting artist", ex);
  1069. return null;
  1070. }
  1071. })
  1072. .Where(i => i != null)
  1073. .ToList();
  1074. }
  1075. var hasAlbumArtist = item as IHasAlbumArtist;
  1076. if (hasAlbumArtist != null)
  1077. {
  1078. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  1079. dto.AlbumArtists = hasAlbumArtist
  1080. .AlbumArtists
  1081. .Select(i =>
  1082. {
  1083. try
  1084. {
  1085. var artist = _libraryManager.GetArtist(i);
  1086. return new NameIdPair
  1087. {
  1088. Name = artist.Name,
  1089. Id = artist.Id.ToString("N")
  1090. };
  1091. }
  1092. catch (Exception ex)
  1093. {
  1094. _logger.ErrorException("Error getting album artist", ex);
  1095. return null;
  1096. }
  1097. })
  1098. .Where(i => i != null)
  1099. .ToList();
  1100. }
  1101. // Add video info
  1102. var video = item as Video;
  1103. if (video != null)
  1104. {
  1105. dto.VideoType = video.VideoType;
  1106. dto.Video3DFormat = video.Video3DFormat;
  1107. dto.IsoType = video.IsoType;
  1108. if (video.HasSubtitles)
  1109. {
  1110. dto.HasSubtitles = video.HasSubtitles;
  1111. }
  1112. if (video.AdditionalParts.Count != 0)
  1113. {
  1114. dto.PartCount = video.AdditionalParts.Count + 1;
  1115. }
  1116. if (fields.Contains(ItemFields.MediaSourceCount))
  1117. {
  1118. if (video.MediaSourceCount != 1)
  1119. {
  1120. dto.MediaSourceCount = video.MediaSourceCount;
  1121. }
  1122. }
  1123. if (fields.Contains(ItemFields.Chapters))
  1124. {
  1125. dto.Chapters = GetChapterInfoDtos(item);
  1126. }
  1127. }
  1128. if (fields.Contains(ItemFields.MediaStreams))
  1129. {
  1130. // Add VideoInfo
  1131. var iHasMediaSources = item as IHasMediaSources;
  1132. if (iHasMediaSources != null)
  1133. {
  1134. List<MediaStream> mediaStreams;
  1135. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  1136. {
  1137. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  1138. .SelectMany(i => i.MediaStreams)
  1139. .ToList();
  1140. }
  1141. else
  1142. {
  1143. mediaStreams = _mediaSourceManager().GetStaticMediaSources(iHasMediaSources, true).First().MediaStreams;
  1144. }
  1145. dto.MediaStreams = mediaStreams;
  1146. }
  1147. }
  1148. // Add MovieInfo
  1149. var movie = item as Movie;
  1150. if (movie != null)
  1151. {
  1152. if (fields.Contains(ItemFields.TmdbCollectionName))
  1153. {
  1154. dto.TmdbCollectionName = movie.TmdbCollectionName;
  1155. }
  1156. }
  1157. var hasSpecialFeatures = item as IHasSpecialFeatures;
  1158. if (hasSpecialFeatures != null)
  1159. {
  1160. var specialFeatureCount = hasSpecialFeatures.SpecialFeatureIds.Count;
  1161. if (specialFeatureCount > 0)
  1162. {
  1163. dto.SpecialFeatureCount = specialFeatureCount;
  1164. }
  1165. }
  1166. // Add EpisodeInfo
  1167. var episode = item as Episode;
  1168. if (episode != null)
  1169. {
  1170. dto.IndexNumberEnd = episode.IndexNumberEnd;
  1171. if (fields.Contains(ItemFields.AlternateEpisodeNumbers))
  1172. {
  1173. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  1174. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  1175. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  1176. }
  1177. if (fields.Contains(ItemFields.SpecialEpisodeNumbers))
  1178. {
  1179. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  1180. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  1181. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  1182. }
  1183. var episodeSeason = episode.Season;
  1184. if (episodeSeason != null)
  1185. {
  1186. dto.SeasonId = episodeSeason.Id.ToString("N");
  1187. if (fields.Contains(ItemFields.SeasonName))
  1188. {
  1189. dto.SeasonName = episodeSeason.Name;
  1190. }
  1191. }
  1192. if (fields.Contains(ItemFields.SeriesGenres))
  1193. {
  1194. var episodeseries = episode.Series;
  1195. if (episodeseries != null)
  1196. {
  1197. dto.SeriesGenres = episodeseries.Genres.ToList();
  1198. }
  1199. }
  1200. }
  1201. // Add SeriesInfo
  1202. var series = item as Series;
  1203. if (series != null)
  1204. {
  1205. dto.AirDays = series.AirDays;
  1206. dto.AirTime = series.AirTime;
  1207. dto.SeriesStatus = series.Status;
  1208. if (fields.Contains(ItemFields.Settings))
  1209. {
  1210. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  1211. }
  1212. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  1213. }
  1214. if (episode != null)
  1215. {
  1216. series = episode.Series;
  1217. if (series != null)
  1218. {
  1219. dto.SeriesId = GetDtoId(series);
  1220. dto.SeriesName = series.Name;
  1221. if (fields.Contains(ItemFields.AirTime))
  1222. {
  1223. dto.AirTime = series.AirTime;
  1224. }
  1225. if (options.GetImageLimit(ImageType.Thumb) > 0)
  1226. {
  1227. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  1228. }
  1229. if (options.GetImageLimit(ImageType.Primary) > 0)
  1230. {
  1231. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1232. }
  1233. if (fields.Contains(ItemFields.SeriesStudio))
  1234. {
  1235. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1236. }
  1237. }
  1238. }
  1239. // Add SeasonInfo
  1240. var season = item as Season;
  1241. if (season != null)
  1242. {
  1243. series = season.Series;
  1244. if (series != null)
  1245. {
  1246. dto.SeriesId = GetDtoId(series);
  1247. dto.SeriesName = series.Name;
  1248. dto.AirTime = series.AirTime;
  1249. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1250. if (options.GetImageLimit(ImageType.Primary) > 0)
  1251. {
  1252. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1253. }
  1254. }
  1255. }
  1256. var game = item as Game;
  1257. if (game != null)
  1258. {
  1259. SetGameProperties(dto, game);
  1260. }
  1261. var gameSystem = item as GameSystem;
  1262. if (gameSystem != null)
  1263. {
  1264. SetGameSystemProperties(dto, gameSystem);
  1265. }
  1266. var musicVideo = item as MusicVideo;
  1267. if (musicVideo != null)
  1268. {
  1269. SetMusicVideoProperties(dto, musicVideo);
  1270. }
  1271. var book = item as Book;
  1272. if (book != null)
  1273. {
  1274. SetBookProperties(dto, book);
  1275. }
  1276. var photo = item as Photo;
  1277. if (photo != null)
  1278. {
  1279. SetPhotoProperties(dto, photo);
  1280. }
  1281. dto.ChannelId = item.ChannelId;
  1282. var channelItem = item as IChannelItem;
  1283. if (channelItem != null)
  1284. {
  1285. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1286. }
  1287. var channelMediaItem = item as IChannelMediaItem;
  1288. if (channelMediaItem != null)
  1289. {
  1290. dto.ExtraType = channelMediaItem.ExtraType;
  1291. }
  1292. }
  1293. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user, DtoOptions options)
  1294. {
  1295. List<BaseItem> linkedChildren = null;
  1296. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1297. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  1298. {
  1299. linkedChildren = user == null
  1300. ? folder.GetRecursiveChildren().ToList()
  1301. : folder.GetRecursiveChildren(user).ToList();
  1302. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1303. if (parentWithBackdrop != null)
  1304. {
  1305. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1306. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  1307. }
  1308. }
  1309. if (!dto.ImageTags.ContainsKey(ImageType.Primary) && options.GetImageLimit(ImageType.Primary) > 0)
  1310. {
  1311. if (linkedChildren == null)
  1312. {
  1313. linkedChildren = user == null
  1314. ? folder.GetRecursiveChildren().ToList()
  1315. : folder.GetRecursiveChildren(user).ToList();
  1316. }
  1317. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1318. if (parentWithImage != null)
  1319. {
  1320. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1321. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1322. }
  1323. }
  1324. }
  1325. private string GetMappedPath(IHasMetadata item)
  1326. {
  1327. var path = item.Path;
  1328. var locationType = item.LocationType;
  1329. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1330. {
  1331. foreach (var map in _config.Configuration.PathSubstitutions)
  1332. {
  1333. path = _libraryManager.SubstitutePath(path, map.From, map.To);
  1334. }
  1335. }
  1336. return path;
  1337. }
  1338. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1339. {
  1340. var hasProductionLocations = item as IHasProductionLocations;
  1341. if (hasProductionLocations != null)
  1342. {
  1343. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1344. }
  1345. var person = item as Person;
  1346. if (person != null)
  1347. {
  1348. dto.ProductionLocations = new List<string>();
  1349. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1350. {
  1351. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1352. }
  1353. }
  1354. if (dto.ProductionLocations == null)
  1355. {
  1356. dto.ProductionLocations = new List<string>();
  1357. }
  1358. }
  1359. /// <summary>
  1360. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1361. /// </summary>
  1362. /// <param name="folder">The folder.</param>
  1363. /// <param name="user">The user.</param>
  1364. /// <param name="dto">The dto.</param>
  1365. /// <param name="fields">The fields.</param>
  1366. /// <param name="syncProgress">The synchronize progress.</param>
  1367. /// <returns>Task.</returns>
  1368. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields, Dictionary<string, SyncedItemProgress> syncProgress)
  1369. {
  1370. var recursiveItemCount = 0;
  1371. var unplayed = 0;
  1372. long runtime = 0;
  1373. DateTime? dateLastMediaAdded = null;
  1374. double totalPercentPlayed = 0;
  1375. double totalSyncPercent = 0;
  1376. var addSyncInfo = fields.Contains(ItemFields.SyncInfo);
  1377. var children = folder.GetItems(new InternalItemsQuery
  1378. {
  1379. IsFolder = false,
  1380. Recursive = true,
  1381. IsVirtualUnaired = false,
  1382. IsMissing = false,
  1383. User = user
  1384. }).Result.Items;
  1385. // Loop through each recursive child
  1386. foreach (var child in children)
  1387. {
  1388. if (!dateLastMediaAdded.HasValue)
  1389. {
  1390. dateLastMediaAdded = child.DateCreated;
  1391. }
  1392. else
  1393. {
  1394. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1395. }
  1396. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1397. recursiveItemCount++;
  1398. var isUnplayed = true;
  1399. // Incrememt totalPercentPlayed
  1400. if (userdata != null)
  1401. {
  1402. if (userdata.Played)
  1403. {
  1404. totalPercentPlayed += 100;
  1405. isUnplayed = false;
  1406. }
  1407. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1408. {
  1409. double itemPercent = userdata.PlaybackPositionTicks;
  1410. itemPercent /= child.RunTimeTicks.Value;
  1411. totalPercentPlayed += itemPercent;
  1412. }
  1413. }
  1414. if (isUnplayed)
  1415. {
  1416. unplayed++;
  1417. }
  1418. runtime += child.RunTimeTicks ?? 0;
  1419. if (addSyncInfo)
  1420. {
  1421. double percent = 0;
  1422. SyncedItemProgress syncItemProgress;
  1423. if (syncProgress.TryGetValue(child.Id.ToString("N"), out syncItemProgress))
  1424. {
  1425. switch (syncItemProgress.Status)
  1426. {
  1427. case SyncJobItemStatus.Synced:
  1428. percent = 100;
  1429. break;
  1430. case SyncJobItemStatus.Converting:
  1431. case SyncJobItemStatus.ReadyToTransfer:
  1432. case SyncJobItemStatus.Transferring:
  1433. percent = 50;
  1434. break;
  1435. }
  1436. }
  1437. totalSyncPercent += percent;
  1438. }
  1439. }
  1440. dto.RecursiveItemCount = recursiveItemCount;
  1441. dto.UserData.UnplayedItemCount = unplayed;
  1442. if (recursiveItemCount > 0)
  1443. {
  1444. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1445. if (addSyncInfo)
  1446. {
  1447. var pct = totalSyncPercent / recursiveItemCount;
  1448. if (pct > 0)
  1449. {
  1450. dto.SyncPercent = pct;
  1451. }
  1452. }
  1453. }
  1454. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1455. {
  1456. dto.CumulativeRunTimeTicks = runtime;
  1457. }
  1458. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1459. {
  1460. dto.DateLastMediaAdded = dateLastMediaAdded;
  1461. }
  1462. }
  1463. /// <summary>
  1464. /// Attaches the primary image aspect ratio.
  1465. /// </summary>
  1466. /// <param name="dto">The dto.</param>
  1467. /// <param name="item">The item.</param>
  1468. /// <returns>Task.</returns>
  1469. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1470. {
  1471. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1472. }
  1473. public double? GetPrimaryImageAspectRatio(IHasImages item)
  1474. {
  1475. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1476. if (imageInfo == null || !imageInfo.IsLocalFile)
  1477. {
  1478. return null;
  1479. }
  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 null;
  1489. }
  1490. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1491. foreach (var enhancer in supportedEnhancers)
  1492. {
  1493. try
  1494. {
  1495. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1496. }
  1497. catch (Exception ex)
  1498. {
  1499. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1500. }
  1501. }
  1502. var width = size.Width;
  1503. var height = size.Height;
  1504. if (width == 0 || height == 0)
  1505. {
  1506. return null;
  1507. }
  1508. var photo = item as Photo;
  1509. if (photo != null && photo.Orientation.HasValue)
  1510. {
  1511. switch (photo.Orientation.Value)
  1512. {
  1513. case ImageOrientation.LeftBottom:
  1514. case ImageOrientation.LeftTop:
  1515. case ImageOrientation.RightBottom:
  1516. case ImageOrientation.RightTop:
  1517. var temp = height;
  1518. height = width;
  1519. width = temp;
  1520. break;
  1521. }
  1522. }
  1523. return width / height;
  1524. }
  1525. }
  1526. }