/
main.go
209 lines (183 loc) · 4.69 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"os"
"time"
"io/ioutil"
logrusgce "github.com/PentoHQ/logrus-gce"
"github.com/go-redis/redis"
"github.com/heptiolabs/healthcheck"
"github.com/sirupsen/logrus"
"github.com/wearebrews/dt_spotify/spotifyhelper"
"golang.org/x/oauth2"
)
type SlackMessage struct {
Text string `json:"text"`
}
type DTEvent struct {
Event struct {
EventID string `json:"eventId"`
TargetName string `json:"targetName"`
EventType string `json:"eventType"`
Data struct {
ObjectPresent *struct {
State string `json:"state"`
} `json:"objectPresent"`
Temperature *struct {
Value float32 `json:"value"`
} `json:"temperature"`
} `json:"data"`
} `json:"event"`
Labels struct {
Action *string `json:"spotify_action"`
Song *string `json:"spotify_song"`
Playlist *string `json:"spotify_playlist"`
} `json:"labels"`
}
var dtEvents chan DTEvent
func postLoginURL(slackURL, loginURL string) {
//Ask user to login
jsonBytes, err := json.Marshal(SlackMessage{loginURL})
if err != nil {
logrus.Panic(err)
}
http.Post(slackURL, "application/json", bytes.NewBuffer(jsonBytes))
}
func main() {
logrus.SetFormatter(logrusgce.NewGCEFormatter(true))
//Load envs
spotifyClientID, ok := os.LookupEnv("SPOTIFY_CLIENT_ID")
if !ok {
logrus.Panic("Missing SPOTIFY_CLIENT_ID")
}
spotifyClientSecret, ok := os.LookupEnv("SPOTIFY_CLIENT_SECRET")
if !ok {
logrus.Panic("Missing SPOTIFY_CLIENT_SECRET")
}
baseURL, ok := os.LookupEnv("BASE_URL")
if !ok {
logrus.Panic("Missing BASE_URL")
}
hostPort, ok := os.LookupEnv("HOST_PORT")
if !ok {
hostPort = "8080"
}
slackURL, ok := os.LookupEnv("SLACK_URL")
if !ok {
logrus.Panic("Missing SLACK URL")
}
health := healthcheck.NewHandler()
logrus.Info(slackURL)
loginPath := "/login"
redirectURL := baseURL + loginPath
//Create new session
session := spotifyhelper.NewSession(context.TODO(), spotifyClientID, spotifyClientSecret, redirectURL)
spotify := spotifyhelper.New(context.TODO(), session, health)
// Kill application if stuck
go func() {
select {
case <-time.After(5 * time.Minute):
logrus.Panic("No token received after 5 minutes")
case <-spotify.Ready():
break
}
}()
//Set up HTTP handler for login session
http.HandleFunc(loginPath, session.Handler())
//Send login url to start authentication
//Create DT handler
http.HandleFunc("/dtconn", handleDTEvents)
redisClient := redis.NewClient(&redis.Options{
Addr: "redis-master:6379",
Password: "",
DB: 0,
})
var token oauth2.Token
rBytes, err := redisClient.Get("spotify_token").Bytes()
if err == nil {
//Load token from redis
err := json.Unmarshal(rBytes, &token)
if err != nil {
logrus.Panic(err)
}
session.SetToken(token)
} else {
postLoginURL(slackURL, session.LoginURL())
}
//Refresh token frequently
go writeSpotifyTokenPeriodically(redisClient, spotify, 5*time.Minute)
//Create channel for DT events
dtEvents = make(chan DTEvent)
//Start
ctx := context.Background()
go run(ctx, dtEvents, spotify)
go http.ListenAndServe("0.0.0.0:8086", health)
http.ListenAndServe(":"+hostPort, nil)
}
func writeSpotifyTokenPeriodically(client *redis.Client, spotify spotifyhelper.Controller, period time.Duration) {
for {
token := spotify.Token()
logrus.WithField("token", token).Info("Refreshing token in redis")
bytes, err := json.Marshal(token)
if err != nil {
logrus.Panic(err)
}
if err := client.Set("spotify_token", bytes, token.Expiry.Sub(time.Now())).Err(); err != nil {
logrus.Panic(err)
}
<-time.After(period)
}
}
func handleDTEvents(w http.ResponseWriter, r *http.Request) {
if dtEvents == nil {
http.Error(w, "Application not ready", http.StatusInternalServerError)
return
}
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Panic(err)
}
event := &DTEvent{}
err = json.Unmarshal(bytes, event)
if err != nil {
logrus.Panic(err)
}
dtEvents <- *event
}
func run(ctx context.Context, dtEvents chan DTEvent, c spotifyhelper.Controller) {
//Wait until spotify is READY
logrus.Info("Application is ready for events")
for {
select {
case <-ctx.Done():
return
case event := <-dtEvents:
if event.Labels.Action != nil {
logrus.WithField("event", event).Info("Processing event")
switch *event.Labels.Action {
case "play":
c.Play()
case "pause":
c.Pause()
case "toggle":
c.Toggle()
case "next_song":
c.NextSong()
case "prev_song":
c.PrevSong()
case "play_song":
if event.Labels.Song != nil {
c.PlaySong(*event.Labels.Song)
}
case "play_playlist":
if event.Labels.Playlist != nil {
c.PlayPlaylist(*event.Labels.Playlist)
}
}
}
}
}
}