feat(channels): align whatsapp calls api
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
@@ -19,6 +24,136 @@ func NewWhatsAppCallHandler(svc *service.WhatsAppCallService) *WhatsAppCallHandl
|
||||
return &WhatsAppCallHandler{svc: svc}
|
||||
}
|
||||
|
||||
// Show returns a Chatwoot WhatsApp call payload.
|
||||
// GET /api/v1/accounts/:account_id/whatsapp_calls/:call_id
|
||||
func (h *WhatsAppCallHandler) Show(c *gin.Context) {
|
||||
accountID, callID, ok := h.parseAccountCallParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
call, err := h.svc.GetAccountCall(c.Request.Context(), accountID, callID)
|
||||
if err != nil {
|
||||
handleServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, serializeWhatsAppAccountCall(call))
|
||||
}
|
||||
|
||||
// Initiate starts an outbound WhatsApp call for a display-ID conversation.
|
||||
// POST /api/v1/accounts/:account_id/whatsapp_calls/initiate
|
||||
func (h *WhatsAppCallHandler) Initiate(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ConversationID uint `json:"conversation_id" binding:"required"`
|
||||
SDPOffer string `json:"sdp_offer"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
result, err := h.svc.Initiate(c.Request.Context(), accountID, service.WhatsAppCallInitiateRequest{
|
||||
ConversationID: req.ConversationID,
|
||||
SDPOffer: req.SDPOffer,
|
||||
AgentID: getUserID(c),
|
||||
})
|
||||
if err != nil {
|
||||
handleWhatsAppCallError(c, err)
|
||||
return
|
||||
}
|
||||
if result.PermissionStatus != "" {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"status": result.PermissionStatus})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "calling", "call_id": result.Call.ProviderCallID})
|
||||
}
|
||||
|
||||
// Accept forwards an SDP answer to Meta and returns the updated call payload.
|
||||
// POST /api/v1/accounts/:account_id/whatsapp_calls/:call_id/accept
|
||||
func (h *WhatsAppCallHandler) Accept(c *gin.Context) {
|
||||
accountID, callID, ok := h.parseAccountCallParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
SDPAnswer string `json:"sdp_answer"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
call, err := h.svc.Accept(c.Request.Context(), accountID, callID, getUserID(c), req.SDPAnswer)
|
||||
if err != nil {
|
||||
handleWhatsAppCallError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, serializeWhatsAppAccountCall(call))
|
||||
}
|
||||
|
||||
// Reject rejects a ringing WhatsApp call.
|
||||
// POST /api/v1/accounts/:account_id/whatsapp_calls/:call_id/reject
|
||||
func (h *WhatsAppCallHandler) Reject(c *gin.Context) {
|
||||
accountID, callID, ok := h.parseAccountCallParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
call, err := h.svc.Reject(c.Request.Context(), accountID, callID, getUserID(c))
|
||||
if err != nil {
|
||||
handleWhatsAppCallError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"id": call.ID, "status": displayWhatsAppStatus(call.Status)})
|
||||
}
|
||||
|
||||
// Terminate terminates an active or ringing WhatsApp call.
|
||||
// POST /api/v1/accounts/:account_id/whatsapp_calls/:call_id/terminate
|
||||
func (h *WhatsAppCallHandler) Terminate(c *gin.Context) {
|
||||
accountID, callID, ok := h.parseAccountCallParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
call, err := h.svc.Terminate(c.Request.Context(), accountID, callID, getUserID(c))
|
||||
if err != nil {
|
||||
handleWhatsAppCallError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"id": call.ID, "status": displayWhatsAppStatus(call.Status)})
|
||||
}
|
||||
|
||||
// UploadRecording attaches an audio recording to the linked voice_call message.
|
||||
// POST /api/v1/accounts/:account_id/whatsapp_calls/:call_id/upload_recording
|
||||
func (h *WhatsAppCallHandler) UploadRecording(c *gin.Context) {
|
||||
accountID, callID, ok := h.parseAccountCallParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
file, err := c.FormFile("recording")
|
||||
if err != nil {
|
||||
handleWhatsAppCallError(c, service.ErrWhatsAppCallNoRecording)
|
||||
return
|
||||
}
|
||||
status, svcErr := h.svc.UploadRecording(c.Request.Context(), accountID, callID, file.Filename, file.Size)
|
||||
if svcErr != nil {
|
||||
handleWhatsAppCallError(c, svcErr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": status})
|
||||
}
|
||||
|
||||
func (h *WhatsAppCallHandler) parseAccountCallParams(c *gin.Context) (uint, uint, bool) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return 0, 0, false
|
||||
}
|
||||
callID, err := parseUintParam(c, "call_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid call id")
|
||||
return 0, 0, false
|
||||
}
|
||||
return accountID, callID, true
|
||||
}
|
||||
|
||||
// Get retrieves a WhatsApp call by call_id.
|
||||
// GET /api/v1/accounts/:account_id/conversations/:conversation_id/whatsapp_calls/:call_id
|
||||
func (h *WhatsAppCallHandler) Get(c *gin.Context) {
|
||||
@@ -137,4 +272,75 @@ func (h *WhatsAppCallHandler) Delete(c *gin.Context) {
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "deleted"})
|
||||
}
|
||||
}
|
||||
|
||||
func handleWhatsAppCallError(c *gin.Context, err error) {
|
||||
status := http.StatusUnprocessableEntity
|
||||
if errors.Is(err, service.ErrWhatsAppCallSDPOfferRequired) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallSDPAnswerRequired) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallContactPhoneRequired) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallNotEnabled) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallNoRecording) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallNoMessage) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallPermissionRequestFailed) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallAlreadyAccepted) ||
|
||||
errors.Is(err, service.ErrWhatsAppCallNotRinging) {
|
||||
c.JSON(status, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
handleServiceError(c, err)
|
||||
}
|
||||
|
||||
func serializeWhatsAppAccountCall(call *model.Call) gin.H {
|
||||
if call == nil {
|
||||
return gin.H{}
|
||||
}
|
||||
attrs := map[string]any{}
|
||||
if len(call.AdditionalAttributes) > 0 {
|
||||
_ = json.Unmarshal(call.AdditionalAttributes, &attrs)
|
||||
}
|
||||
elapsed := 0
|
||||
if call.StartedAt != nil {
|
||||
elapsed = int(time.Since(*call.StartedAt).Seconds())
|
||||
}
|
||||
caller := gin.H{}
|
||||
if call.Contact.ID != 0 {
|
||||
caller = gin.H{"name": call.Contact.Name, "phone": call.Contact.PhoneNumber, "avatar": call.Contact.AvatarURL}
|
||||
}
|
||||
return gin.H{
|
||||
"id": call.ID,
|
||||
"call_id": call.ProviderCallID,
|
||||
"provider": call.Provider,
|
||||
"status": displayWhatsAppStatus(call.Status),
|
||||
"direction": displayWhatsAppDirection(call.Direction),
|
||||
"conversation_id": call.ConversationID,
|
||||
"inbox_id": call.InboxID,
|
||||
"message_id": call.MessageID,
|
||||
"accepted_by_agent_id": call.AcceptedByAgentID,
|
||||
"elapsed_seconds": elapsed,
|
||||
"sdp_offer": attrs["sdp_offer"],
|
||||
"ice_servers": firstNonNilWhatsAppValue(attrs["ice_servers"], []map[string][]string{{"urls": []string{"stun:stun.l.google.com:19302"}}}),
|
||||
"caller": caller,
|
||||
}
|
||||
}
|
||||
|
||||
func displayWhatsAppStatus(status string) string {
|
||||
return strings.ReplaceAll(status, "_", "-")
|
||||
}
|
||||
|
||||
func displayWhatsAppDirection(direction string) string {
|
||||
if direction == "incoming" {
|
||||
return "inbound"
|
||||
}
|
||||
if direction == "outgoing" {
|
||||
return "outbound"
|
||||
}
|
||||
return direction
|
||||
}
|
||||
|
||||
func firstNonNilWhatsAppValue(value any, fallback any) any {
|
||||
if value == nil {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
)
|
||||
|
||||
type fakeHandlerWhatsAppCallProvider struct{}
|
||||
|
||||
func (fakeHandlerWhatsAppCallProvider) InitiateCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) {
|
||||
return "wacid_handler", nil
|
||||
}
|
||||
func (fakeHandlerWhatsAppCallProvider) PreAcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeHandlerWhatsAppCallProvider) AcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeHandlerWhatsAppCallProvider) RejectCall(context.Context, *channelmodel.ChannelWhatsApp, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeHandlerWhatsAppCallProvider) TerminateCall(context.Context, *channelmodel.ChannelWhatsApp, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeHandlerWhatsAppCallProvider) SendCallPermissionRequest(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) {
|
||||
return "wamid.req", nil
|
||||
}
|
||||
|
||||
func setupWhatsAppCallHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Conversation) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Call{}, &model.Message{}, &model.Attachment{}, &channelmodel.ChannelWhatsApp{}))
|
||||
|
||||
account := &model.Account{Name: "Voice Account", Status: "active"}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "WhatsApp", ChannelType: "whatsapp", ChannelID: 1, ChannelConfig: `{"voice_enabled":true}`}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
channel := &channelmodel.ChannelWhatsApp{AccountID: account.ID, InboxID: inbox.ID, PhoneNumber: "+15550000000", PhoneNumberID: "phone-1", BusinessAccountID: "waba-1", AccessToken: "token", Provider: "whatsapp_cloud", ProviderConfig: `{"calling_enabled":true}`}
|
||||
require.NoError(t, db.Create(channel).Error)
|
||||
inbox.ChannelID = channel.ID
|
||||
require.NoError(t, db.Save(inbox).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Ada", PhoneNumber: "+15551234567"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
displayID := uint(42)
|
||||
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "open", ChannelType: "whatsapp", Channel: "whatsapp"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
|
||||
handler := NewWhatsAppCallHandler(service.NewWhatsAppCallService(repository.NewWhatsAppCallRepo(db), fakeHandlerWhatsAppCallProvider{}))
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("user_id", uint(7))
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/api/v1/accounts/:account_id/whatsapp_calls/:call_id", handler.Show)
|
||||
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/initiate", handler.Initiate)
|
||||
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:call_id/accept", handler.Accept)
|
||||
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:call_id/reject", handler.Reject)
|
||||
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:call_id/terminate", handler.Terminate)
|
||||
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:call_id/upload_recording", handler.UploadRecording)
|
||||
return router, db, account, conversation
|
||||
}
|
||||
|
||||
func TestWhatsAppCallHandler_AccountRoutesMatchFrontendAPI(t *testing.T) {
|
||||
router, db, account, conversation := setupWhatsAppCallHandlerTest(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
body := []byte(`{"conversation_id":42,"sdp_offer":"sdp_offer"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/initiate", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
resp := whatsappDecodeMap(t, w.Body.Bytes())
|
||||
require.Equal(t, "calling", resp["status"])
|
||||
require.Equal(t, "wacid_handler", resp["call_id"])
|
||||
|
||||
var call model.Call
|
||||
require.NoError(t, db.Where("account_id = ? AND conversation_id = ?", account.ID, conversation.ID).First(&call).Error)
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID), nil)
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
show := whatsappDecodeMap(t, w.Body.Bytes())
|
||||
require.Equal(t, "wacid_handler", show["call_id"])
|
||||
require.Equal(t, "whatsapp", show["provider"])
|
||||
}
|
||||
|
||||
func TestWhatsAppCallHandler_ActionsAndRecordingPayloads(t *testing.T) {
|
||||
router, db, account, conversation := setupWhatsAppCallHandlerTest(t)
|
||||
call := &model.Call{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContactID: conversation.ContactID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "wacid_in", Status: "ringing", CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound"}
|
||||
require.NoError(t, db.Create(call).Error)
|
||||
message := &model.Message{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContentType: "voice_call", MessageType: "incoming"}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
require.NoError(t, db.Model(call).Update("message_id", message.ID).Error)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/accept", bytes.NewReader([]byte(`{"sdp_answer":"sdp_answer"}`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(t, "in-progress", whatsappDecodeMap(t, w.Body.Bytes())["status"])
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/terminate", nil)
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(t, "completed", whatsappDecodeMap(t, w.Body.Bytes())["status"])
|
||||
|
||||
var upload bytes.Buffer
|
||||
writer := multipart.NewWriter(&upload)
|
||||
part, err := writer.CreateFormFile("recording", "call.webm")
|
||||
require.NoError(t, err)
|
||||
_, err = part.Write([]byte("audio"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
w = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/upload_recording", &upload)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(t, "uploaded", whatsappDecodeMap(t, w.Body.Bytes())["status"])
|
||||
}
|
||||
|
||||
func whatsappDecodeMap(t *testing.T, body []byte) map[string]any {
|
||||
t.Helper()
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(body, &out))
|
||||
return out
|
||||
}
|
||||
|
||||
func whatsappItoaUint(id uint) string {
|
||||
return strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
Reference in New Issue
Block a user