From c19a053126f394f13e109b838e88ad1936159e88 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Sat, 13 Nov 2021 01:34:24 +0530 Subject: [PATCH] Connecting LastFm Api to get Image Urls which is then rendered --- lastfm.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 lastfm.go diff --git a/lastfm.go b/lastfm.go new file mode 100644 index 0000000..a673101 --- /dev/null +++ b/lastfm.go @@ -0,0 +1,53 @@ +package main + +import ( + "errors" + _ "image/jpeg" + "io" + "net/http" + "os" + "strings" + + "github.com/shkh/lastfm-go/lastfm" + "github.com/spf13/viper" +) + +func getImageFromLastFM(artist, album string) (string, error) { + 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 { + return downloadImage(v.Images[len(v.Images)-1].Url) + } +} + +func downloadImage(url string) (string, error) { + 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 { + b, err := os.Create(viper.GetString("COVER_IMAGE_PATH")) + if err == nil { + b.Write(v) + return viper.GetString("COVER_IMAGE_PATH"), nil + } else { + b.Close() + return "", err + } + } else { + return "", err + } + } + return "", errors.New("Image Not Received") +}