This commit is contained in:
parent
1acd1c0cab
commit
7cd5e80468
23 changed files with 988 additions and 5 deletions
81
music-spotify.go
Normal file
81
music-spotify.go
Normal file
|
@ -0,0 +1,81 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
func SearchSpotify(query string, page int) ([]MusicResult, error) {
|
||||
searchUrl := fmt.Sprintf("https://open.spotify.com/search/%s", url.PathEscape(query))
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", searchUrl, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
// Set user agent ?
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("received non-200 status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse document: %v", err)
|
||||
}
|
||||
|
||||
var results []MusicResult
|
||||
|
||||
// Find track elements
|
||||
doc.Find(`div[data-testid="tracklist-row"]`).Each(func(i int, s *goquery.Selection) {
|
||||
// Extract title
|
||||
title := s.Find(`div[data-testid="tracklist-row__title"] a`).Text()
|
||||
title = strings.TrimSpace(title)
|
||||
|
||||
// Extract artist
|
||||
artist := s.Find(`div[data-testid="tracklist-row__artist"] a`).First().Text()
|
||||
artist = strings.TrimSpace(artist)
|
||||
|
||||
// Extract duration
|
||||
duration := s.Find(`div[data-testid="tracklist-row__duration"]`).First().Text()
|
||||
duration = strings.TrimSpace(duration)
|
||||
|
||||
// Extract URL
|
||||
path, _ := s.Find(`div[data-testid="tracklist-row__title"] a`).Attr("href")
|
||||
fullUrl := fmt.Sprintf("https://open.spotify.com%s", path)
|
||||
|
||||
// Extract thumbnail
|
||||
thumbnail, _ := s.Find(`img[aria-hidden="false"]`).Attr("src")
|
||||
|
||||
if title != "" && artist != "" {
|
||||
results = append(results, MusicResult{
|
||||
Title: title,
|
||||
Artist: artist,
|
||||
URL: fullUrl,
|
||||
Duration: duration,
|
||||
Thumbnail: thumbnail,
|
||||
Source: "Spotify",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return results, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue