genres.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package tmdb
  2. import (
  3. "notabug.org/apiote/amuse/config"
  4. "notabug.org/apiote/amuse/datastructure"
  5. "notabug.org/apiote/amuse/network"
  6. "encoding/json"
  7. "errors"
  8. "net/http"
  9. "notabug.org/apiote/gott"
  10. )
  11. type Genres struct {
  12. Genres []struct {
  13. Id int
  14. Name string
  15. }
  16. }
  17. func createGenresRequest(args ...interface{}) (interface{}, error) {
  18. request := args[0].(*network.Request)
  19. result := args[1].(*network.Result)
  20. result.Client = &http.Client{}
  21. var itemType string
  22. if request.Id == datastructure.ItemTypeFilm {
  23. itemType = "movie"
  24. } else if request.Id == datastructure.ItemTypeTvserie {
  25. itemType = "tv"
  26. } else {
  27. return gott.Tuple(args), errors.New("Wrong itemType: " + request.Id)
  28. }
  29. httpRequest, err := http.NewRequest("GET", "https://api.themoviedb.org/3/genre/"+itemType+"/list?api_key="+config.TmdbApiKey+"&language="+request.Language, nil)
  30. result.Request = httpRequest
  31. return gott.Tuple(args), err
  32. }
  33. func unmarshalGenres(args ...interface{}) (interface{}, error) {
  34. result := args[1].(*network.Result)
  35. genres := &Genres{}
  36. err := json.Unmarshal(result.Body, genres)
  37. if err != nil {
  38. return gott.Tuple(args), err
  39. }
  40. genreMap := map[int]string{}
  41. for _, genre := range genres.Genres {
  42. genreMap[genre.Id] = genre.Name
  43. }
  44. result.Result = genreMap
  45. return gott.Tuple(args), nil
  46. }
  47. func GetGenres(language string, itemType datastructure.ItemType) (map[int]string, error) {
  48. genres, err := gott.
  49. NewResult(gott.Tuple{&network.Request{Id: string(itemType), Language: language}, &network.Result{}}).
  50. Bind(createGenresRequest).
  51. Bind(getCacheEntry).
  52. Map(network.AddHeaders).
  53. Bind(network.DoRequest).
  54. Bind(network.HandleRequestError).
  55. Bind(network.ReadResponse).
  56. Tee(cleanCache).
  57. Tee(saveCacheEntry).
  58. Bind(unmarshalGenres).
  59. Finish()
  60. if err != nil {
  61. return map[int]string{}, err
  62. } else {
  63. return genres.(gott.Tuple)[1].(*network.Result).Result.(map[int]string), nil
  64. }
  65. }