feat(integrations): align slack parity
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
@@ -30,7 +32,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.CreateSlackRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -40,7 +42,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, hook)
|
||||
c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook}))
|
||||
}
|
||||
|
||||
// Update updates a Slack integration for an account.
|
||||
@@ -53,17 +55,21 @@ func (h *SlackIntegrationHandler) Update(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.UpdateSlackRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hook, svcErr := h.svc.Update(c.Request.Context(), accountID, req)
|
||||
if svcErr != nil {
|
||||
if errors.Is(svcErr, service.ErrSlackInvalidChannel) {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid slack channel. Please try again"})
|
||||
return
|
||||
}
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, hook)
|
||||
c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook}))
|
||||
}
|
||||
|
||||
// Delete removes a Slack integration for an account.
|
||||
@@ -79,7 +85,7 @@ func (h *SlackIntegrationHandler) Delete(c *gin.Context) {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"message": "Slack integration deleted"})
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// ListAllChannels lists available Slack channels.
|
||||
@@ -96,16 +102,45 @@ func (h *SlackIntegrationHandler) ListAllChannels(c *gin.Context) {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, channels)
|
||||
c.JSON(http.StatusOK, channels)
|
||||
}
|
||||
|
||||
// RegisterSlackIntegrationRoutes registers Slack integration routes.
|
||||
func RegisterSlackIntegrationRoutes(g *gin.RouterGroup, h *SlackIntegrationHandler) {
|
||||
g.POST("/slack", h.Create)
|
||||
g.PATCH("/slack", h.Update)
|
||||
g.PUT("/slack", h.Update)
|
||||
g.DELETE("/slack", h.Delete)
|
||||
|
||||
slack := g.Group("/slack")
|
||||
{
|
||||
slack.POST("/", h.Create)
|
||||
slack.PATCH("/", h.Update)
|
||||
slack.PUT("/", h.Update)
|
||||
slack.DELETE("/", h.Delete)
|
||||
slack.GET("/list_all_channels", h.ListAllChannels)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *SlackIntegrationHandler) slackAppPayload(c *gin.Context, accountID uint, fallback []model.IntegrationHook) gin.H {
|
||||
hooks, err := h.svc.ListHooks(c.Request.Context(), accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
hooks = fallback
|
||||
}
|
||||
serializedHooks := make([]gin.H, 0, len(hooks))
|
||||
for _, hook := range hooks {
|
||||
serializedHooks = append(serializedHooks, serializeIntegrationHook(hook))
|
||||
}
|
||||
return gin.H{
|
||||
"id": "slack",
|
||||
"name": "Slack",
|
||||
"description": "Connect Slack channels for real-time notifications",
|
||||
"short_description": "Connect Slack channels for real-time notifications",
|
||||
"enabled": len(serializedHooks) > 0,
|
||||
"hooks": serializedHooks,
|
||||
"hook_type": integrationAppHookType("slack"),
|
||||
"allow_multiple_hooks": integrationAppAllowsMultipleHooks("slack"),
|
||||
"settings_form_schema": integrationAppSettingsFormSchema("slack"),
|
||||
"visible_properties": integrationAppVisibleProperties("slack"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,14 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"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"
|
||||
)
|
||||
|
||||
func setupSlackIntegrationRouter() *gin.Engine {
|
||||
@@ -24,6 +32,31 @@ func setupSlackIntegrationRouter() *gin.Engine {
|
||||
return r
|
||||
}
|
||||
|
||||
func setupSlackIntegrationRouterWithService(svc *service.SlackIntegrationService) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.RedirectTrailingSlash = false
|
||||
|
||||
handler := NewSlackIntegrationHandler(svc)
|
||||
integrations := r.Group("/api/v1/accounts/:account_id/integrations")
|
||||
RegisterSlackIntegrationRoutes(integrations, handler)
|
||||
return r
|
||||
}
|
||||
|
||||
func setupSlackIntegrationHandlerDB(t *testing.T) (*gorm.DB, uint) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.IntegrationHook{}))
|
||||
account := &model.Account{Name: "Slack Handler Account"}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
t.Cleanup(func() {
|
||||
sqlDB, _ := db.DB()
|
||||
_ = sqlDB.Close()
|
||||
})
|
||||
return db, account.ID
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// SlackIntegration — param validation tests
|
||||
// ========================================
|
||||
@@ -117,3 +150,51 @@ func TestSlackIntegration_ListAllChannels_BadAccountID(t *testing.T) {
|
||||
errBody := resp["error"].(map[string]interface{})
|
||||
assert.Contains(t, errBody["message"], "invalid account_id")
|
||||
}
|
||||
|
||||
func TestSlackIntegration_Create_NoTrailingSlash_ReturnsRawAppPayload(t *testing.T) {
|
||||
db, accountID := setupSlackIntegrationHandlerDB(t)
|
||||
svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db))
|
||||
r := setupSlackIntegrationRouterWithService(svc)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
body := bytes.NewReader([]byte(`{"slack_token":"xoxb-handler-token"}`))
|
||||
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/slack", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var resp map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
assert.Equal(t, "slack", resp["id"])
|
||||
assert.NotContains(t, resp, "success")
|
||||
hooks := resp["hooks"].([]interface{})
|
||||
require.Len(t, hooks, 1)
|
||||
hook := hooks[0].(map[string]interface{})
|
||||
assert.Equal(t, "slack", hook["app_id"])
|
||||
assert.Equal(t, accountID, uint(hook["account_id"].(float64)))
|
||||
assert.Equal(t, false, hook["status"])
|
||||
}
|
||||
|
||||
func TestSlackIntegration_Delete_NoTrailingSlash_ReturnsEmptyOK(t *testing.T) {
|
||||
db, accountID := setupSlackIntegrationHandlerDB(t)
|
||||
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: accountID, AppID: "slack", HookType: model.HookTypeSlack}).Error)
|
||||
svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db))
|
||||
r := setupSlackIntegrationRouterWithService(svc)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/integrations/slack", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Empty(t, w.Body.String())
|
||||
}
|
||||
|
||||
func TestSlackIntegration_Update_PutNoTrailingSlash_BadAccountID(t *testing.T) {
|
||||
r := setupSlackIntegrationRouter()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PUT", "/api/v1/accounts/abc/integrations/slack", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
@@ -3,29 +3,41 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
)
|
||||
|
||||
var ErrSlackInvalidChannel = errors.New("invalid slack channel")
|
||||
|
||||
// SlackIntegrationService implements Slack integration business logic.
|
||||
// Reference: Chatwoot Integrations::SlackController + SlackService
|
||||
// Slack integration sends conversation notifications to a Slack channel and
|
||||
// supports Slack slash commands for ticket creation.
|
||||
type SlackIntegrationService struct {
|
||||
hookRepo *repository.IntegrationHookRepo
|
||||
client *slackAPIClient
|
||||
}
|
||||
|
||||
// NewSlackIntegrationService creates a new SlackIntegrationService.
|
||||
func NewSlackIntegrationService(hookRepo *repository.IntegrationHookRepo) *SlackIntegrationService {
|
||||
return &SlackIntegrationService{hookRepo: hookRepo}
|
||||
return &SlackIntegrationService{hookRepo: hookRepo, client: newSlackAPIClientFromEnv()}
|
||||
}
|
||||
|
||||
// CreateSlackRequest is the DTO for creating/updating a Slack integration.
|
||||
// Reference: Chatwoot SlackController#create — params: {channel_id, channel_name, slack_token}
|
||||
// Reference: Chatwoot SlackController#create — params: {code, inbox_id}
|
||||
type CreateSlackRequest struct {
|
||||
Code string `json:"code,omitempty"`
|
||||
InboxID *uint `json:"inbox_id,omitempty"`
|
||||
ChannelID string `json:"channel_id" validate:"required"`
|
||||
ChannelName string `json:"channel_name,omitempty"`
|
||||
SlackToken string `json:"slack_token,omitempty"`
|
||||
@@ -33,6 +45,7 @@ type CreateSlackRequest struct {
|
||||
|
||||
// UpdateSlackRequest is the DTO for updating a Slack integration.
|
||||
type UpdateSlackRequest struct {
|
||||
ReferenceID string `json:"reference_id,omitempty"`
|
||||
ChannelID string `json:"channel_id,omitempty"`
|
||||
ChannelName string `json:"channel_name,omitempty"`
|
||||
SlackToken string `json:"slack_token,omitempty"`
|
||||
@@ -40,56 +53,63 @@ type UpdateSlackRequest struct {
|
||||
|
||||
// Create creates a Slack integration hook for an account.
|
||||
func (s *SlackIntegrationService) Create(ctx context.Context, accountID uint, req CreateSlackRequest) (*model.IntegrationHook, error) {
|
||||
settings := model.SlackSettings{
|
||||
ChannelID: req.ChannelID,
|
||||
ChannelName: req.ChannelName,
|
||||
SlackToken: req.SlackToken,
|
||||
accessToken := strings.TrimSpace(req.SlackToken)
|
||||
if accessToken == "" {
|
||||
var err error
|
||||
accessToken, err = s.client.exchangeOAuthCode(ctx, accountID, req.Code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
settingsJSON, err := json.Marshal(settings)
|
||||
settingsJSON, err := json.Marshal(slackSettingsFromCreate(req))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal Slack settings: %w", err)
|
||||
}
|
||||
|
||||
hook := &model.IntegrationHook{
|
||||
AccountID: accountID,
|
||||
HookType: model.HookTypeSlack,
|
||||
Status: model.HookStatusActive,
|
||||
Settings: settingsJSON,
|
||||
AccountID: accountID,
|
||||
AppID: "slack",
|
||||
InboxID: req.InboxID,
|
||||
HookType: model.HookTypeSlack,
|
||||
Status: model.HookStatusInactive,
|
||||
AccessToken: accessToken,
|
||||
Settings: settingsJSON,
|
||||
}
|
||||
|
||||
if err := s.hookRepo.Create(ctx, hook); err != nil {
|
||||
return nil, fmt.Errorf("failed to create Slack integration: %w", err)
|
||||
}
|
||||
|
||||
applogger.L().Infof("Slack integration created: account=%d, channel=%s", accountID, req.ChannelID)
|
||||
applogger.L().Infof("Slack integration created: account=%d", accountID)
|
||||
return hook, nil
|
||||
}
|
||||
|
||||
// Update updates a Slack integration hook.
|
||||
func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, req UpdateSlackRequest) (*model.IntegrationHook, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack)
|
||||
hooks, err := s.findSlackHooks(ctx, accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
return nil, fmt.Errorf("Slack integration not found for account %d", accountID)
|
||||
}
|
||||
|
||||
hook := &hooks[0]
|
||||
|
||||
// Update settings
|
||||
var settings model.SlackSettings
|
||||
if hook.Settings != nil {
|
||||
if err := json.Unmarshal(hook.Settings, &settings); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal existing Slack settings: %w", err)
|
||||
referenceID := firstNonBlank(req.ReferenceID, req.ChannelID)
|
||||
channel, err := s.findChannel(ctx, *hook, referenceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channel == nil {
|
||||
return nil, ErrSlackInvalidChannel
|
||||
}
|
||||
if !channel.IsPrivate {
|
||||
if err := s.client.joinChannel(ctx, hook.AccessToken, channel.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if req.ChannelID != "" {
|
||||
settings.ChannelID = req.ChannelID
|
||||
}
|
||||
if req.ChannelName != "" {
|
||||
settings.ChannelName = req.ChannelName
|
||||
}
|
||||
settings := model.SlackSettings{ChannelName: channel.Name}
|
||||
if req.SlackToken != "" {
|
||||
hook.AccessToken = req.SlackToken
|
||||
settings.SlackToken = req.SlackToken
|
||||
}
|
||||
|
||||
@@ -98,6 +118,9 @@ func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, re
|
||||
return nil, fmt.Errorf("failed to marshal Slack settings: %w", err)
|
||||
}
|
||||
hook.Settings = settingsJSON
|
||||
hook.AppID = "slack"
|
||||
hook.ReferenceID = channel.ID
|
||||
hook.Status = model.HookStatusActive
|
||||
|
||||
if err := s.hookRepo.Update(ctx, hook); err != nil {
|
||||
return nil, fmt.Errorf("failed to update Slack integration: %w", err)
|
||||
@@ -109,7 +132,7 @@ func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, re
|
||||
|
||||
// Delete removes a Slack integration hook for an account.
|
||||
func (s *SlackIntegrationService) Delete(ctx context.Context, accountID uint) error {
|
||||
hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack)
|
||||
hooks, err := s.findSlackHooks(ctx, accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
return fmt.Errorf("Slack integration not found for account %d", accountID)
|
||||
}
|
||||
@@ -127,20 +150,222 @@ func (s *SlackIntegrationService) Delete(ctx context.Context, accountID uint) er
|
||||
// ListAllChannels returns available Slack channels (proxy to Slack API).
|
||||
// GET /api/v1/accounts/:account_id/integrations/slack/list_all_channels
|
||||
func (s *SlackIntegrationService) ListAllChannels(ctx context.Context, accountID uint) ([]map[string]interface{}, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack)
|
||||
hooks, err := s.findSlackHooks(ctx, accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
return nil, fmt.Errorf("Slack integration not found for account %d", accountID)
|
||||
}
|
||||
|
||||
var settings model.SlackSettings
|
||||
if err := json.Unmarshal(hooks[0].Settings, &settings); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal Slack settings: %w", err)
|
||||
channels, err := s.client.listChannels(ctx, hooks[0].AccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// In production, this would call the Slack API to list channels using settings.SlackToken.
|
||||
// Production note: when Slack OAuth is wired, this returns real channel list from Slack API.
|
||||
applogger.L().Infof("Listing Slack channels for account=%d", accountID)
|
||||
return []map[string]interface{}{
|
||||
{"id": settings.ChannelID, "name": settings.ChannelName},
|
||||
}, nil
|
||||
return slackChannelsToMaps(channels), nil
|
||||
}
|
||||
|
||||
func (s *SlackIntegrationService) ListHooks(ctx context.Context, accountID uint) ([]model.IntegrationHook, error) {
|
||||
return s.findSlackHooks(ctx, accountID)
|
||||
}
|
||||
|
||||
func (s *SlackIntegrationService) findSlackHooks(ctx context.Context, accountID uint) ([]model.IntegrationHook, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndApp(ctx, accountID, "slack")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(hooks) > 0 {
|
||||
return hooks, nil
|
||||
}
|
||||
return s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack)
|
||||
}
|
||||
|
||||
func (s *SlackIntegrationService) findChannel(ctx context.Context, hook model.IntegrationHook, referenceID string) (*slackChannel, error) {
|
||||
if referenceID == "" {
|
||||
return nil, ErrSlackInvalidChannel
|
||||
}
|
||||
channels, err := s.client.listChannels(ctx, hook.AccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, channel := range channels {
|
||||
if channel.ID == referenceID {
|
||||
return &channel, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func slackSettingsFromCreate(req CreateSlackRequest) model.SlackSettings {
|
||||
return model.SlackSettings{
|
||||
ChannelID: req.ChannelID,
|
||||
ChannelName: req.ChannelName,
|
||||
SlackToken: req.SlackToken,
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonBlank(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type slackAPIClient struct {
|
||||
baseURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type slackChannel struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsPrivate bool `json:"is_private"`
|
||||
}
|
||||
|
||||
func newSlackAPIClientFromEnv() *slackAPIClient {
|
||||
baseURL := strings.TrimRight(os.Getenv("SLACK_API_BASE"), "/")
|
||||
if baseURL == "" {
|
||||
baseURL = "https://slack.com/api"
|
||||
}
|
||||
return &slackAPIClient{baseURL: baseURL, httpClient: &http.Client{Timeout: 15 * time.Second}}
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) exchangeOAuthCode(ctx context.Context, accountID uint, code string) (string, error) {
|
||||
if strings.TrimSpace(code) == "" {
|
||||
return "", fmt.Errorf("slack oauth code is required")
|
||||
}
|
||||
form := url.Values{}
|
||||
form.Set("client_id", os.Getenv("SLACK_CLIENT_ID"))
|
||||
form.Set("client_secret", os.Getenv("SLACK_CLIENT_SECRET"))
|
||||
form.Set("code", code)
|
||||
form.Set("redirect_uri", fmt.Sprintf("%s/app/accounts/%d/settings/integrations/slack", strings.TrimRight(os.Getenv("FRONTEND_URL"), "/"), accountID))
|
||||
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
AccessToken string `json:"access_token"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := c.postForm(ctx, "/oauth.v2.access", "", form, &payload); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !payload.OK || payload.AccessToken == "" {
|
||||
return "", fmt.Errorf("slack oauth failed: %s", payload.Error)
|
||||
}
|
||||
return payload.AccessToken, nil
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) listChannels(ctx context.Context, token string) ([]slackChannel, error) {
|
||||
var channels []slackChannel
|
||||
for _, channelType := range []string{"private_channel", "public_channel"} {
|
||||
cursor := ""
|
||||
for {
|
||||
batch, nextCursor, err := c.listChannelsByType(ctx, token, channelType, cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, batch...)
|
||||
if nextCursor == "" {
|
||||
break
|
||||
}
|
||||
cursor = nextCursor
|
||||
}
|
||||
}
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) listChannelsByType(ctx context.Context, token, channelType, cursor string) ([]slackChannel, string, error) {
|
||||
query := url.Values{}
|
||||
query.Set("types", channelType)
|
||||
query.Set("exclude_archived", "true")
|
||||
query.Set("limit", "1000")
|
||||
if cursor != "" {
|
||||
query.Set("cursor", cursor)
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Channels []slackChannel `json:"channels"`
|
||||
Error string `json:"error"`
|
||||
ResponseMetadata struct {
|
||||
NextCursor string `json:"next_cursor"`
|
||||
} `json:"response_metadata"`
|
||||
}
|
||||
if err := c.get(ctx, "/conversations.list?"+query.Encode(), token, &payload); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if !payload.OK {
|
||||
return nil, "", fmt.Errorf("slack conversations.list failed: %s", payload.Error)
|
||||
}
|
||||
return payload.Channels, payload.ResponseMetadata.NextCursor, nil
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) joinChannel(ctx context.Context, token, channelID string) error {
|
||||
form := url.Values{}
|
||||
form.Set("channel", channelID)
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := c.postForm(ctx, "/conversations.join", token, form, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
if !payload.OK {
|
||||
return fmt.Errorf("slack conversations.join failed: %s", payload.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) get(ctx context.Context, path, token string, out interface{}) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
return c.do(req, out)
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) postForm(ctx context.Context, path, token string, form url.Values, out interface{}) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
return c.do(req, out)
|
||||
}
|
||||
|
||||
func (c *slackAPIClient) do(req *http.Request, out interface{}) error {
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("slack api returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func slackChannelsToMaps(channels []slackChannel) []map[string]interface{} {
|
||||
items := make([]map[string]interface{}, 0, len(channels))
|
||||
for _, channel := range channels {
|
||||
items = append(items, map[string]interface{}{
|
||||
"id": channel.ID,
|
||||
"name": channel.Name,
|
||||
"is_private": channel.IsPrivate,
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -45,6 +48,24 @@ func setupSlackIntegrationService(t *testing.T) (*SlackIntegrationService, *gorm
|
||||
return svc, db
|
||||
}
|
||||
|
||||
type slackRoundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f slackRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
func slackJSONResponse(body string) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
func setFakeSlackClient(svc *SlackIntegrationService, rt slackRoundTripFunc) {
|
||||
svc.client = &slackAPIClient{baseURL: "https://slack.test/api", httpClient: &http.Client{Transport: rt}}
|
||||
}
|
||||
|
||||
func seedSlackAccount(db *gorm.DB, t *testing.T) uint {
|
||||
t.Helper()
|
||||
account := &model.Account{Name: "Test Slack Account"}
|
||||
@@ -59,19 +80,31 @@ func seedSlackAccount(db *gorm.DB, t *testing.T) uint {
|
||||
func TestSlackIntegrationService_Create(t *testing.T) {
|
||||
svc, db := setupSlackIntegrationService(t)
|
||||
accountID := seedSlackAccount(db, t)
|
||||
t.Setenv("SLACK_CLIENT_ID", "client-id")
|
||||
t.Setenv("SLACK_CLIENT_SECRET", "client-secret")
|
||||
t.Setenv("FRONTEND_URL", "https://gochat.test")
|
||||
setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) {
|
||||
assert.Equal(t, "/api/oauth.v2.access", req.URL.Path)
|
||||
assert.Equal(t, http.MethodPost, req.Method)
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
values := string(body)
|
||||
assert.Contains(t, values, "code=oauth-code")
|
||||
assert.Contains(t, values, "redirect_uri=https%3A%2F%2Fgochat.test%2Fapp%2Faccounts%2F1%2Fsettings%2Fintegrations%2Fslack")
|
||||
return slackJSONResponse(`{"ok":true,"access_token":"xoxb-oauth-token"}`), nil
|
||||
})
|
||||
|
||||
req := CreateSlackRequest{
|
||||
ChannelID: "C12345678",
|
||||
ChannelName: "general",
|
||||
SlackToken: "xoxb-test-token",
|
||||
Code: "oauth-code",
|
||||
}
|
||||
|
||||
hook, err := svc.Create(context.Background(), accountID, req)
|
||||
assert.NoError(t, err)
|
||||
assert.NotZero(t, hook.ID)
|
||||
assert.Equal(t, "slack", hook.AppID)
|
||||
assert.Equal(t, model.HookTypeSlack, hook.HookType)
|
||||
assert.Equal(t, model.HookStatusActive, hook.Status)
|
||||
assert.Equal(t, model.HookStatusInactive, hook.Status)
|
||||
assert.Equal(t, accountID, hook.AccountID)
|
||||
assert.Equal(t, "xoxb-oauth-token", hook.AccessToken)
|
||||
assert.NotNil(t, hook.Settings)
|
||||
}
|
||||
|
||||
@@ -116,10 +149,22 @@ func TestSlackIntegrationService_Update(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// Update
|
||||
setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) {
|
||||
switch req.URL.Path {
|
||||
case "/api/conversations.list":
|
||||
if req.URL.Query().Get("types") == "private_channel" {
|
||||
return slackJSONResponse(`{"ok":true,"channels":[],"response_metadata":{"next_cursor":""}}`), nil
|
||||
}
|
||||
return slackJSONResponse(`{"ok":true,"channels":[{"id":"C20000002","name":"new-channel","is_private":false}],"response_metadata":{"next_cursor":""}}`), nil
|
||||
case "/api/conversations.join":
|
||||
return slackJSONResponse(`{"ok":true}`), nil
|
||||
default:
|
||||
t.Fatalf("unexpected Slack API path: %s", req.URL.Path)
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
updateReq := UpdateSlackRequest{
|
||||
ChannelID: "C20000002",
|
||||
ChannelName: "new-channel",
|
||||
SlackToken: "xoxb-new-token",
|
||||
ReferenceID: "C20000002",
|
||||
}
|
||||
|
||||
updated, err := svc.Update(context.Background(), accountID, updateReq)
|
||||
@@ -129,9 +174,11 @@ func TestSlackIntegrationService_Update(t *testing.T) {
|
||||
var settings model.SlackSettings
|
||||
err = json.Unmarshal(updated.Settings, &settings)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "C20000002", settings.ChannelID)
|
||||
assert.Equal(t, "", settings.ChannelID)
|
||||
assert.Equal(t, "new-channel", settings.ChannelName)
|
||||
assert.Equal(t, "xoxb-new-token", settings.SlackToken)
|
||||
assert.Equal(t, "", settings.SlackToken)
|
||||
assert.Equal(t, "C20000002", updated.ReferenceID)
|
||||
assert.Equal(t, model.HookStatusActive, updated.Status)
|
||||
}
|
||||
|
||||
func TestSlackIntegrationService_Update_NotFound(t *testing.T) {
|
||||
@@ -203,14 +250,25 @@ func TestSlackIntegrationService_ListAllChannels(t *testing.T) {
|
||||
}
|
||||
_, err := svc.Create(context.Background(), accountID, createReq)
|
||||
require.NoError(t, err)
|
||||
setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) {
|
||||
require.Equal(t, "/api/conversations.list", req.URL.Path)
|
||||
require.Equal(t, "Bearer xoxb-list-token", req.Header.Get("Authorization"))
|
||||
if req.URL.Query().Get("types") == "private_channel" {
|
||||
return slackJSONResponse(`{"ok":true,"channels":[{"id":"G40000004","name":"private-room","is_private":true}],"response_metadata":{"next_cursor":""}}`), nil
|
||||
}
|
||||
return slackJSONResponse(`{"ok":true,"channels":[{"id":"C40000004","name":"list-channels","is_private":false}],"response_metadata":{"next_cursor":""}}`), nil
|
||||
})
|
||||
|
||||
channels, err := svc.ListAllChannels(context.Background(), accountID)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, channels, 1)
|
||||
assert.Len(t, channels, 2)
|
||||
|
||||
// The placeholder response contains the configured channel
|
||||
assert.Equal(t, "C40000004", channels[0]["id"])
|
||||
assert.Equal(t, "list-channels", channels[0]["name"])
|
||||
assert.Equal(t, "G40000004", channels[0]["id"])
|
||||
assert.Equal(t, "private-room", channels[0]["name"])
|
||||
assert.Equal(t, true, channels[0]["is_private"])
|
||||
assert.Equal(t, "C40000004", channels[1]["id"])
|
||||
assert.Equal(t, "list-channels", channels[1]["name"])
|
||||
assert.Equal(t, false, channels[1]["is_private"])
|
||||
}
|
||||
|
||||
func TestSlackIntegrationService_ListAllChannels_NotFound(t *testing.T) {
|
||||
@@ -222,4 +280,4 @@ func TestSlackIntegrationService_ListAllChannels_NotFound(t *testing.T) {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, channels)
|
||||
assert.Contains(t, err.Error(), "not found")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user