Skip to content

Commit

Permalink
Merge pull request #121 from SongStitch/feature/refactoring
Browse files Browse the repository at this point in the history
Feature/refactoring
  • Loading branch information
BradLewis authored Aug 5, 2023
2 parents e604c07 + 9415b0a commit 0d004d4
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 80 deletions.
22 changes: 11 additions & 11 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ import (
)

type CollageRequest struct {
Rows int `in:"query=rows;default=3" validate:"required,gte=1,lte=15"`
Columns int `in:"query=columns;default=3" validate:"required,gte=1,lte=15"`
Method string `in:"query=method;default=album" validate:"required,oneof=album artist track"`
TextLocation string `in:"query=textlocation;default=topleft" validate:"validateTextLocation"`
Username string `in:"query=username;required" validate:"required"`
Period string `in:"query=period;default=7day" validate:"required,validatePeriod"`
DisplayArtist bool `in:"query=artist;default=false"`
Height uint `in:"query=height;default=0" validate:"gte=0,lte=3000"`
Width uint `in:"query=width;default=0" validate:"gte=0,lte=3000"`
Rows int `in:"query=rows;default=3" validate:"required,gte=1,lte=15"`
FontSize int `in:"query=fontsize;default=12" validate:"gte=8,lte=30"`
Columns int `in:"query=columns;default=3" validate:"required,gte=1,lte=15"`
DisplayAlbum bool `in:"query=album;default=false"`
DisplayTrack bool `in:"query=track;default=false"`
PlayCount bool `in:"query=playcount;default=false"`
Width uint `in:"query=width;default=0" validate:"gte=0,lte=3000"`
Height uint `in:"query=height;default=0" validate:"gte=0,lte=3000"`
Method string `in:"query=method;default=album" validate:"required,oneof=album artist track"`
FontSize int `in:"query=fontsize;default=12" validate:"gte=8,lte=30"`
DisplayArtist bool `in:"query=artist;default=false"`
BoldFont bool `in:"query=boldfont;default=false"`
Webp bool `in:"query=webp;default=false"`
TextLocation string `in:"query=textlocation;default=topleft" validate:"validateTextLocation"`
}

