strip-beats/media/brainz/brainz.go
2023-09-24 22:34:30 -05:00

138 lines
2.5 KiB
Go

package brainz
import (
"encoding/json"
"fmt"
"io"
u "net/url"
h "codeberg.org/danjones000/strip-beats/utils/http"
"github.com/google/uuid"
)
type Recording struct {
Id uuid.UUID
Isrcs []string
FirstReleaseDate string `json:"first-release-date"`
Length int
Title string
Video bool
Releases []Release
Genres []Genre
ArtistCredit []ArtistCredit `json:"artist-credit"`
}
func (r Recording) FirstArtist() Artist {
var a Artist
for _, ac := range r.ArtistCredit {
if ac.Artist.Name != "" {
return ac.Artist
}
}
for _, rel := range r.Releases {
for _, ac := range rel.ArtistCredit {
if ac.Artist.Name != "" {
return ac.Artist
}
}
}
if a.Name == "" {
a.Name = "Unknown Artist"
}
return a
}
func (r Recording) FirstGenre() Genre {
var g Genre
for _, g = range r.Genres {
if g.Name != "" {
return g
}
}
for _, rel := range r.Releases {
for _, g = range rel.Genres {
if g.Name != "" {
return g
}
}
}
return g
}
type Genre struct {
Id uuid.UUID
Name string
}
type Release struct {
Id uuid.UUID
Country string
Date string
Media []Media
Status string
StatusId uuid.UUID `json:"status-id"`
ArtistCredit []ArtistCredit `json:"artist-credit"`
Title string
Genres []Genre
// ReleaseEvents []ReleaseEvent `json:"release-events"`
}
type ArtistCredit struct {
Name string
Artist Artist
}
type Artist struct {
Id uuid.UUID
Name string
TypeId string `json:"type-id"`
Type string
SortName string `json:"sort-name"`
Genres []Genre
}
type Media struct {
FormatId uuid.UUID `json:"format-id"`
Position int
TrackOffset int `json:"track-offset"`
Format string
TrackCount int `json:"track-count"`
Tracks []Track
}
type Track struct {
Id uuid.UUID
Number string
Title string
Position int
Length int
}
func GetRecording(id string) (Recording, error) {
u, err := uuid.Parse(id)
rec := Recording{Id: u}
if err != nil {
return rec, err
}
err = FillRecording(&rec)
return rec, err
}
func FillRecording(rec *Recording) error {
url := fmt.Sprintf("https://musicbrainz.org/ws/2/recording/%s", rec.Id)
resp, err := h.GetWithQuery(url, u.Values{
"fmt": []string{"json"},
"inc": []string{"releases+media+artist-credits+isrcs+genres"}})
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, rec)
return err
}