DtoService.cs 62 KB

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