DtoService.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  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. var children = folder.GetItems(new InternalItemsQuery
  1379. {
  1380. IsFolder = false,
  1381. Recursive = true,
  1382. IsVirtualUnaired = false,
  1383. IsMissing = false
  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. /// <param name="fields">The fields.</param>
  1469. /// <returns>Task.</returns>
  1470. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item, List<ItemFields> fields)
  1471. {
  1472. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1473. if (imageInfo == null)
  1474. {
  1475. return;
  1476. }
  1477. var path = imageInfo.Path;
  1478. ImageSize size;
  1479. try
  1480. {
  1481. size = _imageProcessor.GetImageSize(imageInfo);
  1482. }
  1483. catch (FileNotFoundException)
  1484. {
  1485. _logger.Error("Image file does not exist: {0}", path);
  1486. return;
  1487. }
  1488. catch (Exception ex)
  1489. {
  1490. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1491. return;
  1492. }
  1493. if (fields.Contains(ItemFields.OriginalPrimaryImageAspectRatio))
  1494. {
  1495. if (size.Width > 0 && size.Height > 0)
  1496. {
  1497. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1498. }
  1499. }
  1500. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1501. foreach (var enhancer in supportedEnhancers)
  1502. {
  1503. try
  1504. {
  1505. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1506. }
  1507. catch (Exception ex)
  1508. {
  1509. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1510. }
  1511. }
  1512. if (size.Width > 0 && size.Height > 0)
  1513. {
  1514. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1515. }
  1516. }
  1517. }
  1518. }