-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsonglinkfetcher.go
101 lines (84 loc) · 2.05 KB
/
songlinkfetcher.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/atotto/clipboard"
)
type SonglinkResponse struct {
PageURL string `json:"pageUrl"`
LinksByPlatform LinksByPlatform `json:"linksByPlatform"`
}
type LinksByPlatform struct {
Spotify PlatformMusic `json:"spotify"`
}
type PlatformMusic struct {
URL string `json:"url"`
}
func GetLinks(searchURL string) error {
response, err := makeRequest(searchURL)
if err != nil {
return err
}
platform := PlatformMusic{
URL: "",
}
links := LinksByPlatform{
Spotify: platform,
}
linksResponse := SonglinkResponse{
PageURL: "",
LinksByPlatform: links,
}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&linksResponse)
if err != nil {
return fmt.Errorf("error decoding JSON response: %w", err)
}
nonLocalURL := strings.ReplaceAll(linksResponse.PageURL, "/fi", "")
spotifyURL := linksResponse.LinksByPlatform.Spotify.URL
var outputString string
if *xFlag {
outputString = fmt.Sprintf("%s\n%s", nonLocalURL, spotifyURL)
} else if *dFlag {
outputString = fmt.Sprintf("<%s>\n%s", nonLocalURL, spotifyURL)
} else if *sFlag {
outputString = spotifyURL
} else {
outputString = nonLocalURL
}
err = clipboard.WriteAll(outputString)
if err != nil {
return fmt.Errorf("error copying output string to clipboard: %w", err)
}
fmt.Print(
"\nSuccess ✅\n",
outputString,
"\nCopied to the clipboard\n\n",
)
return nil
}
func makeRequest(searchURL string) (*http.Response, error) {
url := buildURL(searchURL)
response, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("error making HTTP request: %w", err)
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-OK HTTP response status: %s", response.Status)
}
return response, nil
}
func buildURL(searchURL string) string {
url := url.URL{
Scheme: "https",
Host: "api.song.link",
Path: "/v1-alpha.1/links",
}
values := url.Query()
values.Add("url", searchURL)
url.RawQuery = values.Encode()
return url.String()
}