forked from dinofizz/diskplayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recorder.go
58 lines (49 loc) · 1.61 KB
/
recorder.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
package diskplayer
import (
"errors"
"fmt"
"io/ioutil"
"strings"
)
// Record takes in a web URL which links to a Spotify album or playlist and records the corresponding Spotify ID to
// the filepath specified in the diskplayer.yaml configuration file under the recorder.file_path field.
// The web URL should be something like https://open.spotify.com/album/1S7mumn7D4riEX2gVWYgPO
// Returns an error if one is encountered.
func Record(url string, fullPath string) error {
s, err := createSpotifyUri(url)
if err != nil {
return err
}
err = writeToDisk(s, fullPath)
if err != nil {
return err
}
return nil
}
// createSpotifyUri creates a Spotify URI from the web URL.
// The web URL should be something like https://open.spotify.com/album/1S7mumn7D4riEX2gVWYgPO
// A string representing the Spotify URI is returned or any error that is encountered.
func createSpotifyUri(url string) (string, error) {
i := strings.LastIndex(url, "/")
id := url[i+1:]
var u string
if strings.Contains(url, "/album/") {
u = "spotify:album:" + id
} else if strings.Contains(url, "/playlist/") {
u = "spotify:playlist:" + id
} else {
return "", errors.New(fmt.Sprintf("URL represents neither album nor playlist: %s", url))
}
return u, nil
}
// writeToDisk takes a string containing a Spotify URI and writes to the the filepath specified in the diskplayer.yaml
// configuration file under the recorder.file_path field.
// Returns an error if one is encountered.
func writeToDisk(spotifyUri, fullPath string) error {
b := []byte(spotifyUri)
err := ioutil.WriteFile(fullPath, b, 0644)
if err != nil {
return err
}
return nil
}