feat: implement IM channel management in agent editor
- Introduced a new IMChannelPanel component for managing WeCom and Feishu channels. - Added CRUD operations for IM channels, including create, update, delete, and list functionalities. - Enhanced the backend with new API endpoints for IM channel management. - Updated documentation to reflect changes in IM integration and channel management. - Improved localization support for new IM-related UI elements across multiple languages.
This commit is contained in:
+208
-76
@@ -4,45 +4,233 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// IMHandler handles IM platform callback requests.
|
||||
// IMHandler handles IM platform callback requests and channel CRUD.
|
||||
type IMHandler struct {
|
||||
imService *im.Service
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
// NewIMHandler creates a new IM handler.
|
||||
func NewIMHandler(imService *im.Service, cfg *config.Config) *IMHandler {
|
||||
func NewIMHandler(imService *im.Service) *IMHandler {
|
||||
return &IMHandler{
|
||||
imService: imService,
|
||||
config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
// WeComCallback handles WeCom callback requests (both URL verification and message events).
|
||||
func (h *IMHandler) WeComCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
// ── Channel CRUD handlers ──
|
||||
|
||||
adapter, ok := h.imService.GetAdapter(im.PlatformWeCom)
|
||||
if !ok {
|
||||
logger.Error(ctx, "[IM] WeCom adapter not registered")
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "WeCom integration not enabled"})
|
||||
// CreateIMChannel creates a new IM channel for an agent.
|
||||
func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
agentID := c.Param("id")
|
||||
if agentID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "agent_id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Handle URL verification (GET request)
|
||||
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Platform string `json:"platform" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Platform != "wecom" && req.Platform != "feishu" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom' or 'feishu'"})
|
||||
return
|
||||
}
|
||||
|
||||
channel := &im.IMChannel{
|
||||
TenantID: tenantID,
|
||||
AgentID: agentID,
|
||||
Platform: req.Platform,
|
||||
Name: req.Name,
|
||||
Mode: req.Mode,
|
||||
OutputMode: req.OutputMode,
|
||||
Credentials: req.Credentials,
|
||||
Enabled: true,
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
channel.Enabled = *req.Enabled
|
||||
}
|
||||
if channel.Mode == "" {
|
||||
channel.Mode = "websocket"
|
||||
}
|
||||
if channel.OutputMode == "" {
|
||||
channel.OutputMode = "stream"
|
||||
}
|
||||
if channel.Credentials == nil {
|
||||
channel.Credentials = types.JSON("{}")
|
||||
}
|
||||
|
||||
if err := h.imService.CreateChannel(channel); err != nil {
|
||||
logger.Errorf(c.Request.Context(), "[IM] Create channel failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create channel"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": channel})
|
||||
}
|
||||
|
||||
// ListIMChannels lists all IM channels for an agent.
|
||||
func (h *IMHandler) ListIMChannels(c *gin.Context) {
|
||||
agentID := c.Param("id")
|
||||
if agentID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "agent_id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
channels, err := h.imService.ListChannelsByAgent(agentID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list channels"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": channels})
|
||||
}
|
||||
|
||||
// UpdateIMChannel updates an IM channel.
|
||||
func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
|
||||
channelID := c.Param("id")
|
||||
if channelID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
channel, err := h.imService.GetChannelByID(channelID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Mode *string `json:"mode"`
|
||||
OutputMode *string `json:"output_mode"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
channel.Name = *req.Name
|
||||
}
|
||||
if req.Mode != nil {
|
||||
channel.Mode = *req.Mode
|
||||
}
|
||||
if req.OutputMode != nil {
|
||||
channel.OutputMode = *req.OutputMode
|
||||
}
|
||||
if req.Credentials != nil {
|
||||
channel.Credentials = req.Credentials
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
channel.Enabled = *req.Enabled
|
||||
}
|
||||
|
||||
if err := h.imService.UpdateChannel(channel); err != nil {
|
||||
logger.Errorf(c.Request.Context(), "[IM] Update channel failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update channel"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": channel})
|
||||
}
|
||||
|
||||
// DeleteIMChannel deletes an IM channel.
|
||||
func (h *IMHandler) DeleteIMChannel(c *gin.Context) {
|
||||
channelID := c.Param("id")
|
||||
if channelID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.imService.DeleteChannel(channelID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete channel"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// ToggleIMChannel toggles the enabled state of an IM channel.
|
||||
func (h *IMHandler) ToggleIMChannel(c *gin.Context) {
|
||||
channelID := c.Param("id")
|
||||
if channelID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
channel, err := h.imService.ToggleChannel(channelID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to toggle channel"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": channel})
|
||||
}
|
||||
|
||||
// ── Callback handlers ──
|
||||
|
||||
// IMCallback handles IM platform callback requests for a specific channel.
|
||||
// Route: POST /api/v1/im/callback/:channel_id
|
||||
func (h *IMHandler) IMCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
channelID := c.Param("channel_id")
|
||||
|
||||
adapter, channel, ok := h.imService.GetChannelAdapter(channelID)
|
||||
if !ok {
|
||||
// Try loading from DB
|
||||
ch, err := h.imService.GetChannelByID(channelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[IM] Channel not found for callback: %s", channelID)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
|
||||
return
|
||||
}
|
||||
if err := h.imService.StartChannel(ch); err != nil {
|
||||
logger.Errorf(ctx, "[IM] Failed to start channel for callback: %v", err)
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel not available"})
|
||||
return
|
||||
}
|
||||
adapter, channel, ok = h.imService.GetChannelAdapter(channelID)
|
||||
if !ok {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel not available"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if !channel.Enabled {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel is disabled"})
|
||||
return
|
||||
}
|
||||
|
||||
// Handle URL verification
|
||||
if adapter.HandleURLVerification(c) {
|
||||
return
|
||||
}
|
||||
|
||||
// Verify callback signature
|
||||
if err := adapter.VerifyCallback(c); err != nil {
|
||||
logger.Errorf(ctx, "[IM] WeCom callback verification failed: %v", err)
|
||||
logger.Errorf(ctx, "[IM] Callback verification failed for channel %s: %v", channelID, err)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "verification failed"})
|
||||
return
|
||||
}
|
||||
@@ -50,83 +238,27 @@ func (h *IMHandler) WeComCallback(c *gin.Context) {
|
||||
// Parse the callback message
|
||||
msg, err := adapter.ParseCallback(c)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[IM] WeCom parse callback failed: %v", err)
|
||||
logger.Errorf(ctx, "[IM] Parse callback failed for channel %s: %v", channelID, err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "parse failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// If nil, it's a non-message event (e.g., system event) - just acknowledge
|
||||
// If nil, it's a non-message event - just acknowledge
|
||||
if msg == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
return
|
||||
}
|
||||
|
||||
// Respond immediately to avoid WeCom timeout, process asynchronously
|
||||
// Respond immediately to avoid platform timeout
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
|
||||
// Get config for this platform
|
||||
wecomCfg := h.config.IM.WeCom
|
||||
|
||||
// Detach from gin request context to prevent cancellation after HTTP response.
|
||||
// Detach from gin request context
|
||||
asyncCtx := context.WithoutCancel(ctx)
|
||||
|
||||
// Process message asynchronously
|
||||
go func() {
|
||||
if err := h.imService.HandleMessage(asyncCtx, msg, wecomCfg.TenantID, wecomCfg.AgentID, wecomCfg.KnowledgeBases); err != nil {
|
||||
logger.Errorf(asyncCtx, "[IM] WeCom handle message error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// FeishuCallback handles Feishu callback requests (both URL verification and message events).
|
||||
func (h *IMHandler) FeishuCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
adapter, ok := h.imService.GetAdapter(im.PlatformFeishu)
|
||||
if !ok {
|
||||
logger.Error(ctx, "[IM] Feishu adapter not registered")
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Feishu integration not enabled"})
|
||||
return
|
||||
}
|
||||
|
||||
// Handle URL verification (challenge)
|
||||
if adapter.HandleURLVerification(c) {
|
||||
return
|
||||
}
|
||||
|
||||
// Verify callback
|
||||
if err := adapter.VerifyCallback(c); err != nil {
|
||||
logger.Errorf(ctx, "[IM] Feishu callback verification failed: %v", err)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "verification failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse the callback message
|
||||
msg, err := adapter.ParseCallback(c)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[IM] Feishu parse callback failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "parse failed"})
|
||||
return
|
||||
}
|
||||
|
||||
if msg == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
return
|
||||
}
|
||||
|
||||
// Respond immediately
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
|
||||
// Get config
|
||||
feishuCfg := h.config.IM.Feishu
|
||||
|
||||
// Detach from gin request context to prevent cancellation after HTTP response.
|
||||
asyncCtx := context.WithoutCancel(ctx)
|
||||
|
||||
// Process asynchronously
|
||||
go func() {
|
||||
if err := h.imService.HandleMessage(asyncCtx, msg, feishuCfg.TenantID, feishuCfg.AgentID, feishuCfg.KnowledgeBases); err != nil {
|
||||
logger.Errorf(asyncCtx, "[IM] Feishu handle message error: %v", err)
|
||||
if err := h.imService.HandleMessage(asyncCtx, msg, channelID); err != nil {
|
||||
logger.Errorf(asyncCtx, "[IM] Handle message error for channel %s: %v", channelID, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user