feat(integrations): align dyte meeting routes
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
type DyteIntegrationHandler struct {
|
||||
svc *service.DyteIntegrationService
|
||||
}
|
||||
|
||||
func NewDyteIntegrationHandler(svc *service.DyteIntegrationService) *DyteIntegrationHandler {
|
||||
return &DyteIntegrationHandler{svc: svc}
|
||||
}
|
||||
|
||||
type dyteCreateMeetingRequest struct {
|
||||
ConversationID uint `json:"conversation_id"`
|
||||
}
|
||||
|
||||
type dyteAddParticipantRequest struct {
|
||||
MessageID uint `json:"message_id"`
|
||||
}
|
||||
|
||||
// CreateMeeting starts a Dyte meeting and creates the Chatwoot integration message.
|
||||
// Reference: Api::V1::Accounts::Integrations::DyteController#create_a_meeting.
|
||||
func (h *DyteIntegrationHandler) CreateMeeting(c *gin.Context) {
|
||||
accountID, err := parseUintParam(c, "account_id")
|
||||
if err != nil || accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
var req dyteCreateMeetingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.ConversationID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "conversation_id is required")
|
||||
return
|
||||
}
|
||||
message, conversation, apiErr, svcErr := h.svc.CreateMeeting(c.Request.Context(), accountID, getUserID(c), req.ConversationID, getRole(c))
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
if apiErr != nil {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": apiErr.Payload, "error_code": apiErr.Status})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, serializeMessage(c.Request.Context(), h.svc.DB(), message, conversation))
|
||||
}
|
||||
|
||||
// AddParticipant adds the current user as a participant to an existing Dyte meeting.
|
||||
// Reference: Api::V1::Accounts::Integrations::DyteController#add_participant_to_meeting.
|
||||
func (h *DyteIntegrationHandler) AddParticipant(c *gin.Context) {
|
||||
accountID, err := parseUintParam(c, "account_id")
|
||||
if err != nil || accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
var req dyteAddParticipantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.MessageID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "message_id is required")
|
||||
return
|
||||
}
|
||||
payload, apiErr, svcErr := h.svc.AddParticipant(c.Request.Context(), accountID, getUserID(c), req.MessageID, getRole(c))
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
if apiErr != nil {
|
||||
status := http.StatusUnprocessableEntity
|
||||
body := gin.H{"error": apiErr.Payload}
|
||||
if apiErr.Status != http.StatusUnprocessableEntity {
|
||||
body["error_code"] = apiErr.Status
|
||||
}
|
||||
c.JSON(status, body)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func RegisterDyteIntegrationRoutes(g *gin.RouterGroup, h *DyteIntegrationHandler) {
|
||||
dyte := g.Group("/dyte")
|
||||
{
|
||||
dyte.POST("/create_a_meeting", h.CreateMeeting)
|
||||
dyte.POST("/add_participant_to_meeting", h.AddParticipant)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
)
|
||||
|
||||
type dyteHandlerFakeBackend struct{}
|
||||
|
||||
func (dyteHandlerFakeBackend) CreateMeeting(_ context.Context, _ service.DyteCredentials, _ string) (map[string]any, *service.DyteAPIError, error) {
|
||||
return map[string]any{"id": "meeting_id"}, nil, nil
|
||||
}
|
||||
|
||||
func (dyteHandlerFakeBackend) AddParticipant(_ context.Context, _ service.DyteCredentials, _ string, _ service.DyteParticipant) (map[string]any, *service.DyteAPIError, error) {
|
||||
return map[string]any{"id": "participant_id", "auth_token": "json-web-token"}, nil, nil
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerCreateMeetingReturnsMessagePayload(t *testing.T) {
|
||||
router, _, account, user, conversation, _ := setupDyteIntegrationHandler(t)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"conversation_id":%d}`, *conversation.DisplayID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/create_a_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.NotZero(t, payload["id"])
|
||||
require.Equal(t, float64(*conversation.DisplayID), payload["conversation_id"])
|
||||
require.Equal(t, "integrations", payload["content_type"])
|
||||
require.Equal(t, "Dyte Agent has started a meeting", payload["content"])
|
||||
attrs := payload["content_attributes"].(map[string]any)
|
||||
require.Equal(t, "dyte", attrs["type"])
|
||||
require.Equal(t, "meeting_id", attrs["data"].(map[string]any)["meeting_id"])
|
||||
require.Equal(t, float64(user.ID), payload["sender"].(map[string]any)["id"])
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerAddParticipantReturnsAuthToken(t *testing.T) {
|
||||
router, _, account, _, _, message := setupDyteIntegrationHandler(t)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.Equal(t, "participant_id", payload["id"])
|
||||
require.Equal(t, "json-web-token", payload["auth_token"])
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerAddParticipantRejectsNonIntegrationMessage(t *testing.T) {
|
||||
router, db, account, _, conversation, _ := setupDyteIntegrationHandler(t)
|
||||
message := &model.Message{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, MessageType: "outgoing", ContentType: "text", Content: "plain", Status: "sent"}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusUnprocessableEntity, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.Equal(t, "Invalid message type. Action not permitted", payload["error"].(map[string]any)["error"])
|
||||
}
|
||||
|
||||
func setupDyteIntegrationHandler(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.User, *model.Conversation, *model.Message) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Message{}, &model.InboxMember{}, &model.IntegrationHook{}))
|
||||
t.Cleanup(func() { sqlDB, _ := db.DB(); _ = sqlDB.Close() })
|
||||
|
||||
account := &model.Account{Name: "Dyte Account", Locale: "en", Status: "active"}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
user := &model.User{AccountID: account.ID, Name: "Dyte Agent", Email: "dyte-agent@example.test", Password: "secret", Role: "agent"}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: user.ID, Role: "agent"}).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Visitor"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
displayID := uint(11)
|
||||
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "pending", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
settings, _ := json.Marshal(map[string]any{"organization_id": "org", "api_key": "key"})
|
||||
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "dyte", HookType: model.HookType("dyte"), Settings: datatypes.JSON(settings)}).Error)
|
||||
attrs, _ := json.Marshal(map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": "m_id"}})
|
||||
message := &model.Message{AccountID: account.ID, InboxID: inbox.ID, ConversationID: conversation.ID, SenderID: &user.ID, SenderType: "user", MessageType: "outgoing", ContentType: "integrations", Content: "Join", Status: "sent", ContentAttributes: datatypes.JSON(attrs)}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
|
||||
svc := service.NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
|
||||
svc.SetBackend(dyteHandlerFakeBackend{})
|
||||
handler := NewDyteIntegrationHandler(svc)
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("user_id", user.ID)
|
||||
c.Set("role", "agent")
|
||||
c.Next()
|
||||
})
|
||||
integrations := router.Group("/api/v1/accounts/:account_id/integrations")
|
||||
RegisterDyteIntegrationRoutes(integrations, handler)
|
||||
return router, db, account, user, conversation, message
|
||||
}
|
||||
|
||||
func decodeDyteHandlerBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
|
||||
return payload
|
||||
}
|
||||
Reference in New Issue
Block a user