-
Notifications
You must be signed in to change notification settings - Fork 2
/
golyrics.go
100 lines (84 loc) · 2.42 KB
/
golyrics.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
package golyrics
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/buger/jsonparser"
)
const searchBaseURI = "http://lyrics.wikia.com/index.php?action=ajax&rs=getLinkSuggest&format=json&query="
const lyricsBaseURI = "http://lyrics.wikia.com/wiki/"
// Track is a music track containing Artist, Name and Lyrics.
type Track struct {
Artist string
Name string
Lyrics string
}
// FetchLyrics fetches the lyrics of a Track and sets it on that track.
func (track *Track) FetchLyrics() error {
URI := fmt.Sprintf("%s%s:%s", lyricsBaseURI, track.Artist, track.Name)
doc, err := goquery.NewDocument(URI)
if err != nil {
return err
}
lyricsHTML, err := doc.Find(".lyricbox").Html()
if err != nil {
return err
}
track.Lyrics = getFormattedLyrics(lyricsHTML)
return nil
}
func breakToNewLine(HTML string) string {
return strings.Replace(HTML, "<br/>", "\n", -1)
}
func stripeHTMLTags(HTML string) string {
regex := regexp.MustCompile("<[^>]+>")
return regex.ReplaceAllString(HTML, "")
}
func fixApostrophesAndQuotes(text string) string {
apostrophesFixed := strings.Replace(text, "'", "'", -1)
return strings.Replace(apostrophesFixed, """, "\"", -1)
}
func getSearchURI(query string) string {
return fmt.Sprintf("%s%s", searchBaseURI, url.QueryEscape(query))
}
func getFormattedLyrics(text string) string {
noBreaks := breakToNewLine(text)
noHTMLTags := stripeHTMLTags(noBreaks)
return fixApostrophesAndQuotes(noHTMLTags)
}
// SearchTrack searches for tracks
// using a string query that can be part of the track name or artist.
func SearchTrack(query string) ([]Track, error) {
requestURI := getSearchURI(query)
response, err := http.Get(requestURI)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
suggestions := []Track{}
jsonparser.ArrayEach(data, func(value []byte, _ jsonparser.ValueType, offset int, _ error) {
title := string(value)
trackParts := strings.SplitN(title, ":", 2)
if len(trackParts) < 2 {
return
}
track := Track{
Artist: trackParts[0],
Name: trackParts[1],
}
suggestions = append(suggestions, track)
}, "suggestions")
return suggestions, nil
}
// SearchTrackByArtistAndName searches for tracks
// using artist and name of the track.
func SearchTrackByArtistAndName(artist, name string) ([]Track, error) {
return SearchTrack(artist + ":" + name)
}