Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Temba Chat #673

Merged
merged 4 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/courier/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import (
_ "github.com/nyaruka/courier/handlers/start"
_ "github.com/nyaruka/courier/handlers/telegram"
_ "github.com/nyaruka/courier/handlers/telesom"
_ "github.com/nyaruka/courier/handlers/tembachat"
_ "github.com/nyaruka/courier/handlers/thinq"
_ "github.com/nyaruka/courier/handlers/twiml"
_ "github.com/nyaruka/courier/handlers/twitter"
Expand Down
83 changes: 83 additions & 0 deletions handlers/tembachat/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package tembachat

import (
"bytes"
"context"
"net/http"

"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/urns"
)

var (
defaultSendURL = "http://chatserver:8070/send"
)

func init() {
courier.RegisterHandler(newHandler())
}

type handler struct {
handlers.BaseHandler
}

func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("TWC"), "Temba Chat")}
}

// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, handlers.JSONPayload(h, h.receiveMessage))
return nil
}

type receivePayload struct {
Type string `json:"type" validate:"required"`
Message struct {
Identifier string `json:"identifier" validate:"required"`
Text string `json:"text" validate:"required"`
} `json:"message"`
}

// receiveMessage is our HTTP handler function for incoming messages
func (h *handler) receiveMessage(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request, payload *receivePayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if payload.Type == "message" {
urn, err := urns.NewWebChatURN(payload.Message.Identifier)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, c, w, r, err)
}

msg := h.Backend().NewIncomingMsg(c, urn, payload.Message.Text, "", clog)
return handlers.WriteMsgsAndResponse(ctx, h, []courier.MsgIn{msg}, w, r, clog)
}
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, c, w, r, "")

Check warning on line 56 in handlers/tembachat/handler.go

View check run for this annotation

Codecov / codecov/patch

handlers/tembachat/handler.go#L56

Added line #L56 was not covered by tests
}

type sendPayload struct {
Identifier string `json:"identifier"`
Text string `json:"text"`
Origin string `json:"origin"`
}

func (h *handler) Send(ctx context.Context, msg courier.MsgOut, clog *courier.ChannelLog) (courier.StatusUpdate, error) {
sendURL := msg.Channel().StringConfigForKey(courier.ConfigSendURL, defaultSendURL)

payload := &sendPayload{
Identifier: msg.URN().Path(),
Text: msg.Text(),
Origin: string(msg.Origin()),
}
req, _ := http.NewRequest("POST", sendURL, bytes.NewReader(jsonx.MustMarshal(payload)))

status := h.Backend().NewStatusUpdate(msg.Channel(), msg.ID(), courier.MsgStatusWired, clog)

resp, _, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 != 2 {
status.SetStatus(courier.MsgStatusErrored)
}

return status, nil
}
77 changes: 77 additions & 0 deletions handlers/tembachat/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package tembachat

import (
"net/http/httptest"
"testing"

"github.com/nyaruka/courier"
. "github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/test"
)

var testChannels = []courier.Channel{
test.NewMockChannel("8eb23e93-5ecb-45ba-b726-3b064e0c56ab", "TWC", "", "", nil),
}

var handleTestCases = []IncomingTestCase{
{
Label: "Receive Valid Message",
URL: "/c/twc/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/receive",
Data: `{"type": "message", "message": {"identifier": "65vbbDAQCdPdEWlEhDGy4utO", "text": "Join"}}`,
ExpectedRespStatus: 200,
ExpectedBodyContains: "Accepted",
ExpectedMsgText: Sp("Join"),
ExpectedURN: "webchat:65vbbDAQCdPdEWlEhDGy4utO",
},
{
Label: "Invalid URN",
URL: "/c/twc/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/receive",
Data: `{"type": "message", "message": {"identifier": "xxxxx", "text": "Join"}}`,
ExpectedRespStatus: 400,
ExpectedBodyContains: "invalid webchat id: xxxxx",
},
{
Label: "Missing fields",
URL: "/c/twc/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/receive",
Data: `{"foo": "message"}`,
ExpectedRespStatus: 400,
ExpectedBodyContains: "Field validation for 'Type' failed on the 'required' tag",
},
}

func TestIncoming(t *testing.T) {
RunIncomingTestCases(t, testChannels, newHandler(), handleTestCases)
}

func setSendURL(s *httptest.Server, h courier.ChannelHandler, c courier.Channel, m courier.MsgOut) {
defaultSendURL = s.URL
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it i better to set the config send URL here and remove defaultSendURL

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just copying how other handlers are done but I did wonder if all handlers should support send_url in config and then this can be the normal way of overriding it in tests

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that could work too

}

var defaultSendTestCases = []OutgoingTestCase{
{
Label: "Plain Send",
MsgText: "Simple message ☺",
MsgURN: "webchat:65vbbDAQCdPdEWlEhDGy4utO",
MockResponseBody: `{"status": "queued"}`,
MockResponseStatus: 200,
ExpectedRequestBody: `{"identifier":"65vbbDAQCdPdEWlEhDGy4utO","text":"Simple message ☺","origin":"flow"}`,
ExpectedMsgStatus: "W",
SendPrep: setSendURL,
},
{
Label: "Error Sending",
MsgText: "Error message",
MsgURN: "webchat:65vbbDAQCdPdEWlEhDGy4utO",
MockResponseBody: `{"error": "boom"}`,
MockResponseStatus: 400,
ExpectedRequestBody: `{"identifier":"65vbbDAQCdPdEWlEhDGy4utO","text":"Error message","origin":"flow"}`,
ExpectedMsgStatus: "E",
SendPrep: setSendURL,
},
}

func TestOutgoing(t *testing.T) {
var defaultChannel = test.NewMockChannel("8eb23e93-5ecb-45ba-b726-3b064e0c56ab", "TWC", "", "", nil)

RunOutgoingTestCases(t, defaultChannel, newHandler(), defaultSendTestCases, nil, nil)
}
Loading