summaryrefslogtreecommitdiff
path: root/adapters/messaging/http_sms.go
blob: 8d1c99f92f7e2e16192b917054291c078735bd51 (plain)
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
package messaging

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"

	"git.simponic.xyz/simponic/phoneof/utils"
)

type HttpSmsMessageData struct {
	RequestId string `json:"request_id"`
}

type HttpSmsMessageSendResponse struct {
	Data HttpSmsMessageData `json:"data"`
}

func HttpSmsContinuation(apiToken string, fromPhoneNumber string, toPhoneNumber string, httpSmsEndpoint string) Continuation {
	return func(message Message) ContinuationChain {
		encodedMsg := fmt.Sprintf(`{"from":"%s","to":"%s","content":"%s"}`, fromPhoneNumber, toPhoneNumber, utils.Quote(message.Encode()))
		log.Println(encodedMsg)

		return func(success Continuation, failure Continuation) ContinuationChain {
			url := fmt.Sprintf("%s/v1/messages/send", httpSmsEndpoint)
			payload := strings.NewReader(encodedMsg)

			req, _ := http.NewRequest("POST", url, payload)
			req.Header.Add("x-api-key", apiToken)
			req.Header.Add("Content-Type", "application/json")
			res, err := http.DefaultClient.Do(req)
			if err != nil || res.StatusCode/100 != 2 {
				log.Printf("got err sending message send req %s %v %s", message, res, err)
				return failure(message)
			}

			defer res.Body.Close()
			body, _ := io.ReadAll(res.Body)

			var response HttpSmsMessageSendResponse
			err = json.Unmarshal(body, &response)
			if err != nil {
				log.Printf("got error unmarshaling response: %s %s", body, err)
				return failure(message)
			}

			return success(message)
		}
	}
}