DtoService.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Devices;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.Audio;
  10. using MediaBrowser.Controller.Entities.Movies;
  11. using MediaBrowser.Controller.Entities.TV;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Controller.Persistence;
  15. using MediaBrowser.Controller.Playlists;
  16. using MediaBrowser.Controller.Providers;
  17. using MediaBrowser.Controller.Sync;
  18. using MediaBrowser.Model.Drawing;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Querying;
  23. using MediaBrowser.Model.Sync;
  24. using MoreLinq;
  25. using System;
  26. using System.Collections.Generic;
  27. using System.IO;
  28. using System.Linq;
  29. using CommonIO;
  30. namespace MediaBrowser.Server.Implementations.Dto
  31. {
  32. public class DtoService : IDtoService
  33. {
  34. private readonly ILogger _logger;
  35. private readonly ILibraryManager _libraryManager;
  36. private readonly IUserDataManager _userDataRepository;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IImageProcessor _imageProcessor;
  39. private readonly IServerConfigurationManager _config;
  40. private readonly IFileSystem _fileSystem;
  41. private readonly IProviderManager _providerManager;
  42. private readonly Func<IChannelManager> _channelManagerFactory;
  43. private readonly ISyncManager _syncManager;
  44. private readonly IApplicationHost _appHost;
  45. private readonly Func<IDeviceManager> _deviceManager;
  46. private readonly Func<IMediaSourceManager> _mediaSourceManager;
  47. private readonly Func<ILiveTvManager> _livetvManager;
  48. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func<IChannelManager> channelManagerFactory, ISyncManager syncManager, IApplicationHost appHost, Func<IDeviceManager> deviceManager, Func<IMediaSourceManager> mediaSourceManager, Func<ILiveTvManager> livetvManager)
  49. {
  50. _logger = logger;
  51. _libraryManager = libraryManager;
  52. _userDataRepository = userDataRepository;
  53. _itemRepo = itemRepo;
  54. _imageProcessor = imageProcessor;
  55. _config = config;
  56. _fileSystem = fileSystem;
  57. _providerManager = providerManager;
  58. _channelManagerFactory = channelManagerFactory;
  59. _syncManager = syncManager;
  60. _appHost = appHost;
  61. _deviceManager = deviceManager;
  62. _mediaSourceManager = mediaSourceManager;
  63. _livetvManager = livetvManager;
  64. }
  65. /// <summary>
  66. /// Converts a BaseItem to a DTOBaseItem
  67. /// </summary>
  68. /// <param name="item">The item.</param>
  69. /// <param name="fields">The fields.</param>
  70. /// <param name="user">The user.</param>
  71. /// <param name="owner">The owner.</param>
  72. /// <returns>Task{DtoBaseItem}.</returns>
  73. /// <exception cref="System.ArgumentNullException">item</exception>
  74. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  75. {
  76. var options = new DtoOptions
  77. {
  78. Fields = fields
  79. };
  80. return GetBaseItemDto(item, options, user, owner);
  81. }
  82. public IEnumerable<BaseItemDto> GetBaseItemDtos(IEnumerable<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
  83. {
  84. var syncJobItems = GetSyncedItemProgress(options);
  85. var syncDictionary = GetSyncedItemProgressDictionary(syncJobItems);
  86. var list = new List<BaseItemDto>();
  87. foreach (var item in items)
  88. {
  89. var dto = GetBaseItemDtoInternal(item, options, syncDictionary, user, owner);
  90. var byName = item as IItemByName;
  91. if (byName != null)
  92. {
  93. if (options.Fields.Contains(ItemFields.ItemCounts))
  94. {
  95. var itemFilter = byName.GetItemFilter();
  96. var libraryItems = user != null ?
  97. user.RootFolder.GetRecursiveChildren(user, itemFilter) :
  98. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter);
  99. SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
  100. }
  101. }
  102. FillSyncInfo(dto, item, syncJobItems, options, user);
  103. list.Add(dto);
  104. }
  105. return list;
  106. }
  107. private Dictionary<string, SyncedItemProgress> GetSyncedItemProgressDictionary(IEnumerable<SyncedItemProgress> items)
  108. {
  109. var dict = new Dictionary<string, SyncedItemProgress>();
  110. foreach (var item in items)
  111. {
  112. dict[item.ItemId] = item;
  113. }
  114. return dict;
  115. }
  116. public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
  117. {
  118. var syncProgress = GetSyncedItemProgress(options);
  119. var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user, owner);
  120. var byName = item as IItemByName;
  121. if (byName != null)
  122. {
  123. if (options.Fields.Contains(ItemFields.ItemCounts))
  124. {
  125. SetItemByNameInfo(item, dto, GetTaggedItems(byName, user), user);
  126. }
  127. FillSyncInfo(dto, item, options, user, syncProgress);
  128. return dto;
  129. }
  130. FillSyncInfo(dto, item, options, user, syncProgress);
  131. return dto;
  132. }
  133. private List<BaseItem> GetTaggedItems(IItemByName byName, User user)
  134. {
  135. var person = byName as Person;
  136. if (person != null)
  137. {
  138. var items = _libraryManager.GetItems(new InternalItemsQuery(user)
  139. {
  140. Person = byName.Name
  141. }, user, new string[] { });
  142. return items.ToList();
  143. }
  144. var itemFilter = byName.GetItemFilter();
  145. return user != null ?
  146. user.RootFolder.GetRecursiveChildren(user, itemFilter).ToList() :
  147. _libraryManager.RootFolder.GetRecursiveChildren(itemFilter).ToList();
  148. }
  149. private SyncedItemProgress[] GetSyncedItemProgress(DtoOptions options)
  150. {
  151. if (!options.Fields.Contains(ItemFields.SyncInfo))
  152. {
  153. return new SyncedItemProgress[] { };
  154. }
  155. var deviceId = options.DeviceId;
  156. if (string.IsNullOrWhiteSpace(deviceId))
  157. {
  158. return new SyncedItemProgress[] { };
  159. }
  160. var caps = _deviceManager().GetCapabilities(deviceId);
  161. if (caps == null || !caps.SupportsSync)
  162. {
  163. return new SyncedItemProgress[] { };
  164. }
  165. return _syncManager.GetSyncedItemProgresses(new SyncJobItemQuery
  166. {
  167. TargetId = deviceId,
  168. Statuses = new[]
  169. {
  170. SyncJobItemStatus.Converting,
  171. SyncJobItemStatus.Queued,
  172. SyncJobItemStatus.Transferring,
  173. SyncJobItemStatus.ReadyToTransfer,
  174. SyncJobItemStatus.Synced
  175. }
  176. }).Items;
  177. }
  178. public void FillSyncInfo(IEnumerable<IHasSyncInfo> dtos, DtoOptions options, User user)
  179. {
  180. if (options.Fields.Contains(ItemFields.SyncInfo))
  181. {
  182. var syncProgress = GetSyncedItemProgress(options);
  183. foreach (var dto in dtos)
  184. {
  185. var item = _libraryManager.GetItemById(dto.Id);
  186. FillSyncInfo(dto, item, syncProgress, options, user);
  187. }
  188. }
  189. }
  190. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, DtoOptions options, User user, SyncedItemProgress[] syncProgress)
  191. {
  192. if (options.Fields.Contains(ItemFields.SyncInfo))
  193. {
  194. var userCanSync = user != null && user.Policy.EnableSync;
  195. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  196. }
  197. if (dto.SupportsSync ?? false)
  198. {
  199. dto.HasSyncJob = syncProgress.Any(i => i.Status != SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  200. dto.IsSynced = syncProgress.Any(i => i.Status == SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  201. if (dto.IsSynced.Value)
  202. {
  203. dto.SyncStatus = SyncJobItemStatus.Synced;
  204. }
  205. else if (dto.HasSyncJob.Value)
  206. {
  207. dto.SyncStatus = SyncJobItemStatus.Queued;
  208. }
  209. }
  210. }
  211. private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, SyncedItemProgress[] syncProgress, DtoOptions options, User user)
  212. {
  213. if (options.Fields.Contains(ItemFields.SyncInfo))
  214. {
  215. var userCanSync = user != null && user.Policy.EnableSync;
  216. dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
  217. }
  218. if (dto.SupportsSync ?? false)
  219. {
  220. dto.HasSyncJob = syncProgress.Any(i => i.Status != SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  221. dto.IsSynced = syncProgress.Any(i => i.Status == SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
  222. if (dto.IsSynced.Value)
  223. {
  224. dto.SyncStatus = SyncJobItemStatus.Synced;
  225. }
  226. else if (dto.HasSyncJob.Value)
  227. {
  228. dto.SyncStatus = SyncJobItemStatus.Queued;
  229. }
  230. }
  231. }
  232. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, Dictionary<string, SyncedItemProgress> syncProgress, User user = null, BaseItem owner = null)
  233. {
  234. var fields = options.Fields;
  235. if (item == null)
  236. {
  237. throw new ArgumentNullException("item");
  238. }
  239. if (fields == null)
  240. {
  241. throw new ArgumentNullException("fields");
  242. }
  243. var dto = new BaseItemDto
  244. {
  245. ServerId = _appHost.SystemId
  246. };
  247. if (fields.Contains(ItemFields.People))
  248. {
  249. AttachPeople(dto, item);
  250. }
  251. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  252. {
  253. try
  254. {
  255. AttachPrimaryImageAspectRatio(dto, item, fields);
  256. }
  257. catch (Exception ex)
  258. {
  259. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  260. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  261. }
  262. }
  263. if (fields.Contains(ItemFields.DisplayPreferencesId))
  264. {
  265. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  266. }
  267. if (user != null)
  268. {
  269. AttachUserSpecificInfo(dto, item, user, fields, syncProgress);
  270. }
  271. var hasMediaSources = item as IHasMediaSources;
  272. if (hasMediaSources != null)
  273. {
  274. if (fields.Contains(ItemFields.MediaSources))
  275. {
  276. if (user == null)
  277. {
  278. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true).ToList();
  279. }
  280. else
  281. {
  282. dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true, user).ToList();
  283. }
  284. }
  285. }
  286. if (fields.Contains(ItemFields.Studios))
  287. {
  288. AttachStudios(dto, item);
  289. }
  290. AttachBasicFields(dto, item, owner, options);
  291. var tvChannel = item as LiveTvChannel;
  292. if (tvChannel != null)
  293. {
  294. _livetvManager().AddChannelInfo(dto, tvChannel, options, user);
  295. }
  296. var collectionFolder = item as ICollectionFolder;
  297. if (collectionFolder != null)
  298. {
  299. dto.CollectionType = user == null ?
  300. collectionFolder.CollectionType :
  301. collectionFolder.GetViewType(user);
  302. }
  303. var playlist = item as Playlist;
  304. if (playlist != null)
  305. {
  306. AttachLinkedChildImages(dto, playlist, user, options);
  307. }
  308. if (fields.Contains(ItemFields.CanDelete))
  309. {
  310. dto.CanDelete = user == null
  311. ? item.CanDelete()
  312. : item.CanDelete(user);
  313. }
  314. if (fields.Contains(ItemFields.CanDownload))
  315. {
  316. dto.CanDownload = user == null
  317. ? item.CanDownload()
  318. : item.CanDownload(user);
  319. }
  320. if (fields.Contains(ItemFields.Etag))
  321. {
  322. dto.Etag = item.GetEtag(user);
  323. }
  324. if (item is ILiveTvRecording)
  325. {
  326. _livetvManager().AddInfoToRecordingDto(item, dto, user);
  327. }
  328. else if (item is LiveTvProgram)
  329. {
  330. _livetvManager().AddInfoToProgramDto(item, dto, fields.Contains(ItemFields.ChannelInfo), user);
  331. }
  332. return dto;
  333. }
  334. public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null)
  335. {
  336. var syncProgress = GetSyncedItemProgress(options);
  337. var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user);
  338. if (options.Fields.Contains(ItemFields.ItemCounts))
  339. {
  340. SetItemByNameInfo(item, dto, taggedItems, user);
  341. }
  342. FillSyncInfo(dto, item, options, user, syncProgress);
  343. return dto;
  344. }
  345. private void SetItemByNameInfo(BaseItem item, BaseItemDto dto, List<BaseItem> taggedItems, User user = null)
  346. {
  347. if (item is MusicArtist || item is MusicGenre)
  348. {
  349. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  350. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  351. dto.SongCount = taggedItems.Count(i => i is Audio);
  352. }
  353. else if (item is GameGenre)
  354. {
  355. dto.GameCount = taggedItems.Count(i => i is Game);
  356. }
  357. else
  358. {
  359. // This populates them all and covers Genre, Person, Studio, Year
  360. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  361. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  362. dto.GameCount = taggedItems.Count(i => i is Game);
  363. dto.MovieCount = taggedItems.Count(i => i is Movie);
  364. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  365. dto.SeriesCount = taggedItems.Count(i => i is Series);
  366. dto.SongCount = taggedItems.Count(i => i is Audio);
  367. }
  368. dto.ChildCount = taggedItems.Count;
  369. }
  370. /// <summary>
  371. /// Attaches the user specific info.
  372. /// </summary>
  373. /// <param name="dto">The dto.</param>
  374. /// <param name="item">The item.</param>
  375. /// <param name="user">The user.</param>
  376. /// <param name="fields">The fields.</param>
  377. /// <param name="syncProgress">The synchronize progress.</param>
  378. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields, Dictionary<string, SyncedItemProgress> syncProgress)
  379. {
  380. if (item.IsFolder)
  381. {
  382. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  383. // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice
  384. // TODO: Improve in future
  385. dto.UserData = GetUserItemDataDto(userData);
  386. var folder = (Folder)item;
  387. if (!(folder is IChannelItem) && !(folder is Channel))
  388. {
  389. dto.ChildCount = GetChildCount(folder, user);
  390. // These are just far too slow.
  391. if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is ICollectionFolder))
  392. {
  393. SetSpecialCounts(folder, user, dto, fields, syncProgress);
  394. }
  395. }
  396. dto.UserData.Played = dto.UserData.PlayedPercentage.HasValue && dto.UserData.PlayedPercentage.Value >= 100;
  397. }
  398. else
  399. {
  400. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  401. }
  402. dto.PlayAccess = item.GetPlayAccess(user);
  403. if (fields.Contains(ItemFields.SeasonUserData))
  404. {
  405. var episode = item as Episode;
  406. if (episode != null)
  407. {
  408. var season = episode.Season;
  409. if (season != null)
  410. {
  411. dto.SeasonUserData = _userDataRepository.GetUserDataDto(season, user);
  412. }
  413. }
  414. }
  415. var userView = item as UserView;
  416. if (userView != null)
  417. {
  418. dto.HasDynamicCategories = userView.ContainsDynamicCategories(user);
  419. }
  420. var collectionFolder = item as ICollectionFolder;
  421. if (collectionFolder != null)
  422. {
  423. dto.HasDynamicCategories = false;
  424. }
  425. }
  426. private int GetChildCount(Folder folder, User user)
  427. {
  428. return folder.GetChildren(user, true)
  429. .Count();
  430. }
  431. /// <summary>
  432. /// Gets client-side Id of a server-side BaseItem
  433. /// </summary>
  434. /// <param name="item">The item.</param>
  435. /// <returns>System.String.</returns>
  436. /// <exception cref="System.ArgumentNullException">item</exception>
  437. public string GetDtoId(BaseItem item)
  438. {
  439. if (item == null)
  440. {
  441. throw new ArgumentNullException("item");
  442. }
  443. return item.Id.ToString("N");
  444. }
  445. /// <summary>
  446. /// Converts a UserItemData to a DTOUserItemData
  447. /// </summary>
  448. /// <param name="data">The data.</param>
  449. /// <returns>DtoUserItemData.</returns>
  450. /// <exception cref="System.ArgumentNullException"></exception>
  451. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  452. {
  453. if (data == null)
  454. {
  455. throw new ArgumentNullException("data");
  456. }
  457. return new UserItemDataDto
  458. {
  459. IsFavorite = data.IsFavorite,
  460. Likes = data.Likes,
  461. PlaybackPositionTicks = data.PlaybackPositionTicks,
  462. PlayCount = data.PlayCount,
  463. Rating = data.Rating,
  464. Played = data.Played,
  465. LastPlayedDate = data.LastPlayedDate,
  466. Key = data.Key
  467. };
  468. }
  469. private void SetBookProperties(BaseItemDto dto, Book item)
  470. {
  471. dto.SeriesName = item.SeriesName;
  472. }
  473. private void SetPhotoProperties(BaseItemDto dto, Photo item)
  474. {
  475. dto.Width = item.Width;
  476. dto.Height = item.Height;
  477. dto.CameraMake = item.CameraMake;
  478. dto.CameraModel = item.CameraModel;
  479. dto.Software = item.Software;
  480. dto.ExposureTime = item.ExposureTime;
  481. dto.FocalLength = item.FocalLength;
  482. dto.ImageOrientation = item.Orientation;
  483. dto.Aperture = item.Aperture;
  484. dto.ShutterSpeed = item.ShutterSpeed;
  485. dto.Latitude = item.Latitude;
  486. dto.Longitude = item.Longitude;
  487. dto.Altitude = item.Altitude;
  488. dto.IsoSpeedRating = item.IsoSpeedRating;
  489. var album = item.Album;
  490. if (album != null)
  491. {
  492. dto.Album = album.Name;
  493. dto.AlbumId = album.Id.ToString("N");
  494. }
  495. }
  496. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  497. {
  498. if (!string.IsNullOrEmpty(item.Album))
  499. {
  500. var parentAlbum = _libraryManager.RootFolder
  501. .GetRecursiveChildren(i => i is MusicAlbum && string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase))
  502. .FirstOrDefault();
  503. if (parentAlbum != null)
  504. {
  505. dto.AlbumId = GetDtoId(parentAlbum);
  506. }
  507. }
  508. dto.Album = item.Album;
  509. }
  510. private void SetGameProperties(BaseItemDto dto, Game item)
  511. {
  512. dto.Players = item.PlayersSupported;
  513. dto.GameSystem = item.GameSystem;
  514. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  515. }
  516. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  517. {
  518. dto.GameSystem = item.GameSystemName;
  519. }
  520. private List<string> GetBackdropImageTags(BaseItem item, int limit)
  521. {
  522. return GetCacheTags(item, ImageType.Backdrop, limit).ToList();
  523. }
  524. private List<string> GetScreenshotImageTags(BaseItem item, int limit)
  525. {
  526. var hasScreenshots = item as IHasScreenshots;
  527. if (hasScreenshots == null)
  528. {
  529. return new List<string>();
  530. }
  531. return GetCacheTags(item, ImageType.Screenshot, limit).ToList();
  532. }
  533. private IEnumerable<string> GetCacheTags(BaseItem item, ImageType type, int limit)
  534. {
  535. return item.GetImages(type)
  536. .Select(p => GetImageCacheTag(item, p))
  537. .Where(i => i != null)
  538. .Take(limit)
  539. .ToList();
  540. }
  541. private string GetImageCacheTag(BaseItem item, ImageType type)
  542. {
  543. try
  544. {
  545. return _imageProcessor.GetImageCacheTag(item, type);
  546. }
  547. catch (Exception ex)
  548. {
  549. _logger.ErrorException("Error getting {0} image info", ex, type);
  550. return null;
  551. }
  552. }
  553. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  554. {
  555. try
  556. {
  557. return _imageProcessor.GetImageCacheTag(item, image);
  558. }
  559. catch (Exception ex)
  560. {
  561. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  562. return null;
  563. }
  564. }
  565. /// <summary>
  566. /// Attaches People DTO's to a DTOBaseItem
  567. /// </summary>
  568. /// <param name="dto">The dto.</param>
  569. /// <param name="item">The item.</param>
  570. /// <returns>Task.</returns>
  571. private void AttachPeople(BaseItemDto dto, BaseItem item)
  572. {
  573. // Ordering by person type to ensure actors and artists are at the front.
  574. // This is taking advantage of the fact that they both begin with A
  575. // This should be improved in the future
  576. var people = _libraryManager.GetPeople(item).OrderBy(i => i.SortOrder ?? int.MaxValue)
  577. .ThenBy(i =>
  578. {
  579. if (i.IsType(PersonType.Actor))
  580. {
  581. return 0;
  582. }
  583. if (i.IsType(PersonType.GuestStar))
  584. {
  585. return 1;
  586. }
  587. if (i.IsType(PersonType.Director))
  588. {
  589. return 2;
  590. }
  591. if (i.IsType(PersonType.Writer))
  592. {
  593. return 3;
  594. }
  595. if (i.IsType(PersonType.Producer))
  596. {
  597. return 4;
  598. }
  599. if (i.IsType(PersonType.Composer))
  600. {
  601. return 4;
  602. }
  603. return 10;
  604. })
  605. .ToList();
  606. var list = new List<BaseItemPerson>();
  607. var dictionary = people.Select(p => p.Name)
  608. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  609. {
  610. try
  611. {
  612. return _libraryManager.GetPerson(c);
  613. }
  614. catch (Exception ex)
  615. {
  616. _logger.ErrorException("Error getting person {0}", ex, c);
  617. return null;
  618. }
  619. }).Where(i => i != null)
  620. .DistinctBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  621. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  622. for (var i = 0; i < people.Count; i++)
  623. {
  624. var person = people[i];
  625. var baseItemPerson = new BaseItemPerson
  626. {
  627. Name = person.Name,
  628. Role = person.Role,
  629. Type = person.Type
  630. };
  631. Person entity;
  632. if (dictionary.TryGetValue(person.Name, out entity))
  633. {
  634. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  635. baseItemPerson.Id = entity.Id.ToString("N");
  636. list.Add(baseItemPerson);
  637. }
  638. }
  639. dto.People = list.ToArray();
  640. }
  641. /// <summary>
  642. /// Attaches the studios.
  643. /// </summary>
  644. /// <param name="dto">The dto.</param>
  645. /// <param name="item">The item.</param>
  646. /// <returns>Task.</returns>
  647. private void AttachStudios(BaseItemDto dto, BaseItem item)
  648. {
  649. var studios = item.Studios.ToList();
  650. dto.Studios = new StudioDto[studios.Count];
  651. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  652. {
  653. try
  654. {
  655. return _libraryManager.GetStudio(name);
  656. }
  657. catch (IOException ex)
  658. {
  659. _logger.ErrorException("Error getting studio {0}", ex, name);
  660. return null;
  661. }
  662. })
  663. .Where(i => i != null)
  664. .DistinctBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  665. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  666. for (var i = 0; i < studios.Count; i++)
  667. {
  668. var studio = studios[i];
  669. var studioDto = new StudioDto
  670. {
  671. Name = studio
  672. };
  673. Studio entity;
  674. if (dictionary.TryGetValue(studio, out entity))
  675. {
  676. studioDto.Id = entity.Id.ToString("N");
  677. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  678. }
  679. dto.Studios[i] = studioDto;
  680. }
  681. }
  682. /// <summary>
  683. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  684. /// </summary>
  685. /// <param name="item">The item.</param>
  686. /// <param name="owner">The owner.</param>
  687. /// <returns>BaseItem.</returns>
  688. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  689. {
  690. var parent = item.Parent ?? owner;
  691. while (parent != null)
  692. {
  693. if (parent.GetImages(ImageType.Backdrop).Any())
  694. {
  695. return parent;
  696. }
  697. parent = parent.Parent;
  698. }
  699. return null;
  700. }
  701. /// <summary>
  702. /// If an item does not have a logo, this can be used to find the first parent that does have one
  703. /// </summary>
  704. /// <param name="item">The item.</param>
  705. /// <param name="type">The type.</param>
  706. /// <param name="owner">The owner.</param>
  707. /// <returns>BaseItem.</returns>
  708. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  709. {
  710. var parent = item.Parent ?? owner;
  711. while (parent != null)
  712. {
  713. if (parent.HasImage(type))
  714. {
  715. return parent;
  716. }
  717. parent = parent.Parent;
  718. }
  719. return null;
  720. }
  721. /// <summary>
  722. /// Gets the chapter info dto.
  723. /// </summary>
  724. /// <param name="chapterInfo">The chapter info.</param>
  725. /// <param name="item">The item.</param>
  726. /// <returns>ChapterInfoDto.</returns>
  727. private ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  728. {
  729. var dto = new ChapterInfoDto
  730. {
  731. Name = chapterInfo.Name,
  732. StartPositionTicks = chapterInfo.StartPositionTicks
  733. };
  734. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  735. {
  736. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  737. {
  738. Path = chapterInfo.ImagePath,
  739. Type = ImageType.Chapter,
  740. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  741. });
  742. }
  743. return dto;
  744. }
  745. public List<ChapterInfoDto> GetChapterInfoDtos(BaseItem item)
  746. {
  747. return _itemRepo.GetChapters(item.Id)
  748. .Select(c => GetChapterInfoDto(c, item))
  749. .ToList();
  750. }
  751. /// <summary>
  752. /// Sets simple property values on a DTOBaseItem
  753. /// </summary>
  754. /// <param name="dto">The dto.</param>
  755. /// <param name="item">The item.</param>
  756. /// <param name="owner">The owner.</param>
  757. /// <param name="options">The options.</param>
  758. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  759. {
  760. var fields = options.Fields;
  761. if (fields.Contains(ItemFields.DateCreated))
  762. {
  763. dto.DateCreated = item.DateCreated;
  764. }
  765. if (fields.Contains(ItemFields.DisplayMediaType))
  766. {
  767. dto.DisplayMediaType = item.DisplayMediaType;
  768. }
  769. if (fields.Contains(ItemFields.Settings))
  770. {
  771. dto.LockedFields = item.LockedFields;
  772. dto.LockData = item.IsLocked;
  773. dto.ForcedSortName = item.ForcedSortName;
  774. }
  775. var hasBudget = item as IHasBudget;
  776. if (hasBudget != null)
  777. {
  778. if (fields.Contains(ItemFields.Budget))
  779. {
  780. dto.Budget = hasBudget.Budget;
  781. }
  782. if (fields.Contains(ItemFields.Revenue))
  783. {
  784. dto.Revenue = hasBudget.Revenue;
  785. }
  786. }
  787. dto.EndDate = item.EndDate;
  788. if (fields.Contains(ItemFields.HomePageUrl))
  789. {
  790. dto.HomePageUrl = item.HomePageUrl;
  791. }
  792. if (fields.Contains(ItemFields.ExternalUrls))
  793. {
  794. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  795. }
  796. if (fields.Contains(ItemFields.Tags))
  797. {
  798. var hasTags = item as IHasTags;
  799. if (hasTags != null)
  800. {
  801. dto.Tags = hasTags.Tags;
  802. }
  803. if (dto.Tags == null)
  804. {
  805. dto.Tags = new List<string>();
  806. }
  807. }
  808. if (fields.Contains(ItemFields.Keywords))
  809. {
  810. var hasTags = item as IHasKeywords;
  811. if (hasTags != null)
  812. {
  813. dto.Keywords = hasTags.Keywords;
  814. }
  815. if (dto.Keywords == null)
  816. {
  817. dto.Keywords = new List<string>();
  818. }
  819. }
  820. if (fields.Contains(ItemFields.ProductionLocations))
  821. {
  822. SetProductionLocations(item, dto);
  823. }
  824. var hasAspectRatio = item as IHasAspectRatio;
  825. if (hasAspectRatio != null)
  826. {
  827. dto.AspectRatio = hasAspectRatio.AspectRatio;
  828. }
  829. if (fields.Contains(ItemFields.Metascore))
  830. {
  831. var hasMetascore = item as IHasMetascore;
  832. if (hasMetascore != null)
  833. {
  834. dto.Metascore = hasMetascore.Metascore;
  835. }
  836. }
  837. if (fields.Contains(ItemFields.AwardSummary))
  838. {
  839. var hasAwards = item as IHasAwards;
  840. if (hasAwards != null)
  841. {
  842. dto.AwardSummary = hasAwards.AwardSummary;
  843. }
  844. }
  845. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  846. if (backdropLimit > 0)
  847. {
  848. dto.BackdropImageTags = GetBackdropImageTags(item, backdropLimit);
  849. }
  850. if (fields.Contains(ItemFields.ScreenshotImageTags))
  851. {
  852. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  853. if (screenshotLimit > 0)
  854. {
  855. dto.ScreenshotImageTags = GetScreenshotImageTags(item, screenshotLimit);
  856. }
  857. }
  858. if (fields.Contains(ItemFields.Genres))
  859. {
  860. dto.Genres = item.Genres;
  861. }
  862. dto.ImageTags = new Dictionary<ImageType, string>();
  863. // Prevent implicitly captured closure
  864. var currentItem = item;
  865. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  866. .ToList())
  867. {
  868. if (options.GetImageLimit(image.Type) > 0)
  869. {
  870. var tag = GetImageCacheTag(item, image);
  871. if (tag != null)
  872. {
  873. dto.ImageTags[image.Type] = tag;
  874. }
  875. }
  876. }
  877. dto.Id = GetDtoId(item);
  878. dto.IndexNumber = item.IndexNumber;
  879. dto.IsFolder = item.IsFolder;
  880. dto.MediaType = item.MediaType;
  881. dto.LocationType = item.LocationType;
  882. if (item.IsHD.HasValue && item.IsHD.Value)
  883. {
  884. dto.IsHD = item.IsHD;
  885. }
  886. dto.Audio = item.Audio;
  887. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  888. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  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. if (video.HasSubtitles)
  1108. {
  1109. dto.HasSubtitles = video.HasSubtitles;
  1110. }
  1111. if (video.AdditionalParts.Count != 0)
  1112. {
  1113. dto.PartCount = video.AdditionalParts.Count + 1;
  1114. }
  1115. if (fields.Contains(ItemFields.MediaSourceCount))
  1116. {
  1117. if (video.MediaSourceCount != 1)
  1118. {
  1119. dto.MediaSourceCount = video.MediaSourceCount;
  1120. }
  1121. }
  1122. if (fields.Contains(ItemFields.Chapters))
  1123. {
  1124. dto.Chapters = GetChapterInfoDtos(item);
  1125. }
  1126. }
  1127. if (fields.Contains(ItemFields.MediaStreams))
  1128. {
  1129. // Add VideoInfo
  1130. var iHasMediaSources = item as IHasMediaSources;
  1131. if (iHasMediaSources != null)
  1132. {
  1133. List<MediaStream> mediaStreams;
  1134. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  1135. {
  1136. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  1137. .SelectMany(i => i.MediaStreams)
  1138. .ToList();
  1139. }
  1140. else
  1141. {
  1142. mediaStreams = _mediaSourceManager().GetStaticMediaSources(iHasMediaSources, true).First().MediaStreams;
  1143. }
  1144. dto.MediaStreams = mediaStreams;
  1145. }
  1146. }
  1147. // Add MovieInfo
  1148. var movie = item as Movie;
  1149. if (movie != null)
  1150. {
  1151. if (fields.Contains(ItemFields.TmdbCollectionName))
  1152. {
  1153. dto.TmdbCollectionName = movie.TmdbCollectionName;
  1154. }
  1155. }
  1156. var hasSpecialFeatures = item as IHasSpecialFeatures;
  1157. if (hasSpecialFeatures != null)
  1158. {
  1159. var specialFeatureCount = hasSpecialFeatures.SpecialFeatureIds.Count;
  1160. if (specialFeatureCount > 0)
  1161. {
  1162. dto.SpecialFeatureCount = specialFeatureCount;
  1163. }
  1164. }
  1165. // Add EpisodeInfo
  1166. var episode = item as Episode;
  1167. if (episode != null)
  1168. {
  1169. dto.IndexNumberEnd = episode.IndexNumberEnd;
  1170. if (fields.Contains(ItemFields.AlternateEpisodeNumbers))
  1171. {
  1172. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  1173. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  1174. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  1175. }
  1176. if (fields.Contains(ItemFields.SpecialEpisodeNumbers))
  1177. {
  1178. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  1179. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  1180. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  1181. }
  1182. var episodeSeason = episode.Season;
  1183. if (episodeSeason != null)
  1184. {
  1185. dto.SeasonId = episodeSeason.Id.ToString("N");
  1186. if (fields.Contains(ItemFields.SeasonName))
  1187. {
  1188. dto.SeasonName = episodeSeason.Name;
  1189. }
  1190. }
  1191. if (fields.Contains(ItemFields.SeriesGenres))
  1192. {
  1193. var episodeseries = episode.Series;
  1194. if (episodeseries != null)
  1195. {
  1196. dto.SeriesGenres = episodeseries.Genres.ToList();
  1197. }
  1198. }
  1199. }
  1200. // Add SeriesInfo
  1201. var series = item as Series;
  1202. if (series != null)
  1203. {
  1204. dto.AirDays = series.AirDays;
  1205. dto.AirTime = series.AirTime;
  1206. dto.SeriesStatus = series.Status;
  1207. if (fields.Contains(ItemFields.Settings))
  1208. {
  1209. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  1210. }
  1211. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  1212. }
  1213. if (episode != null)
  1214. {
  1215. series = episode.Series;
  1216. if (series != null)
  1217. {
  1218. dto.SeriesId = GetDtoId(series);
  1219. dto.SeriesName = series.Name;
  1220. if (fields.Contains(ItemFields.AirTime))
  1221. {
  1222. dto.AirTime = series.AirTime;
  1223. }
  1224. if (options.GetImageLimit(ImageType.Thumb) > 0)
  1225. {
  1226. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  1227. }
  1228. if (options.GetImageLimit(ImageType.Primary) > 0)
  1229. {
  1230. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1231. }
  1232. if (fields.Contains(ItemFields.SeriesStudio))
  1233. {
  1234. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1235. }
  1236. }
  1237. }
  1238. // Add SeasonInfo
  1239. var season = item as Season;
  1240. if (season != null)
  1241. {
  1242. series = season.Series;
  1243. if (series != null)
  1244. {
  1245. dto.SeriesId = GetDtoId(series);
  1246. dto.SeriesName = series.Name;
  1247. dto.AirTime = series.AirTime;
  1248. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1249. if (options.GetImageLimit(ImageType.Primary) > 0)
  1250. {
  1251. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1252. }
  1253. }
  1254. }
  1255. var game = item as Game;
  1256. if (game != null)
  1257. {
  1258. SetGameProperties(dto, game);
  1259. }
  1260. var gameSystem = item as GameSystem;
  1261. if (gameSystem != null)
  1262. {
  1263. SetGameSystemProperties(dto, gameSystem);
  1264. }
  1265. var musicVideo = item as MusicVideo;
  1266. if (musicVideo != null)
  1267. {
  1268. SetMusicVideoProperties(dto, musicVideo);
  1269. }
  1270. var book = item as Book;
  1271. if (book != null)
  1272. {
  1273. SetBookProperties(dto, book);
  1274. }
  1275. var photo = item as Photo;
  1276. if (photo != null)
  1277. {
  1278. SetPhotoProperties(dto, photo);
  1279. }
  1280. dto.ChannelId = item.ChannelId;
  1281. var channelItem = item as IChannelItem;
  1282. if (channelItem != null)
  1283. {
  1284. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1285. }
  1286. var channelMediaItem = item as IChannelMediaItem;
  1287. if (channelMediaItem != null)
  1288. {
  1289. dto.ExtraType = channelMediaItem.ExtraType;
  1290. }
  1291. }
  1292. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user, DtoOptions options)
  1293. {
  1294. List<BaseItem> linkedChildren = null;
  1295. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1296. if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
  1297. {
  1298. linkedChildren = user == null
  1299. ? folder.GetRecursiveChildren().ToList()
  1300. : folder.GetRecursiveChildren(user).ToList();
  1301. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1302. if (parentWithBackdrop != null)
  1303. {
  1304. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1305. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
  1306. }
  1307. }
  1308. if (!dto.ImageTags.ContainsKey(ImageType.Primary) && options.GetImageLimit(ImageType.Primary) > 0)
  1309. {
  1310. if (linkedChildren == null)
  1311. {
  1312. linkedChildren = user == null
  1313. ? folder.GetRecursiveChildren().ToList()
  1314. : folder.GetRecursiveChildren(user).ToList();
  1315. }
  1316. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1317. if (parentWithImage != null)
  1318. {
  1319. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1320. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1321. }
  1322. }
  1323. }
  1324. private string GetMappedPath(IHasMetadata item)
  1325. {
  1326. var path = item.Path;
  1327. var locationType = item.LocationType;
  1328. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1329. {
  1330. foreach (var map in _config.Configuration.PathSubstitutions)
  1331. {
  1332. path = _libraryManager.SubstitutePath(path, map.From, map.To);
  1333. }
  1334. }
  1335. return path;
  1336. }
  1337. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1338. {
  1339. var hasProductionLocations = item as IHasProductionLocations;
  1340. if (hasProductionLocations != null)
  1341. {
  1342. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1343. }
  1344. var person = item as Person;
  1345. if (person != null)
  1346. {
  1347. dto.ProductionLocations = new List<string>();
  1348. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1349. {
  1350. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1351. }
  1352. }
  1353. if (dto.ProductionLocations == null)
  1354. {
  1355. dto.ProductionLocations = new List<string>();
  1356. }
  1357. }
  1358. /// <summary>
  1359. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1360. /// </summary>
  1361. /// <param name="folder">The folder.</param>
  1362. /// <param name="user">The user.</param>
  1363. /// <param name="dto">The dto.</param>
  1364. /// <param name="fields">The fields.</param>
  1365. /// <param name="syncProgress">The synchronize progress.</param>
  1366. /// <returns>Task.</returns>
  1367. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields, Dictionary<string, SyncedItemProgress> syncProgress)
  1368. {
  1369. var recursiveItemCount = 0;
  1370. var unplayed = 0;
  1371. long runtime = 0;
  1372. DateTime? dateLastMediaAdded = null;
  1373. double totalPercentPlayed = 0;
  1374. double totalSyncPercent = 0;
  1375. var addSyncInfo = fields.Contains(ItemFields.SyncInfo);
  1376. var children = folder.GetItems(new InternalItemsQuery
  1377. {
  1378. IsFolder = false,
  1379. Recursive = true,
  1380. IsVirtualUnaired = false,
  1381. IsMissing = false,
  1382. User = user
  1383. }).Result.Items;
  1384. // Loop through each recursive child
  1385. foreach (var child in children)
  1386. {
  1387. if (!dateLastMediaAdded.HasValue)
  1388. {
  1389. dateLastMediaAdded = child.DateCreated;
  1390. }
  1391. else
  1392. {
  1393. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1394. }
  1395. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1396. recursiveItemCount++;
  1397. var isUnplayed = true;
  1398. // Incrememt totalPercentPlayed
  1399. if (userdata != null)
  1400. {
  1401. if (userdata.Played)
  1402. {
  1403. totalPercentPlayed += 100;
  1404. isUnplayed = false;
  1405. }
  1406. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1407. {
  1408. double itemPercent = userdata.PlaybackPositionTicks;
  1409. itemPercent /= child.RunTimeTicks.Value;
  1410. totalPercentPlayed += itemPercent;
  1411. }
  1412. }
  1413. if (isUnplayed)
  1414. {
  1415. unplayed++;
  1416. }
  1417. runtime += child.RunTimeTicks ?? 0;
  1418. if (addSyncInfo)
  1419. {
  1420. double percent = 0;
  1421. SyncedItemProgress syncItemProgress;
  1422. if (syncProgress.TryGetValue(child.Id.ToString("N"), out syncItemProgress))
  1423. {
  1424. switch (syncItemProgress.Status)
  1425. {
  1426. case SyncJobItemStatus.Synced:
  1427. percent = 100;
  1428. break;
  1429. case SyncJobItemStatus.Converting:
  1430. case SyncJobItemStatus.ReadyToTransfer:
  1431. case SyncJobItemStatus.Transferring:
  1432. percent = 50;
  1433. break;
  1434. }
  1435. }
  1436. totalSyncPercent += percent;
  1437. }
  1438. }
  1439. dto.RecursiveItemCount = recursiveItemCount;
  1440. dto.UserData.UnplayedItemCount = unplayed;
  1441. if (recursiveItemCount > 0)
  1442. {
  1443. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1444. if (addSyncInfo)
  1445. {
  1446. var pct = totalSyncPercent / recursiveItemCount;
  1447. if (pct > 0)
  1448. {
  1449. dto.SyncPercent = pct;
  1450. }
  1451. }
  1452. }
  1453. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1454. {
  1455. dto.CumulativeRunTimeTicks = runtime;
  1456. }
  1457. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1458. {
  1459. dto.DateLastMediaAdded = dateLastMediaAdded;
  1460. }
  1461. }
  1462. /// <summary>
  1463. /// Attaches the primary image aspect ratio.
  1464. /// </summary>
  1465. /// <param name="dto">The dto.</param>
  1466. /// <param name="item">The item.</param>
  1467. /// <param name="fields">The fields.</param>
  1468. /// <returns>Task.</returns>
  1469. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item, List<ItemFields> fields)
  1470. {
  1471. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1472. if (imageInfo == null || !imageInfo.IsLocalFile)
  1473. {
  1474. return;
  1475. }
  1476. ImageSize size;
  1477. try
  1478. {
  1479. size = _imageProcessor.GetImageSize(imageInfo);
  1480. }
  1481. catch (Exception ex)
  1482. {
  1483. //_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1484. return;
  1485. }
  1486. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1487. foreach (var enhancer in supportedEnhancers)
  1488. {
  1489. try
  1490. {
  1491. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1492. }
  1493. catch (Exception ex)
  1494. {
  1495. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1496. }
  1497. }
  1498. if (size.Width > 0 && size.Height > 0)
  1499. {
  1500. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1501. }
  1502. }
  1503. }
  1504. }