Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-28 20:56:11 +01:00

Add feishu webhook support (#10229)

Add feishu webhook support
This commit is contained in:
Lunny Xiao 2020-02-12 16:48:28 +08:00 committed by GitHub
parent ea7ad382e7
commit 83a8944fcf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 327 additions and 3 deletions

View file

@ -445,6 +445,7 @@ const (
DINGTALK
TELEGRAM
MSTEAMS
FEISHU
)
var hookTaskTypes = map[string]HookTaskType{
@ -455,6 +456,7 @@ var hookTaskTypes = map[string]HookTaskType{
"dingtalk": DINGTALK,
"telegram": TELEGRAM,
"msteams": MSTEAMS,
"feishu": FEISHU,
}
// ToHookTaskType returns HookTaskType by given name.
@ -479,6 +481,8 @@ func (t HookTaskType) Name() string {
return "telegram"
case MSTEAMS:
return "msteams"
case FEISHU:
return "feishu"
}
return ""
}

View file

@ -313,6 +313,17 @@ func (f *NewMSTeamsHookForm) Validate(ctx *macaron.Context, errs binding.Errors)
return validate(errs, ctx.Data, f, ctx.Locale)
}
// NewFeishuHookForm form for creating feishu hook
type NewFeishuHookForm struct {
PayloadURL string `binding:"Required;ValidUrl"`
WebhookForm
}
// Validate validates the fields
func (f *NewFeishuHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// .___
// | | ______ ________ __ ____
// | |/ ___// ___/ | \_/ __ \

View file

@ -36,7 +36,7 @@ func newWebhookService() {
Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
Webhook.Types = []string{"gitea", "gogs", "slack", "discord", "dingtalk", "telegram", "msteams"}
Webhook.Types = []string{"gitea", "gogs", "slack", "discord", "dingtalk", "telegram", "msteams", "feishu"}
Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
Webhook.ProxyURL = sec.Key("PROXY_URL").MustString("")
if Webhook.ProxyURL != "" {

View file

@ -41,7 +41,7 @@ type CreateHookOptionConfig map[string]string
// CreateHookOption options when create a hook
type CreateHookOption struct {
// required: true
// enum: dingtalk,discord,gitea,gogs,msteams,slack,telegram
// enum: dingtalk,discord,gitea,gogs,msteams,slack,telegram,feishu
Type string `json:"type" binding:"Required"`
// required: true
Config CreateHookOptionConfig `json:"config" binding:"Required"`

201
modules/webhook/feishu.go Normal file
View file

@ -0,0 +1,201 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package webhook
import (
"encoding/json"
"fmt"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
)
type (
// FeishuPayload represents
FeishuPayload struct {
Title string `json:"title"`
Text string `json:"text"`
}
)
// SetSecret sets the Feishu secret
func (p *FeishuPayload) SetSecret(_ string) {}
// JSONPayload Marshals the FeishuPayload to json
func (p *FeishuPayload) JSONPayload() ([]byte, error) {
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
return []byte{}, err
}
return data, nil
}
func getFeishuCreatePayload(p *api.CreatePayload) (*FeishuPayload, error) {
// created tag/branch
refName := git.RefEndName(p.Ref)
title := fmt.Sprintf("[%s] %s %s created", p.Repo.FullName, p.RefType, refName)
return &FeishuPayload{
Text: title,
Title: title,
}, nil
}
func getFeishuDeletePayload(p *api.DeletePayload) (*FeishuPayload, error) {
// created tag/branch
refName := git.RefEndName(p.Ref)
title := fmt.Sprintf("[%s] %s %s deleted", p.Repo.FullName, p.RefType, refName)
return &FeishuPayload{
Text: title,
Title: title,
}, nil
}
func getFeishuForkPayload(p *api.ForkPayload) (*FeishuPayload, error) {
title := fmt.Sprintf("%s is forked to %s", p.Forkee.FullName, p.Repo.FullName)
return &FeishuPayload{
Text: title,
Title: title,
}, nil
}
func getFeishuPushPayload(p *api.PushPayload) (*FeishuPayload, error) {
var (
branchName = git.RefEndName(p.Ref)
commitDesc string
)
title := fmt.Sprintf("[%s:%s] %s", p.Repo.FullName, branchName, commitDesc)
var text string
// for each commit, generate attachment text
for i, commit := range p.Commits {
var authorName string
if commit.Author != nil {
authorName = " - " + commit.Author.Name
}
text += fmt.Sprintf("[%s](%s) %s", commit.ID[:7], commit.URL,
strings.TrimRight(commit.Message, "\r\n")) + authorName
// add linebreak to each commit but the last
if i < len(p.Commits)-1 {
text += "\n"
}
}
return &FeishuPayload{
Text: text,
Title: title,
}, nil
}
func getFeishuIssuesPayload(p *api.IssuePayload) (*FeishuPayload, error) {
text, issueTitle, attachmentText, _ := getIssuesPayloadInfo(p, noneLinkFormatter, true)
return &FeishuPayload{
Text: text + "\r\n\r\n" + attachmentText,
Title: issueTitle,
}, nil
}
func getFeishuIssueCommentPayload(p *api.IssueCommentPayload) (*FeishuPayload, error) {
text, issueTitle, _ := getIssueCommentPayloadInfo(p, noneLinkFormatter, true)
return &FeishuPayload{
Text: text + "\r\n\r\n" + p.Comment.Body,
Title: issueTitle,
}, nil
}
func getFeishuPullRequestPayload(p *api.PullRequestPayload) (*FeishuPayload, error) {
text, issueTitle, attachmentText, _ := getPullRequestPayloadInfo(p, noneLinkFormatter, true)
return &FeishuPayload{
Text: text + "\r\n\r\n" + attachmentText,
Title: issueTitle,
}, nil
}
func getFeishuPullRequestApprovalPayload(p *api.PullRequestPayload, event models.HookEventType) (*FeishuPayload, error) {
var text, title string
switch p.Action {
case api.HookIssueSynchronized:
action, err := parseHookPullRequestEventType(event)
if err != nil {
return nil, err
}
title = fmt.Sprintf("[%s] Pull request review %s : #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title)
text = p.Review.Content
}
return &FeishuPayload{
Text: title + "\r\n\r\n" + text,
Title: title,
}, nil
}
func getFeishuRepositoryPayload(p *api.RepositoryPayload) (*FeishuPayload, error) {
var title string
switch p.Action {
case api.HookRepoCreated:
title = fmt.Sprintf("[%s] Repository created", p.Repository.FullName)
return &FeishuPayload{
Text: title,
Title: title,
}, nil
case api.HookRepoDeleted:
title = fmt.Sprintf("[%s] Repository deleted", p.Repository.FullName)
return &FeishuPayload{
Title: title,
Text: title,
}, nil
}
return nil, nil
}
func getFeishuReleasePayload(p *api.ReleasePayload) (*FeishuPayload, error) {
text, _ := getReleasePayloadInfo(p, noneLinkFormatter, true)
return &FeishuPayload{
Text: text,
Title: text,
}, nil
}
// GetFeishuPayload converts a ding talk webhook into a FeishuPayload
func GetFeishuPayload(p api.Payloader, event models.HookEventType, meta string) (*FeishuPayload, error) {
s := new(FeishuPayload)
switch event {
case models.HookEventCreate:
return getFeishuCreatePayload(p.(*api.CreatePayload))
case models.HookEventDelete:
return getFeishuDeletePayload(p.(*api.DeletePayload))
case models.HookEventFork:
return getFeishuForkPayload(p.(*api.ForkPayload))
case models.HookEventIssues:
return getFeishuIssuesPayload(p.(*api.IssuePayload))
case models.HookEventIssueComment:
return getFeishuIssueCommentPayload(p.(*api.IssueCommentPayload))
case models.HookEventPush:
return getFeishuPushPayload(p.(*api.PushPayload))
case models.HookEventPullRequest:
return getFeishuPullRequestPayload(p.(*api.PullRequestPayload))
case models.HookEventPullRequestApproved, models.HookEventPullRequestRejected, models.HookEventPullRequestComment:
return getFeishuPullRequestApprovalPayload(p.(*api.PullRequestPayload), event)
case models.HookEventRepository:
return getFeishuRepositoryPayload(p.(*api.RepositoryPayload))
case models.HookEventRelease:
return getFeishuReleasePayload(p.(*api.ReleasePayload))
}
return s, nil
}

View file

@ -114,6 +114,11 @@ func prepareWebhook(w *models.Webhook, repo *models.Repository, event models.Hoo
if err != nil {
return fmt.Errorf("GetMSTeamsPayload: %v", err)
}
case models.FEISHU:
payloader, err = GetFeishuPayload(p, event, w.Meta)
if err != nil {
return fmt.Errorf("GetFeishuPayload: %v", err)
}
default:
p.SetSecret(w.Secret)
payloader = p

View file

@ -1398,6 +1398,7 @@ settings.add_discord_hook_desc = Integrate <a href="%s">Discord</a> into your re
settings.add_dingtalk_hook_desc = Integrate <a href="%s">Dingtalk</a> into your repository.
settings.add_telegram_hook_desc = Integrate <a href="%s">Telegram</a> into your repository.
settings.add_msteams_hook_desc = Integrate <a href="%s">Microsoft Teams</a> into your repository.
settings.add_feishu_hook_desc = Integrate <a href="%s">Feishu</a> into your repository.
settings.deploy_keys = Deploy Keys
settings.add_deploy_key = Add Deploy Key
settings.deploy_key_desc = Deploy keys have read-only pull access to the repository.

BIN
public/img/feishu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -485,6 +485,46 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) {
ctx.Redirect(orCtx.Link)
}
// FeishuHooksNewPost response for creating feishu hook
func FeishuHooksNewPost(ctx *context.Context, form auth.NewFeishuHookForm) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx)
if err != nil {
ctx.ServerError("getOrgRepoCtx", err)
return
}
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
return
}
w := &models.Webhook{
RepoID: orCtx.RepoID,
URL: form.PayloadURL,
ContentType: models.ContentTypeJSON,
HookEvent: ParseHookEvent(form.WebhookForm),
IsActive: form.Active,
HookTaskType: models.FEISHU,
Meta: "",
OrgID: orCtx.OrgID,
}
if err := w.UpdateEvent(); err != nil {
ctx.ServerError("UpdateEvent", err)
return
} else if err := models.CreateWebhook(w); err != nil {
ctx.ServerError("CreateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link)
}
func checkWebhook(ctx *context.Context) (*orgRepoCtx, *models.Webhook) {
ctx.Data["RequireHighlightJS"] = true
@ -819,6 +859,38 @@ func MSTeamsHooksEditPost(ctx *context.Context, form auth.NewMSTeamsHookForm) {
ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
}
// FeishuHooksEditPost response for editing feishu hook
func FeishuHooksEditPost(ctx *context.Context, form auth.NewFeishuHookForm) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx)
if ctx.Written() {
return
}
ctx.Data["Webhook"] = w
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
return
}
w.URL = form.PayloadURL
w.HookEvent = ParseHookEvent(form.WebhookForm)
w.IsActive = form.Active
if err := w.UpdateEvent(); err != nil {
ctx.ServerError("UpdateEvent", err)
return
} else if err := models.UpdateWebhook(w); err != nil {
ctx.ServerError("UpdateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
}
// TestWebhook test if web hook is work fine
func TestWebhook(ctx *context.Context) {
hookID := ctx.ParamsInt64(":id")

View file

@ -463,6 +463,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
@ -471,6 +472,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
})
m.Group("/auths", func() {
@ -568,6 +570,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
@ -576,6 +579,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
})
m.Route("/delete", "GET,POST", org.SettingsDelete)
@ -632,6 +636,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/:id/test", repo.TestWebhook)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
@ -641,6 +646,7 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
m.Group("/git", func() {
m.Get("", repo.GitHooks)

View file

@ -24,6 +24,8 @@
<img class="img-13" src="{{StaticUrlPrefix}}/img/telegram.png">
{{else if eq .HookType "msteams"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/msteams.png">
{{else if eq .HookType "feishu"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/feishu.png">
{{end}}
</div>
</h4>
@ -35,6 +37,7 @@
{{template "repo/settings/webhook/dingtalk" .}}
{{template "repo/settings/webhook/telegram" .}}
{{template "repo/settings/webhook/msteams" .}}
{{template "repo/settings/webhook/feishu" .}}
</div>
{{template "repo/settings/webhook/history" .}}

View file

@ -23,6 +23,8 @@
<img class="img-13" src="{{StaticUrlPrefix}}/img/telegram.png">
{{else if eq .HookType "msteams"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/msteams.png">
{{else if eq .HookType "feishu"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/feishu.png">
{{end}}
</div>
</h4>
@ -34,6 +36,7 @@
{{template "repo/settings/webhook/dingtalk" .}}
{{template "repo/settings/webhook/telegram" .}}
{{template "repo/settings/webhook/msteams" .}}
{{template "repo/settings/webhook/feishu" .}}
</div>
{{template "repo/settings/webhook/history" .}}

View file

@ -0,0 +1,11 @@
{{if eq .HookType "feishu"}}
<p>{{.i18n.Tr "repo.settings.add_feishu_hook_desc" "https://feishu.cn" | Str2html}}</p>
<form class="ui form" action="{{.BaseLink}}/feishu/{{or .Webhook.ID "new"}}" method="post">
{{.CsrfTokenHtml}}
<div class="required field {{if .Err_PayloadURL}}error{{end}}">
<label for="payload_url">{{.i18n.Tr "repo.settings.payload_url"}}</label>
<input id="payload_url" name="payload_url" type="url" value="{{.Webhook.URL}}" autofocus required>
</div>
{{template "repo/settings/webhook/settings" .}}
</form>
{{end}}

View file

@ -26,6 +26,9 @@
<a class="item" href="{{.BaseLink}}/msteams/new">
<img class="img-10" src="{{StaticUrlPrefix}}/img/msteams.png">Microsoft Teams
</a>
<a class="item" href="{{.BaseLink}}/feishu/new">
<img class="img-10" src="{{StaticUrlPrefix}}/img/feishu.png">Feishu
</a>
</div>
</div>
</div>

View file

@ -21,6 +21,8 @@
<img class="img-13" src="{{StaticUrlPrefix}}/img/telegram.png">
{{else if eq .HookType "msteams"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/msteams.png">
{{else if eq .HookType "feishu"}}
<img class="img-13" src="{{StaticUrlPrefix}}/img/feishu.png">
{{end}}
</div>
</h4>
@ -32,6 +34,7 @@
{{template "repo/settings/webhook/dingtalk" .}}
{{template "repo/settings/webhook/telegram" .}}
{{template "repo/settings/webhook/msteams" .}}
{{template "repo/settings/webhook/feishu" .}}
</div>
{{template "repo/settings/webhook/history" .}}

View file

@ -9752,7 +9752,8 @@
"gogs",
"msteams",
"slack",
"telegram"
"telegram",
"feishu"
],
"x-go-name": "Type"
}