package movies import ( "encoding/json" "fmt" "hugo-medialog/utils" "io/ioutil" "net/http" "os" "path/filepath" "strconv" ) // FanartResponse Struct type FanartResponse struct { MoviePosters []FanartImage `json:"movieposter"` MovieBackgrounds []FanartImage `json:"moviebackground"` MovieLogos []FanartImage `json:"movielogo"` } // FanartImage struct type FanartImage struct { URL string `json:"url"` Likes string `json:"likes"` } func FetchImagesFromFanart(ID int) (posterURL, backgroundURL string, logoURL string, err error) { fanartAPIKey := os.Getenv("FANART_API_KEY") url := fmt.Sprintf("https://webservice.fanart.tv/v3/movies/%s?api_key=%s", strconv.Itoa(ID), fanartAPIKey) resp, err := http.Get(url) if err != nil { return "", "", "", fmt.Errorf("error fetching data from fanart.tv: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", "", "", fmt.Errorf("fanart.tv returned non-200 status: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", "", "", fmt.Errorf("error reading response body: %w", err) } var fanartResp FanartResponse err = json.Unmarshal(body, &fanartResp) if err != nil { return "", "", "", fmt.Errorf("error unmarshalling response: %w", err) } // Get the most voted poster if len(fanartResp.MoviePosters) > 0 { posterURL = fanartResp.MoviePosters[0].URL } // Get the most voted background if len(fanartResp.MovieBackgrounds) > 0 { backgroundURL = fanartResp.MovieBackgrounds[0].URL } // Get the most voted logo if len(fanartResp.MovieLogos) > 0 { logoURL = fanartResp.MovieLogos[0].URL } return posterURL, backgroundURL, logoURL, nil } func DownloadImage(url, slug, imageType string) error { imageDir := filepath.Join(os.Getenv("MARKDOWN_OUTPUT_MOVIES_DIR"), os.Getenv("IMAGES_OUTPUT_DIR")) if err := utils.CreateDirIfNotExists(imageDir); err != nil { return err } filename := fmt.Sprintf("%s-%s.jpg", slug, imageType) filePath := filepath.Join(imageDir, filename) resp, err := http.Get(url) if err != nil { return fmt.Errorf("error downloading image: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("non-200 response while downloading image: %d", resp.StatusCode) } file, err := os.Create(filePath) if err != nil { return fmt.Errorf("error creating image file: %w", err) } defer file.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return fmt.Errorf("error reading image data: %w", err) } _, err = file.Write(body) if err != nil { return fmt.Errorf("error writing image data: %w", err) } fmt.Printf(" - Image saved successfully at: %s\n", filePath) return nil }