78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package apple
|
|
|
|
import (
|
|
"fmt"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
// PlaylistRef is a parsed public Apple Music playlist URL.
|
|
type PlaylistRef struct {
|
|
Storefront string
|
|
PlaylistID string
|
|
RawURL string
|
|
}
|
|
|
|
// ParsePlaylistURL validates a public music.apple.com playlist link.
|
|
func ParsePlaylistURL(raw string) (PlaylistRef, error) {
|
|
raw = strings.TrimSpace(raw)
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
return PlaylistRef{}, fmt.Errorf("invalid Apple Music URL: %w", err)
|
|
}
|
|
if u.Scheme != "https" && u.Scheme != "http" {
|
|
return PlaylistRef{}, fmt.Errorf("Apple Music URL must use https")
|
|
}
|
|
host := strings.ToLower(u.Hostname())
|
|
switch host {
|
|
case "music.apple.com", "beta.music.apple.com", "classical.music.apple.com":
|
|
default:
|
|
return PlaylistRef{}, fmt.Errorf("not an Apple Music URL: host %q", host)
|
|
}
|
|
|
|
segments := splitPath(u.Path)
|
|
for _, segment := range segments {
|
|
if strings.EqualFold(segment, "library") {
|
|
return PlaylistRef{}, fmt.Errorf("library (private) playlists are not supported; use a public catalog playlist")
|
|
}
|
|
}
|
|
|
|
ref := PlaylistRef{RawURL: raw, Storefront: "us"}
|
|
if len(segments) > 0 && isStorefront(segments[0]) {
|
|
ref.Storefront = strings.ToLower(segments[0])
|
|
}
|
|
for _, segment := range segments {
|
|
if strings.HasPrefix(segment, "pl.") && len(segment) > 3 {
|
|
ref.PlaylistID = segment
|
|
break
|
|
}
|
|
}
|
|
if ref.PlaylistID == "" {
|
|
return PlaylistRef{}, fmt.Errorf("Apple Music URL does not contain a playlist id (pl.…)")
|
|
}
|
|
return ref, nil
|
|
}
|
|
|
|
func splitPath(path string) []string {
|
|
parts := strings.Split(path, "/")
|
|
out := make([]string, 0, len(parts))
|
|
for _, p := range parts {
|
|
if p != "" {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func isStorefront(s string) bool {
|
|
if len(s) != 2 {
|
|
return false
|
|
}
|
|
for _, r := range strings.ToLower(s) {
|
|
if r < 'a' || r > 'z' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|