2021-12-22 08:49:37 -07:00
|
|
|
package render
|
2021-11-12 13:04:24 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
_ "image/jpeg"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/shkh/lastfm-go/lastfm"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
2021-11-20 09:15:32 -07:00
|
|
|
func getImageFromLastFM(artist, album, imagePath string) (string, error) {
|
2021-11-12 13:04:24 -07:00
|
|
|
api := lastfm.New(viper.GetString("LASTFM_API_KEY"), viper.GetString("LASTFM_API_SECRET"))
|
|
|
|
v, err := api.Album.GetInfo(map[string]interface{}{
|
|
|
|
"artist": artist,
|
|
|
|
"album": album,
|
|
|
|
"autocorrect": viper.GetInt("LASTFM_AUTO_CORRECT"),
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
} else {
|
2021-11-20 09:15:32 -07:00
|
|
|
return downloadImage(v.Images[len(v.Images)-1].Url, imagePath)
|
2021-11-12 13:04:24 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-20 09:15:32 -07:00
|
|
|
func downloadImage(url string, imagePath string) (string, error) {
|
2021-11-12 13:04:24 -07:00
|
|
|
var reader io.Reader
|
|
|
|
if strings.HasPrefix(url, "http") {
|
|
|
|
r, err := http.Get(url)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer r.Body.Close()
|
|
|
|
reader = r.Body
|
|
|
|
v, err := io.ReadAll(reader)
|
|
|
|
if err == nil {
|
2021-11-20 09:15:32 -07:00
|
|
|
b, err := os.Create(imagePath)
|
2021-11-12 13:04:24 -07:00
|
|
|
if err == nil {
|
2022-03-15 15:18:53 -06:00
|
|
|
if _, err := b.Write(v); err == nil {
|
|
|
|
return imagePath, nil
|
|
|
|
} else {
|
|
|
|
return "", errors.New("could Not Write Image")
|
|
|
|
}
|
2021-11-12 13:04:24 -07:00
|
|
|
} else {
|
|
|
|
b.Close()
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
2022-03-15 15:18:53 -06:00
|
|
|
return "", errors.New("image Not Received")
|
2021-11-12 13:04:24 -07:00
|
|
|
}
|