-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
173 lines (150 loc) · 4.78 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
package main
import (
"database/sql"
"encoding/csv"
"flag"
"math/rand"
"os"
"strings"
"time"
"github.com/fasthttp/router"
log "github.com/golang/glog"
"github.com/jasonlvhit/gocron"
"github.com/jchorl/watchdog"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"github.com/jchorl/gowaker/alarms"
"github.com/jchorl/gowaker/config"
"github.com/jchorl/gowaker/plugin/calendar"
"github.com/jchorl/gowaker/plugin/weather"
"github.com/jchorl/gowaker/speech"
"github.com/jchorl/gowaker/spotify"
)
var (
spotifyCredFile = flag.String("spotify-cred-file", "./spotifycreds.json", "File to cache spotify credentials.")
gcalCredFile = flag.String("gcal-cred-file", "./gcalcreds.json", "File to cache gcal credentials.")
gcalConfigFile = flag.String("gcal-config-file", "./gcalconfig.json", "Oauth config file provided by google.")
ttsServiceAccountFile = flag.String("tts-service-account-file", "./tts-service-account-key.json", "Service account file provided by google.")
)
func initDB() (*sql.DB, error) {
db, err := sql.Open("sqlite3", "./waker.db")
if err != nil {
return nil, errors.Wrap(err, "error opening db file")
}
sqlStmt := `
create table if not exists alarms (
id text not null primary key,
hour int not null,
minute int not null,
repeat bool not null,
days string -- csv of days to repeat
);
create table if not exists spotify_config (
key text not null primary key,
value text not null
);
`
_, err = db.Exec(sqlStmt)
if err != nil {
err = errors.Wrapf(err, "error executing sql statement: %s", sqlStmt)
return nil, err
}
return db, nil
}
func main() {
flag.Parse()
db, err := initDB()
if err != nil {
log.Fatalf("error initing db: %s", err)
}
defer db.Close()
scheduler := gocron.NewScheduler()
scheduler.ChangeLoc(time.UTC) // all timestamps are in UTC
job := scheduler.Every(1).Hour()
job.Tag("watchdog")
job.Do(func() {
wdClient := watchdog.Client{Domain: "https://watchdog.joshchorlton.com"}
wdClient.Ping("waker", watchdog.Watch_DAILY)
})
spotifyClient, err := spotify.New(*spotifyCredFile)
if err != nil {
log.Fatalf("creating spotify client: %s", err)
}
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
speechClient, err := speech.New(*ttsServiceAccountFile)
if err != nil {
log.Fatalf("creating speech client: %s", err)
}
weatherPlugin := weather.Weather{
APIKey: os.Getenv("OPENWEATHERMAP_API_KEY"),
TempUnit: weather.Celsius,
OWMID: config.OWMID,
}
calendars, err := csv.NewReader(strings.NewReader(config.GoogleCalendars)).Read()
if err != nil {
log.Fatalf("parsing calendars: %s", err)
}
calendarPlugin, err := calendar.New(calendars, *gcalConfigFile, *gcalCredFile)
if err != nil {
log.Fatalf("creating calendar plugin: %s", err)
}
middlewares := []middleware{
dbMiddleware(db),
schedulerMiddleware(scheduler),
spotifyMiddleware(spotifyClient),
randMiddleware(rng),
speechMiddleware(speechClient),
pluginsMiddleware(weatherPlugin, calendarPlugin),
logMiddleware(),
}
middlewareApplier := func(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
wrapped := handler
for _, m := range middlewares {
wrapped = m(wrapped)
}
return wrapped
}
// this is a fun hack that uses the middlewares to create a ctx that we use to restore crons
fakeHandler := middlewareApplier(func(ctx *fasthttp.RequestCtx) {
err = alarms.RestoreAlarmsFromDB(ctx)
if err != nil {
log.Fatalf("restoring db: %s", err)
}
})
fakeHandler(&fasthttp.RequestCtx{})
r := router.New()
r.GET("/alarms", middlewareApplier(alarms.HandlerGet))
r.DELETE("/alarms", middlewareApplier(alarms.HandlerDelete))
r.POST("/alarms", middlewareApplier(alarms.HandlerPost))
r.GET("/spotify/playlists", middlewareApplier(spotify.HandlerGetPlaylists))
r.GET("/spotify/default_playlist", middlewareApplier(spotify.HandlerGetDefaultPlaylist))
r.PUT("/spotify/default_playlist", middlewareApplier(spotify.HandlerSetDefaultPlaylist))
r.GET("/spotify/next_wakeup_song", middlewareApplier(spotify.HandlerGetNextWakeupSong))
r.PUT("/spotify/next_wakeup_song", middlewareApplier(spotify.HandlerSetNextWakeupSong))
r.GET("/spotify/search", middlewareApplier(spotify.HandlerSearch))
r.GET("/spotify/devices", middlewareApplier(spotify.HandlerDevices))
serverDone := make(chan struct{})
go func() {
port := ":8080"
log.Infof("listening on %s", port)
log.Error(fasthttp.ListenAndServe(port, r.Handler))
serverDone <- struct{}{}
}()
schedulerDone := make(chan struct{})
go func() {
log.Info("starting the job processor")
ticker := time.NewTicker(30 * time.Second)
for {
<-ticker.C
scheduler.RunPending()
}
schedulerDone <- struct{}{}
}()
select {
case <-schedulerDone:
log.Fatalf("scheduler crashed")
case <-serverDone:
log.Fatalf("server crashed")
}
}