movies.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package movies
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. type Movie struct {
  9. Title string
  10. Director string
  11. Poster string
  12. Rating *Rating
  13. IMDBID string
  14. OMDB OMDBMovie
  15. }
  16. type Rating struct {
  17. Note float64
  18. Votes int64
  19. }
  20. type OMDBMovie struct {
  21. Title string
  22. Year string
  23. Rated string
  24. Released string
  25. Runtime string
  26. Genre string
  27. Director string
  28. Writer string
  29. Actors string
  30. Plot string
  31. Language string
  32. Country string
  33. Awards string
  34. Poster string
  35. Ratings []OMDBRating
  36. Metascore string
  37. IMDBRating string `json: "imdbRating"`
  38. IMDBVotes string `json: "imdbVotes"`
  39. IMDBID string `json: "imdbID"`
  40. Type string
  41. DVD string
  42. BoxOffice string
  43. Production string
  44. Website string
  45. Response string
  46. }
  47. type OMDBRating struct {
  48. Source, Value string
  49. }
  50. func Unmarshal(b []byte) (*Movie, error) {
  51. var omdb OMDBMovie
  52. if err := json.Unmarshal(b, &omdb); err != nil {
  53. return nil, err
  54. }
  55. m := &Movie{
  56. OMDB: omdb,
  57. }
  58. if err := m.FillFromOMDB(); err != nil {
  59. return nil, err
  60. }
  61. return m, nil
  62. }
  63. func (m *Movie) FillFromOMDB() error {
  64. if m.Title == "" {
  65. m.Title = m.OMDB.Title
  66. }
  67. if m.Director == "" {
  68. m.Director = m.OMDB.Director
  69. }
  70. if m.Poster == "" {
  71. m.Poster = m.OMDB.Poster
  72. }
  73. if m.IMDBID == "" {
  74. m.IMDBID = m.OMDB.IMDBID
  75. }
  76. if m.Rating == nil {
  77. note, err := strconv.ParseFloat(m.OMDB.IMDBRating, 64)
  78. if err != nil {
  79. return fmt.Errorf("cannot convert %q to float64: %w", m.OMDB.IMDBRating, err)
  80. }
  81. votes, err := strconv.ParseInt(strings.ReplaceAll(m.OMDB.IMDBVotes, ",", ""), 10, 64)
  82. if err != nil {
  83. return fmt.Errorf("cannot convert %q to int: %w", m.OMDB.IMDBVotes, err)
  84. }
  85. m.Rating = &Rating{
  86. Note: note,
  87. Votes: votes,
  88. }
  89. }
  90. return nil
  91. }