DtoService.cs 61 KB

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