func generateCollage(ctx context.Context, request *CollageRequest) (*image.Image, *bytes.Buffer, error) {
Expand Down Expand Up @@ -123,11 +123,11 @@ func Collage(w http.ResponseWriter, r *http.Request) {
return
}
if err != nil {
switch {
case err == constants.ErrUserNotFound:
switch err {
case constants.ErrUserNotFound:
logger.Warn().Err(err).Str("username", request.Username).Msg("User not found")
http.Error(w, "User not found", http.StatusNotFound)
case err == constants.ErrTooManyImages:
case constants.ErrTooManyImages:
logger.Warn().Err(err).Str("method", request.Method).Int("rows", request.Rows).Int("columns", request.Columns).Msg("Too many images requested for the collage type")
http.Error(w, "Requested collage size is too large for the collage type", http.StatusBadRequest)
default:
Expand Down
2 changes: 1 addition & 1 deletion internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
const MAX_CACHE_SIZE = 10000

type Map[K comparable, V any] struct {
count atomic.Uint64
m sync.Map
count atomic.Uint64
}

func (m *Map[K, V]) Load(key K) (value V, ok bool) {
Expand Down
11 changes: 4 additions & 7 deletions internal/clients/lastfm/lastfm.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ func cleanError(err error) error {
return CleanError{errStr: modifiedString}
}

func GetLastFmResponse[T LastFMResponse](ctx context.Context, collageType constants.CollageType, username string, period constants.Period, count int, imageSize string) (*T, error) {
func GetLastFmResponse[T LastFMResponse](ctx context.Context, collageType constants.CollageType, username string, period constants.Period, count int) (*T, error) {
endpoint := os.Getenv("LASTFM_ENDPOINT")
key := os.Getenv("LASTFM_API_KEY")

// Image URLs stop getting returned by the API at around 500
const maxPerPage = 500
var totalFetched = 0
var page = 1
totalFetched := 0
page := 1

var result T
initialised := false
Expand Down Expand Up @@ -164,14 +164,13 @@ func GetLastFmResponse[T LastFMResponse](ctx context.Context, collageType consta
type GetTrackInfoResponse struct {
Track struct {
Album struct {
Images []LastFMImage `json:"image"`
AlbumName string `json:"title"`
Images []LastFMImage `json:"image"`
} `json:"Album"`
} `json:"track"`
}

func GetTrackInfo(trackName string, artistName string, imageSize string) (*models.TrackInfo, error) {

endpoint := os.Getenv("LASTFM_ENDPOINT")
key := os.Getenv("LASTFM_API_KEY")
u, err := url.Parse(endpoint)
Expand Down Expand Up @@ -220,7 +219,6 @@ func GetTrackInfo(trackName string, artistName string, imageSize string) (*model
}
}
return nil, errors.New("no image found")

}

func GetImageIdForArtist(ctx context.Context, artistUrl string) (string, error) {
Expand All @@ -245,5 +243,4 @@ func GetImageIdForArtist(ctx context.Context, artistUrl string) (string, error)
return "", errors.New("no image found")
}
return path.Base(href), nil

}
50 changes: 25 additions & 25 deletions internal/clients/spotify/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,48 +10,48 @@ type AlbumResponse struct {

type SearchResult[T any] struct {
Href string `json:"href"`
Next string `json:"next"`
Previous string `json:"previous"`
Items []T `json:"items"`
Limit int `json:"limit"`
Next string `json:"next"`
Offset int `json:"offset"`
Previous string `json:"previous"`
Total int `json:"total"`
}

type TrackItem struct {
Album Album `json:"album"`
Artists []Artist `json:"artists"`
AvailableMarkets []string `json:"available_markets"`
DiscNumber int `json:"disc_number"`
DurationMs int `json:"duration_ms"`
Explicit bool `json:"explicit"`
Name string `json:"name"`
URI string `json:"uri"`
Type string `json:"type"`
ExternalIds ExternalID `json:"external_ids"`
ExternalUrls ExternalURL `json:"external_urls"`
Href string `json:"href"`
ID string `json:"id"`
IsLocal bool `json:"is_local"`
Name string `json:"name"`
Popularity int `json:"popularity"`
PreviewURL string `json:"preview_url"`
Artists []Artist `json:"artists"`
AvailableMarkets []string `json:"available_markets"`
DurationMs int `json:"duration_ms"`
Popularity int `json:"popularity"`
TrackNumber int `json:"track_number"`
Type string `json:"type"`
URI string `json:"uri"`
DiscNumber int `json:"disc_number"`
IsLocal bool `json:"is_local"`
Explicit bool `json:"explicit"`
}

type Album struct {
AlbumType string `json:"album_type"`
Artists []Artist `json:"artists"`
AvailableMarkets []string `json:"available_markets"`
ReleaseDatePrecision string `json:"release_date_precision"`
ExternalUrls ExternalURL `json:"external_urls"`
Href string `json:"href"`
ID string `json:"id"`
Images []Image `json:"images"`
Name string `json:"name"`
ReleaseDate string `json:"release_date"`
ReleaseDatePrecision string `json:"release_date_precision"`
TotalTracks int `json:"total_tracks"`
AlbumType string `json:"album_type"`
Type string `json:"type"`
URI string `json:"uri"`
Artists []Artist `json:"artists"`
AvailableMarkets []string `json:"available_markets"`
Images []Image `json:"images"`
TotalTracks int `json:"total_tracks"`
}

type Artist struct {
Expand All @@ -72,23 +72,23 @@ type ExternalURL struct {
}

type Image struct {
Height int `json:"height"`
URL string `json:"url"`
Height int `json:"height"`
Width int `json:"width"`
}

type AlbumItem struct {
AlbumType string `json:"album_type"`
Artists []Artist `json:"artists"`
ReleaseDatePrecision string `json:"release_date_precision"`
ExternalURLs ExternalURL `json:"external_urls"`
Href string `json:"href"`
ID string `json:"id"`
Images []Image `json:"images"`
IsPlayable bool `json:"is_playable"`
Name string `json:"name"`
ReleaseDate string `json:"release_date"`
ReleaseDatePrecision string `json:"release_date_precision"`
TotalTracks int `json:"total_tracks"`
AlbumType string `json:"album_type"`
Type string `json:"type"`
URI string `json:"uri"`
Artists []Artist `json:"artists"`
Images []Image `json:"images"`
TotalTracks int `json:"total_tracks"`
IsPlayable bool `json:"is_playable"`
}
6 changes: 3 additions & 3 deletions internal/clients/spotify/spotify.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ type SpotifyAuthResponse struct {
}

type Token struct {
AccessToken string
ExpiresIn int
client *http.Client
AccessToken string
endpoint string
ExpiresIn int
}

func (t *Token) Refresh() error {
Expand Down Expand Up @@ -89,8 +89,8 @@ func (t *Token) KeepAlive(log zerolog.Logger) {

type SpotifyClient struct {
token *Token
endpoint string
client *http.Client
endpoint string
}

var spotifyClient *SpotifyClient
Expand Down
14 changes: 7 additions & 7 deletions internal/collages/album.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,20 @@ type LastFMAlbum struct {
ArtistName string `json:"name"`
Mbid string `json:"mbid"`
} `json:"artist"`
Images []lastfm.LastFMImage `json:"image"`
Mbid string `json:"mbid"`
URL string `json:"url"`
Playcount string `json:"playcount"`
Mbid string `json:"mbid"`
URL string `json:"url"`
Playcount string `json:"playcount"`
Attr struct {
Rank string `json:"rank"`
} `json:"@attr"`
AlbumName string `json:"name"`
AlbumName string `json:"name"`
Images []lastfm.LastFMImage `json:"image"`
}

type LastFMTopAlbums struct {
TopAlbums struct {
Albums []LastFMAlbum `json:"album"`
Attr lastfm.LastFMUser `json:"@attr"`
Albums []LastFMAlbum `json:"album"`
} `json:"topalbums"`
}

Expand Down Expand Up @@ -73,7 +73,7 @@ func GenerateCollageForAlbum(ctx context.Context, username string, period consta
}

func getAlbums(ctx context.Context, username string, period constants.Period, count int, imageSize string) ([]*Album, error) {
result, err := lastfm.GetLastFmResponse[*LastFMTopAlbums](ctx, constants.ALBUM, username, period, count, imageSize)
result, err := lastfm.GetLastFmResponse[*LastFMTopAlbums](ctx, constants.ALBUM, username, period, count)
if err != nil {
return nil, err
}
Expand Down
17 changes: 8 additions & 9 deletions internal/collages/artist.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,31 @@ import (
)

type LastFMArtist struct {
Images []lastfm.LastFMImage `json:"image"`
Mbid string `json:"mbid"`
URL string `json:"url"`
Playcount string `json:"playcount"`
Mbid string `json:"mbid"`
URL string `json:"url"`
Playcount string `json:"playcount"`
Attr struct {
Rank string `json:"rank"`
} `json:"@attr"`
Name string `json:"name"`
Name string `json:"name"`
Images []lastfm.LastFMImage `json:"image"`
}

type LastFMTopArtists struct {
TopArtists struct {
Artists []LastFMArtist `json:"artist"`
Attr lastfm.LastFMUser `json:"@attr"`
Artists []LastFMArtist `json:"artist"`
} `json:"topartists"`
}

func (a *LastFMTopArtists) Append(l lastfm.LastFMResponse) error {

if artists, ok := l.(*LastFMTopArtists); ok {
a.TopArtists.Artists = append(a.TopArtists.Artists, artists.TopArtists.Artists...)
return nil
}
return errors.New("type LastFMResponse is not a LastFMTopArtists")
}

func (a *LastFMTopArtists) GetTotalPages() int {
totalPages, _ := strconv.Atoi(a.TopArtists.Attr.TotalPages)
return totalPages
Expand All @@ -67,8 +67,7 @@ func GenerateCollageForArtist(ctx context.Context, username string, period const
}

func getArtists(ctx context.Context, username string, period constants.Period, count int, imageSize string) ([]*Artist, error) {

result, err := lastfm.GetLastFmResponse[*LastFMTopArtists](ctx, constants.ARTIST, username, period, count, imageSize)
result, err := lastfm.GetLastFmResponse[*LastFMTopArtists](ctx, constants.ARTIST, username, period, count)
if err != nil {
return nil, err
}
Expand Down
13 changes: 7 additions & 6 deletions internal/collages/track.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,26 @@ import (
)

type LastFMTrack struct {
Mbid string `json:"mbid"`
Name string `json:"name"`
Images []lastfm.LastFMImage `json:"image"`
Artist struct {
URL string `json:"url"`
Name string `json:"name"`
Mbid string `json:"mbid"`
} `json:"artist"`
Mbid string `json:"mbid"`
Name string `json:"name"`
URL string `json:"url"`
Duration string `json:"duration"`
Attr struct {
Rank string `json:"rank"`
} `json:"@attr"`
Playcount string `json:"playcount"`
Playcount string `json:"playcount"`
Images []lastfm.LastFMImage `json:"image"`
}

type LastFMTopTracks struct {
TopTracks struct {
Tracks []LastFMTrack `json:"track"`
Attr lastfm.LastFMUser `json:"@attr"`
Tracks []LastFMTrack `json:"track"`
} `json:"toptracks"`
}

Expand Down Expand Up @@ -75,7 +75,7 @@ func GenerateCollageForTrack(ctx context.Context, username string, period consta
}

func getTracks(ctx context.Context, username string, period constants.Period, count int, imageSize string) ([]*Track, error) {
result, err := lastfm.GetLastFmResponse[*LastFMTopTracks](ctx, constants.TRACK, username, period, count, imageSize)
result, err := lastfm.GetLastFmResponse[*LastFMTopTracks](ctx, constants.TRACK, username, period, count)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -199,6 +199,7 @@ func (t *Track) GetIdentifier() string {
}
return t.Name + t.Artist + t.ImageSize
}

func (t *Track) GetCacheEntry() cache.CacheEntry {
return cache.CacheEntry{Url: t.ImageUrl, Album: t.Album}
}
Expand Down
22 changes: 11 additions & 11 deletions internal/generator/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@ import (
)

type DisplayOptions struct {
ArtistName bool
AlbumName bool
TrackName bool
PlayCount bool
Compress bool
Resize bool
Width uint
TextLocation constants.TextLocation
Height uint
ImageDimension int
Columns int
Rows int
FontSize float64
Width uint
PlayCount bool
Resize bool
BoldFont bool
Rows int
Columns int
ImageDimension int
Compress bool
ArtistName bool
TrackName bool
Webp bool
TextLocation constants.TextLocation
AlbumName bool
}

const (
Expand Down

0 comments on commit 0d004d4

Please sign in to comment.