feat(integrations): align dyte meeting routes

This commit is contained in:
2026-06-06 12:45:35 +08:00
parent 3391340f9e
commit 11e5537f9b
11 changed files with 699 additions and 14 deletions
+2
View File
@@ -326,6 +326,7 @@ func Bootstrap(env string) (*App, error) {
shopifyIntegrationService := service.NewShopifyIntegrationService(integrationHookRepo)
linearIntegrationService := service.NewLinearIntegrationService(integrationHookRepo)
notionIntegrationService := service.NewNotionIntegrationService(integrationHookRepo)
dyteIntegrationService := service.NewDyteIntegrationService(integrationHookRepo, messageRepo)
// Create channel dispatcher for event-driven architecture (ref: Chatwoot Dispatcher)
channelDispatcher := channel.NewDispatcher(workerPool)
@@ -836,6 +837,7 @@ func Bootstrap(env string) (*App, error) {
ShopifyIntegration: v1.NewShopifyIntegrationHandler(shopifyIntegrationService),
LinearIntegration: v1.NewLinearIntegrationHandler(linearIntegrationService),
NotionIntegration: v1.NewNotionIntegrationHandler(notionIntegrationService),
DyteIntegration: v1.NewDyteIntegrationHandler(dyteIntegrationService),
PlatformUserSSO: v1.NewPlatformUserSSOHandler(),
// Platform API AccessToken-authenticated handlers
PlatformUser: v1.NewPlatformUserHandler(platformUserService),
@@ -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
}
+3
View File
@@ -149,6 +149,7 @@ type Handlers struct {
ShopifyIntegration *v1.ShopifyIntegrationHandler
LinearIntegration *v1.LinearIntegrationHandler
NotionIntegration *v1.NotionIntegrationHandler
DyteIntegration *v1.DyteIntegrationHandler
PlatformUserSSO *v1.PlatformUserSSOHandler
// Platform API AccessToken-authenticated handlers (distinct from SuperAdmin routes)
PlatformUser *v1.PlatformUserHandler
@@ -1570,6 +1571,8 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
v1.RegisterLinearIntegrationRoutes(integrations, h.LinearIntegration)
// Notion integration
v1.RegisterNotionIntegrationRoutes(integrations, h.NotionIntegration)
// Dyte video meeting integration
v1.RegisterDyteIntegrationRoutes(integrations, h.DyteIntegration)
}
// CSAT Survey Responses — list, metrics, review notes
@@ -0,0 +1,329 @@
package service
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
"gorm.io/datatypes"
"gorm.io/gorm"
)
const dyteBaseURL = "https://api.dyte.io/v2"
type DyteIntegrationService struct {
hookRepo *repository.IntegrationHookRepo
messageRepo *repository.MessageRepo
backend DyteBackend
frontendURL string
}
type DyteCredentials struct {
OrganizationID string
APIKey string
}
type DyteParticipant struct {
ID uint
Name string
AvatarURL string
}
type DyteAPIError struct {
Payload map[string]any
Status int
}
type DyteBackend interface {
CreateMeeting(ctx context.Context, credentials DyteCredentials, title string) (map[string]any, *DyteAPIError, error)
AddParticipant(ctx context.Context, credentials DyteCredentials, meetingID string, participant DyteParticipant) (map[string]any, *DyteAPIError, error)
}
type HTTPDyteBackend struct {
baseURL string
client *http.Client
}
func NewHTTPDyteBackend() *HTTPDyteBackend {
return &HTTPDyteBackend{
baseURL: dyteBaseURL,
client: &http.Client{Timeout: 10 * time.Second},
}
}
func NewDyteIntegrationService(hookRepo *repository.IntegrationHookRepo, messageRepo *repository.MessageRepo) *DyteIntegrationService {
return &DyteIntegrationService{
hookRepo: hookRepo,
messageRepo: messageRepo,
backend: NewHTTPDyteBackend(),
}
}
func (s *DyteIntegrationService) SetBackend(backend DyteBackend) {
if backend != nil {
s.backend = backend
}
}
func (s *DyteIntegrationService) SetFrontendURL(frontendURL string) {
s.frontendURL = strings.TrimRight(frontendURL, "/")
}
func (s *DyteIntegrationService) DB() *gorm.DB {
if s == nil || s.messageRepo == nil {
return nil
}
return s.messageRepo.DB()
}
func (s *DyteIntegrationService) CreateMeeting(ctx context.Context, accountID, userID, conversationDisplayID uint, role string) (*model.Message, *model.Conversation, *DyteAPIError, error) {
conversation, err := s.findConversation(ctx, accountID, conversationDisplayID)
if err != nil {
return nil, nil, nil, err
}
if !s.canAccessConversation(ctx, accountID, conversation.InboxID, userID, role) {
return nil, nil, nil, fmt.Errorf("forbidden")
}
user, err := s.findUser(ctx, userID)
if err != nil {
return nil, nil, nil, err
}
credentials, err := s.credentials(ctx, accountID)
if err != nil {
return nil, nil, nil, err
}
title := fmt.Sprintf("%s has started a meeting", availableUserName(user))
meeting, apiErr, err := s.backend.CreateMeeting(ctx, credentials, title)
if err != nil || apiErr != nil {
return nil, conversation, apiErr, err
}
meetingID, _ := meeting["id"].(string)
if strings.TrimSpace(meetingID) == "" {
return nil, conversation, nil, fmt.Errorf("dyte meeting id missing")
}
attrs := map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": meetingID}}
attrsJSON, _ := json.Marshal(attrs)
message := &model.Message{
AccountID: accountID,
InboxID: conversation.InboxID,
ConversationID: conversation.ID,
SenderID: &user.ID,
SenderType: "user",
MessageType: string(model.MessageTypeOutgoing),
ContentType: "integrations",
Content: title,
Status: "sent",
ContentAttributes: datatypes.JSON(attrsJSON),
}
if err := s.messageRepo.Create(ctx, message); err != nil {
return nil, conversation, nil, err
}
return message, conversation, nil, nil
}
func (s *DyteIntegrationService) AddParticipant(ctx context.Context, accountID, userID, messageID uint, role string) (map[string]any, *DyteAPIError, error) {
message, err := s.messageRepo.FindByAccountAndID(ctx, accountID, messageID)
if err != nil {
return nil, nil, err
}
var conversation model.Conversation
if err := s.DB().WithContext(ctx).Where("account_id = ? AND id = ?", accountID, message.ConversationID).First(&conversation).Error; err != nil {
return nil, nil, err
}
if !s.canAccessConversation(ctx, accountID, conversation.InboxID, userID, role) {
return nil, nil, fmt.Errorf("forbidden")
}
if message.ContentType != "integrations" {
return nil, &DyteAPIError{Payload: map[string]any{"error": "Invalid message type. Action not permitted"}, Status: http.StatusUnprocessableEntity}, nil
}
meetingID := dyteMeetingID(message.ContentAttributes)
if meetingID == "" {
return nil, nil, fmt.Errorf("meeting_id is required")
}
user, err := s.findUser(ctx, userID)
if err != nil {
return nil, nil, err
}
credentials, err := s.credentials(ctx, accountID)
if err != nil {
return nil, nil, err
}
payload, apiErr, err := s.backend.AddParticipant(ctx, credentials, meetingID, DyteParticipant{ID: user.ID, Name: availableUserName(user), AvatarURL: s.avatarURL(user)})
if err != nil || apiErr != nil {
return nil, apiErr, err
}
return payload, nil, nil
}
func (s *DyteIntegrationService) findConversation(ctx context.Context, accountID, displayID uint) (*model.Conversation, error) {
var conversation model.Conversation
db := s.DB().WithContext(ctx)
if err := db.Where("account_id = ? AND display_id = ?", accountID, displayID).First(&conversation).Error; err == nil {
return &conversation, nil
}
if err := db.Where("account_id = ? AND id = ?", accountID, displayID).First(&conversation).Error; err != nil {
return nil, err
}
return &conversation, nil
}
func (s *DyteIntegrationService) findUser(ctx context.Context, userID uint) (*model.User, error) {
if userID == 0 {
return nil, fmt.Errorf("user not authenticated")
}
var user model.User
if err := s.DB().WithContext(ctx).First(&user, userID).Error; err != nil {
return nil, err
}
return &user, nil
}
func (s *DyteIntegrationService) canAccessConversation(ctx context.Context, accountID, inboxID, userID uint, role string) bool {
if userID == 0 {
return false
}
switch strings.ToLower(role) {
case "administrator", "admin", "super_admin":
return true
}
var member model.InboxMember
return s.DB().WithContext(ctx).
Joins("JOIN inboxes ON inboxes.id = inbox_members.inbox_id").
Where("inbox_members.inbox_id = ? AND inbox_members.user_id = ? AND inboxes.account_id = ?", inboxID, userID, accountID).
First(&member).Error == nil
}
func (s *DyteIntegrationService) credentials(ctx context.Context, accountID uint) (DyteCredentials, error) {
hooks, err := s.hookRepo.FindByAccountAndApp(ctx, accountID, "dyte")
if err != nil {
return DyteCredentials{}, err
}
if len(hooks) == 0 {
return DyteCredentials{}, fmt.Errorf("dyte integration not found")
}
var settings map[string]any
if err := json.Unmarshal(hooks[0].Settings, &settings); err != nil {
return DyteCredentials{}, err
}
credentials := DyteCredentials{
OrganizationID: stringMapValue(settings, "organization_id"),
APIKey: stringMapValue(settings, "api_key"),
}
if credentials.OrganizationID == "" || credentials.APIKey == "" {
return DyteCredentials{}, fmt.Errorf("dyte credentials are required")
}
return credentials, nil
}
func (s *DyteIntegrationService) avatarURL(user *model.User) string {
if user.AvatarURL != "" {
return user.AvatarURL
}
base := s.frontendURL
if base == "" {
base = strings.TrimRight(os.Getenv("FRONTEND_URL"), "/")
}
if base == "" {
base = "http://localhost:3000"
}
return base + "/integrations/slack/user.png"
}
func dyteMeetingID(attrs datatypes.JSON) string {
var raw map[string]any
if err := json.Unmarshal(attrs, &raw); err != nil {
return ""
}
data, _ := raw["data"].(map[string]any)
return stringMapValue(data, "meeting_id")
}
func availableUserName(user *model.User) string {
if user == nil {
return ""
}
if strings.TrimSpace(user.DisplayName) != "" {
return strings.TrimSpace(user.DisplayName)
}
return strings.TrimSpace(user.Name)
}
func stringMapValue(values map[string]any, key string) string {
if values == nil {
return ""
}
switch value := values[key].(type) {
case string:
return strings.TrimSpace(value)
case fmt.Stringer:
return strings.TrimSpace(value.String())
default:
return ""
}
}
func (b *HTTPDyteBackend) CreateMeeting(ctx context.Context, credentials DyteCredentials, title string) (map[string]any, *DyteAPIError, error) {
return b.post(ctx, credentials, "meetings", map[string]any{"title": title})
}
func (b *HTTPDyteBackend) AddParticipant(ctx context.Context, credentials DyteCredentials, meetingID string, participant DyteParticipant) (map[string]any, *DyteAPIError, error) {
if meetingID == "" || participant.ID == 0 || strings.TrimSpace(participant.Name) == "" || strings.TrimSpace(participant.AvatarURL) == "" {
return nil, nil, errors.New("missing information")
}
payload := map[string]any{
"custom_participant_id": fmt.Sprintf("%d", participant.ID),
"name": participant.Name,
"picture": participant.AvatarURL,
"preset_name": "group_call_host",
}
return b.post(ctx, credentials, "meetings/"+meetingID+"/participants", payload)
}
func (b *HTTPDyteBackend) post(ctx context.Context, credentials DyteCredentials, path string, payload map[string]any) (map[string]any, *DyteAPIError, error) {
if credentials.OrganizationID == "" || credentials.APIKey == "" {
return nil, nil, errors.New("missing credentials")
}
body, _ := json.Marshal(payload)
baseURL := strings.TrimRight(b.baseURL, "/")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/"+strings.TrimLeft(path, "/"), bytes.NewReader(body))
if err != nil {
return nil, nil, err
}
auth := base64.StdEncoding.EncodeToString([]byte(credentials.OrganizationID + ":" + credentials.APIKey))
req.Header.Set("Authorization", "Basic "+auth)
req.Header.Set("Content-Type", "application/json")
client := b.client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
var decoded map[string]any
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil {
decoded = map[string]any{"message": err.Error()}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, &DyteAPIError{Payload: decoded, Status: resp.StatusCode}, nil
}
if data, ok := decoded["data"].(map[string]any); ok {
return data, nil, nil
}
return decoded, nil, nil
}
@@ -0,0 +1,127 @@
package service
import (
"context"
"encoding/json"
"net/http"
"testing"
"github.com/stretchr/testify/require"
"gorm.io/datatypes"
"gorm.io/gorm"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
)
type fakeDyteBackend struct {
createPayload map[string]any
createError *DyteAPIError
joinPayload map[string]any
joinError *DyteAPIError
lastTitle string
lastMeetingID string
}
func (f *fakeDyteBackend) CreateMeeting(_ context.Context, _ DyteCredentials, title string) (map[string]any, *DyteAPIError, error) {
f.lastTitle = title
return f.createPayload, f.createError, nil
}
func (f *fakeDyteBackend) AddParticipant(_ context.Context, _ DyteCredentials, meetingID string, _ DyteParticipant) (map[string]any, *DyteAPIError, error) {
f.lastMeetingID = meetingID
return f.joinPayload, f.joinError, nil
}
func TestDyteIntegrationServiceCreateMeetingCreatesIntegrationMessage(t *testing.T) {
db := setupServiceTestDB(t)
require.NoError(t, db.AutoMigrate(&model.IntegrationHook{}))
account := createTestAccount(t, db)
user := createTestUser(t, db, account.ID)
user.Name = "Ada Agent"
require.NoError(t, db.Save(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(42)
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)
backend := &fakeDyteBackend{createPayload: map[string]any{"id": "meeting_id"}}
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
svc.SetBackend(backend)
message, resolvedConversation, apiErr, err := svc.CreateMeeting(context.Background(), account.ID, user.ID, displayID, "agent")
require.NoError(t, err)
require.Nil(t, apiErr)
require.Equal(t, conversation.ID, resolvedConversation.ID)
require.Equal(t, "Ada Agent has started a meeting", backend.lastTitle)
require.Equal(t, "integrations", message.ContentType)
require.Equal(t, "outgoing", message.MessageType)
require.Equal(t, "Ada Agent has started a meeting", message.Content)
require.Equal(t, user.ID, *message.SenderID)
require.Equal(t, "meeting_id", dyteMeetingID(message.ContentAttributes))
}
func TestDyteIntegrationServiceCreateMeetingPropagatesDyteErrors(t *testing.T) {
db, account, user, displayID := setupDyteServiceFixture(t)
backend := &fakeDyteBackend{createError: &DyteAPIError{Payload: map[string]any{"success": false, "data": map[string]any{"message": "Title is required"}}, Status: http.StatusUnprocessableEntity}}
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
svc.SetBackend(backend)
message, _, apiErr, err := svc.CreateMeeting(context.Background(), account.ID, user.ID, displayID, "agent")
require.NoError(t, err)
require.Nil(t, message)
require.NotNil(t, apiErr)
require.Equal(t, http.StatusUnprocessableEntity, apiErr.Status)
var count int64
require.NoError(t, db.Model(&model.Message{}).Count(&count).Error)
require.Zero(t, count)
}
func TestDyteIntegrationServiceAddParticipant(t *testing.T) {
db, account, user, _ := setupDyteServiceFixture(t)
message := createDyteIntegrationMessage(t, db, account.ID, user.ID)
backend := &fakeDyteBackend{joinPayload: map[string]any{"id": "participant", "auth_token": "jwt"}}
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
svc.SetBackend(backend)
payload, apiErr, err := svc.AddParticipant(context.Background(), account.ID, user.ID, message.ID, "agent")
require.NoError(t, err)
require.Nil(t, apiErr)
require.Equal(t, "m_id", backend.lastMeetingID)
require.Equal(t, "jwt", payload["auth_token"])
}
func setupDyteServiceFixture(t *testing.T) (*gorm.DB, *model.Account, *model.User, uint) {
t.Helper()
db := setupServiceTestDB(t)
require.NoError(t, db.AutoMigrate(&model.IntegrationHook{}))
account := createTestAccount(t, db)
user := createTestUser(t, db, account.ID)
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(7)
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)
return db, account, user, displayID
}
func createDyteIntegrationMessage(t *testing.T, db *gorm.DB, accountID, userID uint) *model.Message {
t.Helper()
var conversation model.Conversation
require.NoError(t, db.Where("account_id = ?", accountID).First(&conversation).Error)
attrs, _ := json.Marshal(map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": "m_id"}})
message := &model.Message{AccountID: accountID, InboxID: conversation.InboxID, ConversationID: conversation.ID, SenderID: &userID, SenderType: "user", MessageType: "outgoing", ContentType: "integrations", Content: "Join", Status: "sent", ContentAttributes: datatypes.JSON(attrs)}
require.NoError(t, db.Create(message).Error)
return message
}
+1 -1
View File
@@ -258,7 +258,7 @@ func validMessageType(value string) bool {
func validContentType(value string) bool {
switch value {
case "text", "input_text", "input_email", "input_phone", "select", "card", "private_note", "input_csat", "file", "image", "audio", "video", "voice_call":
case "text", "input_text", "input_email", "input_phone", "select", "card", "private_note", "input_csat", "file", "image", "audio", "video", "voice_call", "integrations":
return true
default:
return false