Skip to content

Commit

Permalink
refactor: process track images concurrently
Browse files Browse the repository at this point in the history
  • Loading branch information
mgjules committed Apr 11, 2022
1 parent c557c6a commit 5a75e6d
Showing 1 changed file with 38 additions and 24 deletions.
62 changes: 38 additions & 24 deletions spoty/spoty.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
_ "image/jpeg"
_ "image/png"
"net/http"
"sync"
"time"

"github.com/JulesMike/spoty/cache"
Expand Down Expand Up @@ -107,34 +108,47 @@ func (s *Spoty) TrackImages(track *spotify.FullTrack) ([]Image, error) {
return cachedImages.([]Image), nil
}

httpClient := &http.Client{
Timeout: 5 * time.Second,
}

var wg sync.WaitGroup

var images []Image
for _, albumImage := range track.Album.Images {
img := Image{
URL: albumImage.URL,
Height: albumImage.Height,
Width: albumImage.Width,
}

resp, err := http.Get(albumImage.URL)
if err != nil {
img.Error = "could not retrieve album image"
images = append(images, img)
continue
}
defer resp.Body.Close()

processedImg, _, err := image.Decode(resp.Body)
if err != nil {
img.Error = "could not process album image"
images = append(images, img)
continue
}

img.RGBA = dominantcolor.Find(processedImg)
img.Hex = dominantcolor.Hex(img.RGBA)
images = append(images, img)
wg.Add(1)
go func(albumImage spotify.Image) {
img := Image{
URL: albumImage.URL,
Height: albumImage.Height,
Width: albumImage.Width,
}

defer func() {
images = append(images, img)
wg.Done()
}()

resp, err := httpClient.Get(albumImage.URL)
if err != nil {
img.Error = "could not retrieve album image"
return
}
defer resp.Body.Close()

processedImg, _, err := image.Decode(resp.Body)
if err != nil {
img.Error = "could not process album image"
return
}

img.RGBA = dominantcolor.Find(processedImg)
img.Hex = dominantcolor.Hex(img.RGBA)
}(albumImage)
}

wg.Wait()

s.cache.SetWithTTL(cacheTrackImagesKey, images, 0, 5*time.Second)

return images, nil
Expand Down

0 comments on commit 5a75e6d

Please sign in to comment.