Created
October 6, 2020 14:03
-
-
Save darrenparkinson/054b9c39c2fd619b37c41a879ef86bb1 to your computer and use it in GitHub Desktop.
Simple go file to download album artwork from spotify using CSV file of albums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/csv" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"strings" | |
"github.com/zmb3/spotify" | |
"golang.org/x/oauth2/clientcredentials" | |
) | |
func main() { | |
// Set up before we do anything else | |
config := &clientcredentials.Config{ | |
ClientID: os.Getenv("SPOTIFY_CLIENT_ID"), | |
ClientSecret: os.Getenv("SPOTIFY_CLIENT_SECRET"), | |
TokenURL: spotify.TokenURL, | |
} | |
token, err := config.Token(context.Background()) | |
if err != nil { | |
log.Fatalf("couldn't get token: %v", err) | |
} | |
client := spotify.Authenticator{}.NewClient(token) | |
client.AutoRetry = true // will retry if we're throttled by the API | |
// Now get the albums from the CSV | |
albums, err := getAlbumsFromCSV("albumlist.csv") // artist,album,spotifyid (spotifyid in format spotify:album:asdf1234) | |
if err != nil { | |
log.Fatalf("error reading csv: %v", err) | |
} | |
for _, album := range albums { | |
s := strings.Split(album, ":") | |
if len(s) == 3 { | |
downloadArtworkForAlbum(client, spotify.ID(s[2])) | |
} | |
} | |
} | |
func getAlbumsFromCSV(filename string) ([]string, error) { | |
albums := []string{} | |
csvfile, err := os.Open(filename) | |
if err != nil { | |
return albums, err | |
} | |
r := csv.NewReader(csvfile) | |
for { | |
record, err := r.Read() | |
if err == io.EOF { | |
break | |
} | |
if err != nil { | |
return albums, err | |
} | |
albums = append(albums, record[2]) | |
} | |
return albums, nil | |
} | |
func downloadArtworkForAlbum(client spotify.Client, albumID spotify.ID) error { | |
album, err := client.GetAlbum(albumID) | |
if err != nil { | |
return err | |
} | |
var largest spotify.Image | |
largestSize := 0 | |
for _, img := range album.Images { | |
if img.Height > largestSize { | |
largest = img | |
largestSize = img.Height | |
} | |
} | |
filename := fmt.Sprintf("%s-%s.jpg", album.Artists[0].Name, album.Name) | |
f, err := os.Create(fmt.Sprintf("./artwork/%s", filename)) | |
if err != nil { | |
f.Close() | |
return err | |
} | |
largest.Download(f) | |
f.Close() | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment