2026-03-15 10:45:53 +00:00
package handler
import (
"context"
"net/http"
2026-03-17 03:17:17 +00:00
"strings"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
2026-03-15 18:23:22 +00:00
"github.com/Tencent/WeKnora/internal/types"
2026-03-15 10:45:53 +00:00
"github.com/gin-gonic/gin"
)
2026-03-24 08:48:13 +00:00
// validIMPlatforms is the set of supported IM platforms.
2026-03-27 03:07:09 +00:00
var validIMPlatforms = map [ string ] bool {
"wecom" : true , "feishu" : true , "slack" : true , "telegram" : true , "dingtalk" : true , "mattermost" : true ,
2026-03-23 10:27:21 +00:00
"wechat" : true ,
2026-03-27 03:07:09 +00:00
}
2026-03-24 08:48:13 +00:00
2026-03-15 18:23:22 +00:00
// IMHandler handles IM platform callback requests and channel CRUD.
2026-03-15 10:45:53 +00:00
type IMHandler struct {
imService * im . Service
}
// NewIMHandler creates a new IM handler.
2026-03-15 18:23:22 +00:00
func NewIMHandler ( imService * im . Service ) * IMHandler {
2026-03-15 10:45:53 +00:00
return & IMHandler {
imService : imService ,
}
}
2026-03-15 18:23:22 +00:00
// ── Channel CRUD handlers ──
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// 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
}
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
2026-03-15 10:45:53 +00:00
if ! ok {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
var req struct {
2026-03-23 10:27:21 +00:00
Platform string ` json:"platform" binding:"required" `
Name string ` json:"name" `
Mode string ` json:"mode" `
OutputMode string ` json:"output_mode" `
KnowledgeBaseID string ` json:"knowledge_base_id" `
Credentials types . JSON ` json:"credentials" `
Enabled * bool ` json:"enabled" `
2026-03-15 18:23:22 +00:00
}
if err := c . ShouldBindJSON ( & req ) ; err != nil {
c . JSON ( http . StatusBadRequest , gin . H { "error" : err . Error ( ) } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-24 08:48:13 +00:00
if ! validIMPlatforms [ req . Platform ] {
2026-03-23 10:27:21 +00:00
c . JSON ( http . StatusBadRequest , gin . H { "error" : "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk', 'mattermost' or 'wechat'" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
channel := & im . IMChannel {
2026-03-17 03:17:17 +00:00
TenantID : tenantID ,
AgentID : agentID ,
Platform : req . Platform ,
Name : req . Name ,
Mode : req . Mode ,
OutputMode : req . OutputMode ,
KnowledgeBaseID : req . KnowledgeBaseID ,
Credentials : req . Credentials ,
Enabled : true ,
2026-03-15 18:23:22 +00:00
}
if req . Enabled != nil {
channel . Enabled = * req . Enabled
}
2026-03-23 10:27:21 +00:00
// WeChat uses long-polling mode and full output only
if req . Platform == "wechat" {
channel . Mode = "longpoll"
channel . OutputMode = "full"
} else {
if channel . Mode == "" {
if channel . Platform == "mattermost" {
channel . Mode = "webhook"
} else {
channel . Mode = "websocket"
}
}
if channel . OutputMode == "" {
channel . OutputMode = "stream"
2026-03-27 03:07:09 +00:00
}
2026-03-15 18:23:22 +00:00
}
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 )
2026-03-17 03:17:17 +00:00
if strings . HasPrefix ( err . Error ( ) , "duplicate_bot:" ) {
c . JSON ( http . StatusConflict , gin . H { "error" : strings . TrimPrefix ( err . Error ( ) , "duplicate_bot: " ) } )
return
}
2026-03-15 18:23:22 +00:00
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
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channels , err := h . imService . ListChannelsByAgent ( agentID , tenantID )
2026-03-15 10:45:53 +00:00
if err != nil {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to list channels" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
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
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channel , err := h . imService . GetChannelByIDAndTenant ( channelID , tenantID )
2026-03-15 18:23:22 +00:00
if err != nil {
c . JSON ( http . StatusNotFound , gin . H { "error" : "channel not found" } )
return
}
var req struct {
2026-03-17 03:17:17 +00:00
Name * string ` json:"name" `
Mode * string ` json:"mode" `
OutputMode * string ` json:"output_mode" `
KnowledgeBaseID * string ` json:"knowledge_base_id" `
Credentials types . JSON ` json:"credentials" `
Enabled * bool ` json:"enabled" `
2026-03-15 18:23:22 +00:00
}
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
}
2026-03-17 03:17:17 +00:00
if req . KnowledgeBaseID != nil {
channel . KnowledgeBaseID = * req . KnowledgeBaseID
}
2026-03-15 18:23:22 +00:00
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 )
2026-03-17 03:17:17 +00:00
if strings . HasPrefix ( err . Error ( ) , "duplicate_bot:" ) {
c . JSON ( http . StatusConflict , gin . H { "error" : strings . TrimPrefix ( err . Error ( ) , "duplicate_bot: " ) } )
return
}
2026-03-15 18:23:22 +00:00
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
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
if err := h . imService . DeleteChannel ( channelID , tenantID ) ; err != nil {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to delete channel" } )
2026-03-15 10:45:53 +00:00
return
}
c . JSON ( http . StatusOK , gin . H { "success" : true } )
2026-03-15 18:23:22 +00:00
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// 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
}
2026-03-15 10:45:53 +00:00
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channel , err := h . imService . ToggleChannel ( channelID , tenantID )
2026-03-15 18:23:22 +00:00
if err != nil {
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to toggle channel" } )
return
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusOK , gin . H { "data" : channel } )
2026-03-15 10:45:53 +00:00
}
2026-03-15 18:23:22 +00:00
// ── 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 ) {
2026-03-15 10:45:53 +00:00
ctx := c . Request . Context ( )
2026-03-15 18:23:22 +00:00
channelID := c . Param ( "channel_id" )
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
adapter , channel , ok := h . imService . GetChannelAdapter ( channelID )
2026-03-15 10:45:53 +00:00
if ! ok {
2026-03-15 18:23:22 +00:00
// 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" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-27 03:07:09 +00:00
logger . Infof ( ctx , "[IM] Callback received platform=%s path_channel_id=%s" , channel . Platform , channelID )
2026-03-15 18:23:22 +00:00
// Handle URL verification
2026-03-15 10:45:53 +00:00
if adapter . HandleURLVerification ( c ) {
return
}
2026-03-15 18:23:22 +00:00
// Verify callback signature
2026-03-15 10:45:53 +00:00
if err := adapter . VerifyCallback ( c ) ; err != nil {
2026-03-15 18:23:22 +00:00
logger . Errorf ( ctx , "[IM] Callback verification failed for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusForbidden , gin . H { "error" : "verification failed" } )
return
}
// Parse the callback message
msg , err := adapter . ParseCallback ( c )
if err != nil {
2026-03-15 18:23:22 +00:00
logger . Errorf ( ctx , "[IM] Parse callback failed for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusBadRequest , gin . H { "error" : "parse failed" } )
return
}
2026-03-15 18:23:22 +00:00
// If nil, it's a non-message event - just acknowledge
2026-03-15 10:45:53 +00:00
if msg == nil {
2026-03-27 03:07:09 +00:00
if channel . Platform == "mattermost" {
logger . Infof ( ctx , "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender" , channelID )
} else {
logger . Infof ( ctx , "[IM] Callback parsed no message to process platform=%s path_channel_id=%s" , channel . Platform , channelID )
}
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusOK , gin . H { "success" : true } )
return
}
2026-03-15 18:23:22 +00:00
// Respond immediately to avoid platform timeout
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusOK , gin . H { "success" : true } )
2026-03-15 18:23:22 +00:00
// Detach from gin request context
2026-03-15 10:45:53 +00:00
asyncCtx := context . WithoutCancel ( ctx )
2026-03-15 18:23:22 +00:00
// Process message asynchronously
2026-03-15 10:45:53 +00:00
go func ( ) {
2026-03-15 18:23:22 +00:00
if err := h . imService . HandleMessage ( asyncCtx , msg , channelID ) ; err != nil {
logger . Errorf ( asyncCtx , "[IM] Handle message error for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
}
} ( )
}