movies.go 1.8 KB

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