-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrack.go
More file actions
244 lines (208 loc) · 5.8 KB
/
track.go
File metadata and controls
244 lines (208 loc) · 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package scdl
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
)
// Track holds metadata for a SoundCloud track.
type Track struct {
ID int
Title string
Album string
Artist string
ArtworkURL string
ArtistAvatarURL string
Genre string
Description string
Year string
Duration int // milliseconds
TrackAuthorization string
HLSURL string // HLS transcoding URL for audio/mpeg
}
var hydrationRe = regexp.MustCompile(`window\.__sc_hydration\s*=\s*(\[.+?]);`)
// nullableTime is a time.Time that safely handles null or empty string JSON values.
type nullableTime struct {
time.Time
}
func (t *nullableTime) UnmarshalJSON(data []byte) error {
s := string(data)
if s == "null" || s == `""` {
return nil
}
return json.Unmarshal(data, &t.Time)
}
// GetTrack fetches a SoundCloud track page and extracts metadata from the
// hydration data embedded in the HTML.
func (c *Client) GetTrack(ctx context.Context, trackURL string) (*Track, error) {
body, err := c.get(ctx, trackURL)
if err != nil {
return nil, fmt.Errorf("fetch track page: %w", err)
}
matches := hydrationRe.FindSubmatch(body)
if len(matches) < 2 {
return nil, fmt.Errorf("hydration data not found on page")
}
var hydration []struct {
Hydratable string `json:"hydratable"`
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(matches[1], &hydration); err != nil {
return nil, fmt.Errorf("parse hydration JSON: %w", err)
}
for _, entry := range hydration {
if entry.Hydratable != "sound" {
continue
}
var data struct {
ID int `json:"id"`
Title string `json:"title"`
CreatedAt nullableTime `json:"created_at"`
ReleaseDate nullableTime `json:"release_date"`
Description string `json:"description"`
Genre string `json:"genre"`
Duration int `json:"duration"`
ArtworkURL string `json:"artwork_url"`
TrackAuthorization string `json:"track_authorization"`
PublisherMetadata struct {
Artist string `json:"artist"`
AlbumTitle string `json:"album_title"`
ReleaseTitle string `json:"release_title"`
} `json:"publisher_metadata"`
User struct {
AvatarURL string `json:"avatar_url"`
Username string `json:"username"`
} `json:"user"`
Media struct {
Transcodings []struct {
URL string `json:"url"`
Format struct {
Protocol string `json:"protocol"`
MimeType string `json:"mime_type"`
} `json:"format"`
} `json:"transcodings"`
} `json:"media"`
}
if err := json.Unmarshal(entry.Data, &data); err != nil {
return nil, fmt.Errorf("parse track data: %w", err)
}
artist := data.User.Username
if data.PublisherMetadata.Artist != "" {
artist = data.PublisherMetadata.Artist
}
title := data.Title
if data.PublisherMetadata.ReleaseTitle != "" {
title = data.PublisherMetadata.ReleaseTitle
} else {
title = cleanupTrackTitle(title, artist, data.PublisherMetadata.AlbumTitle)
}
var year string
if !data.ReleaseDate.IsZero() {
year = data.ReleaseDate.Format("2006")
} else if !data.CreatedAt.IsZero() {
year = data.CreatedAt.Format("2006")
}
track := &Track{
ID: data.ID,
Title: title,
Album: data.PublisherMetadata.AlbumTitle,
Artist: artist,
ArtworkURL: data.ArtworkURL,
ArtistAvatarURL: data.User.AvatarURL,
Genre: data.Genre,
Description: data.Description,
Year: year,
Duration: data.Duration,
TrackAuthorization: data.TrackAuthorization,
}
for _, t := range data.Media.Transcodings {
if t.Format.MimeType == "audio/mpeg" && t.Format.Protocol == "hls" {
track.HLSURL = t.URL
break
}
}
if track.HLSURL == "" {
return nil, fmt.Errorf("no HLS audio/mpeg transcoding found")
}
return track, nil
}
return nil, fmt.Errorf("no sound entry found in hydration data")
}
// cleanupTrackTitle cleanly removes the artist and album name from the title
// while respecting hyphenated titles (e.g. "Artist - Album - Example-Title")
func cleanupTrackTitle(title, artist, album string) string {
if artist == "" && album == "" {
return title
}
var (
start int
segments []string
removed bool
)
for i := range len(title) + 1 {
if i == len(title) || isTrackTitleSeparator(title, i) {
trimmed := strings.TrimSpace(title[start:i])
if trimmed != "" {
if matchesAnyFold(trimmed, artist, album) {
removed = true
} else {
segments = append(segments, trimmed)
}
} else {
removed = true
}
start = i + 1
}
}
if len(segments) == 0 || !removed {
return title
}
return strings.Join(segments, " - ")
}
func isTrackTitleSeparator(title string, i int) bool {
if title[i] != '-' {
return false
}
return (i > 0 && title[i-1] == ' ') || (i+1 < len(title) && title[i+1] == ' ')
}
func matchesAnyFold(str, artist, album string) bool {
if album != "" && strings.EqualFold(str, album) {
return true
}
if artist == "" {
return false
}
if strings.EqualFold(str, artist) {
return true
}
var start int
for i := 0; i < len(str); {
isSep := false
sepLen := 1
if str[i] == '&' || str[i] == ',' {
isSep = true
} else if str[i] == ' ' && i+5 <= len(str) && strings.EqualFold(str[i:i+5], " and ") {
isSep = true
sepLen = 5
}
if isSep {
part := strings.TrimSpace(str[start:i])
if part != "" && strings.EqualFold(part, artist) {
return true
}
start = i + sepLen
i = start
} else {
i++
}
}
if start < len(str) {
part := strings.TrimSpace(str[start:])
if part != "" && strings.EqualFold(part, artist) {
return true
}
}
return false
}