| 1 | package slacktest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io/ioutil" |
| 8 | "log" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "time" |
| 12 | |
| 13 | websocket "github.com/gorilla/websocket" |
| 14 | |
| 15 | slack "github.com/slack-go/slack" |
| 16 | ) |
| 17 | |
| 18 | func contextHandler(server *Server, next http.HandlerFunc) http.Handler { |
| 19 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 20 | ctx := context.WithValue(r.Context(), ServerURLContextKey, server.GetAPIURL()) |
| 21 | ctx = context.WithValue(ctx, ServerWSContextKey, server.GetWSURL()) |
| 22 | ctx = context.WithValue(ctx, ServerBotNameContextKey, server.BotName) |
| 23 | ctx = context.WithValue(ctx, ServerBotChannelsContextKey, server.GetChannels()) |
| 24 | ctx = context.WithValue(ctx, ServerBotGroupsContextKey, server.GetGroups()) |
| 25 | ctx = context.WithValue(ctx, ServerBotHubNameContextKey, server.ServerAddr) |
| 26 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 27 | }) |
| 28 | } |
| 29 | |
| 30 | // handle auth.test |
| 31 | func authTestHandler(w http.ResponseWriter, _ *http.Request) { |
| 32 | _, _ = w.Write([]byte(defaultAuthTestJSON)) |
| 33 | } |
| 34 | |
| 35 | func usersInfoHandler(w http.ResponseWriter, _ *http.Request) { |
| 36 | _, _ = w.Write([]byte(defaultUsersInfoJSON)) |
| 37 | } |
| 38 | |
| 39 | func botsInfoHandler(w http.ResponseWriter, r *http.Request) { |
| 40 | _, _ = w.Write([]byte(defaultBotInfoJSON(r.Context()))) |
| 41 | } |
| 42 | |
| 43 | type GroupConversationResponse struct { |
| 44 | Ok bool `json:"ok"` |
| 45 | Channel slack.GroupConversation `json:"channel"` |
| 46 | } |
| 47 | |
| 48 | func (sts *Server) conversationsInfoHandler(w http.ResponseWriter, r *http.Request) { |
| 49 | data, err := ioutil.ReadAll(r.Body) |
| 50 | if err != nil { |
| 51 | msg := fmt.Sprintf("error reading body: %s", err.Error()) |
| 52 | log.Printf(msg) |
| 53 | http.Error(w, msg, http.StatusInternalServerError) |
| 54 | return |
| 55 | } |
| 56 | values, vErr := url.ParseQuery(string(data)) |
| 57 | if vErr != nil { |
| 58 | msg := fmt.Sprintf("Unable to decode query params: %s", vErr.Error()) |
| 59 | log.Printf(msg) |
| 60 | http.Error(w, msg, http.StatusInternalServerError) |
| 61 | return |
| 62 | } |
| 63 | ch := values.Get("channel") |
| 64 | |
| 65 | response := GroupConversationResponse{ |
| 66 | Ok: true, |
| 67 | Channel: slack.GroupConversation{ |
| 68 | Conversation: slack.Conversation{ |
| 69 | ID: ch, |
| 70 | }, |
| 71 | // Since we don't join channels by name, only ID, let's strip the C prefix and use that as the name. |
| 72 | Name: ch[1:], |
| 73 | }, |
| 74 | } |
| 75 | encoded, err := json.Marshal(&response) |
| 76 | if err != nil { |
| 77 | msg := fmt.Sprintf("Unable to encode response: %s", err.Error()) |
| 78 | log.Printf(msg) |
| 79 | http.Error(w, msg, http.StatusInternalServerError) |
| 80 | return |
| 81 | } |
| 82 | |
| 83 | _, _ = w.Write(encoded) |
| 84 | } |
| 85 | |
| 86 | // handle conversations.create |
| 87 | func createConversationHandler(w http.ResponseWriter, r *http.Request) { |
| 88 | _, _ = w.Write([]byte(defaultConversationJSON)) |
| 89 | } |
| 90 | |
| 91 | // handle conversations.setTopic |
| 92 | func setConversationTopicHandler(w http.ResponseWriter, r *http.Request) { |
| 93 | _, _ = w.Write([]byte(conversionPurposeTopicJSON)) |
| 94 | } |
| 95 | |
| 96 | // handle conversations.setPurpose |
| 97 | func setConversationPurposeHandler(w http.ResponseWriter, r *http.Request) { |
| 98 | _, _ = w.Write([]byte(conversionPurposeTopicJSON)) |
| 99 | } |
| 100 | |
| 101 | // handle conversations.rename |
| 102 | func renameConversationHandler(w http.ResponseWriter, r *http.Request) { |
| 103 | _, _ = w.Write([]byte(renameConversationJSON)) |
| 104 | } |
| 105 | |
| 106 | // handle conversations.invite |
| 107 | func inviteConversationHandler(w http.ResponseWriter, r *http.Request) { |
| 108 | _, _ = w.Write([]byte(inviteConversationJSON)) |
| 109 | } |
| 110 | |
| 111 | // handle groups.list |
| 112 | func listGroupsHandler(w http.ResponseWriter, _ *http.Request) { |
| 113 | _, _ = w.Write([]byte(defaultGroupsListJSON)) |
| 114 | } |
| 115 | |
| 116 | // handle reaction.Add |
| 117 | func reactionAddHandler(w http.ResponseWriter, _ *http.Request) { |
| 118 | _, _ = w.Write([]byte(defaultOkJSON)) |
| 119 | } |
| 120 | |
| 121 | // handle chat.postMessage |
| 122 | func (sts *Server) postMessageHandler(w http.ResponseWriter, r *http.Request) { |
| 123 | serverAddr := r.Context().Value(ServerBotHubNameContextKey).(string) |
| 124 | data, err := ioutil.ReadAll(r.Body) |
| 125 | if err != nil { |
| 126 | msg := fmt.Sprintf("error reading body: %s", err.Error()) |
| 127 | log.Printf(msg) |
| 128 | http.Error(w, msg, http.StatusInternalServerError) |
| 129 | return |
| 130 | } |
| 131 | values, vErr := url.ParseQuery(string(data)) |
| 132 | if vErr != nil { |
| 133 | msg := fmt.Sprintf("Unable to decode query params: %s", vErr.Error()) |
| 134 | log.Printf(msg) |
| 135 | http.Error(w, msg, http.StatusInternalServerError) |
| 136 | return |
| 137 | } |
| 138 | |
| 139 | ts := time.Now().Unix() |
| 140 | resp := &struct { |
| 141 | Ok bool `json:"ok"` |
| 142 | Channel string `json:"channel"` |
| 143 | Ts string `json:"ts"` |
| 144 | Text string `json:"text"` |
| 145 | }{ |
| 146 | Ok: true, |
| 147 | Channel: values.Get("channel"), |
| 148 | Ts: fmt.Sprintf("%d", ts), |
| 149 | Text: values.Get("text"), |
| 150 | } |
| 151 | |
| 152 | m := slack.Message{} |
| 153 | m.Type = "message" |
| 154 | m.Channel = values.Get("channel") |
| 155 | m.Timestamp = fmt.Sprintf("%d", ts) |
| 156 | m.Text = values.Get("text") |
| 157 | m.ThreadTimestamp = values.Get("thread_ts") |
| 158 | if values.Get("as_user") != "true" { |
| 159 | m.User = defaultNonBotUserID |
| 160 | m.Username = defaultNonBotUserName |
| 161 | } else { |
| 162 | m.User = BotIDFromContext(r.Context()) |
| 163 | m.Username = BotNameFromContext(r.Context()) |
| 164 | } |
| 165 | attachments := values.Get("attachments") |
| 166 | if attachments != "" { |
| 167 | decoded, err := url.QueryUnescape(attachments) |
| 168 | if err != nil { |
| 169 | msg := fmt.Sprintf("Unable to decode attachments: %s", err.Error()) |
| 170 | log.Printf(msg) |
| 171 | http.Error(w, msg, http.StatusInternalServerError) |
| 172 | return |
| 173 | } |
| 174 | var attaches []slack.Attachment |
| 175 | aJErr := json.Unmarshal([]byte(decoded), &attaches) |
| 176 | if aJErr != nil { |
| 177 | msg := fmt.Sprintf("Unable to decode attachments string to json: %s", aJErr.Error()) |
| 178 | log.Printf(msg) |
| 179 | http.Error(w, msg, http.StatusInternalServerError) |
| 180 | return |
| 181 | } |
| 182 | m.Attachments = attaches |
| 183 | } |
| 184 | blocks := values.Get("blocks") |
| 185 | if blocks != "" { |
| 186 | decoded, err := url.QueryUnescape(blocks) |
| 187 | if err != nil { |
| 188 | msg := fmt.Sprintf("Unable to decode blocks: %s", err.Error()) |
| 189 | log.Printf(msg) |
| 190 | http.Error(w, msg, http.StatusInternalServerError) |
| 191 | return |
| 192 | } |
| 193 | var decodedBlocks slack.Blocks |
| 194 | dbJErr := json.Unmarshal([]byte(decoded), &decodedBlocks) |
| 195 | if dbJErr != nil { |
| 196 | msg := fmt.Sprintf("Unable to decode blocks string to json: %s", dbJErr.Error()) |
| 197 | log.Printf(msg) |
| 198 | http.Error(w, msg, http.StatusInternalServerError) |
| 199 | return |
| 200 | } |
| 201 | m.Blocks = decodedBlocks |
| 202 | } |
| 203 | jsonMessage, jsonErr := json.Marshal(m) |
| 204 | if jsonErr != nil { |
| 205 | msg := fmt.Sprintf("Unable to marshal message: %s", jsonErr.Error()) |
| 206 | log.Printf(msg) |
| 207 | http.Error(w, msg, http.StatusInternalServerError) |
| 208 | return |
| 209 | } |
| 210 | go sts.queueForWebsocket(string(jsonMessage), serverAddr) |
| 211 | _ = json.NewEncoder(w).Encode(resp) |
| 212 | } |
| 213 | |
| 214 | // RTMConnectHandler generates a valid connection |
| 215 | func RTMConnectHandler(w http.ResponseWriter, r *http.Request) { |
| 216 | _, err := ioutil.ReadAll(r.Body) |
| 217 | if err != nil { |
| 218 | msg := fmt.Sprintf("Error reading body: %s", err.Error()) |
| 219 | log.Printf(msg) |
| 220 | http.Error(w, msg, http.StatusInternalServerError) |
| 221 | return |
| 222 | } |
| 223 | wsurl := r.Context().Value(ServerWSContextKey).(string) |
| 224 | if wsurl == "" { |
| 225 | msg := "missing webservice url from context" |
| 226 | log.Printf(msg) |
| 227 | http.Error(w, msg, http.StatusInternalServerError) |
| 228 | return |
| 229 | } |
| 230 | |
| 231 | fullresponse := generateRTMInfo(r.Context(), wsurl) |
| 232 | j, jErr := json.Marshal(fullresponse) |
| 233 | if jErr != nil { |
| 234 | msg := fmt.Sprintf("Unable to marshal response: %s", jErr.Error()) |
| 235 | log.Printf("Error: %s", msg) |
| 236 | http.Error(w, msg, http.StatusInternalServerError) |
| 237 | return |
| 238 | } |
| 239 | _, wErr := w.Write(j) |
| 240 | if wErr != nil { |
| 241 | log.Printf("Error writing response: %s", wErr.Error()) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | func rtmStartHandler(w http.ResponseWriter, r *http.Request) { |
| 246 | _, err := ioutil.ReadAll(r.Body) |
| 247 | if err != nil { |
| 248 | msg := fmt.Sprintf("Error reading body: %s", err.Error()) |
| 249 | log.Printf(msg) |
| 250 | http.Error(w, msg, http.StatusInternalServerError) |
| 251 | return |
| 252 | } |
| 253 | wsurl := r.Context().Value(ServerWSContextKey).(string) |
| 254 | if wsurl == "" { |
| 255 | msg := "missing webservice url from context" |
| 256 | log.Printf(msg) |
| 257 | http.Error(w, msg, http.StatusInternalServerError) |
| 258 | return |
| 259 | } |
| 260 | |
| 261 | fullresponse := generateRTMInfo(r.Context(), wsurl) |
| 262 | j, jErr := json.Marshal(fullresponse) |
| 263 | if jErr != nil { |
| 264 | msg := fmt.Sprintf("Unable to marshal response: %s", jErr.Error()) |
| 265 | log.Printf("Error: %s", msg) |
| 266 | http.Error(w, msg, http.StatusInternalServerError) |
| 267 | return |
| 268 | } |
| 269 | _, wErr := w.Write(j) |
| 270 | if wErr != nil { |
| 271 | log.Printf("Error writing response: %s", wErr.Error()) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func (sts *Server) wsHandler(w http.ResponseWriter, r *http.Request) { |
| 276 | Websocket(func(c *websocket.Conn) { |
| 277 | serverAddr := r.Context().Value(ServerBotHubNameContextKey).(string) |
| 278 | go handlePendingMessages(c, serverAddr) |
| 279 | for { |
| 280 | var ( |
| 281 | err error |
| 282 | m json.RawMessage |
| 283 | mtype string |
| 284 | ) |
| 285 | |
| 286 | if mtype, m, err = RTMRespEventType(c); err != nil { |
| 287 | if websocket.IsUnexpectedCloseError(err) { |
| 288 | return |
| 289 | } |
| 290 | |
| 291 | log.Printf("read error: %s", err.Error()) |
| 292 | continue |
| 293 | } |
| 294 | |
| 295 | switch mtype { |
| 296 | case "ping": |
| 297 | if err = RTMRespPong(c, m); err != nil { |
| 298 | log.Println("ping error:", err) |
| 299 | } |
| 300 | default: |
| 301 | sts.postProcessMessage(string(m), serverAddr) |
| 302 | } |
| 303 | } |
| 304 | })(w, r) |
| 305 | } |
| 306 | |
| 307 | // Websocket handler |
| 308 | func Websocket(delegate func(c *websocket.Conn)) func(w http.ResponseWriter, r *http.Request) { |
| 309 | return func(w http.ResponseWriter, r *http.Request) { |
| 310 | upgrader := websocket.Upgrader{ |
| 311 | ReadBufferSize: 1024, |
| 312 | WriteBufferSize: 1024, |
| 313 | CheckOrigin: func(r *http.Request) bool { |
| 314 | return true |
| 315 | }, |
| 316 | } |
| 317 | c, err := upgrader.Upgrade(w, r, nil) |
| 318 | if err != nil { |
| 319 | msg := fmt.Sprintf("Unable to upgrade to ws connection: %s", err.Error()) |
| 320 | log.Print(msg) |
| 321 | http.Error(w, msg, http.StatusInternalServerError) |
| 322 | return |
| 323 | } |
| 324 | defer func() { _ = c.Close() }() |
| 325 | delegate(c) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // RTMServerSendGoodbye send a goodbye event |
| 330 | func RTMServerSendGoodbye(c *websocket.Conn) error { |
| 331 | return c.WriteJSON(slack.Event{Type: "goodbye"}) |
| 332 | } |
| 333 | |
| 334 | // RTMRespEventType retrieve the event type from the next message |
| 335 | func RTMRespEventType(c *websocket.Conn) (t string, m json.RawMessage, err error) { |
| 336 | var ( |
| 337 | evt slack.Event |
| 338 | ) |
| 339 | |
| 340 | if err = c.ReadJSON(&m); err != nil { |
| 341 | return "", m, err |
| 342 | } |
| 343 | |
| 344 | if err = json.Unmarshal(m, &evt); err != nil { |
| 345 | return "", m, err |
| 346 | } |
| 347 | |
| 348 | return evt.Type, m, nil |
| 349 | } |
| 350 | |
| 351 | // RTMRespPong decode a ping and respond with a pong event. |
| 352 | func RTMRespPong(c *websocket.Conn, m json.RawMessage) (err error) { |
| 353 | var ( |
| 354 | ping slack.Ping |
| 355 | pong slack.Pong |
| 356 | ) |
| 357 | |
| 358 | if err = json.Unmarshal(m, &ping); err != nil { |
| 359 | return err |
| 360 | } |
| 361 | |
| 362 | pong = slack.Pong{ |
| 363 | Type: "pong", |
| 364 | ReplyTo: ping.ID, |
| 365 | } |
| 366 | |
| 367 | if err = c.WriteJSON(pong); err != nil { |
| 368 | return err |
| 369 | } |
| 370 | |
| 371 | return nil |
| 372 | } |