81 lines
2 KiB
Go
81 lines
2 KiB
Go
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
|
|
}
|