GenresHandler.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using MediaBrowser.Common.Net.Handlers;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Model.DTO;
  4. using MediaBrowser.Model.Entities;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace MediaBrowser.Api.HttpHandlers
  9. {
  10. public class GenresHandler : BaseSerializationHandler<IBNItem[]>
  11. {
  12. protected override Task<IBNItem[]> GetObjectToSerialize()
  13. {
  14. Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder;
  15. User user = ApiService.GetUserById(QueryString["userid"], true);
  16. return GetAllGenres(parent, user);
  17. }
  18. /// <summary>
  19. /// Gets all genres from all recursive children of a folder
  20. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  21. /// </summary>
  22. private async Task<IBNItem[]> GetAllGenres(Folder parent, User user)
  23. {
  24. Dictionary<string, int> data = new Dictionary<string, int>();
  25. // Get all the allowed recursive children
  26. IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user);
  27. foreach (var item in allItems)
  28. {
  29. // Add each genre from the item to the data dictionary
  30. // If the genre already exists, increment the count
  31. if (item.Genres == null)
  32. {
  33. continue;
  34. }
  35. foreach (string val in item.Genres)
  36. {
  37. if (!data.ContainsKey(val))
  38. {
  39. data.Add(val, 1);
  40. }
  41. else
  42. {
  43. data[val]++;
  44. }
  45. }
  46. }
  47. // Get the Genre objects
  48. Genre[] entities = await Task.WhenAll<Genre>(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetGenre(key); })).ConfigureAwait(false);
  49. // Convert to an array of IBNItem
  50. IBNItem[] items = new IBNItem[entities.Length];
  51. for (int i = 0; i < entities.Length; i++)
  52. {
  53. Genre e = entities[i];
  54. items[i] = ApiService.GetIBNItem(e, data[e.Name]);
  55. }
  56. return items;
  57. }
  58. }
  59. }