This repository was archived by the owner on Dec 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhook.go
315 lines (282 loc) · 8.45 KB
/
hook.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright (C) 2021 The Takeout Authors.
//
// This file is part of Takeout.
//
// Takeout is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Takeout is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Takeout. If not, see <https://www.gnu.org/licenses/>.
package server
import (
"fmt"
"net/http"
"github.com/defsub/takeout/auth"
"github.com/defsub/takeout/config"
"github.com/defsub/takeout/lib/actions"
"github.com/defsub/takeout/lib/token"
"github.com/defsub/takeout/music"
"github.com/defsub/takeout/view"
)
const (
IntentAuth = "TAKEOUT_AUTH"
IntentPlay = "TAKEOUT_PLAY"
IntentNew = "TAKEOUT_NEW"
UserParamCookie = "cookie"
)
func hookHandler(w http.ResponseWriter, r *http.Request) {
ctx := contextValue(r)
w.Header().Set(HeaderContentType, ApplicationJson)
tokenString := r.Header.Get(actions.GoogleAssistantSignature)
err := token.ValidateGoogleToken(ctx.Config(), tokenString, ctx.Config().Assistant.ProjectID)
if err != nil {
serverErr(w, err)
return
}
hookRequest := actions.NewWebhookRequest(r)
hookResponse := actions.NewWebhookResponse(hookRequest)
// fmt.Printf("got intent=%s %+v\n", hookRequest.IntentName(), hookRequest)
// fmt.Printf("got user %+v\n", *hookRequest.User)
// if hookRequest.User != nil && hookRequest.User.Params != nil {
// for k, v := range hookRequest.User.Params {
// fmt.Printf("request user[%s]=%s\n", k, v)
// }
// }
// if hookRequest.Session != nil && hookRequest.Session.Params != nil {
// for k, v := range hookRequest.Session.Params {
// fmt.Printf("request session[%s]=%s\n", k, v)
// }
// }
if !hookRequest.Verified() {
verificationRequired(ctx, hookRequest, hookResponse)
} else {
cookie := hookRequest.UserParam(UserParamCookie)
if cookie == "" {
if hookRequest.IntentName() == IntentAuth {
// try to authenticate
authNext(ctx, hookRequest, hookResponse)
} else {
authRequired(ctx, hookRequest, hookResponse)
}
} else {
user, _ := authCheck(ctx, hookRequest, hookResponse, cookie)
if user == nil {
authRequired(ctx, hookRequest, hookResponse)
} else {
fulfillIntent(ctx, user, w, hookRequest, hookResponse)
}
}
}
// fmt.Printf("sending %+v\n", hookResponse)
// if hookResponse.User != nil && hookResponse.User.Params != nil {
// for k, v := range hookResponse.User.Params {
// fmt.Printf("response user[%s]=%s\n", k, v)
// }
// }
// if hookResponse.Session != nil && hookResponse.Session.Params != nil {
// for k, v := range hookResponse.Session.Params {
// fmt.Printf("response session[%s]=%s\n", k, v)
// }
// }
hookResponse.Send(w)
}
func fulfillIntent(ctx Context, user *auth.User, resp http.ResponseWriter,
r *actions.WebhookRequest, w *actions.WebhookResponse) {
ctx, err := upgradeContext(ctx, user)
if err != nil {
serverErr(resp, err)
return
}
switch r.IntentName() {
case IntentPlay:
fulfillPlay(ctx, r, w)
case IntentNew:
fulfillNew(ctx, r, w)
default:
fulfillWelcome(ctx, r, w)
}
}
func releaseLike(m *music.Music, release string) []music.Track {
var tracks []music.Track
releases := m.ReleasesLike("%" + release + "%")
if len(releases) > 0 {
r := releases[0]
tracks = m.ReleaseTracks(r)
}
return tracks
}
func fulfillPlay(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
var tracks []music.Track
m := ctx.Music()
config := ctx.Config()
song := r.SongParam()
artist := r.ArtistParam()
release := r.ReleaseParam()
radio := r.RadioParam()
popular := r.PopularParam()
latest := r.LatestParam()
any := r.AnyParam()
query := ""
if artist != "" {
a := m.ArtistLike(artist)
if a != nil {
v := view.ArtistView(ctx, *a)
if radio != "" {
// play [artist] radio
tracks = v.Radio.Tracks()
} else if popular != "" {
// play popular songs by [artist]
tracks = v.Popular.Tracks()
} else if latest != "" {
// play the new [artist]
// play the latest [artist]
// play the latest by/from [artist]
releases := v.Releases
if len(releases) > 0 {
r := releases[len(releases)-1]
tracks = m.ReleaseTracks(r)
}
} else if song != "" {
// play [song] by [artist]
query = fmt.Sprintf(`+artist:"%s" +title:"%s*"`, artist, song)
} else if release != "" {
// play album [release] by [artist]
// first try to find a fuzzy match
releases := m.ArtistReleases(a)
for _, r := range releases {
if music.FuzzyName(r.Name) == music.FuzzyName(release) {
tracks = m.ReleaseTracks(r)
break
}
}
// fallback to search
if len(tracks) == 0 {
query = fmt.Sprintf(`+artist:"%s" +release:"%s"`, artist, release)
}
} else {
// play [artist] songs
// play songs by [artist]
query = fmt.Sprintf(`+artist:"%s" +type:"single"`, artist)
}
}
} else if song != "" {
// play song [song]
query = fmt.Sprintf(`+title:"%s*"`, song)
} else if release != "" {
// play album [release]
tracks = releaseLike(m, release)
if len(tracks) == 0 {
query = fmt.Sprintf(`+release:"%s*"`, release)
}
} else if any != "" {
// play [any]
a := m.ArtistLike(any)
if a != nil {
v := view.ArtistView(ctx, *a)
tracks = v.Popular.Tracks()
}
if len(tracks) == 0 {
tracks = releaseLike(m, any)
}
if len(tracks) == 0 {
query = fmt.Sprintf(`+title:"%s*"`, any)
}
}
if query != "" {
tracks = m.Search(query, config.Assistant.TrackLimit)
}
if len(tracks) > 0 {
addSimple(w, config.Assistant.Play)
for _, t := range tracks {
name := config.Assistant.MediaObjectName.Execute(t)
desc := config.Assistant.MediaObjectDesc.Execute(t)
w.AddMedia(name, desc,
m.TrackURL(&t).String(),
m.TrackImage(t).String())
}
} else {
addSimple(w, config.Assistant.Error)
}
}
func fulfillNew(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
home := view.HomeView(ctx)
config := ctx.Config()
speech := config.Assistant.Recent.Speech.Text
text := config.Assistant.Recent.Text.Text
for i, rel := range home.AddedReleases {
if i == config.Assistant.RecentLimit {
break
} else if i > 0 {
speech += " and " // TODO
text += ", "
}
speech += config.Assistant.Release.Speech.Execute(rel)
text += config.Assistant.Release.Speech.Execute(rel)
}
w.AddSimple(speech, text)
}
func fulfillWelcome(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
config := ctx.Config()
addSimple(w, config.Assistant.Welcome)
w.AddSuggestions(config.Assistant.SuggestionNew)
}
func addSimple(w *actions.WebhookResponse, m config.AssistantResponse) {
w.AddSimple(m.Speech.Text, m.Text.Text)
}
func addSimpleTemplate(w *actions.WebhookResponse, m config.AssistantResponse, vars interface{}) {
w.AddSimple(m.Speech.Execute(vars), m.Text.Execute(vars))
}
func authRequired(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
code := ctx.Auth().GenerateCode()
config := ctx.Config()
vars := map[string]string{"Code": code.Value}
addSimpleTemplate(w, config.Assistant.Link, vars)
w.AddSuggestions(config.Assistant.SuggestionAuth)
w.AddSessionParam("code", code.Value)
}
func authNext(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
ok := true
value := r.SessionParam("code")
if value == "" {
ok = false
}
code := ctx.Auth().LinkedCode(value)
if code == nil {
ok = false
}
if !ok {
authRequired(ctx, r, w)
return
}
w.AddUserParam(UserParamCookie, code.Token)
addSimple(w, ctx.Config().Assistant.Linked)
w.AddSuggestions("Talk to Takeout")
}
func authCheck(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse,
cookie string) (*auth.User, error) {
a := ctx.Auth()
session := a.TokenSession(cookie)
if session == nil {
return nil, ErrUnauthorized
} else if session.Expired() {
a.DeleteSession(*session)
return nil, ErrUnauthorized
}
user, err := a.SessionUser(session)
if err != nil {
a.DeleteSession(*session)
return nil, ErrUnauthorized
}
a.Refresh(session) // TODO remove
return user, nil
}
func verificationRequired(ctx Context, r *actions.WebhookRequest, w *actions.WebhookResponse) {
addSimple(w, ctx.Config().Assistant.Guest)
}