DtoService.cs 62 KB

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