DtoService.cs 61 KB

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