58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package util
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"strings"
|
||
)
|
||
|
||
func GetSongIdsByHash(hashs []string) (hashToSongId map[string]string, err error) {
|
||
if len(hashs) == 0 {
|
||
return nil, nil
|
||
}
|
||
//每批最多49个
|
||
hashToSongId = make(map[string]string)
|
||
batchSize := 49
|
||
for i := 0; i < len(hashs); i += batchSize {
|
||
end := i + batchSize
|
||
if end > len(hashs) {
|
||
end = len(hashs)
|
||
}
|
||
batchHashs := hashs[i:end]
|
||
queryUrl := "https://api.beatsaver.com/maps/hash/" + strings.Join(batchHashs, ",")
|
||
resp, err := http.Get(queryUrl)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
if resp.StatusCode != 200 {
|
||
return nil, fmt.Errorf("获取歌曲ID失败,状态码:%d,url:%s", resp.StatusCode, queryUrl)
|
||
}
|
||
body, err := io.ReadAll(resp.Body)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var response = make(map[string]struct {
|
||
ID string `json:"id"`
|
||
})
|
||
if len(batchHashs) == 1 {
|
||
var singleResponse struct {
|
||
ID string `json:"id"`
|
||
}
|
||
err = json.Unmarshal(body, &singleResponse)
|
||
response[batchHashs[0]] = singleResponse
|
||
} else {
|
||
err = json.Unmarshal(body, &response)
|
||
}
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
for hash, data := range response {
|
||
hashToSongId[hash] = data.ID
|
||
}
|
||
}
|
||
return hashToSongId, nil
|
||
}
|