Skip to content

Commit

Permalink
album cover
Browse files Browse the repository at this point in the history
  • Loading branch information
sayem314 committed Sep 27, 2024
1 parent ca06215 commit 9ea5bce
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
63 changes: 63 additions & 0 deletions pkg/metadata/album_cover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package metadata

import (
"errors"
"fmt"
"time"

"github.com/d-fi/GoFi/pkg/request"
"github.com/hashicorp/golang-lru/v2/expirable"
)

const (
cacheSize = 50
cacheTTL = 30 * time.Minute
)

// Valid cover sizes
const (
CoverSize56 = 56
CoverSize250 = 250
CoverSize500 = 500
CoverSize1000 = 1000
CoverSize1500 = 1500
CoverSize1800 = 1800
)

var validCoverSizes = map[int]bool{
CoverSize56: true,
CoverSize250: true,
CoverSize500: true,
CoverSize1000: true,
CoverSize1500: true,
CoverSize1800: true,
}

var albumCoverCache = expirable.NewLRU[string, []byte](cacheSize, nil, cacheTTL)

func DownloadAlbumCover(albumPicture string, albumCoverSize int) ([]byte, error) {
if albumPicture == "" {
return nil, errors.New("album picture hash is empty")
}

if !validCoverSizes[albumCoverSize] {
return nil, fmt.Errorf("invalid cover size: %d", albumCoverSize)
}

cacheKey := fmt.Sprintf("%s%d", albumPicture, albumCoverSize)
if cachedData, ok := albumCoverCache.Get(cacheKey); ok {
return cachedData, nil
}

url := fmt.Sprintf("https://e-cdns-images.dzcdn.net/images/cover/%s/%dx%d-000000-80-0-0.jpg",
albumPicture, albumCoverSize, albumCoverSize)

resp, err := request.Client.R().Get(url)
if err != nil {
return nil, fmt.Errorf("failed to download album cover: %w", err)
}
data := resp.Body()

albumCoverCache.Add(cacheKey, data)
return data, nil
}
30 changes: 30 additions & 0 deletions pkg/metadata/album_cover_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package metadata

import (
"testing"

"github.com/stretchr/testify/assert"
)

const ALB_PICTURE = "2e018122cb56986277102d2041a592c8" // Discovery by Daft Punk

func TestDownloadAlbumCover(t *testing.T) {
// Test valid cover sizes
coverSizes := []int{56, 250, 500, 1000, 1500, 1800}
for _, size := range coverSizes {
cover, err := DownloadAlbumCover(ALB_PICTURE, size)
assert.NoError(t, err)
assert.NotNil(t, cover)
assert.Greater(t, len(cover), 0)
}

// Test invalid cover sizes
_, err := DownloadAlbumCover(ALB_PICTURE, 2000)
assert.Error(t, err)
assert.Equal(t, "invalid cover size: 2000", err.Error())

// Test empty album picture hash
_, err = DownloadAlbumCover("", 500)
assert.Error(t, err)
assert.Equal(t, "album picture hash is empty", err.Error())
}

0 comments on commit 9ea5bce

Please sign in to comment.