-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
200 lines (177 loc) · 5.07 KB
/
server.go
File metadata and controls
200 lines (177 loc) · 5.07 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package main
import (
"encoding/json"
"fmt"
"github.com/nlopes/slack"
"github.com/zmb3/spotify"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"strconv"
)
const (
contentType = "Content-Type"
jsonType = "application/json"
textHtml = "text/html"
)
var (
spotifyClient *SpotifyClient
slackSigningSecret string
contactUser string
slackAdminWebhook string
songHistoryLength int
)
func run(config *Config) error {
spotifyClient = &SpotifyClient{
Client: nil,
Authenticator: spotify.NewAuthenticator(config.SpotifyRedirectURI, spotify.ScopeUserReadCurrentlyPlaying, spotify.ScopeUserReadRecentlyPlayed),
State: RandomString(16),
Channel: make(chan *spotify.Client),
}
slackSigningSecret = config.SlackSigingSecret
slackAdminWebhook = config.SlackAdminWebhook
songHistoryLength = config.SongHistoryLength
contactUser = config.ContactUser
http.HandleFunc("/callback", completeAuth)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/nowplaying", nowPlayingHandler)
http.HandleFunc("/recentlyplayed", recentlyPlayedHandler)
http.HandleFunc("/slack", slackHandler)
go spotifyClient.Login()
go func() {
log.Print("Listening on port 443")
err := http.ListenAndServeTLS(":443", "_certs/certificate.crt", "_certs/private.key", nil)
if err != nil {
log.Fatal("ListenAndServeTLS: ", err)
}
}()
log.Print("Listening on port 80")
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Print("ListenAndServe: ", err)
return err
}
return nil
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
go spotifyClient.Login()
w.Header().Set(contentType, textHtml)
_, _ = fmt.Fprint(w, "A link to log in to Spotify has been sent to the Slack Admin")
}
func slackHandler(w http.ResponseWriter, r *http.Request) {
verifier, err := slack.NewSecretsVerifier(r.Header, slackSigningSecret)
if err != nil {
log.Printf("new secrets verifier err: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &verifier))
s, err := slack.SlashCommandParse(r)
if err != nil {
log.Printf("error parsing slash command: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("username:%s userID:%s command:%s", s.UserName, s.UserID, s.Command)
if err = verifier.Ensure(); err != nil {
log.Printf("error verifying authorization: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
switch s.Command {
case "/nowplaying":
b, err := NowPlayingMessage()
if err != nil {
w.Header().Set(contentType, jsonType)
b, _ = ErrorMessage("⛔️ Cannot get currently playing song.")
}
w.Header().Set(contentType, jsonType)
_, _ = w.Write(b)
case "/recentlyplayed":
b, err := RecentlyPlayedMessage()
if err != nil {
w.Header().Set(contentType, jsonType)
b, _ = ErrorMessage("⛔️ Cannot get recently played songs.")
}
w.Header().Set(contentType, jsonType)
_, _ = w.Write(b)
default:
w.Header().Set(contentType, jsonType)
b, _ := ErrorMessage("Unrecognized Command")
_, _ = w.Write(b)
}
}
func nowPlayingHandler(w http.ResponseWriter, r *http.Request) {
if spotifyClient.Client == nil {
_, _ = fmt.Fprint(w, "Please Log in to the BounceX Spotify Account")
return
}
w.Header().Set(contentType, jsonType)
w.Header().Set("Access-Control-Allow-Origin", "*")
nowPlaying, _ := spotifyClient.NowPlaying()
var b []byte
var err error
if nowPlaying != nil {
b, err = json.Marshal(nowPlaying)
} else {
w.WriteHeader(http.StatusNoContent)
b, err = json.Marshal(Song{})
}
_, _ = w.Write(b)
if err != nil {
log.Print(err)
}
}
func recentlyPlayedHandler(w http.ResponseWriter, r *http.Request) {
if spotifyClient.Client == nil {
_, _ = fmt.Fprint(w, "Please Log in to the BounceX Spotify Account")
return
}
w.Header().Set(contentType, jsonType)
w.Header().Set("Access-Control-Allow-Origin", "*")
lengthParam := r.URL.Query().Get("length")
var size int
if lengthParam == "" {
size = songHistoryLength
} else {
s, err := strconv.Atoi(lengthParam)
if err != nil {
size = songHistoryLength
} else {
size = s
}
}
recentlyPlayed, _ := spotifyClient.RecentlyPlayed(size)
b, err := json.Marshal(recentlyPlayed)
_, _ = w.Write(b)
if err != nil {
log.Print(err)
}
}
func completeAuth(w http.ResponseWriter, r *http.Request) {
tok, err := spotifyClient.Authenticator.Token(spotifyClient.State, r)
if err != nil {
http.Error(w, "Couldn't get token", http.StatusForbidden)
log.Print(err)
}
if st := r.FormValue("state"); st != spotifyClient.State {
http.NotFound(w, r)
log.Printf("State mismatch: %s != %s\n", st, spotifyClient.State)
}
client := spotifyClient.Authenticator.NewClient(tok)
user, _ := client.CurrentUser()
w.Header().Set(contentType, textHtml)
_, _ = fmt.Fprintf(w, "Login Completed!")
spotifyClient.Channel <- &client
SendLoginSuccessMessage(user)
}
func RandomString(length int) string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, length)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}