2
0

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