Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: slack dm (#12297)

p0nye4226bcdd2a7
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index addae6135c..0bedea5f92 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -329,8 +329,30 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *v1pb.Update
}
storeSettingValue = string(bytes)
case api.SettingAppIM:
- // TODO(p0ny): impl
- return nil, status.Errorf(codes.Unimplemented, "not implemented")
+ payload := new(storepb.AppIMSetting)
+ if err := convertV1PbToStorePb(request.Setting.Value.GetAppImSettingValue(), payload); err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to unmarshal setting value for %s, error: %v", apiSettingName, err)
+ }
+ setting, err := s.store.GetAppIMSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get old app im setting")
+ }
+ for _, path := range request.UpdateMask.Paths {
+ switch path {
+ case "value.app_im_setting_value.slack":
+ setting.Slack = payload.Slack
+ case "value.app_im_setting_value.feishu":
+ setting.Feishu = payload.Feishu
+ default:
+ return nil, status.Errorf(codes.InvalidArgument, "invalid update mask path %v", path)
+ }
+ }
+
+ bytes, err := protojson.Marshal(setting)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to marshal setting for %s, error: %v", apiSettingName, err)
+ }
+ storeSettingValue = string(bytes)
case api.SettingWorkspaceExternalApproval:
oldSetting, err := s.store.GetWorkspaceExternalApprovalSetting(ctx)
if err != nil {
@@ -537,7 +559,6 @@ func (s *SettingService) convertToSettingMessage(ctx context.Context, setting *s
},
})
case api.SettingAppIM:
- // TODO(p0ny): impl
return &v1pb.Setting{
Name: settingName,
Value: &v1pb.Value{
diff --git a/backend/component/webhook/manager.go b/backend/component/webhook/manager.go
index 2d0ffca1c1..57aaf970ab 100644
--- a/backend/component/webhook/manager.go
+++ b/backend/component/webhook/manager.go
@@ -85,13 +85,14 @@ func (m *Manager) CreateEvent(ctx context.Context, e *Event) {
return
}
// Call external webhook endpoint in Go routine to avoid blocking web serving thread.
- go postWebhookList(ctx, webhookCtx, webhookList)
+ go m.postWebhookList(ctx, webhookCtx, webhookList)
}
func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, activityType api.ActivityType) (*webhook.Context, error) {
var webhookCtx webhook.Context
var webhookTaskResult *webhook.TaskResult
var mentions []string
+ var mentionUsers []*store.UserMessage
setting, err := m.store.GetWorkspaceGeneralSetting(ctx)
if err != nil {
@@ -183,6 +184,7 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
title = "Issue approved - " + e.Issue.Title
titleZh = "工单审批通过 - " + e.Issue.Title
+ mentionUsers = append(mentionUsers, e.Issue.Creator)
phone, err := maybeGetPhoneFromUser(e.Issue.Creator)
if err != nil {
slog.Warn("failed to parse phone number", slog.String("issue_title", e.Issue.Title), log.BBError(err))
@@ -229,6 +231,7 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
continue
}
mentionedUser[user.ID] = true
+ mentionUsers = append(mentionUsers, user)
phone, err := maybeGetPhoneFromUser(user)
if err != nil {
slog.Warn("failed to parse phone number",
@@ -292,6 +295,7 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
return nil, err
}
for _, user := range users {
+ mentionUsers = append(mentionUsers, user)
phone, err := maybeGetPhoneFromUser(user)
if err != nil {
slog.Warn("failed to parse phone number",
@@ -327,16 +331,25 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
CreatorID: e.Actor.ID,
CreatorName: e.Actor.Name,
CreatorEmail: e.Actor.Email,
+ MentionUsers: mentionUsers,
MentionUsersByPhone: mentions,
}
return &webhookCtx, nil
}
-func postWebhookList(ctx context.Context, webhookCtx *webhook.Context, webhookList []*store.ProjectWebhookMessage) {
+func (m *Manager) postWebhookList(ctx context.Context, webhookCtx *webhook.Context, webhookList []*store.ProjectWebhookMessage) {
+ setting, err := m.store.GetAppIMSetting(ctx)
+ if err != nil {
+ slog.Error("failed to get app im setting", log.BBError(err))
+ } else {
+ webhookCtx.IMSetting = setting
+ }
+
for _, hook := range webhookList {
webhookCtx := *webhookCtx
webhookCtx.URL = hook.URL
webhookCtx.CreatedTs = time.Now().Unix()
+ webhookCtx.DirectMessage = hook.Payload.GetDirectMessage()
go func(webhookCtx *webhook.Context, hook *store.ProjectWebhookMessage) {
if err := common.Retry(ctx, func() error {
return webhook.Post(hook.Type, *webhookCtx)
diff --git a/backend/plugin/webhook/custom.go b/backend/plugin/webhook/custom.go
index 6b6c2cff92..03f5206c9d 100644
--- a/backend/plugin/webhook/custom.go
+++ b/backend/plugin/webhook/custom.go
@@ -30,13 +30,13 @@ type CustomWebhookRequest struct {
}
func init() {
- register("bb.plugin.webhook.custom", &CustomReceiver{})
+ Register("bb.plugin.webhook.custom", &CustomReceiver{})
}
// CustomReceiver is the receiver for custom.
type CustomReceiver struct{}
-func (*CustomReceiver) post(context Context) error {
+func (*CustomReceiver) Post(context Context) error {
// TODO(p0ny): handle context.Task
payload := CustomWebhookRequest{
Level: context.Level,
diff --git a/backend/plugin/webhook/dingtalk.go b/backend/plugin/webhook/dingtalk.go
index 1ed4c606bd..70f376728b 100644
--- a/backend/plugin/webhook/dingtalk.go
+++ b/backend/plugin/webhook/dingtalk.go
@@ -37,16 +37,16 @@ type DingTalkWebhook struct {
}
func init() {
- register("bb.plugin.webhook.dingtalk", &DingTalkReceiver{})
+ Register("bb.plugin.webhook.dingtalk", &DingTalkReceiver{})
}
// DingTalkReceiver is the receiver for DingTalk.
type DingTalkReceiver struct {
}
-func (*DingTalkReceiver) post(context Context) error {
+func (*DingTalkReceiver) Post(context Context) error {
metaStrList := []string{}
- for _, meta := range context.getMetaListZh() {
+ for _, meta := range context.GetMetaListZh() {
metaStrList = append(metaStrList, fmt.Sprintf("##### **%s:** %s", meta.Name, meta.Value))
}
metaStrList = append(metaStrList, fmt.Sprintf("##### **由:** %s (%s)", context.CreatorName, context.CreatorEmail))
diff --git a/backend/plugin/webhook/discord.go b/backend/plugin/webhook/discord.go
index ac8624f354..211ff91bfa 100644
--- a/backend/plugin/webhook/discord.go
+++ b/backend/plugin/webhook/discord.go
@@ -44,18 +44,18 @@ type DiscordWebhook struct {
}
func init() {
- register("bb.plugin.webhook.discord", &DiscordReceiver{})
+ Register("bb.plugin.webhook.discord", &DiscordReceiver{})
}
// DiscordReceiver is the receiver for Discord.
type DiscordReceiver struct {
}
-func (*DiscordReceiver) post(context Context) error {
+func (*DiscordReceiver) Post(context Context) error {
embedList := []DiscordWebhookEmbed{}
fieldList := []DiscordWebhookEmbedField{}
- for _, meta := range context.getMetaList() {
+ for _, meta := range context.GetMetaList() {
fieldList = append(fieldList, DiscordWebhookEmbedField(meta))
}
diff --git a/backend/plugin/webhook/feishu.go b/backend/plugin/webhook/feishu.go
index 68d35a28d3..98327b13a7 100644
--- a/backend/plugin/webhook/feishu.go
+++ b/backend/plugin/webhook/feishu.go
@@ -88,14 +88,14 @@ type FeishuWebhook struct {
}
func init() {
- register("bb.plugin.webhook.feishu", &FeishuReceiver{})
+ Register("bb.plugin.webhook.feishu", &FeishuReceiver{})
}
// FeishuReceiver is the receiver for Feishu.
type FeishuReceiver struct {
}
-func (*FeishuReceiver) post(context Context) error {
+func (*FeishuReceiver) Post(context Context) error {
var markdownBuf strings.Builder
if context.Description != "" {
@@ -104,7 +104,7 @@ func (*FeishuReceiver) post(context Context) error {
}
}
- for _, meta := range context.getMetaList() {
+ for _, meta := range context.GetMetaList() {
if _, err := markdownBuf.WriteString(fmt.Sprintf("**%s**: %s\n", meta.Name, meta.Value)); err != nil {
return err
}
diff --git a/backend/plugin/webhook/slack.go b/backend/plugin/webhook/slack.go
deleted file mode 100644
index a1e4b51185..0000000000
--- a/backend/plugin/webhook/slack.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package webhook
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
-
- "github.com/pkg/errors"
-)
-
-// SlackWebhookBlockMarkdown is the API message for Slack webhook block markdown.
-type SlackWebhookBlockMarkdown struct {
- Type string `json:"type"`
- Text string `json:"text"`
-}
-
-// SlackWebhookElementButton is the API message for Slack webhook element button.
-type SlackWebhookElementButton struct {
- Type string `json:"type"`
- Text string `json:"text,omitempty"`
-}
-
-// SlackWebhookElement is the API message for Slack webhook element.
-type SlackWebhookElement struct {
- Type string `json:"type"`
- Button SlackWebhookElementButton `json:"text,omitempty"`
- URL string `json:"url,omitempty"`
-}
-
-// SlackWebhookBlock is the API message for Slack webhook block.
-type SlackWebhookBlock struct {
- Type string `json:"type"`
- Text *SlackWebhookBlockMarkdown `json:"text,omitempty"`
- ElementList []SlackWebhookElement `json:"elements,omitempty"`
-}
-
-// SlackWebhook is the API message for Slack webhook.
-type SlackWebhook struct {
- Text string `json:"text"`
- BlockList []SlackWebhookBlock `json:"blocks"`
-}
-
-func init() {
- register("bb.plugin.webhook.slack", &SlackReceiver{})
-}
-
-// SlackReceiver is the receiver for Slack.
-type SlackReceiver struct {
-}
-
-func (*SlackReceiver) post(context Context) error {
- blockList := []SlackWebhookBlock{}
-
- status := ""
- switch context.Level {
- case WebhookSuccess:
- status = ":white_check_mark: "
- case WebhookWarn:
- status = ":warning: "
- case WebhookError:
- status = ":exclamation: "
- }
- blockList = append(blockList, SlackWebhookBlock{
- Type: "section",
- Text: &SlackWebhookBlockMarkdown{
- Type: "mrkdwn",
- Text: fmt.Sprintf("*%s%s*", status, context.Title),
- },
- })
-
- if context.Description != "" {
- blockList = append(blockList, SlackWebhookBlock{
- Type: "section",
- Text: &SlackWebhookBlockMarkdown{
- Type: "mrkdwn",
- Text: fmt.Sprintf("```%s```", context.Description),
- },
- })
- }
-
- for _, meta := range context.getMetaList() {
- blockList = append(blockList, SlackWebhookBlock{
- Type: "section",
- Text: &SlackWebhookBlockMarkdown{
- Type: "mrkdwn",
- Text: fmt.Sprintf("*%s:* %s", meta.Name, meta.Value),
- },
- })
- }
-
- blockList = append(blockList, SlackWebhookBlock{
- Type: "section",
- Text: &SlackWebhookBlockMarkdown{
- Type: "mrkdwn",
- Text: fmt.Sprintf("By: %s (%s)", context.CreatorName, context.CreatorEmail),
- },
- })
-
- blockList = append(blockList, SlackWebhookBlock{
- Type: "actions",
- ElementList: []SlackWebhookElement{
- {
- Type: "button",
- Button: SlackWebhookElementButton{
- Type: "plain_text",
- Text: "View in Bytebase",
- },
- URL: context.Link,
- },
- },
- })
-
- post := SlackWebhook{
- Text: context.Title,
- BlockList: blockList,
- }
- body, err := json.Marshal(post)
- if err != nil {
- return errors.Wrapf(err, "failed to marshal webhook POST request to %s", context.URL)
- }
- req, err := http.NewRequest("POST",
- context.URL, bytes.NewBuffer(body))
- if err != nil {
- return errors.Wrapf(err, "failed to construct webhook POST request to %s", context.URL)
- }
-
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{
- Timeout: timeout,
- }
- resp, err := client.Do(req)
- if err != nil {
- return errors.Wrapf(err, "failed to POST webhook to %s", context.URL)
- }
-
- b, err := io.ReadAll(resp.Body)
- if err != nil {
- return errors.Wrapf(err, "failed to read POST webhook response from %s", context.URL)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK {
- return errors.Errorf("failed to POST webhook to %s, status code: %d, response body: %s", context.URL, resp.StatusCode, b)
- }
-
- if string(b) != "ok" {
- return errors.Errorf("%.100s", string(b))
- }
-
- return nil
-}
diff --git a/backend/plugin/webhook/slack/app.go b/backend/plugin/webhook/slack/app.go
new file mode 100644
index 0000000000..6ebb89851a
--- /dev/null
+++ b/backend/plugin/webhook/slack/app.go
@@ -0,0 +1,164 @@
+package slack
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/webhook"
+)
+
+type provider struct {
+ c *http.Client
+ token string
+}
+
+func newProvider(token string) *provider {
+ return &provider{
+ c: &http.Client{},
+ token: token,
+ }
+}
+
+type lookupByEmailResponse struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ User struct {
+ ID string `json:"id"`
+ } `json:"user"`
+}
+
+type conversationsOpenResponse struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ Channel struct {
+ ID string `json:"id"`
+ } `json:"channel"`
+}
+
+type chatPostMessageResponse struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+}
+
+// https://api.slack.com/methods/users.lookupByEmail
+func (p *provider) lookupByEmail(ctx context.Context, email string) (string, error) {
+ q := url.Values{}
+ q.Set("email", email)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://slack.com/api/users.lookupByEmail", nil)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to new request")
+ }
+ req.URL.RawQuery = q.Encode()
+ req.Header.Add("Authorization", "Bearer "+p.token)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := p.c.Do(req)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to send GET request")
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", errors.Errorf("received non-200 status code %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to read body")
+ }
+ var res lookupByEmailResponse
+ if err := json.Unmarshal(body, &res); err != nil {
+ return "", errors.Wrapf(err, "failed to unmarshal")
+ }
+ if !res.OK {
+ return "", errors.Errorf("failed to get user, error: %v", res.Error)
+ }
+
+ return res.User.ID, nil
+}
+
+// https://api.slack.com/methods/conversations.open
+func (p *provider) openConversation(ctx context.Context, userID string) (string, error) {
+ data := url.Values{}
+ data.Set("users", userID)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://slack.com/api/conversations.open", strings.NewReader(data.Encode()))
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to new request")
+ }
+ req.Header.Add("Authorization", "Bearer "+p.token)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := p.c.Do(req)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to send request")
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", errors.Errorf("received non-200 status code %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to read body")
+ }
+ var res conversationsOpenResponse
+ if err := json.Unmarshal(body, &res); err != nil {
+ return "", errors.Wrapf(err, "failed to unmarshal")
+ }
+ if !res.OK {
+ return "", errors.Errorf("failed to open conversation, error: %v", res.Error)
+ }
+
+ return res.Channel.ID, nil
+}
+
+// https://api.slack.com/methods/chat.postMessage
+func (p *provider) chatPostMessage(ctx context.Context, channelID string, webhookContext webhook.Context) error {
+ blocks := GetBlocks(webhookContext)
+ blocksJSON, err := json.Marshal(blocks)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal blocks")
+ }
+
+ data := url.Values{}
+ data.Set("channel", channelID)
+ data.Set("blocks", string(blocksJSON))
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://slack.com/api/chat.postMessage", strings.NewReader(data.Encode()))
+ if err != nil {
+ return errors.Wrapf(err, "failed to new request")
+ }
+ req.Header.Add("Authorization", "Bearer "+p.token)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := p.c.Do(req)
+ if err != nil {
+ return errors.Wrapf(err, "failed to send request")
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return errors.Errorf("received non-200 status code %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return errors.Wrapf(err, "failed to read body")
+ }
+ var res chatPostMessageResponse
+ if err := json.Unmarshal(body, &res); err != nil {
+ return errors.Wrapf(err, "failed to unmarshal")
+ }
+ if !res.OK {
+ return errors.Errorf("failed to post message, error: %v", res.Error)
+ }
+
+ return nil
+}
diff --git a/backend/plugin/webhook/slack/slack.go b/backend/plugin/webhook/slack/slack.go
new file mode 100644
index 0000000000..f8cd2b368a
--- /dev/null
+++ b/backend/plugin/webhook/slack/slack.go
@@ -0,0 +1,202 @@
+package slack
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/pkg/errors"
+ "go.uber.org/multierr"
+
+ "github.com/bytebase/bytebase/backend/plugin/webhook"
+)
+
+// BlockMarkdown is the API message for Slack webhook block markdown.
+type BlockMarkdown struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+}
+
+// ElementButton is the API message for Slack webhook element button.
+type ElementButton struct {
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
+}
+
+// Element is the API message for Slack webhook element.
+type Element struct {
+ Type string `json:"type"`
+ Button ElementButton `json:"text,omitempty"`
+ URL string `json:"url,omitempty"`
+}
+
+// Block is the API message for Slack webhook block.
+type Block struct {
+ Type string `json:"type"`
+ Text *BlockMarkdown `json:"text,omitempty"`
+ ElementList []Element `json:"elements,omitempty"`
+}
+
+// MessagePayload is the API message for Slack webhook.
+type MessagePayload struct {
+ Text string `json:"text"`
+ BlockList []Block `json:"blocks"`
+}
+
+func init() {
+ webhook.Register("bb.plugin.webhook.slack", &Receiver{})
+}
+
+// Receiver is the receiver for Slack.
+type Receiver struct {
+}
+
+func GetBlocks(context webhook.Context) []Block {
+ blockList := []Block{}
+
+ status := ""
+ switch context.Level {
+ case webhook.WebhookSuccess:
+ status = ":white_check_mark: "
+ case webhook.WebhookWarn:
+ status = ":warning: "
+ case webhook.WebhookError:
+ status = ":exclamation: "
+ }
+ blockList = append(blockList, Block{
+ Type: "section",
+ Text: &BlockMarkdown{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("*%s%s*", status, context.Title),
+ },
+ })
+
+ if context.Description != "" {
+ blockList = append(blockList, Block{
+ Type: "section",
+ Text: &BlockMarkdown{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("```%s```", context.Description),
+ },
+ })
+ }
+
+ for _, meta := range context.GetMetaList() {
+ blockList = append(blockList, Block{
+ Type: "section",
+ Text: &BlockMarkdown{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("*%s:* %s", meta.Name, meta.Value),
+ },
+ })
+ }
+
+ blockList = append(blockList, Block{
+ Type: "section",
+ Text: &BlockMarkdown{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("By: %s (%s)", context.CreatorName, context.CreatorEmail),
+ },
+ })
+
+ blockList = append(blockList, Block{
+ Type: "actions",
+ ElementList: []Element{
+ {
+ Type: "button",
+ Button: ElementButton{
+ Type: "plain_text",
+ Text: "View in Bytebase",
+ },
+ URL: context.Link,
+ },
+ },
+ })
+
+ return blockList
+}
+
+func (*Receiver) Post(context webhook.Context) error {
+ if len(context.MentionUsers) > 0 {
+ return postDirectMessage(context)
+ }
+ return postMessage(context)
+}
+
+func postMessage(context webhook.Context) error {
+ blockList := GetBlocks(context)
+
+ post := MessagePayload{
+ Text: context.Title,
+ BlockList: blockList,
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal webhook POST request to %s", context.URL)
+ }
+ req, err := http.NewRequest("POST",
+ context.URL, bytes.NewBuffer(body))
+ if err != nil {
+ return errors.Wrapf(err, "failed to construct webhook POST request to %s", context.URL)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: 3 * time.Second,
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return errors.Wrapf(err, "failed to POST webhook to %s", context.URL)
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return errors.Wrapf(err, "failed to read POST webhook response from %s", context.URL)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return errors.Errorf("failed to POST webhook to %s, status code: %d, response body: %s", context.URL, resp.StatusCode, b)
+ }
+
+ if string(b) != "ok" {
+ return errors.Errorf("%.100s", string(b))
+ }
+
+ return nil
+}
+
+func postDirectMessage(webhookCtx webhook.Context) error {
+ ctx := context.Background()
+ t := webhookCtx.IMSetting.GetSlack().GetToken()
+ if t == "" {
+ return errors.Errorf("slack token not set")
+ }
+ p := newProvider(t)
+ var errs error
+ for _, u := range webhookCtx.MentionUsers {
+ err := func() error {
+ userID, err := p.lookupByEmail(ctx, u.Email)
+ if err != nil {
+ return errors.Wrapf(err, "failed to lookup user")
+ }
+ channelID, err := p.openConversation(ctx, userID)
+ if err != nil {
+ return errors.Wrapf(err, "failed to open conversation")
+ }
+ if err := p.chatPostMessage(ctx, channelID, webhookCtx); err != nil {
+ return errors.Wrapf(err, "failed to post message")
+ }
+ return nil
+ }()
+ if err != nil {
+ err = errors.Wrapf(err, "failed to send direct message to user %v", u.Email)
+ multierr.AppendInto(&errs, err)
+ }
+ }
+ return errs
+}
diff --git a/backend/plugin/webhook/teams.go b/backend/plugin/webhook/teams.go
index 5b85da8b3a..59363d4cd5 100644
--- a/backend/plugin/webhook/teams.go
+++ b/backend/plugin/webhook/teams.go
@@ -51,16 +51,16 @@ type TeamsWebhook struct {
}
func init() {
- register("bb.plugin.webhook.teams", &TeamsReceiver{})
+ Register("bb.plugin.webhook.teams", &TeamsReceiver{})
}
// TeamsReceiver is the receiver for Teams.
type TeamsReceiver struct {
}
-func (*TeamsReceiver) post(context Context) error {
+func (*TeamsReceiver) Post(context Context) error {
factList := []TeamsWebhookSectionFact{}
- for _, meta := range context.getMetaList() {
+ for _, meta := range context.GetMetaList() {
factList = append(factList, TeamsWebhookSectionFact(meta))
}
diff --git a/backend/plugin/webhook/webhook.go b/backend/plugin/webhook/webhook.go
index 3c9783a98f..e31c08f62a 100644
--- a/backend/plugin/webhook/webhook.go
+++ b/backend/plugin/webhook/webhook.go
@@ -7,7 +7,10 @@ import (
"github.com/pkg/errors"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/store"
)
var (
@@ -17,8 +20,8 @@ var (
timeout = 3 * time.Second
)
-// meta is the webhook metadata.
-type meta struct {
+// Meta is the webhook metadata.
+type Meta struct {
Name string
Value string
}
@@ -78,26 +81,30 @@ type Context struct {
Issue *Issue
Project *Project
TaskResult *TaskResult
+ MentionUsers []*store.UserMessage
MentionUsersByPhone []string
+
+ DirectMessage bool
+ IMSetting *storepb.AppIMSetting
}
// Receiver is the webhook receiver.
type Receiver interface {
- post(context Context) error
+ Post(context Context) error
}
-func (c *Context) getMetaList() []meta {
- m := []meta{}
+func (c *Context) GetMetaList() []Meta {
+ m := []Meta{}
if c.Project != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Project",
Value: c.Project.Name,
})
}
if c.Issue != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Issue",
Value: c.Issue.Name,
})
@@ -105,29 +112,29 @@ func (c *Context) getMetaList() []meta {
// So the description could be long, which is hard to display if merged into the issue name.
// We also trim it to 200 bytes to limit the message size in the webhook body, so that users can
// view it easily in the corresponding webhook client.
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Issue Description",
Value: common.TruncateStringWithDescription(c.Issue.Description),
})
}
if c.TaskResult != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Task",
Value: c.TaskResult.Name,
})
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Status",
Value: c.TaskResult.Status,
})
if c.TaskResult.Detail != "" {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Result Detail",
Value: common.TruncateStringWithDescription(c.TaskResult.Detail),
})
}
if c.TaskResult.SkippedReason != "" {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "Skipped Reason",
Value: c.TaskResult.SkippedReason,
})
@@ -137,18 +144,18 @@ func (c *Context) getMetaList() []meta {
return m
}
-func (c *Context) getMetaListZh() []meta {
- m := []meta{}
+func (c *Context) GetMetaListZh() []Meta {
+ m := []Meta{}
if c.Project != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "项目",
Value: c.Project.Name,
})
}
if c.Issue != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "工单",
Value: c.Issue.Name,
})
@@ -156,29 +163,29 @@ func (c *Context) getMetaListZh() []meta {
// So the description could be long, which is hard to display if merged into the issue name.
// We also trim it to 200 bytes to limit the message size in the webhook body, so that users can
// view it easily in the corresponding webhook client.
- m = append(m, meta{
+ m = append(m, Meta{
Name: "工单描述",
Value: common.TruncateStringWithDescription(c.Issue.Description),
})
}
if c.TaskResult != nil {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "任务",
Value: c.TaskResult.Name,
})
- m = append(m, meta{
+ m = append(m, Meta{
Name: "状态",
Value: c.TaskResult.Status,
})
if c.TaskResult.Detail != "" {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "结果详情",
Value: common.TruncateStringWithDescription(c.TaskResult.Detail),
})
}
if c.TaskResult.SkippedReason != "" {
- m = append(m, meta{
+ m = append(m, Meta{
Name: "跳过原因",
Value: c.TaskResult.SkippedReason,
})
@@ -191,7 +198,7 @@ func (c *Context) getMetaListZh() []meta {
// Register makes a receiver available by the url host
// If Register is called twice with the same url host or if receiver is nil,
// it panics.
-func register(host string, r Receiver) {
+func Register(host string, r Receiver) {
receiverMu.Lock()
defer receiverMu.Unlock()
if r == nil {
@@ -211,5 +218,5 @@ func Post(webhookType string, context Context) error {
if !ok {
return errors.Errorf("webhook: no applicable receiver for webhook type: %v", webhookType)
}
- return r.post(context)
+ return r.Post(context)
}
diff --git a/backend/plugin/webhook/webhook_test.go b/backend/plugin/webhook/webhook_test.go
index fd5cc2ca00..abf042bee9 100644
--- a/backend/plugin/webhook/webhook_test.go
+++ b/backend/plugin/webhook/webhook_test.go
@@ -18,7 +18,7 @@ func TestContext_getMetaList(t *testing.T) {
Status: "PENDING_APPROVAL",
},
}
- want := []meta{
+ want := []Meta{
{
Name: "Task",
Value: "task name",
@@ -28,7 +28,7 @@ func TestContext_getMetaList(t *testing.T) {
Value: "PENDING_APPROVAL",
},
}
- a.Equal(want, context.getMetaList())
+ a.Equal(want, context.GetMetaList())
})
t.Run("task2", func(t *testing.T) {
a := require.New(t)
@@ -39,7 +39,7 @@ func TestContext_getMetaList(t *testing.T) {
Detail: "SQL STATE",
},
}
- want := []meta{
+ want := []Meta{
{
Name: "Task",
Value: "task name",
@@ -53,7 +53,7 @@ func TestContext_getMetaList(t *testing.T) {
Value: "SQL STATE",
},
}
- a.Equal(want, context.getMetaList())
+ a.Equal(want, context.GetMetaList())
})
t.Run("task3", func(t *testing.T) {
a := require.New(t)
@@ -72,7 +72,7 @@ func TestContext_getMetaList(t *testing.T) {
Detail: detail,
},
}
- want := []meta{
+ want := []Meta{
{
Name: "Task",
Value: "task name",
@@ -86,7 +86,7 @@ func TestContext_getMetaList(t *testing.T) {
Value: common.TruncateStringWithDescription(detail),
},
}
- a.Equal(want, context.getMetaList())
+ a.Equal(want, context.GetMetaList())
})
t.Run("task4", func(t *testing.T) {
a := require.New(t)
@@ -105,7 +105,7 @@ func TestContext_getMetaList(t *testing.T) {
Detail: detail,
},
}
- want := []meta{
+ want := []Meta{
{
Name: "Task",
Value: "task name",
@@ -119,6 +119,6 @@ func TestContext_getMetaList(t *testing.T) {
Value: common.TruncateStringWithDescription(detail),
},
}
- a.Equal(want, context.getMetaList())
+ a.Equal(want, context.GetMetaList())
})
}
diff --git a/backend/plugin/webhook/wecom.go b/backend/plugin/webhook/wecom.go
index 302e8fec62..ac9a0babee 100644
--- a/backend/plugin/webhook/wecom.go
+++ b/backend/plugin/webhook/wecom.go
@@ -29,16 +29,16 @@ type WeComWebhook struct {
}
func init() {
- register("bb.plugin.webhook.wecom", &WeComReceiver{})
+ Register("bb.plugin.webhook.wecom", &WeComReceiver{})
}
// WeComReceiver is the receiver for WeCom.
type WeComReceiver struct {
}
-func (*WeComReceiver) post(context Context) error {
+func (*WeComReceiver) Post(context Context) error {
metaStrList := []string{}
- for _, meta := range context.getMetaList() {
+ for _, meta := range context.GetMetaList() {
metaStrList = append(metaStrList, fmt.Sprintf("%s: <font color=\"comment\">%s</font>", meta.Name, meta.Value))
}
metaStrList = append(metaStrList, fmt.Sprintf("By: <font color=\"comment\">%s (%s)</font>", context.CreatorName, context.CreatorEmail))
diff --git a/backend/server/minimal.go b/backend/server/minimal.go
index e28cb4833c..ea19c006c4 100644
--- a/backend/server/minimal.go
+++ b/backend/server/minimal.go
@@ -17,4 +17,7 @@ import (
// Editors.
_ "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg"
+
+ // IM webhooks.
+ _ "github.com/bytebase/bytebase/backend/plugin/webhook/slack"
)
diff --git a/backend/server/ultimate.go b/backend/server/ultimate.go
index 73a0a5e029..838b469d6b 100644
--- a/backend/server/ultimate.go
+++ b/backend/server/ultimate.go
@@ -48,4 +48,7 @@ import (
// Transformers.
_ "github.com/bytebase/bytebase/backend/plugin/parser/sql/transform/mysql"
+
+ // IM webhooks.
+ _ "github.com/bytebase/bytebase/backend/plugin/webhook/slack"
)
diff --git a/backend/store/setting.go b/backend/store/setting.go
index e934b10b61..11bcb5ee28 100644
--- a/backend/store/setting.go
+++ b/backend/store/setting.go
@@ -57,6 +57,25 @@ func (s *Store) GetWorkspaceGeneralSetting(ctx context.Context) (*storepb.Worksp
return payload, nil
}
+func (s *Store) GetAppIMSetting(ctx context.Context) (*storepb.AppIMSetting, error) {
+ settingName := api.SettingAppIM
+ setting, err := s.GetSettingV2(ctx, &FindSettingMessage{
+ Name: &settingName,
+ })
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get setting %s", settingName)
+ }
+ if setting == nil {
+ return nil, errors.Errorf("cannot find setting %v", settingName)
+ }
+
+ payload := new(storepb.AppIMSetting)
+ if err := protojson.Unmarshal([]byte(setting.Value), payload); err != nil {
+ return nil, err
+ }
+ return payload, nil
+}
+
// GetWorkspaceID finds the workspace id in setting bb.workspace.id.
func (s *Store) GetWorkspaceID(ctx context.Context) (string, error) {
settingName := api.SettingWorkspaceID