LibraryService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. using MediaBrowser.Controller.Channels;
  2. using MediaBrowser.Controller.Dto;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Persistence;
  9. using MediaBrowser.Controller.Session;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Querying;
  13. using ServiceStack;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.Api.Library
  23. {
  24. [Route("/Items/{Id}/File", "GET")]
  25. [Api(Description = "Gets the original file of an item")]
  26. public class GetFile
  27. {
  28. /// <summary>
  29. /// Gets or sets the id.
  30. /// </summary>
  31. /// <value>The id.</value>
  32. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  33. public string Id { get; set; }
  34. }
  35. /// <summary>
  36. /// Class GetCriticReviews
  37. /// </summary>
  38. [Route("/Items/{Id}/CriticReviews", "GET")]
  39. [Api(Description = "Gets critic reviews for an item")]
  40. public class GetCriticReviews : IReturn<QueryResult<ItemReview>>
  41. {
  42. /// <summary>
  43. /// Gets or sets the id.
  44. /// </summary>
  45. /// <value>The id.</value>
  46. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  47. public string Id { get; set; }
  48. /// <summary>
  49. /// Skips over a given number of items within the results. Use for paging.
  50. /// </summary>
  51. /// <value>The start index.</value>
  52. [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  53. public int? StartIndex { get; set; }
  54. /// <summary>
  55. /// The maximum number of items to return
  56. /// </summary>
  57. /// <value>The limit.</value>
  58. [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  59. public int? Limit { get; set; }
  60. }
  61. /// <summary>
  62. /// Class GetThemeSongs
  63. /// </summary>
  64. [Route("/Items/{Id}/ThemeSongs", "GET")]
  65. [Api(Description = "Gets theme songs for an item")]
  66. public class GetThemeSongs : IReturn<ThemeMediaResult>
  67. {
  68. /// <summary>
  69. /// Gets or sets the user id.
  70. /// </summary>
  71. /// <value>The user id.</value>
  72. [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  73. public Guid? UserId { get; set; }
  74. /// <summary>
  75. /// Gets or sets the id.
  76. /// </summary>
  77. /// <value>The id.</value>
  78. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  79. public string Id { get; set; }
  80. [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  81. public bool InheritFromParent { get; set; }
  82. }
  83. /// <summary>
  84. /// Class GetThemeVideos
  85. /// </summary>
  86. [Route("/Items/{Id}/ThemeVideos", "GET")]
  87. [Api(Description = "Gets theme videos for an item")]
  88. public class GetThemeVideos : IReturn<ThemeMediaResult>
  89. {
  90. /// <summary>
  91. /// Gets or sets the user id.
  92. /// </summary>
  93. /// <value>The user id.</value>
  94. [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  95. public Guid? UserId { get; set; }
  96. /// <summary>
  97. /// Gets or sets the id.
  98. /// </summary>
  99. /// <value>The id.</value>
  100. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  101. public string Id { get; set; }
  102. [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  103. public bool InheritFromParent { get; set; }
  104. }
  105. /// <summary>
  106. /// Class GetThemeVideos
  107. /// </summary>
  108. [Route("/Items/{Id}/ThemeMedia", "GET")]
  109. [Api(Description = "Gets theme videos and songs for an item")]
  110. public class GetThemeMedia : IReturn<AllThemeMediaResult>
  111. {
  112. /// <summary>
  113. /// Gets or sets the user id.
  114. /// </summary>
  115. /// <value>The user id.</value>
  116. [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  117. public Guid? UserId { get; set; }
  118. /// <summary>
  119. /// Gets or sets the id.
  120. /// </summary>
  121. /// <value>The id.</value>
  122. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  123. public string Id { get; set; }
  124. [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  125. public bool InheritFromParent { get; set; }
  126. }
  127. [Route("/Library/Refresh", "POST")]
  128. [Api(Description = "Starts a library scan")]
  129. public class RefreshLibrary : IReturnVoid
  130. {
  131. }
  132. [Route("/Items/{Id}", "DELETE")]
  133. [Api(Description = "Deletes an item from the library and file system")]
  134. public class DeleteItem : IReturnVoid
  135. {
  136. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
  137. public string Id { get; set; }
  138. }
  139. [Route("/Items/Counts", "GET")]
  140. [Api(Description = "Gets counts of various item types")]
  141. public class GetItemCounts : IReturn<ItemCounts>
  142. {
  143. [ApiMember(Name = "UserId", Description = "Optional. Get counts from a specific user's library.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  144. public Guid? UserId { get; set; }
  145. [ApiMember(Name = "IsFavorite", Description = "Optional. Get counts of favorite items", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  146. public bool? IsFavorite { get; set; }
  147. }
  148. [Route("/Items/{Id}/Ancestors", "GET")]
  149. [Api(Description = "Gets all parents of an item")]
  150. public class GetAncestors : IReturn<BaseItemDto[]>
  151. {
  152. /// <summary>
  153. /// Gets or sets the user id.
  154. /// </summary>
  155. /// <value>The user id.</value>
  156. [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  157. public Guid? UserId { get; set; }
  158. /// <summary>
  159. /// Gets or sets the id.
  160. /// </summary>
  161. /// <value>The id.</value>
  162. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  163. public string Id { get; set; }
  164. }
  165. [Route("/Items/YearIndex", "GET")]
  166. [Api(Description = "Gets a year index based on an item query.")]
  167. public class GetYearIndex : IReturn<List<ItemIndex>>
  168. {
  169. /// <summary>
  170. /// Gets or sets the user id.
  171. /// </summary>
  172. /// <value>The user id.</value>
  173. [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  174. public Guid? UserId { get; set; }
  175. [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
  176. public string IncludeItemTypes { get; set; }
  177. }
  178. /// <summary>
  179. /// Class GetPhyscialPaths
  180. /// </summary>
  181. [Route("/Library/PhysicalPaths", "GET")]
  182. [Api(Description = "Gets a list of physical paths from virtual folders")]
  183. public class GetPhyscialPaths : IReturn<List<string>>
  184. {
  185. }
  186. [Route("/Library/MediaFolders", "GET")]
  187. [Api(Description = "Gets all user media folders.")]
  188. public class GetMediaFolders : IReturn<ItemsResult>
  189. {
  190. }
  191. [Route("/Library/Series/Added", "POST")]
  192. [Route("/Library/Series/Updated", "POST")]
  193. [Api(Description = "Reports that new episodes of a series have been added by an external source")]
  194. public class PostUpdatedSeries : IReturnVoid
  195. {
  196. [ApiMember(Name = "TvdbId", Description = "Tvdb Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  197. public string TvdbId { get; set; }
  198. }
  199. /// <summary>
  200. /// Class LibraryService
  201. /// </summary>
  202. public class LibraryService : BaseApiService
  203. {
  204. /// <summary>
  205. /// The _item repo
  206. /// </summary>
  207. private readonly IItemRepository _itemRepo;
  208. private readonly ILibraryManager _libraryManager;
  209. private readonly IUserManager _userManager;
  210. private readonly IUserDataManager _userDataManager;
  211. private readonly IDtoService _dtoService;
  212. private readonly IChannelManager _channelManager;
  213. private readonly ISessionManager _sessionManager;
  214. /// <summary>
  215. /// Initializes a new instance of the <see cref="LibraryService" /> class.
  216. /// </summary>
  217. public LibraryService(IItemRepository itemRepo, ILibraryManager libraryManager, IUserManager userManager,
  218. IDtoService dtoService, IUserDataManager userDataManager, IChannelManager channelManager, ISessionManager sessionManager)
  219. {
  220. _itemRepo = itemRepo;
  221. _libraryManager = libraryManager;
  222. _userManager = userManager;
  223. _dtoService = dtoService;
  224. _userDataManager = userDataManager;
  225. _channelManager = channelManager;
  226. _sessionManager = sessionManager;
  227. }
  228. public object Get(GetMediaFolders request)
  229. {
  230. var items = _libraryManager.GetUserRootFolder().Children.OrderBy(i => i.SortName).ToList();
  231. // Get everything
  232. var fields = Enum.GetNames(typeof(ItemFields))
  233. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  234. .ToList();
  235. var result = new ItemsResult
  236. {
  237. TotalRecordCount = items.Count,
  238. Items = items.Select(i => _dtoService.GetBaseItemDto(i, fields)).ToArray()
  239. };
  240. return ToOptimizedResult(result);
  241. }
  242. public object Get(GetFile request)
  243. {
  244. var item = _libraryManager.GetItemById(request.Id);
  245. var locationType = item.LocationType;
  246. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  247. {
  248. throw new ArgumentException("This command cannot be used for remote or virtual items.");
  249. }
  250. if (Directory.Exists(item.Path))
  251. {
  252. throw new ArgumentException("This command cannot be used for directories.");
  253. }
  254. return ToStaticFileResult(item.Path);
  255. }
  256. /// <summary>
  257. /// Gets the specified request.
  258. /// </summary>
  259. /// <param name="request">The request.</param>
  260. /// <returns>System.Object.</returns>
  261. public object Get(GetPhyscialPaths request)
  262. {
  263. var result = _libraryManager.RootFolder.Children
  264. .SelectMany(c => c.PhysicalLocations)
  265. .ToList();
  266. return ToOptimizedSerializedResultUsingCache(result);
  267. }
  268. /// <summary>
  269. /// Gets the specified request.
  270. /// </summary>
  271. /// <param name="request">The request.</param>
  272. /// <returns>System.Object.</returns>
  273. public object Get(GetAncestors request)
  274. {
  275. var result = GetAncestors(request);
  276. return ToOptimizedSerializedResultUsingCache(result);
  277. }
  278. /// <summary>
  279. /// Gets the ancestors.
  280. /// </summary>
  281. /// <param name="request">The request.</param>
  282. /// <returns>Task{BaseItemDto[]}.</returns>
  283. public List<BaseItemDto> GetAncestors(GetAncestors request)
  284. {
  285. var item = _libraryManager.GetItemById(request.Id);
  286. var baseItemDtos = new List<BaseItemDto>();
  287. var user = request.UserId.HasValue ? _userManager.GetUserById(request.UserId.Value) : null;
  288. // Get everything
  289. var fields = Enum.GetNames(typeof(ItemFields))
  290. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  291. .ToList();
  292. BaseItem parent = item.Parent;
  293. while (parent != null)
  294. {
  295. if (user != null)
  296. {
  297. parent = TranslateParentItem(parent, user);
  298. }
  299. baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, fields, user));
  300. parent = parent.Parent;
  301. }
  302. return baseItemDtos.ToList();
  303. }
  304. private BaseItem TranslateParentItem(BaseItem item, User user)
  305. {
  306. if (item.Parent is AggregateFolder)
  307. {
  308. return user.RootFolder.GetChildren(user, true).FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path));
  309. }
  310. return item;
  311. }
  312. /// <summary>
  313. /// Gets the specified request.
  314. /// </summary>
  315. /// <param name="request">The request.</param>
  316. /// <returns>System.Object.</returns>
  317. public object Get(GetCriticReviews request)
  318. {
  319. var result = GetCriticReviews(request);
  320. return ToOptimizedSerializedResultUsingCache(result);
  321. }
  322. /// <summary>
  323. /// Gets the specified request.
  324. /// </summary>
  325. /// <param name="request">The request.</param>
  326. /// <returns>System.Object.</returns>
  327. public object Get(GetItemCounts request)
  328. {
  329. var items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager)
  330. .Where(i => i.LocationType != LocationType.Virtual)
  331. .ToList();
  332. var filteredItems = request.UserId.HasValue ? FilterItems(items, request, request.UserId.Value).ToList() : items;
  333. var albums = filteredItems.OfType<MusicAlbum>().ToList();
  334. var episodes = filteredItems.OfType<Episode>().ToList();
  335. var games = filteredItems.OfType<Game>().ToList();
  336. var movies = filteredItems.OfType<Movie>().ToList();
  337. var musicVideos = filteredItems.OfType<MusicVideo>().ToList();
  338. var adultVideos = filteredItems.OfType<AdultVideo>().ToList();
  339. var boxsets = filteredItems.OfType<BoxSet>().ToList();
  340. var books = filteredItems.OfType<Book>().ToList();
  341. var songs = filteredItems.OfType<Audio>().ToList();
  342. var series = filteredItems.OfType<Series>().ToList();
  343. var counts = new ItemCounts
  344. {
  345. AlbumCount = albums.Count,
  346. EpisodeCount = episodes.Count,
  347. GameCount = games.Count,
  348. GameSystemCount = filteredItems.OfType<GameSystem>().Count(),
  349. MovieCount = movies.Count,
  350. SeriesCount = series.Count,
  351. SongCount = songs.Count,
  352. TrailerCount = filteredItems.OfType<Trailer>().Count(),
  353. MusicVideoCount = musicVideos.Count,
  354. AdultVideoCount = adultVideos.Count,
  355. BoxSetCount = boxsets.Count,
  356. BookCount = books.Count,
  357. UniqueTypes = items.Select(i => i.GetClientTypeName()).Distinct().ToList()
  358. };
  359. return ToOptimizedSerializedResultUsingCache(counts);
  360. }
  361. private IEnumerable<T> FilterItems<T>(IEnumerable<T> items, GetItemCounts request, Guid userId)
  362. where T : BaseItem
  363. {
  364. if (request.IsFavorite.HasValue)
  365. {
  366. var val = request.IsFavorite.Value;
  367. items = items.Where(i => _userDataManager.GetUserData(userId, i.GetUserDataKey()).IsFavorite == val);
  368. }
  369. return items;
  370. }
  371. /// <summary>
  372. /// Posts the specified request.
  373. /// </summary>
  374. /// <param name="request">The request.</param>
  375. public void Post(RefreshLibrary request)
  376. {
  377. try
  378. {
  379. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  380. }
  381. catch (Exception ex)
  382. {
  383. Logger.ErrorException("Error refreshing library", ex);
  384. }
  385. }
  386. /// <summary>
  387. /// Deletes the specified request.
  388. /// </summary>
  389. /// <param name="request">The request.</param>
  390. public void Delete(DeleteItem request)
  391. {
  392. var task = DeleteItem(request);
  393. Task.WaitAll(task);
  394. }
  395. private Task DeleteItem(DeleteItem request)
  396. {
  397. var item = _libraryManager.GetItemById(request.Id);
  398. var session = GetSession(_sessionManager);
  399. if (!session.UserId.HasValue || !_userManager.GetUserById(session.UserId.Value).Configuration.EnableContentDeletion)
  400. {
  401. throw new UnauthorizedAccessException("This operation requires a logged in user with delete access.");
  402. }
  403. return _libraryManager.DeleteItem(item);
  404. }
  405. /// <summary>
  406. /// Gets the critic reviews async.
  407. /// </summary>
  408. /// <param name="request">The request.</param>
  409. /// <returns>Task{ItemReviewsResult}.</returns>
  410. private QueryResult<ItemReview> GetCriticReviews(GetCriticReviews request)
  411. {
  412. var reviews = _itemRepo.GetCriticReviews(new Guid(request.Id));
  413. var reviewsArray = reviews.ToArray();
  414. var result = new QueryResult<ItemReview>
  415. {
  416. TotalRecordCount = reviewsArray.Length
  417. };
  418. if (request.StartIndex.HasValue)
  419. {
  420. reviewsArray = reviewsArray.Skip(request.StartIndex.Value).ToArray();
  421. }
  422. if (request.Limit.HasValue)
  423. {
  424. reviewsArray = reviewsArray.Take(request.Limit.Value).ToArray();
  425. }
  426. result.Items = reviewsArray;
  427. return result;
  428. }
  429. public object Get(GetThemeMedia request)
  430. {
  431. var themeSongs = GetThemeSongs(new GetThemeSongs
  432. {
  433. InheritFromParent = request.InheritFromParent,
  434. Id = request.Id,
  435. UserId = request.UserId
  436. });
  437. var themeVideos = GetThemeVideos(new GetThemeVideos
  438. {
  439. InheritFromParent = request.InheritFromParent,
  440. Id = request.Id,
  441. UserId = request.UserId
  442. });
  443. return ToOptimizedSerializedResultUsingCache(new AllThemeMediaResult
  444. {
  445. ThemeSongsResult = themeSongs,
  446. ThemeVideosResult = themeVideos,
  447. SoundtrackSongsResult = GetSoundtrackSongs(request.Id, request.UserId, request.InheritFromParent)
  448. });
  449. }
  450. /// <summary>
  451. /// Gets the specified request.
  452. /// </summary>
  453. /// <param name="request">The request.</param>
  454. /// <returns>System.Object.</returns>
  455. public object Get(GetThemeSongs request)
  456. {
  457. var result = GetThemeSongs(request);
  458. return ToOptimizedSerializedResultUsingCache(result);
  459. }
  460. private ThemeMediaResult GetThemeSongs(GetThemeSongs request)
  461. {
  462. var user = request.UserId.HasValue ? _userManager.GetUserById(request.UserId.Value) : null;
  463. var item = string.IsNullOrEmpty(request.Id)
  464. ? (request.UserId.HasValue
  465. ? user.RootFolder
  466. : (Folder)_libraryManager.RootFolder)
  467. : _libraryManager.GetItemById(request.Id);
  468. var originalItem = item;
  469. while (GetThemeSongIds(item).Count == 0 && request.InheritFromParent && item.Parent != null)
  470. {
  471. item = item.Parent;
  472. }
  473. // Get everything
  474. var fields = Enum.GetNames(typeof(ItemFields))
  475. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  476. .ToList();
  477. var themeSongIds = GetThemeSongIds(item);
  478. if (themeSongIds.Count == 0 && request.InheritFromParent)
  479. {
  480. var album = originalItem as MusicAlbum;
  481. if (album != null)
  482. {
  483. var linkedItemWithThemes = album.SoundtrackIds
  484. .Select(i => _libraryManager.GetItemById(i))
  485. .FirstOrDefault(i => GetThemeSongIds(i).Count > 0);
  486. if (linkedItemWithThemes != null)
  487. {
  488. themeSongIds = GetThemeSongIds(linkedItemWithThemes);
  489. item = linkedItemWithThemes;
  490. }
  491. }
  492. }
  493. var dtos = themeSongIds.Select(_libraryManager.GetItemById)
  494. .OrderBy(i => i.SortName)
  495. .Select(i => _dtoService.GetBaseItemDto(i, fields, user, item));
  496. var items = dtos.ToArray();
  497. return new ThemeMediaResult
  498. {
  499. Items = items,
  500. TotalRecordCount = items.Length,
  501. OwnerId = _dtoService.GetDtoId(item)
  502. };
  503. }
  504. /// <summary>
  505. /// Gets the specified request.
  506. /// </summary>
  507. /// <param name="request">The request.</param>
  508. /// <returns>System.Object.</returns>
  509. public object Get(GetThemeVideos request)
  510. {
  511. var result = GetThemeVideos(request);
  512. return ToOptimizedSerializedResultUsingCache(result);
  513. }
  514. public ThemeMediaResult GetThemeVideos(GetThemeVideos request)
  515. {
  516. var user = request.UserId.HasValue ? _userManager.GetUserById(request.UserId.Value) : null;
  517. var item = string.IsNullOrEmpty(request.Id)
  518. ? (request.UserId.HasValue
  519. ? user.RootFolder
  520. : (Folder)_libraryManager.RootFolder)
  521. : _libraryManager.GetItemById(request.Id);
  522. var originalItem = item;
  523. while (GetThemeVideoIds(item).Count == 0 && request.InheritFromParent && item.Parent != null)
  524. {
  525. item = item.Parent;
  526. }
  527. // Get everything
  528. var fields = Enum.GetNames(typeof(ItemFields))
  529. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  530. .ToList();
  531. var themeVideoIds = GetThemeVideoIds(item);
  532. if (themeVideoIds.Count == 0 && request.InheritFromParent)
  533. {
  534. var album = originalItem as MusicAlbum;
  535. if (album == null)
  536. {
  537. album = originalItem.Parents.OfType<MusicAlbum>().FirstOrDefault();
  538. }
  539. if (album != null)
  540. {
  541. var linkedItemWithThemes = album.SoundtrackIds
  542. .Select(i => _libraryManager.GetItemById(i))
  543. .FirstOrDefault(i => GetThemeVideoIds(i).Count > 0);
  544. if (linkedItemWithThemes != null)
  545. {
  546. themeVideoIds = GetThemeVideoIds(linkedItemWithThemes);
  547. item = linkedItemWithThemes;
  548. }
  549. }
  550. }
  551. var dtos = themeVideoIds.Select(_libraryManager.GetItemById)
  552. .OrderBy(i => i.SortName)
  553. .Select(i => _dtoService.GetBaseItemDto(i, fields, user, item));
  554. var items = dtos.ToArray();
  555. return new ThemeMediaResult
  556. {
  557. Items = items,
  558. TotalRecordCount = items.Length,
  559. OwnerId = _dtoService.GetDtoId(item)
  560. };
  561. }
  562. private List<Guid> GetThemeVideoIds(BaseItem item)
  563. {
  564. var i = item as IHasThemeMedia;
  565. if (i != null)
  566. {
  567. return i.ThemeVideoIds;
  568. }
  569. return new List<Guid>();
  570. }
  571. private List<Guid> GetThemeSongIds(BaseItem item)
  572. {
  573. var i = item as IHasThemeMedia;
  574. if (i != null)
  575. {
  576. return i.ThemeSongIds;
  577. }
  578. return new List<Guid>();
  579. }
  580. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  581. public object Get(GetYearIndex request)
  582. {
  583. IEnumerable<BaseItem> items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager);
  584. if (!string.IsNullOrEmpty(request.IncludeItemTypes))
  585. {
  586. var vals = request.IncludeItemTypes.Split(',');
  587. items = items.Where(f => vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
  588. }
  589. var lookup = items
  590. .ToLookup(i => i.ProductionYear ?? -1)
  591. .OrderBy(i => i.Key)
  592. .Select(i => new ItemIndex
  593. {
  594. ItemCount = i.Count(),
  595. Name = i.Key == -1 ? string.Empty : i.Key.ToString(_usCulture)
  596. })
  597. .ToList();
  598. return ToOptimizedSerializedResultUsingCache(lookup);
  599. }
  600. public ThemeMediaResult GetSoundtrackSongs(string id, Guid? userId, bool inheritFromParent)
  601. {
  602. var user = userId.HasValue ? _userManager.GetUserById(userId.Value) : null;
  603. var item = string.IsNullOrEmpty(id)
  604. ? (userId.HasValue
  605. ? user.RootFolder
  606. : (Folder)_libraryManager.RootFolder)
  607. : _libraryManager.GetItemById(id);
  608. // Get everything
  609. var fields = Enum.GetNames(typeof(ItemFields))
  610. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  611. .ToList();
  612. var dtos = GetSoundtrackSongIds(item, inheritFromParent)
  613. .Select(_libraryManager.GetItemById)
  614. .OfType<MusicAlbum>()
  615. .SelectMany(i => i.RecursiveChildren)
  616. .OfType<Audio>()
  617. .OrderBy(i => i.SortName)
  618. .Select(i => _dtoService.GetBaseItemDto(i, fields, user, item));
  619. var items = dtos.ToArray();
  620. return new ThemeMediaResult
  621. {
  622. Items = items,
  623. TotalRecordCount = items.Length,
  624. OwnerId = _dtoService.GetDtoId(item)
  625. };
  626. }
  627. private IEnumerable<Guid> GetSoundtrackSongIds(BaseItem item, bool inherit)
  628. {
  629. var hasSoundtracks = item as IHasSoundtracks;
  630. if (hasSoundtracks != null)
  631. {
  632. return hasSoundtracks.SoundtrackIds;
  633. }
  634. if (!inherit)
  635. {
  636. return null;
  637. }
  638. hasSoundtracks = item.Parents.OfType<IHasSoundtracks>().FirstOrDefault();
  639. return hasSoundtracks != null ? hasSoundtracks.SoundtrackIds : new List<Guid>();
  640. }
  641. }
  642. }