refactor: modularize downloader architecture
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type AMAPIClient struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func (c *AMAPIClient) Search(keyword, source string, page, limit int) (*http.Response, error) {
|
||||
u, err := url.Parse(strings.TrimRight(c.BaseURL, "/") + "/search")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("keyword", keyword)
|
||||
q.Set("source", source)
|
||||
q.Set("page", strconv.Itoa(page))
|
||||
q.Set("limit", strconv.Itoa(limit))
|
||||
u.RawQuery = q.Encode()
|
||||
return c.HTTP.Get(u.String())
|
||||
}
|
||||
|
||||
func (c *AMAPIClient) Resolve(source, rid, quality string) (playInfo, error) {
|
||||
u, err := url.Parse(strings.TrimRight(c.BaseURL, "/") + "/song/play-url")
|
||||
if err != nil {
|
||||
return playInfo{}, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("source", source)
|
||||
q.Set("rid", rid)
|
||||
q.Set("level", quality)
|
||||
u.RawQuery = q.Encode()
|
||||
resp, err := c.HTTP.Get(u.String())
|
||||
if err != nil {
|
||||
return playInfo{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var x struct {
|
||||
Code int `json:"code"`
|
||||
Data playInfo `json:"data"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&x); err != nil {
|
||||
return playInfo{}, err
|
||||
}
|
||||
if x.Code != 0 || x.Data.URL == "" {
|
||||
if x.Message == "" {
|
||||
x.Message = "music API returned no playable URL"
|
||||
}
|
||||
return playInfo{}, errors.New(x.Message)
|
||||
}
|
||||
return x.Data, nil
|
||||
}
|
||||
Reference in New Issue
Block a user