hugo-medialog/internal/series/api_fanart.go

107 lines
2.7 KiB
Go

package series
import (
"encoding/json"
"fmt"
"hugo-medialog/utils"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
)
// FanartResponse Struct
type FanartResponse struct {
SeriePosters []FanartImage `json:"tvposter"`
SerieBackgrounds []FanartImage `json:"showbackground"`
SerieLogos []FanartImage `json:"hdtvlogo"`
}
// 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/tv/%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.SeriePosters) > 0 {
posterURL = fanartResp.SeriePosters[0].URL
}
// Get the most voted background
if len(fanartResp.SerieBackgrounds) > 0 {
backgroundURL = fanartResp.SerieBackgrounds[0].URL
}
// Get the most voted logo
if len(fanartResp.SerieLogos) > 0 {
logoURL = fanartResp.SerieLogos[0].URL
}
return posterURL, backgroundURL, logoURL, nil
}
func DownloadImage(url, slug, imageType string) error {
imageDir := filepath.Join(os.Getenv("MARKDOWN_OUTPUT_SERIES_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
}