-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (162 loc) · 4.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
func getCurdir() string {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
return dir
}
const Endpoint = "http://www.kuwo.cn"
const UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
type SearchKeyReponse struct {
Data *DataField
}
type DataField struct {
List []*MusicInfo
Total string
}
type MusicInfo struct {
Rid int
Name string
Artist string
Album string
SongTimeMinutes string
}
type MusicUrlResponse struct {
Code int
Msg string
Url string
}
type Client struct {
}
func ConcatUrl(endpoint string, path string) string {
return strings.Join([]string{endpoint, path}, "")
}
func GetTimeStamp() string {
return strconv.Itoa(int(time.Now().UnixNano()))
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func (this *Client) Get(path string, reqHeaders map[string]string, args ...interface{}) ([]byte, error) {
url := fmt.Sprintf(path, args...)
if !strings.HasPrefix(url, "http") {
url = ConcatUrl(Endpoint, url)
}
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
check(err)
if reqHeaders != nil {
for key, value := range reqHeaders {
req.Header.Add(key, value)
}
}
resp, err := client.Do(req)
check(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
func (this *Client) GetUrlCookie(url, name string) string {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
check(err)
resp, err := client.Do(req)
check(err)
m := map[string]string{}
for _, cookie := range resp.Cookies() {
cookieStr := cookie.String()
index := strings.Index(cookieStr, ";")
cookieStr = cookieStr[:index]
pairs := strings.Split(cookieStr, "=")
key, value := pairs[0], pairs[1]
m[key] = value
}
return m[name]
}
func (this *Client) SearchMusicBykeyWord(key string, pageNum, rowNum int) []*MusicInfo {
/*GET Music List*/
urlSearchList := "http://www.kuwo.cn/search/list"
kw_token := this.GetUrlCookie(urlSearchList, "kw_token")
path := "/api/www/search/searchMusicBykeyWord?key=%s&pn=%d&rn=%d"
referer := fmt.Sprintf("%s?key=%s", urlSearchList, url.QueryEscape(key))
reqHeaders := map[string]string{
"Cookie": fmt.Sprintf("kw_token=%s", kw_token),
"csrf": kw_token,
"Referer": referer,
"User-Agent": UA,
}
respBytes, err := this.Get(path, reqHeaders, url.QueryEscape(key), pageNum, rowNum)
check(err)
searchKeyRes := new(SearchKeyReponse)
json.Unmarshal(respBytes, searchKeyRes)
return searchKeyRes.Data.List
}
func (this *Client) DowloadMusicByInfo(musicInfo *MusicInfo, name string, dl bool) {
path := "/url?format=mp3&rid=%d&response=url&type=convert_url3&br=128kmp3&from=web&t=%s"
respBytes, err := this.Get(path, nil, musicInfo.Rid, GetTimeStamp()[:13])
check(err)
result := new(MusicUrlResponse)
json.Unmarshal(respBytes, result)
fmt.Printf("%s\n", result.Url)
if dl {
respBytes, err = this.Get(result.Url, nil)
check(err)
if len(name) == 0 {
name = musicInfo.Name
}
outputname := fmt.Sprintf("%s-%s.mp3", musicInfo.Artist, name)
outputpath := filepath.Join(getCurdir(), outputname)
fmt.Printf("Save to:%s\n", outputpath)
Save(respBytes, outputpath)
}
}
func Save(bytes []byte, savepath string) {
out, err := os.Create(savepath)
check(err)
defer out.Close()
out.Write(bytes)
out.Sync()
}
func main() {
keywordPtr := flag.String("k", "", "the keyword for searching")
pagenumPtr := flag.Int("p", 1, "number of page of music list")
rownumPtr := flag.Int("r", 20, "number of rows of every page")
ridPtr := flag.Int("rid", -1, "id of song")
dlPtr := flag.Bool("dl", false, "download mp3 file?")
namePtr := flag.String("n", "", "name of song without artist or file-extension")
flag.Parse()
keyword, pagenum, rownum, rid, name := *keywordPtr, *pagenumPtr, *rownumPtr, *ridPtr, *namePtr
if len(keyword) == 0 {
fmt.Printf("[WARNING] Argument -k Required\n")
return
}
clt := new(Client)
memo := make(map[int]*MusicInfo)
musicInfoList := clt.SearchMusicBykeyWord(keyword, pagenum, rownum)
lineFormat := "[%02d] %v | %s | %s | %s | %s\n"
for i, info := range musicInfoList {
memo[info.Rid] = info
if rid == -1 {
fmt.Printf(lineFormat, i+1, info.Rid, info.Artist, info.Name, info.Album, info.SongTimeMinutes)
}
}
if rid > 0 {
if info, ok := memo[rid]; ok {
clt.DowloadMusicByInfo(info, name, *dlPtr)
}
}
}