Files
likedream/internal/application/music/downloader.go
T
sugarBecomer 4a29772de0 🐛 下载地址返回
2025-11-09 00:58:59 +08:00

69 lines
2.1 KiB
Go

package music
import (
"context"
"likedream-goframe/internal/application/httpclient"
"likedream-goframe/internal/common/errors"
"likedream-goframe/internal/utils"
"net/url"
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/samber/oops"
"github.com/tidwall/gjson"
)
var MusicDownloader *Downloader
type Downloader struct {
}
func (c *Downloader) Search(ctx context.Context, keyword string) (result []MusicSearchResult) {
client := httpclient.Music.Clone(ctx)
response, err := client.R().Get("https://www.gequbao.net/s/" + url.PathEscape(keyword))
if err != nil {
utils.OkOrPanic(errors.NewBusinessError(503, "搜索出错1"), oops.WithContext(ctx).Wrap)
}
defer response.Body.Close()
reader, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
utils.OkOrPanic(errors.NewBusinessError(503, "搜索出错2"), oops.WithContext(ctx).Wrap)
}
card := reader.Find(".card")
find := card.Find(".card-text > .row:not(:first-child)")
find.Each(func(i int, item *goquery.Selection) {
selection := item.Find("a")
url, _ := selection.Attr("href")
name := strings.TrimSpace(selection.Find(".text-primary span").Text())
singer := strings.TrimSpace(selection.Find(".text-jade").Text())
result = append(result, MusicSearchResult{
Name: name,
Singer: singer,
Path: url,
})
})
return
}
func (c *Downloader) Download(ctx context.Context, url string) string {
client := httpclient.Music.Clone(ctx)
response, err := client.R().Get("https://www.gequbao.net" + url)
if err != nil {
utils.OkOrPanic(errors.NewBusinessError(503, "下载出错1"), oops.WithContext(ctx).Wrap)
}
html := response.String()
reg := regexp.MustCompile("window\\.play_id = '(.*?)';")
play_id := reg.FindStringSubmatch(html)[1]
post, err := client.R().SetBody(map[string]string{
"id": play_id,
}).Post("https://www.gequbao.net/api/play-url")
if err != nil {
utils.OkOrPanic(errors.NewBusinessError(503, "下载出错2"), oops.WithContext(ctx).Wrap)
}
download_url := gjson.Get(post.String(), "data.url").String()
// 下载音频文件
return download_url
}