-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
222 lines (188 loc) · 5.3 KB
/
handler.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/chiefy/go-slack-utils/pkg/blockui"
"github.com/chiefy/go-slack-utils/pkg/payload"
tmdb "github.com/ryanbradynd05/go-tmdb"
)
const (
// TmdbAPIKey is the env var name containing the TMDB API key
TmdbAPIKeyEnv = "TMDB_API_KEY"
tmdbImageURLBase = "https://image.tmdb.org/t/p"
tmdbImageSmall = "w92"
tmdbImageLarge = "w342"
numResults = 5
// OmdbAPIKeyEnv is the env var name containing the OMDB API key
OmdbAPIKeyEnv = "OMDB_API_KEY"
omdbURLBase = "http://www.omdbapi.com/"
)
var (
tmdbAPI *tmdb.TMDb
omdbAPIKey string
)
func init() {
k := os.Getenv(TmdbAPIKeyEnv)
if k == "" {
log.Fatalf("no env var found for %s", TmdbAPIKeyEnv)
}
config := tmdb.Config{
APIKey: k,
Proxies: nil,
UseProxy: false,
}
tmdbAPI = tmdb.Init(config)
omdbAPIKey = os.Getenv(OmdbAPIKeyEnv)
if omdbAPIKey == "" {
log.Fatalf("no env var found for %s", OmdbAPIKeyEnv)
}
}
func GetOMDBInfo(imdbID string) (string, string, error) {
url := fmt.Sprintf("%s?apikey=%s&tomatoes=true&i=%s", omdbURLBase, omdbAPIKey, imdbID)
c := &http.Client{}
res, err := c.Get(url)
if err != nil {
return "", "", err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return "", "", err
}
var rt map[string]interface{}
if err := json.Unmarshal(body, &rt); err != nil {
return "", "", err
}
return rt["Metascore"].(string), rt["imdbRating"].(string), nil
}
// MovieLookupHandler looks up specific movie info on TMDB and creates blocks
func MovieLookupHandler(w http.ResponseWriter, r *http.Request) {
// Send back empty 200 right away so Slack doesn't hit the 3000ms timeout
w.WriteHeader(http.StatusOK)
w.Write(nil)
log.Println("sent back initial 200 response")
r.ParseForm()
action := &payload.BlockActionsPayload{}
p := r.Form.Get("payload")
err := json.Unmarshal([]byte(p), &action)
if err != nil {
log.Printf("ERROR: error decoding JSON from payload - %s", err)
return
}
id, err := strconv.Atoi(action.Actions[0].GetValue())
if err != nil {
log.Printf("ERROR: error converting movie ID from string: %s, %s", action.Actions[0].GetValue(), err)
return
}
movie, err := tmdbAPI.GetMovieInfo(id, map[string]string{})
if err != nil {
log.Printf("ERROR: error looking up movie ID - %s", err)
return
}
metascore, imdbRating, err := GetOMDBInfo(movie.ImdbID)
if err != nil {
log.Printf("ERROR: error looking up movie ID - %s", err)
return
}
sm := payload.NewMessagePayload("in_channel")
ib := blockui.NewBlockImage(
fmt.Sprintf("%s/%s/%s", tmdbImageURLBase, tmdbImageLarge, movie.PosterPath),
movie.Title,
)
tb := blockui.NewBlockSection()
tb.SetText(
"mrkdwn",
makeMovieMarkdown(movie, metascore, imdbRating),
)
sm.AddBlock(tb)
sm.AddBlock(ib)
j, err := json.Marshal(sm)
if err != nil {
log.Printf("ERROR: error marshalling json %s", err)
return
}
c := &http.Client{}
url := action.ResponseURL
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(j))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", action.Token))
_, err = c.Do(req)
if err != nil {
log.Printf("ERROR: error sending response %s", err)
return
}
log.Println("done with lookup, sent response to ", url)
}
// MovieSearchHandler handles the slack slash command POST request
func MovieSearchHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
movieStr := r.FormValue("text")
log.Printf("Got request to moviehandler for %s", movieStr)
res, err := tmdbAPI.SearchMovie(movieStr, map[string]string{})
if err != nil {
log.Println(err)
http.Error(w, "movie lookup error", http.StatusInternalServerError)
return
}
sm := payload.NewMessagePayload("ephemeral")
sel := blockui.NewBlockSelect()
for i, m := range res.Results {
y := strings.Split(m.ReleaseDate, "-")
opt := &blockui.BlockOption{
Text: &blockui.BlockTitleText{
Type: "plain_text",
Text: fmt.Sprintf("%s (%s)", m.Title, y[0]),
Emoji: false,
},
Value: strconv.Itoa(m.ID),
}
sel.AddOption(opt)
if i >= numResults-1 {
break
}
}
mb := blockui.NewBlockSectionWithSelect(sel)
mb.SetText(
"mrkdwn",
fmt.Sprintf("Found %d results for *\"%s\"*:", len(res.Results), movieStr),
)
sm.AddBlock(mb)
j, err := json.Marshal(sm)
if err != nil {
log.Printf("error marshalling json %s", err)
http.Error(w, "JSON Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
func reverseSlice(a []string) []string {
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
return a
}
func formatMoney(m uint32) string {
d := strconv.Itoa(int(m))
dSplit := reverseSlice(strings.Split(d, ""))
f := []string{}
for i, v := range dSplit {
if i%3 == 0 && i != 0 {
f = append(f, ",")
}
f = append(f, v)
}
return strings.Join(reverseSlice(f), "")
}
func makeMovieMarkdown(movie *tmdb.Movie, metascore string, imdbRating string) string {
l := fmt.Sprintf("<https://www.imdb.com/title/%s|IMDB>", movie.ImdbID)
return fmt.Sprintf("*%s*\nRelease Date: %s\nBudget: $%s | Runtime: %dm\n Metascore: %s | IMDB Rating: %s\n>%s\n\n%s",
movie.Title, movie.ReleaseDate, formatMoney(movie.Budget), movie.Runtime, metascore, imdbRating, movie.Overview, l)
}