From 0f4e1b9ac66b8ffa0083a5a2516e4710393bb0da Mon Sep 17 00:00:00 2001 From: delvh Date: Sun, 1 Jan 2023 16:23:15 +0100 Subject: [PATCH] Restructure `webhook` module (#22256) Previously, there was an `import services/webhooks` inside `modules/notification/webhook`. This import was removed (after fighting against many import cycles). Additionally, `modules/notification/webhook` was moved to `modules/webhook`, and a few structs/constants were extracted from `models/webhooks` to `modules/webhook`. Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lunny Xiao --- models/migrations/v1_19/v233.go | 7 +- models/migrations/v1_19/v233_test.go | 8 +- models/webhook/hooktask.go | 3 +- models/webhook/webhook.go | 147 +++++------------- models/webhook/webhook_test.go | 11 +- modules/notification/notification.go | 2 - modules/webhook/structs.go | 38 +++++ modules/webhook/type.go | 95 +++++++++++ routers/api/v1/org/hook.go | 18 +-- routers/api/v1/repo/hook.go | 7 +- routers/api/v1/utils/hook.go | 12 +- routers/web/repo/webhook.go | 45 +++--- services/convert/convert.go | 34 ---- services/webhook/deliver.go | 7 +- services/webhook/deliver_test.go | 5 +- services/webhook/dingtalk.go | 6 +- services/webhook/dingtalk_test.go | 4 +- services/webhook/discord.go | 19 +-- services/webhook/discord_test.go | 4 +- services/webhook/feishu.go | 6 +- services/webhook/feishu_test.go | 4 +- services/webhook/general.go | 35 +++++ services/webhook/matrix.go | 5 +- services/webhook/matrix_test.go | 4 +- services/webhook/msteams.go | 12 +- services/webhook/msteams_test.go | 4 +- .../webhook/notifier.go | 110 ++++++------- services/webhook/packagist.go | 27 ++-- services/webhook/packagist_test.go | 4 +- services/webhook/payloader.go | 30 ++-- services/webhook/slack.go | 5 +- services/webhook/slack_test.go | 4 +- services/webhook/telegram.go | 5 +- services/webhook/telegram_test.go | 4 +- services/webhook/webhook.go | 56 ++++--- services/webhook/webhook_test.go | 13 +- services/webhook/wechatwork.go | 6 +- 37 files changed, 444 insertions(+), 362 deletions(-) create mode 100644 modules/webhook/structs.go create mode 100644 modules/webhook/type.go rename modules/notification/webhook/webhook.go => services/webhook/notifier.go (80%) diff --git a/models/migrations/v1_19/v233.go b/models/migrations/v1_19/v233.go index fe568b64e..ba4cd8e20 100644 --- a/models/migrations/v1_19/v233.go +++ b/models/migrations/v1_19/v233.go @@ -6,7 +6,6 @@ package v1_19 //nolint import ( "fmt" - "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/secret" "code.gitea.io/gitea/modules/setting" @@ -56,9 +55,9 @@ func batchProcess[T any](x *xorm.Engine, buf []T, query func(limit, start int) * func AddHeaderAuthorizationEncryptedColWebhook(x *xorm.Engine) error { // Add the column to the table type Webhook struct { - ID int64 `xorm:"pk autoincr"` - Type webhook.HookType `xorm:"VARCHAR(16) 'type'"` - Meta string `xorm:"TEXT"` // store hook-specific attributes + ID int64 `xorm:"pk autoincr"` + Type string `xorm:"VARCHAR(16) 'type'"` + Meta string `xorm:"TEXT"` // store hook-specific attributes // HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization() HeaderAuthorizationEncrypted string `xorm:"TEXT"` diff --git a/models/migrations/v1_19/v233_test.go b/models/migrations/v1_19/v233_test.go index 9902b7e4a..83558da33 100644 --- a/models/migrations/v1_19/v233_test.go +++ b/models/migrations/v1_19/v233_test.go @@ -7,10 +7,10 @@ import ( "testing" "code.gitea.io/gitea/models/migrations/base" - "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/secret" "code.gitea.io/gitea/modules/setting" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" ) @@ -18,9 +18,9 @@ import ( func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { // Create Webhook table type Webhook struct { - ID int64 `xorm:"pk autoincr"` - Type webhook.HookType `xorm:"VARCHAR(16) 'type'"` - Meta string `xorm:"TEXT"` // store hook-specific attributes + ID int64 `xorm:"pk autoincr"` + Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"` + Meta string `xorm:"TEXT"` // store hook-specific attributes // HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization() HeaderAuthorizationEncrypted string `xorm:"TEXT"` diff --git a/models/webhook/hooktask.go b/models/webhook/hooktask.go index 2a37ff31d..ccce1447b 100644 --- a/models/webhook/hooktask.go +++ b/models/webhook/hooktask.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" gouuid "github.com/google/uuid" ) @@ -107,7 +108,7 @@ type HookTask struct { UUID string `xorm:"unique"` api.Payloader `xorm:"-"` PayloadContent string `xorm:"LONGTEXT"` - EventType HookEventType + EventType webhook_module.HookEventType IsDelivered bool Delivered int64 DeliveredString string `xorm:"-"` diff --git a/models/webhook/webhook.go b/models/webhook/webhook.go index 5defc67fd..c24404c42 100644 --- a/models/webhook/webhook.go +++ b/models/webhook/webhook.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" "xorm.io/builder" ) @@ -46,7 +47,7 @@ type ErrHookTaskNotExist struct { UUID string } -// IsErrWebhookNotExist checks if an error is a ErrWebhookNotExist. +// IsErrHookTaskNotExist checks if an error is a ErrHookTaskNotExist. func IsErrHookTaskNotExist(err error) bool { _, ok := err.(ErrHookTaskNotExist) return ok @@ -117,84 +118,22 @@ func IsValidHookContentType(name string) bool { return ok } -// HookEvents is a set of web hook events -type HookEvents struct { - Create bool `json:"create"` - Delete bool `json:"delete"` - Fork bool `json:"fork"` - Issues bool `json:"issues"` - IssueAssign bool `json:"issue_assign"` - IssueLabel bool `json:"issue_label"` - IssueMilestone bool `json:"issue_milestone"` - IssueComment bool `json:"issue_comment"` - Push bool `json:"push"` - PullRequest bool `json:"pull_request"` - PullRequestAssign bool `json:"pull_request_assign"` - PullRequestLabel bool `json:"pull_request_label"` - PullRequestMilestone bool `json:"pull_request_milestone"` - PullRequestComment bool `json:"pull_request_comment"` - PullRequestReview bool `json:"pull_request_review"` - PullRequestSync bool `json:"pull_request_sync"` - Wiki bool `json:"wiki"` - Repository bool `json:"repository"` - Release bool `json:"release"` - Package bool `json:"package"` -} - -// HookEvent represents events that will delivery hook. -type HookEvent struct { - PushOnly bool `json:"push_only"` - SendEverything bool `json:"send_everything"` - ChooseEvents bool `json:"choose_events"` - BranchFilter string `json:"branch_filter"` - - HookEvents `json:"events"` -} - -// HookType is the type of a webhook -type HookType = string - -// Types of webhooks -const ( - GITEA HookType = "gitea" - GOGS HookType = "gogs" - SLACK HookType = "slack" - DISCORD HookType = "discord" - DINGTALK HookType = "dingtalk" - TELEGRAM HookType = "telegram" - MSTEAMS HookType = "msteams" - FEISHU HookType = "feishu" - MATRIX HookType = "matrix" - WECHATWORK HookType = "wechatwork" - PACKAGIST HookType = "packagist" -) - -// HookStatus is the status of a web hook -type HookStatus int - -// Possible statuses of a web hook -const ( - HookStatusNone = iota - HookStatusSucceed - HookStatusFail -) - // Webhook represents a web hook object. type Webhook struct { - ID int64 `xorm:"pk autoincr"` - RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook - OrgID int64 `xorm:"INDEX"` - IsSystemWebhook bool - URL string `xorm:"url TEXT"` - HTTPMethod string `xorm:"http_method"` - ContentType HookContentType - Secret string `xorm:"TEXT"` - Events string `xorm:"TEXT"` - *HookEvent `xorm:"-"` - IsActive bool `xorm:"INDEX"` - Type HookType `xorm:"VARCHAR(16) 'type'"` - Meta string `xorm:"TEXT"` // store hook-specific attributes - LastStatus HookStatus // Last delivery status + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook + OrgID int64 `xorm:"INDEX"` + IsSystemWebhook bool + URL string `xorm:"url TEXT"` + HTTPMethod string `xorm:"http_method"` + ContentType HookContentType + Secret string `xorm:"TEXT"` + Events string `xorm:"TEXT"` + *webhook_module.HookEvent `xorm:"-"` + IsActive bool `xorm:"INDEX"` + Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"` + Meta string `xorm:"TEXT"` // store hook-specific attributes + LastStatus webhook_module.HookStatus // Last delivery status // HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization() HeaderAuthorizationEncrypted string `xorm:"TEXT"` @@ -209,7 +148,7 @@ func init() { // AfterLoad updates the webhook object upon setting a column func (w *Webhook) AfterLoad() { - w.HookEvent = &HookEvent{} + w.HookEvent = &webhook_module.HookEvent{} if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil { log.Error("Unmarshal[%d]: %v", w.ID, err) } @@ -362,34 +301,34 @@ func (w *Webhook) HasPackageEvent() bool { // EventCheckers returns event checkers func (w *Webhook) EventCheckers() []struct { Has func() bool - Type HookEventType + Type webhook_module.HookEventType } { return []struct { Has func() bool - Type HookEventType + Type webhook_module.HookEventType }{ - {w.HasCreateEvent, HookEventCreate}, - {w.HasDeleteEvent, HookEventDelete}, - {w.HasForkEvent, HookEventFork}, - {w.HasPushEvent, HookEventPush}, - {w.HasIssuesEvent, HookEventIssues}, - {w.HasIssuesAssignEvent, HookEventIssueAssign}, - {w.HasIssuesLabelEvent, HookEventIssueLabel}, - {w.HasIssuesMilestoneEvent, HookEventIssueMilestone}, - {w.HasIssueCommentEvent, HookEventIssueComment}, - {w.HasPullRequestEvent, HookEventPullRequest}, - {w.HasPullRequestAssignEvent, HookEventPullRequestAssign}, - {w.HasPullRequestLabelEvent, HookEventPullRequestLabel}, - {w.HasPullRequestMilestoneEvent, HookEventPullRequestMilestone}, - {w.HasPullRequestCommentEvent, HookEventPullRequestComment}, - {w.HasPullRequestApprovedEvent, HookEventPullRequestReviewApproved}, - {w.HasPullRequestRejectedEvent, HookEventPullRequestReviewRejected}, - {w.HasPullRequestCommentEvent, HookEventPullRequestReviewComment}, - {w.HasPullRequestSyncEvent, HookEventPullRequestSync}, - {w.HasWikiEvent, HookEventWiki}, - {w.HasRepositoryEvent, HookEventRepository}, - {w.HasReleaseEvent, HookEventRelease}, - {w.HasPackageEvent, HookEventPackage}, + {w.HasCreateEvent, webhook_module.HookEventCreate}, + {w.HasDeleteEvent, webhook_module.HookEventDelete}, + {w.HasForkEvent, webhook_module.HookEventFork}, + {w.HasPushEvent, webhook_module.HookEventPush}, + {w.HasIssuesEvent, webhook_module.HookEventIssues}, + {w.HasIssuesAssignEvent, webhook_module.HookEventIssueAssign}, + {w.HasIssuesLabelEvent, webhook_module.HookEventIssueLabel}, + {w.HasIssuesMilestoneEvent, webhook_module.HookEventIssueMilestone}, + {w.HasIssueCommentEvent, webhook_module.HookEventIssueComment}, + {w.HasPullRequestEvent, webhook_module.HookEventPullRequest}, + {w.HasPullRequestAssignEvent, webhook_module.HookEventPullRequestAssign}, + {w.HasPullRequestLabelEvent, webhook_module.HookEventPullRequestLabel}, + {w.HasPullRequestMilestoneEvent, webhook_module.HookEventPullRequestMilestone}, + {w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestComment}, + {w.HasPullRequestApprovedEvent, webhook_module.HookEventPullRequestReviewApproved}, + {w.HasPullRequestRejectedEvent, webhook_module.HookEventPullRequestReviewRejected}, + {w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestReviewComment}, + {w.HasPullRequestSyncEvent, webhook_module.HookEventPullRequestSync}, + {w.HasWikiEvent, webhook_module.HookEventWiki}, + {w.HasRepositoryEvent, webhook_module.HookEventRepository}, + {w.HasReleaseEvent, webhook_module.HookEventRelease}, + {w.HasPackageEvent, webhook_module.HookEventPackage}, } } @@ -453,7 +392,7 @@ func getWebhook(bean *Webhook) (*Webhook, error) { if err != nil { return nil, err } else if !has { - return nil, ErrWebhookNotExist{bean.ID} + return nil, ErrWebhookNotExist{ID: bean.ID} } return bean, nil } @@ -541,7 +480,7 @@ func GetSystemOrDefaultWebhook(id int64) (*Webhook, error) { if err != nil { return nil, err } else if !has { - return nil, ErrWebhookNotExist{id} + return nil, ErrWebhookNotExist{ID: id} } return webhook, nil } diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index 2bdafb61b..c368fc620 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" ) @@ -46,11 +47,11 @@ func TestWebhook_History(t *testing.T) { func TestWebhook_UpdateEvent(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}) - hookEvent := &HookEvent{ + hookEvent := &webhook_module.HookEvent{ PushOnly: true, SendEverything: false, ChooseEvents: false, - HookEvents: HookEvents{ + HookEvents: webhook_module.HookEvents{ Create: false, Push: true, PullRequest: false, @@ -59,7 +60,7 @@ func TestWebhook_UpdateEvent(t *testing.T) { webhook.HookEvent = hookEvent assert.NoError(t, webhook.UpdateEvent()) assert.NotEmpty(t, webhook.Events) - actualHookEvent := &HookEvent{} + actualHookEvent := &webhook_module.HookEvent{} assert.NoError(t, json.Unmarshal([]byte(webhook.Events), actualHookEvent)) assert.Equal(t, *hookEvent, *actualHookEvent) } @@ -74,13 +75,13 @@ func TestWebhook_EventsArray(t *testing.T) { "package", }, (&Webhook{ - HookEvent: &HookEvent{SendEverything: true}, + HookEvent: &webhook_module.HookEvent{SendEverything: true}, }).EventsArray(), ) assert.Equal(t, []string{"push"}, (&Webhook{ - HookEvent: &HookEvent{PushOnly: true}, + HookEvent: &webhook_module.HookEvent{PushOnly: true}, }).EventsArray(), ) } diff --git a/modules/notification/notification.go b/modules/notification/notification.go index c3e09bb8a..10581eb87 100644 --- a/modules/notification/notification.go +++ b/modules/notification/notification.go @@ -16,7 +16,6 @@ import ( "code.gitea.io/gitea/modules/notification/mail" "code.gitea.io/gitea/modules/notification/mirror" "code.gitea.io/gitea/modules/notification/ui" - "code.gitea.io/gitea/modules/notification/webhook" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" ) @@ -36,7 +35,6 @@ func NewContext() { RegisterNotifier(mail.NewNotifier()) } RegisterNotifier(indexer.NewNotifier()) - RegisterNotifier(webhook.NewNotifier()) RegisterNotifier(action.NewNotifier()) RegisterNotifier(mirror.NewNotifier()) } diff --git a/modules/webhook/structs.go b/modules/webhook/structs.go new file mode 100644 index 000000000..96012de35 --- /dev/null +++ b/modules/webhook/structs.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package webhook + +// HookEvents is a set of web hook events +type HookEvents struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + Fork bool `json:"fork"` + Issues bool `json:"issues"` + IssueAssign bool `json:"issue_assign"` + IssueLabel bool `json:"issue_label"` + IssueMilestone bool `json:"issue_milestone"` + IssueComment bool `json:"issue_comment"` + Push bool `json:"push"` + PullRequest bool `json:"pull_request"` + PullRequestAssign bool `json:"pull_request_assign"` + PullRequestLabel bool `json:"pull_request_label"` + PullRequestMilestone bool `json:"pull_request_milestone"` + PullRequestComment bool `json:"pull_request_comment"` + PullRequestReview bool `json:"pull_request_review"` + PullRequestSync bool `json:"pull_request_sync"` + Wiki bool `json:"wiki"` + Repository bool `json:"repository"` + Release bool `json:"release"` + Package bool `json:"package"` +} + +// HookEvent represents events that will delivery hook. +type HookEvent struct { + PushOnly bool `json:"push_only"` + SendEverything bool `json:"send_everything"` + ChooseEvents bool `json:"choose_events"` + BranchFilter string `json:"branch_filter"` + + HookEvents `json:"events"` +} diff --git a/modules/webhook/type.go b/modules/webhook/type.go new file mode 100644 index 000000000..db4ab1793 --- /dev/null +++ b/modules/webhook/type.go @@ -0,0 +1,95 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package webhook + +// HookEventType is the type of a hook event +type HookEventType string + +// Types of hook events +const ( + HookEventCreate HookEventType = "create" + HookEventDelete HookEventType = "delete" + HookEventFork HookEventType = "fork" + HookEventPush HookEventType = "push" + HookEventIssues HookEventType = "issues" + HookEventIssueAssign HookEventType = "issue_assign" + HookEventIssueLabel HookEventType = "issue_label" + HookEventIssueMilestone HookEventType = "issue_milestone" + HookEventIssueComment HookEventType = "issue_comment" + HookEventPullRequest HookEventType = "pull_request" + HookEventPullRequestAssign HookEventType = "pull_request_assign" + HookEventPullRequestLabel HookEventType = "pull_request_label" + HookEventPullRequestMilestone HookEventType = "pull_request_milestone" + HookEventPullRequestComment HookEventType = "pull_request_comment" + HookEventPullRequestReviewApproved HookEventType = "pull_request_review_approved" + HookEventPullRequestReviewRejected HookEventType = "pull_request_review_rejected" + HookEventPullRequestReviewComment HookEventType = "pull_request_review_comment" + HookEventPullRequestSync HookEventType = "pull_request_sync" + HookEventWiki HookEventType = "wiki" + HookEventRepository HookEventType = "repository" + HookEventRelease HookEventType = "release" + HookEventPackage HookEventType = "package" +) + +// Event returns the HookEventType as an event string +func (h HookEventType) Event() string { + switch h { + case HookEventCreate: + return "create" + case HookEventDelete: + return "delete" + case HookEventFork: + return "fork" + case HookEventPush: + return "push" + case HookEventIssues, HookEventIssueAssign, HookEventIssueLabel, HookEventIssueMilestone: + return "issues" + case HookEventPullRequest, HookEventPullRequestAssign, HookEventPullRequestLabel, HookEventPullRequestMilestone, + HookEventPullRequestSync: + return "pull_request" + case HookEventIssueComment, HookEventPullRequestComment: + return "issue_comment" + case HookEventPullRequestReviewApproved: + return "pull_request_approved" + case HookEventPullRequestReviewRejected: + return "pull_request_rejected" + case HookEventPullRequestReviewComment: + return "pull_request_comment" + case HookEventWiki: + return "wiki" + case HookEventRepository: + return "repository" + case HookEventRelease: + return "release" + } + return "" +} + +// HookType is the type of a webhook +type HookType = string + +// Types of webhooks +const ( + GITEA HookType = "gitea" + GOGS HookType = "gogs" + SLACK HookType = "slack" + DISCORD HookType = "discord" + DINGTALK HookType = "dingtalk" + TELEGRAM HookType = "telegram" + MSTEAMS HookType = "msteams" + FEISHU HookType = "feishu" + MATRIX HookType = "matrix" + WECHATWORK HookType = "wechatwork" + PACKAGIST HookType = "packagist" +) + +// HookStatus is the status of a web hook +type HookStatus int + +// Possible statuses of a web hook +const ( + HookStatusNone HookStatus = iota + HookStatusSucceed + HookStatusFail +) diff --git a/routers/api/v1/org/hook.go b/routers/api/v1/org/hook.go index ef08a08be..4e435c959 100644 --- a/routers/api/v1/org/hook.go +++ b/routers/api/v1/org/hook.go @@ -6,12 +6,12 @@ package org import ( "net/http" - "code.gitea.io/gitea/models/webhook" + webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/utils" - "code.gitea.io/gitea/services/convert" + webhook_service "code.gitea.io/gitea/services/webhook" ) // ListHooks list an organziation's webhooks @@ -39,18 +39,18 @@ func ListHooks(ctx *context.APIContext) { // "200": // "$ref": "#/responses/HookList" - opts := &webhook.ListWebhookOptions{ + opts := &webhook_model.ListWebhookOptions{ ListOptions: utils.GetListOptions(ctx), OrgID: ctx.Org.Organization.ID, } - count, err := webhook.CountWebhooksByOpts(opts) + count, err := webhook_model.CountWebhooksByOpts(opts) if err != nil { ctx.InternalServerError(err) return } - orgHooks, err := webhook.ListWebhooksByOpts(ctx, opts) + orgHooks, err := webhook_model.ListWebhooksByOpts(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -58,7 +58,7 @@ func ListHooks(ctx *context.APIContext) { hooks := make([]*api.Hook, len(orgHooks)) for i, hook := range orgHooks { - hooks[i], err = convert.ToHook(ctx.Org.Organization.AsUser().HomeLink(), hook) + hooks[i], err = webhook_service.ToHook(ctx.Org.Organization.AsUser().HomeLink(), hook) if err != nil { ctx.InternalServerError(err) return @@ -99,7 +99,7 @@ func GetHook(ctx *context.APIContext) { return } - apiHook, err := convert.ToHook(org.AsUser().HomeLink(), hook) + apiHook, err := webhook_service.ToHook(org.AsUser().HomeLink(), hook) if err != nil { ctx.InternalServerError(err) return @@ -200,8 +200,8 @@ func DeleteHook(ctx *context.APIContext) { org := ctx.Org.Organization hookID := ctx.ParamsInt64(":id") - if err := webhook.DeleteWebhookByOrgID(org.ID, hookID); err != nil { - if webhook.IsErrWebhookNotExist(err) { + if err := webhook_model.DeleteWebhookByOrgID(org.ID, hookID); err != nil { + if webhook_model.IsErrWebhookNotExist(err) { ctx.NotFound() } else { ctx.Error(http.StatusInternalServerError, "DeleteWebhookByOrgID", err) diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 757ae7247..100a28d7f 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/web" + webhook_module "code.gitea.io/gitea/modules/webhook" "code.gitea.io/gitea/routers/api/v1/utils" "code.gitea.io/gitea/services/convert" webhook_service "code.gitea.io/gitea/services/webhook" @@ -68,7 +69,7 @@ func ListHooks(ctx *context.APIContext) { apiHooks := make([]*api.Hook, len(hooks)) for i := range hooks { - apiHooks[i], err = convert.ToHook(ctx.Repo.RepoLink, hooks[i]) + apiHooks[i], err = webhook_service.ToHook(ctx.Repo.RepoLink, hooks[i]) if err != nil { ctx.InternalServerError(err) return @@ -115,7 +116,7 @@ func GetHook(ctx *context.APIContext) { if err != nil { return } - apiHook, err := convert.ToHook(repo.RepoLink, hook) + apiHook, err := webhook_service.ToHook(repo.RepoLink, hook) if err != nil { ctx.InternalServerError(err) return @@ -176,7 +177,7 @@ func TestHook(ctx *context.APIContext) { commit := convert.ToPayloadCommit(ctx.Repo.Repository, ctx.Repo.Commit) commitID := ctx.Repo.Commit.ID.String() - if err := webhook_service.PrepareWebhook(ctx, hook, webhook.HookEventPush, &api.PushPayload{ + if err := webhook_service.PrepareWebhook(ctx, hook, webhook_module.HookEventPush, &api.PushPayload{ Ref: ref, Before: commitID, After: commitID, diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index 1a27ececf..fc202f51c 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -13,7 +13,7 @@ import ( "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" - "code.gitea.io/gitea/services/convert" + webhook_module "code.gitea.io/gitea/modules/webhook" webhook_service "code.gitea.io/gitea/services/webhook" ) @@ -98,7 +98,7 @@ func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) { // toAPIHook converts the hook to its API representation. // If there is an error, write to `ctx` accordingly. Return (hook, ok) func toAPIHook(ctx *context.APIContext, repoLink string, hook *webhook.Webhook) (*api.Hook, bool) { - apiHook, err := convert.ToHook(repoLink, hook) + apiHook, err := webhook_service.ToHook(repoLink, hook) if err != nil { ctx.Error(http.StatusInternalServerError, "ToHook", err) return nil, false @@ -127,9 +127,9 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID ContentType: webhook.ToHookContentType(form.Config["content_type"]), Secret: form.Config["secret"], HTTPMethod: "POST", - HookEvent: &webhook.HookEvent{ + HookEvent: &webhook_module.HookEvent{ ChooseEvents: true, - HookEvents: webhook.HookEvents{ + HookEvents: webhook_module.HookEvents{ Create: util.IsStringInSlice(string(webhook.HookEventCreate), form.Events, true), Delete: util.IsStringInSlice(string(webhook.HookEventDelete), form.Events, true), Fork: util.IsStringInSlice(string(webhook.HookEventFork), form.Events, true), @@ -160,7 +160,7 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID ctx.Error(http.StatusInternalServerError, "SetHeaderAuthorization", err) return nil, false } - if w.Type == webhook.SLACK { + if w.Type == webhook_module.SLACK { channel, ok := form.Config["channel"] if !ok { ctx.Error(http.StatusUnprocessableEntity, "", "Missing config option: channel") @@ -253,7 +253,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh w.ContentType = webhook.ToHookContentType(ct) } - if w.Type == webhook.SLACK { + if w.Type == webhook_module.SLACK { if channel, ok := form.Config["channel"]; ok { meta, err := json.Marshal(&webhook_service.SlackMeta{ Channel: channel, diff --git a/routers/web/repo/webhook.go b/routers/web/repo/webhook.go index 2b6f107fa..bf56e3d0b 100644 --- a/routers/web/repo/webhook.go +++ b/routers/web/repo/webhook.go @@ -23,6 +23,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" + webhook_module "code.gitea.io/gitea/modules/webhook" "code.gitea.io/gitea/services/convert" "code.gitea.io/gitea/services/forms" webhook_service "code.gitea.io/gitea/services/webhook" @@ -119,7 +120,7 @@ func checkHookType(ctx *context.Context) string { // WebhooksNew render creating webhook page func WebhooksNew(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") - ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook.HookEvent{}} + ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}} orCtx, err := getOrgRepoCtx(ctx) if err != nil { @@ -154,12 +155,12 @@ func WebhooksNew(ctx *context.Context) { } // ParseHookEvent convert web form content to webhook.HookEvent -func ParseHookEvent(form forms.WebhookForm) *webhook.HookEvent { - return &webhook.HookEvent{ +func ParseHookEvent(form forms.WebhookForm) *webhook_module.HookEvent { + return &webhook_module.HookEvent{ PushOnly: form.PushOnly(), SendEverything: form.SendEverything(), ChooseEvents: form.ChooseEvents(), - HookEvents: webhook.HookEvents{ + HookEvents: webhook_module.HookEvents{ Create: form.Create, Delete: form.Delete, Fork: form.Fork, @@ -201,7 +202,7 @@ func createWebhook(ctx *context.Context, params webhookParams) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true - ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook.HookEvent{}} + ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}} ctx.Data["HookType"] = params.Type orCtx, err := getOrgRepoCtx(ctx) @@ -326,7 +327,7 @@ func giteaHookParams(ctx *context.Context) webhookParams { } return webhookParams{ - Type: webhook.GITEA, + Type: webhook_module.GITEA, URL: form.PayloadURL, ContentType: contentType, Secret: form.Secret, @@ -354,7 +355,7 @@ func gogsHookParams(ctx *context.Context) webhookParams { } return webhookParams{ - Type: webhook.GOGS, + Type: webhook_module.GOGS, URL: form.PayloadURL, ContentType: contentType, Secret: form.Secret, @@ -376,7 +377,7 @@ func discordHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewDiscordHookForm) return webhookParams{ - Type: webhook.DISCORD, + Type: webhook_module.DISCORD, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -401,7 +402,7 @@ func dingtalkHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewDingtalkHookForm) return webhookParams{ - Type: webhook.DINGTALK, + Type: webhook_module.DINGTALK, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -422,7 +423,7 @@ func telegramHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewTelegramHookForm) return webhookParams{ - Type: webhook.TELEGRAM, + Type: webhook_module.TELEGRAM, URL: fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s", url.PathEscape(form.BotToken), url.QueryEscape(form.ChatID)), ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -447,7 +448,7 @@ func matrixHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewMatrixHookForm) return webhookParams{ - Type: webhook.MATRIX, + Type: webhook_module.MATRIX, URL: fmt.Sprintf("%s/_matrix/client/r0/rooms/%s/send/m.room.message", form.HomeserverURL, url.PathEscape(form.RoomID)), ContentType: webhook.ContentTypeJSON, HTTPMethod: http.MethodPut, @@ -474,7 +475,7 @@ func mSTeamsHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewMSTeamsHookForm) return webhookParams{ - Type: webhook.MSTEAMS, + Type: webhook_module.MSTEAMS, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -495,7 +496,7 @@ func slackHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewSlackHookForm) return webhookParams{ - Type: webhook.SLACK, + Type: webhook_module.SLACK, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -522,7 +523,7 @@ func feishuHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewFeishuHookForm) return webhookParams{ - Type: webhook.FEISHU, + Type: webhook_module.FEISHU, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -543,7 +544,7 @@ func wechatworkHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewWechatWorkHookForm) return webhookParams{ - Type: webhook.WECHATWORK, + Type: webhook_module.WECHATWORK, URL: form.PayloadURL, ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -564,7 +565,7 @@ func packagistHookParams(ctx *context.Context) webhookParams { form := web.GetForm(ctx).(*forms.NewPackagistHookForm) return webhookParams{ - Type: webhook.PACKAGIST, + Type: webhook_module.PACKAGIST, URL: fmt.Sprintf("https://packagist.org/api/update-package?username=%s&apiToken=%s", url.QueryEscape(form.Username), url.QueryEscape(form.APIToken)), ContentType: webhook.ContentTypeJSON, WebhookForm: form.WebhookForm, @@ -603,15 +604,15 @@ func checkWebhook(ctx *context.Context) (*orgRepoCtx, *webhook.Webhook) { ctx.Data["HookType"] = w.Type switch w.Type { - case webhook.SLACK: + case webhook_module.SLACK: ctx.Data["SlackHook"] = webhook_service.GetSlackHook(w) - case webhook.DISCORD: + case webhook_module.DISCORD: ctx.Data["DiscordHook"] = webhook_service.GetDiscordHook(w) - case webhook.TELEGRAM: + case webhook_module.TELEGRAM: ctx.Data["TelegramHook"] = webhook_service.GetTelegramHook(w) - case webhook.MATRIX: + case webhook_module.MATRIX: ctx.Data["MatrixHook"] = webhook_service.GetMatrixHook(w) - case webhook.PACKAGIST: + case webhook_module.PACKAGIST: ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w) } @@ -688,7 +689,7 @@ func TestWebhook(ctx *context.Context) { Pusher: apiUser, Sender: apiUser, } - if err := webhook_service.PrepareWebhook(ctx, w, webhook.HookEventPush, p); err != nil { + if err := webhook_service.PrepareWebhook(ctx, w, webhook_module.HookEventPush, p); err != nil { ctx.Flash.Error("PrepareWebhook: " + err.Error()) ctx.Status(http.StatusInternalServerError) } else { diff --git a/services/convert/convert.go b/services/convert/convert.go index 756a1f95d..a8329f528 100644 --- a/services/convert/convert.go +++ b/services/convert/convert.go @@ -22,13 +22,11 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/gitdiff" - webhook_service "code.gitea.io/gitea/services/webhook" ) // ToEmail convert models.EmailAddress to api.Email @@ -242,38 +240,6 @@ func ToGPGKeyEmail(email *user_model.EmailAddress) *api.GPGKeyEmail { } } -// ToHook convert models.Webhook to api.Hook -func ToHook(repoLink string, w *webhook.Webhook) (*api.Hook, error) { - config := map[string]string{ - "url": w.URL, - "content_type": w.ContentType.Name(), - } - if w.Type == webhook.SLACK { - s := webhook_service.GetSlackHook(w) - config["channel"] = s.Channel - config["username"] = s.Username - config["icon_url"] = s.IconURL - config["color"] = s.Color - } - - authorizationHeader, err := w.HeaderAuthorization() - if err != nil { - return nil, err - } - - return &api.Hook{ - ID: w.ID, - Type: w.Type, - URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID), - Active: w.IsActive, - Config: config, - Events: w.EventsArray(), - AuthorizationHeader: authorizationHeader, - Updated: w.UpdatedUnix.AsTime(), - Created: w.CreatedUnix.AsTime(), - }, nil -} - // ToGitHook convert git.Hook to api.GitHook func ToGitHook(h *git.Hook) *api.GitHook { return &api.GitHook{ diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go index eed711c58..effbe45e5 100644 --- a/services/webhook/deliver.go +++ b/services/webhook/deliver.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/modules/proxy" "code.gitea.io/gitea/modules/queue" "code.gitea.io/gitea/modules/setting" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/gobwas/glob" ) @@ -89,7 +90,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { } case http.MethodPut: switch w.Type { - case webhook_model.MATRIX: + case webhook_module.MATRIX: txnID, err := getMatrixTxnID([]byte(t.PayloadContent)) if err != nil { return err @@ -189,9 +190,9 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { // Update webhook last delivery status. if t.IsSucceed { - w.LastStatus = webhook_model.HookStatusSucceed + w.LastStatus = webhook_module.HookStatusSucceed } else { - w.LastStatus = webhook_model.HookStatusFail + w.LastStatus = webhook_module.HookStatusFail } if err = webhook_model.UpdateWebhookLastStatus(w); err != nil { log.Error("UpdateWebhookLastStatus: %v", err) diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go index e7a042f4d..ee63975ad 100644 --- a/services/webhook/deliver_test.go +++ b/services/webhook/deliver_test.go @@ -16,6 +16,7 @@ import ( webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" ) @@ -62,14 +63,14 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { URL: s.URL + "/webhook", ContentType: webhook_model.ContentTypeJSON, IsActive: true, - Type: webhook_model.GITEA, + Type: webhook_module.GITEA, } err := hook.SetHeaderAuthorization("Bearer s3cr3t-t0ken") assert.NoError(t, err) assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) db.GetEngine(db.DefaultContext).NoAutoTime().DB().Logger.ShowSQL(true) - hookTask := &webhook_model.HookTask{HookID: hook.ID, EventType: webhook_model.HookEventPush, Payloader: &api.PushPayload{}} + hookTask := &webhook_model.HookTask{HookID: hook.ID, EventType: webhook_module.HookEventPush, Payloader: &api.PushPayload{}} hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) assert.NoError(t, err) diff --git a/services/webhook/dingtalk.go b/services/webhook/dingtalk.go index 7cb1fb75f..99ee6e4d1 100644 --- a/services/webhook/dingtalk.go +++ b/services/webhook/dingtalk.go @@ -8,11 +8,11 @@ import ( "net/url" "strings" - webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" dingtalk "gitea.com/lunny/dingtalk_webhook" ) @@ -129,7 +129,7 @@ func (d *DingtalkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, } // Review implements PayloadConvertor Review method -func (d *DingtalkPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (d *DingtalkPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { var text, title string switch p.Action { case api.HookIssueReviewed: @@ -190,6 +190,6 @@ func createDingtalkPayload(title, text, singleTitle, singleURL string) *Dingtalk } // GetDingtalkPayload converts a ding talk webhook into a DingtalkPayload -func GetDingtalkPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetDingtalkPayload(p api.Payloader, event webhook_module.HookEventType, _ string) (api.Payloader, error) { return convertPayloader(new(DingtalkPayload), p, event) } diff --git a/services/webhook/dingtalk_test.go b/services/webhook/dingtalk_test.go index 89b5f9d21..e3122d2f3 100644 --- a/services/webhook/dingtalk_test.go +++ b/services/webhook/dingtalk_test.go @@ -7,8 +7,8 @@ import ( "net/url" "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -162,7 +162,7 @@ func TestDingTalkPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(DingtalkPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &DingtalkPayload{}, pl) diff --git a/services/webhook/discord.go b/services/webhook/discord.go index c9fdc9532..ed44fef40 100644 --- a/services/webhook/discord.go +++ b/services/webhook/discord.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -190,7 +191,7 @@ func (d *DiscordPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, } // Review implements PayloadConvertor Review method -func (d *DiscordPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (d *DiscordPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { var text, title string var color int switch p.Action { @@ -204,11 +205,11 @@ func (d *DiscordPayload) Review(p *api.PullRequestPayload, event webhook_model.H text = p.Review.Content switch event { - case webhook_model.HookEventPullRequestReviewApproved: + case webhook_module.HookEventPullRequestReviewApproved: color = greenColor - case webhook_model.HookEventPullRequestReviewRejected: + case webhook_module.HookEventPullRequestReviewRejected: color = redColor - case webhook_model.HookEventPullRequestComment: + case webhook_module.HookEventPullRequestComment: color = greyColor default: color = yellowColor @@ -256,7 +257,7 @@ func (d *DiscordPayload) Release(p *api.ReleasePayload) (api.Payloader, error) { } // GetDiscordPayload converts a discord webhook into a DiscordPayload -func GetDiscordPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetDiscordPayload(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) { s := new(DiscordPayload) discord := &DiscordMeta{} @@ -269,14 +270,14 @@ func GetDiscordPayload(p api.Payloader, event webhook_model.HookEventType, meta return convertPayloader(s, p, event) } -func parseHookPullRequestEventType(event webhook_model.HookEventType) (string, error) { +func parseHookPullRequestEventType(event webhook_module.HookEventType) (string, error) { switch event { - case webhook_model.HookEventPullRequestReviewApproved: + case webhook_module.HookEventPullRequestReviewApproved: return "approved", nil - case webhook_model.HookEventPullRequestReviewRejected: + case webhook_module.HookEventPullRequestReviewRejected: return "rejected", nil - case webhook_model.HookEventPullRequestComment: + case webhook_module.HookEventPullRequestComment: return "comment", nil default: diff --git a/services/webhook/discord_test.go b/services/webhook/discord_test.go index df3cdc15b..624d53446 100644 --- a/services/webhook/discord_test.go +++ b/services/webhook/discord_test.go @@ -6,9 +6,9 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -179,7 +179,7 @@ func TestDiscordPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(DiscordPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &DiscordPayload{}, pl) diff --git a/services/webhook/feishu.go b/services/webhook/feishu.go index 58b6fff33..4fbf8f76a 100644 --- a/services/webhook/feishu.go +++ b/services/webhook/feishu.go @@ -7,10 +7,10 @@ import ( "fmt" "strings" - webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -117,7 +117,7 @@ func (f *FeishuPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, e } // Review implements PayloadConvertor Review method -func (f *FeishuPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (f *FeishuPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { action, err := parseHookPullRequestEventType(event) if err != nil { return nil, err @@ -159,6 +159,6 @@ func (f *FeishuPayload) Release(p *api.ReleasePayload) (api.Payloader, error) { } // GetFeishuPayload converts a ding talk webhook into a FeishuPayload -func GetFeishuPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetFeishuPayload(p api.Payloader, event webhook_module.HookEventType, _ string) (api.Payloader, error) { return convertPayloader(new(FeishuPayload), p, event) } diff --git a/services/webhook/feishu_test.go b/services/webhook/feishu_test.go index df44fd1f7..84549c1fa 100644 --- a/services/webhook/feishu_test.go +++ b/services/webhook/feishu_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -124,7 +124,7 @@ func TestFeishuPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(FeishuPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &FeishuPayload{}, pl) diff --git a/services/webhook/general.go b/services/webhook/general.go index bec752cff..1f7d204d1 100644 --- a/services/webhook/general.go +++ b/services/webhook/general.go @@ -9,9 +9,11 @@ import ( "net/url" "strings" + webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type linkFormatter = func(string, string) string @@ -223,3 +225,36 @@ func getIssueCommentPayloadInfo(p *api.IssueCommentPayload, linkFormatter linkFo return text, issueTitle, color } + +// ToHook convert models.Webhook to api.Hook +// This function is not part of the convert package to prevent an import cycle +func ToHook(repoLink string, w *webhook_model.Webhook) (*api.Hook, error) { + config := map[string]string{ + "url": w.URL, + "content_type": w.ContentType.Name(), + } + if w.Type == webhook_module.SLACK { + s := GetSlackHook(w) + config["channel"] = s.Channel + config["username"] = s.Username + config["icon_url"] = s.IconURL + config["color"] = s.Color + } + + authorizationHeader, err := w.HeaderAuthorization() + if err != nil { + return nil, err + } + + return &api.Hook{ + ID: w.ID, + Type: w.Type, + URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID), + Active: w.IsActive, + Config: config, + Events: w.EventsArray(), + AuthorizationHeader: authorizationHeader, + Updated: w.UpdatedUnix.AsTime(), + Created: w.CreatedUnix.AsTime(), + }, nil +} diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go index bd3efd46b..cf2b503cd 100644 --- a/services/webhook/matrix.go +++ b/services/webhook/matrix.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" ) const matrixPayloadSizeLimit = 1024 * 64 @@ -173,7 +174,7 @@ func (m *MatrixPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, e } // Review implements PayloadConvertor Review method -func (m *MatrixPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (m *MatrixPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { senderLink := MatrixLinkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName) title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) titleLink := MatrixLinkFormatter(p.PullRequest.URL, title) @@ -210,7 +211,7 @@ func (m *MatrixPayload) Repository(p *api.RepositoryPayload) (api.Payloader, err } // GetMatrixPayload converts a Matrix webhook into a MatrixPayload -func GetMatrixPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetMatrixPayload(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) { s := new(MatrixPayload) matrix := &MatrixMeta{} diff --git a/services/webhook/matrix_test.go b/services/webhook/matrix_test.go index 754234ecc..8c7109422 100644 --- a/services/webhook/matrix_test.go +++ b/services/webhook/matrix_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -133,7 +133,7 @@ func TestMatrixPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(MatrixPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &MatrixPayload{}, pl) diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go index ef8366f8d..03d92821b 100644 --- a/services/webhook/msteams.go +++ b/services/webhook/msteams.go @@ -8,11 +8,11 @@ import ( "net/url" "strings" - webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -205,7 +205,7 @@ func (m *MSTeamsPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, } // Review implements PayloadConvertor Review method -func (m *MSTeamsPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (m *MSTeamsPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { var text, title string var color int switch p.Action { @@ -219,11 +219,11 @@ func (m *MSTeamsPayload) Review(p *api.PullRequestPayload, event webhook_model.H text = p.Review.Content switch event { - case webhook_model.HookEventPullRequestReviewApproved: + case webhook_module.HookEventPullRequestReviewApproved: color = greenColor - case webhook_model.HookEventPullRequestReviewRejected: + case webhook_module.HookEventPullRequestReviewRejected: color = redColor - case webhook_model.HookEventPullRequestComment: + case webhook_module.HookEventPullRequestComment: color = greyColor default: color = yellowColor @@ -297,7 +297,7 @@ func (m *MSTeamsPayload) Release(p *api.ReleasePayload) (api.Payloader, error) { } // GetMSTeamsPayload converts a MSTeams webhook into a MSTeamsPayload -func GetMSTeamsPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetMSTeamsPayload(p api.Payloader, event webhook_module.HookEventType, _ string) (api.Payloader, error) { return convertPayloader(new(MSTeamsPayload), p, event) } diff --git a/services/webhook/msteams_test.go b/services/webhook/msteams_test.go index 8daf99f86..4f378713c 100644 --- a/services/webhook/msteams_test.go +++ b/services/webhook/msteams_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -277,7 +277,7 @@ func TestMSTeamsPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(MSTeamsPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &MSTeamsPayload{}, pl) diff --git a/modules/notification/webhook/webhook.go b/services/webhook/notifier.go similarity index 80% rename from modules/notification/webhook/webhook.go rename to services/webhook/notifier.go index 97d5e0434..ee8076603 100644 --- a/modules/notification/webhook/webhook.go +++ b/services/webhook/notifier.go @@ -13,17 +13,21 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification/base" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "code.gitea.io/gitea/services/convert" - webhook_services "code.gitea.io/gitea/services/webhook" ) +func init() { + notification.RegisterNotifier(&webhookNotifier{}) +} + type webhookNotifier struct { base.NullNotifier } @@ -54,7 +58,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user return } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequestLabel, &api.PullRequestPayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequestLabel, &api.PullRequestPayload{ Action: api.HookIssueLabelCleared, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), @@ -62,7 +66,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user Sender: convert.ToUser(doer, nil), }) } else { - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssueLabel, &api.IssuePayload{ Action: api.HookIssueLabelCleared, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), @@ -80,7 +84,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m mode, _ := access_model.AccessLevel(ctx, doer, repo) // forked webhook - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: oldRepo}, webhook_module.HookEventFork, &api.ForkPayload{ Forkee: convert.ToRepo(ctx, oldRepo, oldMode), Repo: convert.ToRepo(ctx, repo, mode), Sender: convert.ToUser(doer, nil), @@ -92,7 +96,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m // Add to hook queue for created repo after session commit. if u.IsOrganization() { - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), @@ -105,7 +109,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), @@ -116,7 +120,7 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u } func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoDeleted, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(repo.MustOwner(ctx), nil), @@ -128,7 +132,7 @@ func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), @@ -159,7 +163,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u apiPullRequest.Action = api.HookIssueAssigned } // Assignee comment triggers a webhook - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequestAssign, apiPullRequest); err != nil { + if err := PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequestAssign, apiPullRequest); err != nil { log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, removed, err) return } @@ -177,7 +181,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u apiIssue.Action = api.HookIssueAssigned } // Assignee comment triggers a webhook - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueAssign, apiIssue); err != nil { + if err := PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssueAssign, apiIssue); err != nil { log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, removed, err) return } @@ -193,7 +197,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user return } issue.PullRequest.Issue = issue - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -206,7 +210,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user Sender: convert.ToUser(doer, nil), }) } else { - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssues, &api.IssuePayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -245,7 +249,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use } else { apiPullRequest.Action = api.HookIssueReOpened } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, apiPullRequest) + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequest, apiPullRequest) } else { apiIssue := &api.IssuePayload{ Index: issue.Index, @@ -258,7 +262,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use } else { apiIssue.Action = api.HookIssueReOpened } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, apiIssue) + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssues, apiIssue) } if err != nil { log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err) @@ -276,7 +280,7 @@ func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_mode } mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssues, &api.IssuePayload{ Action: api.HookIssueOpened, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), @@ -302,7 +306,7 @@ func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues } mode, _ := access_model.AccessLevel(ctx, pull.Issue.Poster, pull.Issue.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pull.Issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: pull.Issue.Repo}, webhook_module.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueOpened, Index: pull.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pull, nil), @@ -323,7 +327,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us var err error if issue.IsPull { issue.PullRequest.Issue = issue - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -336,7 +340,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us Sender: convert.ToUser(doer, nil), }) } else { - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssues, &api.IssuePayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -369,15 +373,15 @@ func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_mo return } - var eventType webhook.HookEventType + var eventType webhook_module.HookEventType if c.Issue.IsPull { - eventType = webhook.HookEventPullRequestComment + eventType = webhook_module.HookEventPullRequestComment } else { - eventType = webhook.HookEventIssueComment + eventType = webhook_module.HookEventIssueComment } mode, _ := access_model.AccessLevel(ctx, doer, c.Issue.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentEdited, Issue: convert.ToAPIIssue(ctx, c.Issue), Comment: convert.ToComment(c), @@ -397,15 +401,15 @@ func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_mo func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { - var eventType webhook.HookEventType + var eventType webhook_module.HookEventType if issue.IsPull { - eventType = webhook.HookEventPullRequestComment + eventType = webhook_module.HookEventPullRequestComment } else { - eventType = webhook.HookEventIssueComment + eventType = webhook_module.HookEventIssueComment } mode, _ := access_model.AccessLevel(ctx, doer, repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentCreated, Issue: convert.ToAPIIssue(ctx, issue), Comment: convert.ToComment(comment), @@ -434,15 +438,15 @@ func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_mo return } - var eventType webhook.HookEventType + var eventType webhook_module.HookEventType if comment.Issue.IsPull { - eventType = webhook.HookEventPullRequestComment + eventType = webhook_module.HookEventPullRequestComment } else { - eventType = webhook.HookEventIssueComment + eventType = webhook_module.HookEventIssueComment } mode, _ := access_model.AccessLevel(ctx, doer, comment.Issue.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentDeleted, Issue: convert.ToAPIIssue(ctx, comment.Issue), Comment: convert.ToComment(comment), @@ -456,7 +460,7 @@ func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_mo func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { // Add to hook queue for created wiki page. - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), @@ -469,7 +473,7 @@ func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_mode func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { // Add to hook queue for edit wiki page. - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiEdited, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), @@ -482,7 +486,7 @@ func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_mod func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) { // Add to hook queue for edit wiki page. - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiDeleted, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), @@ -517,7 +521,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use log.Error("LoadIssue: %v", err) return } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequestLabel, &api.PullRequestPayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequestLabel, &api.PullRequestPayload{ Action: api.HookIssueLabelUpdated, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), @@ -525,7 +529,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use Sender: convert.ToUser(doer, nil), }) } else { - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssueLabel, &api.IssuePayload{ Action: api.HookIssueLabelUpdated, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), @@ -559,7 +563,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * log.Error("LoadIssue: %v", err) return } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequestMilestone, &api.PullRequestPayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequestMilestone, &api.PullRequestPayload{ Action: hookAction, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), @@ -567,7 +571,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * Sender: convert.ToUser(doer, nil), }) } else { - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueMilestone, &api.IssuePayload{ + err = PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventIssueMilestone, &api.IssuePayload{ Action: hookAction, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), @@ -588,7 +592,7 @@ func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_mo return } - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventPush, &api.PushPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{ Ref: opts.RefFullName, Before: opts.OldCommitID, After: opts.NewCommitID, @@ -641,7 +645,7 @@ func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m Action: api.HookIssueClosed, } - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequest, apiPullRequest); err != nil { + if err := PrepareWebhooks(ctx, EventSource{Repository: pr.Issue.Repo}, webhook_module.HookEventPullRequest, apiPullRequest); err != nil { log.Error("PrepareWebhooks: %v", err) } } @@ -655,7 +659,7 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex issue := pr.Issue mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: issue.Repo}, webhook_module.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -672,15 +676,15 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex } func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { - var reviewHookType webhook.HookEventType + var reviewHookType webhook_module.HookEventType switch review.Type { case issues_model.ReviewTypeApprove: - reviewHookType = webhook.HookEventPullRequestReviewApproved + reviewHookType = webhook_module.HookEventPullRequestReviewApproved case issues_model.ReviewTypeComment: - reviewHookType = webhook.HookEventPullRequestComment + reviewHookType = webhook_module.HookEventPullRequestComment case issues_model.ReviewTypeReject: - reviewHookType = webhook.HookEventPullRequestReviewRejected + reviewHookType = webhook_module.HookEventPullRequestReviewRejected default: // unsupported review webhook type here log.Error("Unsupported review webhook type") @@ -697,7 +701,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue log.Error("models.AccessLevel: %v", err) return } - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: review.Issue.Repo}, reviewHookType, &api.PullRequestPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: review.Issue.Repo}, reviewHookType, &api.PullRequestPayload{ Action: api.HookIssueReviewed, Index: review.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), @@ -717,7 +721,7 @@ func (m *webhookNotifier) NotifyCreateRef(ctx context.Context, pusher *user_mode apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventCreate, &api.CreatePayload{ Ref: refName, Sha: refID, RefType: refType, @@ -738,7 +742,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe return } - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequestSync, &api.PullRequestPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: pr.Issue.Repo}, webhook_module.HookEventPullRequestSync, &api.PullRequestPayload{ Action: api.HookIssueSynchronized, Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), @@ -754,7 +758,7 @@ func (m *webhookNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_mode apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventDelete, &api.DeletePayload{ Ref: refName, RefType: refType, PusherType: api.PusherTypeUser, @@ -772,7 +776,7 @@ func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model } mode, _ := access_model.AccessLevel(ctx, doer, rel.Repo) - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: rel.Repo}, webhook_module.HookEventRelease, &api.ReleasePayload{ Action: action, Release: convert.ToRelease(rel), Repository: convert.ToRepo(ctx, rel.Repo, mode), @@ -802,7 +806,7 @@ func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *use return } - if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventPush, &api.PushPayload{ + if err := PrepareWebhooks(ctx, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{ Ref: opts.RefFullName, Before: opts.OldCommitID, After: opts.NewCommitID, @@ -835,7 +839,7 @@ func (m *webhookNotifier) NotifyPackageDelete(ctx context.Context, doer *user_mo } func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_model.PackageDescriptor, action api.HookPackageAction) { - source := webhook_services.EventSource{ + source := EventSource{ Repository: pd.Repository, Owner: pd.Owner, } @@ -846,7 +850,7 @@ func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_mo return } - if err := webhook_services.PrepareWebhooks(ctx, source, webhook.HookEventPackage, &api.PackagePayload{ + if err := PrepareWebhooks(ctx, source, webhook_module.HookEventPackage, &api.PackagePayload{ Action: action, Package: apiPackage, Sender: convert.ToUser(sender, nil), diff --git a/services/webhook/packagist.go b/services/webhook/packagist.go index 815e1a93e..e47e7d328 100644 --- a/services/webhook/packagist.go +++ b/services/webhook/packagist.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -20,7 +21,7 @@ type ( } `json:"repository"` } - // PackagistMeta contains the meta data for the webhook + // PackagistMeta contains the metadata for the webhook PackagistMeta struct { Username string `json:"username"` APIToken string `json:"api_token"` @@ -49,62 +50,62 @@ func (f *PackagistPayload) JSONPayload() ([]byte, error) { var _ PayloadConvertor = &PackagistPayload{} // Create implements PayloadConvertor Create method -func (f *PackagistPayload) Create(p *api.CreatePayload) (api.Payloader, error) { +func (f *PackagistPayload) Create(_ *api.CreatePayload) (api.Payloader, error) { return nil, nil } // Delete implements PayloadConvertor Delete method -func (f *PackagistPayload) Delete(p *api.DeletePayload) (api.Payloader, error) { +func (f *PackagistPayload) Delete(_ *api.DeletePayload) (api.Payloader, error) { return nil, nil } // Fork implements PayloadConvertor Fork method -func (f *PackagistPayload) Fork(p *api.ForkPayload) (api.Payloader, error) { +func (f *PackagistPayload) Fork(_ *api.ForkPayload) (api.Payloader, error) { return nil, nil } // Push implements PayloadConvertor Push method -func (f *PackagistPayload) Push(p *api.PushPayload) (api.Payloader, error) { +func (f *PackagistPayload) Push(_ *api.PushPayload) (api.Payloader, error) { return f, nil } // Issue implements PayloadConvertor Issue method -func (f *PackagistPayload) Issue(p *api.IssuePayload) (api.Payloader, error) { +func (f *PackagistPayload) Issue(_ *api.IssuePayload) (api.Payloader, error) { return nil, nil } // IssueComment implements PayloadConvertor IssueComment method -func (f *PackagistPayload) IssueComment(p *api.IssueCommentPayload) (api.Payloader, error) { +func (f *PackagistPayload) IssueComment(_ *api.IssueCommentPayload) (api.Payloader, error) { return nil, nil } // PullRequest implements PayloadConvertor PullRequest method -func (f *PackagistPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, error) { +func (f *PackagistPayload) PullRequest(_ *api.PullRequestPayload) (api.Payloader, error) { return nil, nil } // Review implements PayloadConvertor Review method -func (f *PackagistPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (f *PackagistPayload) Review(_ *api.PullRequestPayload, _ webhook_module.HookEventType) (api.Payloader, error) { return nil, nil } // Repository implements PayloadConvertor Repository method -func (f *PackagistPayload) Repository(p *api.RepositoryPayload) (api.Payloader, error) { +func (f *PackagistPayload) Repository(_ *api.RepositoryPayload) (api.Payloader, error) { return nil, nil } // Wiki implements PayloadConvertor Wiki method -func (f *PackagistPayload) Wiki(p *api.WikiPayload) (api.Payloader, error) { +func (f *PackagistPayload) Wiki(_ *api.WikiPayload) (api.Payloader, error) { return nil, nil } // Release implements PayloadConvertor Release method -func (f *PackagistPayload) Release(p *api.ReleasePayload) (api.Payloader, error) { +func (f *PackagistPayload) Release(_ *api.ReleasePayload) (api.Payloader, error) { return nil, nil } // GetPackagistPayload converts a packagist webhook into a PackagistPayload -func GetPackagistPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetPackagistPayload(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) { s := new(PackagistPayload) packagist := &PackagistMeta{} diff --git a/services/webhook/packagist_test.go b/services/webhook/packagist_test.go index 4941ae3f0..932b56fe9 100644 --- a/services/webhook/packagist_test.go +++ b/services/webhook/packagist_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -101,7 +101,7 @@ func TestPackagistPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(PackagistPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.Nil(t, pl) }) diff --git a/services/webhook/payloader.go b/services/webhook/payloader.go index 7b04f1dd3..9eff25628 100644 --- a/services/webhook/payloader.go +++ b/services/webhook/payloader.go @@ -4,8 +4,8 @@ package webhook import ( - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) // PayloadConvertor defines the interface to convert system webhook payload to external payload @@ -18,40 +18,40 @@ type PayloadConvertor interface { IssueComment(*api.IssueCommentPayload) (api.Payloader, error) Push(*api.PushPayload) (api.Payloader, error) PullRequest(*api.PullRequestPayload) (api.Payloader, error) - Review(*api.PullRequestPayload, webhook_model.HookEventType) (api.Payloader, error) + Review(*api.PullRequestPayload, webhook_module.HookEventType) (api.Payloader, error) Repository(*api.RepositoryPayload) (api.Payloader, error) Release(*api.ReleasePayload) (api.Payloader, error) Wiki(*api.WikiPayload) (api.Payloader, error) } -func convertPayloader(s PayloadConvertor, p api.Payloader, event webhook_model.HookEventType) (api.Payloader, error) { +func convertPayloader(s PayloadConvertor, p api.Payloader, event webhook_module.HookEventType) (api.Payloader, error) { switch event { - case webhook_model.HookEventCreate: + case webhook_module.HookEventCreate: return s.Create(p.(*api.CreatePayload)) - case webhook_model.HookEventDelete: + case webhook_module.HookEventDelete: return s.Delete(p.(*api.DeletePayload)) - case webhook_model.HookEventFork: + case webhook_module.HookEventFork: return s.Fork(p.(*api.ForkPayload)) - case webhook_model.HookEventIssues, webhook_model.HookEventIssueAssign, webhook_model.HookEventIssueLabel, webhook_model.HookEventIssueMilestone: + case webhook_module.HookEventIssues, webhook_module.HookEventIssueAssign, webhook_module.HookEventIssueLabel, webhook_module.HookEventIssueMilestone: return s.Issue(p.(*api.IssuePayload)) - case webhook_model.HookEventIssueComment, webhook_model.HookEventPullRequestComment: + case webhook_module.HookEventIssueComment, webhook_module.HookEventPullRequestComment: pl, ok := p.(*api.IssueCommentPayload) if ok { return s.IssueComment(pl) } return s.PullRequest(p.(*api.PullRequestPayload)) - case webhook_model.HookEventPush: + case webhook_module.HookEventPush: return s.Push(p.(*api.PushPayload)) - case webhook_model.HookEventPullRequest, webhook_model.HookEventPullRequestAssign, webhook_model.HookEventPullRequestLabel, - webhook_model.HookEventPullRequestMilestone, webhook_model.HookEventPullRequestSync: + case webhook_module.HookEventPullRequest, webhook_module.HookEventPullRequestAssign, webhook_module.HookEventPullRequestLabel, + webhook_module.HookEventPullRequestMilestone, webhook_module.HookEventPullRequestSync: return s.PullRequest(p.(*api.PullRequestPayload)) - case webhook_model.HookEventPullRequestReviewApproved, webhook_model.HookEventPullRequestReviewRejected, webhook_model.HookEventPullRequestReviewComment: + case webhook_module.HookEventPullRequestReviewApproved, webhook_module.HookEventPullRequestReviewRejected, webhook_module.HookEventPullRequestReviewComment: return s.Review(p.(*api.PullRequestPayload), event) - case webhook_model.HookEventRepository: + case webhook_module.HookEventRepository: return s.Repository(p.(*api.RepositoryPayload)) - case webhook_model.HookEventRelease: + case webhook_module.HookEventRelease: return s.Release(p.(*api.ReleasePayload)) - case webhook_model.HookEventWiki: + case webhook_module.HookEventWiki: return s.Wiki(p.(*api.WikiPayload)) } return s, nil diff --git a/services/webhook/slack.go b/services/webhook/slack.go index 1814361a1..c2d4a7731 100644 --- a/services/webhook/slack.go +++ b/services/webhook/slack.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) // SlackMeta contains the slack metadata @@ -231,7 +232,7 @@ func (s *SlackPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, er } // Review implements PayloadConvertor Review method -func (s *SlackPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (s *SlackPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName) title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) titleLink := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index) @@ -278,7 +279,7 @@ func (s *SlackPayload) createPayload(text string, attachments []SlackAttachment) } // GetSlackPayload converts a slack webhook into a SlackPayload -func GetSlackPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetSlackPayload(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) { s := new(SlackPayload) slack := &SlackMeta{} diff --git a/services/webhook/slack_test.go b/services/webhook/slack_test.go index db97b351c..d9828f374 100644 --- a/services/webhook/slack_test.go +++ b/services/webhook/slack_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -124,7 +124,7 @@ func TestSlackPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(SlackPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &SlackPayload{}, pl) diff --git a/services/webhook/telegram.go b/services/webhook/telegram.go index 8bc68490e..e5c731fc9 100644 --- a/services/webhook/telegram.go +++ b/services/webhook/telegram.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/markup" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -140,7 +141,7 @@ func (t *TelegramPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, } // Review implements PayloadConvertor Review method -func (t *TelegramPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (t *TelegramPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { var text, attachmentText string switch p.Action { case api.HookIssueReviewed: @@ -185,7 +186,7 @@ func (t *TelegramPayload) Release(p *api.ReleasePayload) (api.Payloader, error) } // GetTelegramPayload converts a telegram webhook into a TelegramPayload -func GetTelegramPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetTelegramPayload(p api.Payloader, event webhook_module.HookEventType, _ string) (api.Payloader, error) { return convertPayloader(new(TelegramPayload), p, event) } diff --git a/services/webhook/telegram_test.go b/services/webhook/telegram_test.go index b092f7e73..b42b0ccda 100644 --- a/services/webhook/telegram_test.go +++ b/services/webhook/telegram_test.go @@ -6,8 +6,8 @@ package webhook import ( "testing" - webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -124,7 +124,7 @@ func TestTelegramPayload(t *testing.T) { p.Action = api.HookIssueReviewed d := new(TelegramPayload) - pl, err := d.Review(p, webhook_model.HookEventPullRequestReviewApproved) + pl, err := d.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) require.NotNil(t, pl) require.IsType(t, &TelegramPayload{}, pl) diff --git a/services/webhook/webhook.go b/services/webhook/webhook.go index 21173e7cd..afd8e3c10 100644 --- a/services/webhook/webhook.go +++ b/services/webhook/webhook.go @@ -18,62 +18,58 @@ import ( "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/gobwas/glob" ) type webhook struct { - name webhook_model.HookType - payloadCreator func(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) + name webhook_module.HookType + payloadCreator func(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) } -var webhooks = map[webhook_model.HookType]*webhook{ - webhook_model.SLACK: { - name: webhook_model.SLACK, +var webhooks = map[webhook_module.HookType]*webhook{ + webhook_module.SLACK: { + name: webhook_module.SLACK, payloadCreator: GetSlackPayload, }, - webhook_model.DISCORD: { - name: webhook_model.DISCORD, + webhook_module.DISCORD: { + name: webhook_module.DISCORD, payloadCreator: GetDiscordPayload, }, - webhook_model.DINGTALK: { - name: webhook_model.DINGTALK, + webhook_module.DINGTALK: { + name: webhook_module.DINGTALK, payloadCreator: GetDingtalkPayload, }, - webhook_model.TELEGRAM: { - name: webhook_model.TELEGRAM, + webhook_module.TELEGRAM: { + name: webhook_module.TELEGRAM, payloadCreator: GetTelegramPayload, }, - webhook_model.MSTEAMS: { - name: webhook_model.MSTEAMS, + webhook_module.MSTEAMS: { + name: webhook_module.MSTEAMS, payloadCreator: GetMSTeamsPayload, }, - webhook_model.FEISHU: { - name: webhook_model.FEISHU, + webhook_module.FEISHU: { + name: webhook_module.FEISHU, payloadCreator: GetFeishuPayload, }, - webhook_model.MATRIX: { - name: webhook_model.MATRIX, + webhook_module.MATRIX: { + name: webhook_module.MATRIX, payloadCreator: GetMatrixPayload, }, - webhook_model.WECHATWORK: { - name: webhook_model.WECHATWORK, + webhook_module.WECHATWORK: { + name: webhook_module.WECHATWORK, payloadCreator: GetWechatworkPayload, }, - webhook_model.PACKAGIST: { - name: webhook_model.PACKAGIST, + webhook_module.PACKAGIST: { + name: webhook_module.PACKAGIST, payloadCreator: GetPackagistPayload, }, } -// RegisterWebhook registers a webhook -func RegisterWebhook(name string, webhook *webhook) { - webhooks[name] = webhook -} - // IsValidHookTaskType returns true if a webhook registered func IsValidHookTaskType(name string) bool { - if name == webhook_model.GITEA || name == webhook_model.GOGS { + if name == webhook_module.GITEA || name == webhook_module.GOGS { return true } _, ok := webhooks[name] @@ -157,7 +153,7 @@ func checkBranch(w *webhook_model.Webhook, branch string) bool { } // PrepareWebhook creates a hook task and enqueues it for processing -func PrepareWebhook(ctx context.Context, w *webhook_model.Webhook, event webhook_model.HookEventType, p api.Payloader) error { +func PrepareWebhook(ctx context.Context, w *webhook_model.Webhook, event webhook_module.HookEventType, p api.Payloader) error { // Skip sending if webhooks are disabled. if setting.DisableWebhooks { return nil @@ -176,7 +172,7 @@ func PrepareWebhook(ctx context.Context, w *webhook_model.Webhook, event webhook // Avoid sending "0 new commits" to non-integration relevant webhooks (e.g. slack, discord, etc.). // Integration webhooks (e.g. drone) still receive the required data. if pushEvent, ok := p.(*api.PushPayload); ok && - w.Type != webhook_model.GITEA && w.Type != webhook_model.GOGS && + w.Type != webhook_module.GITEA && w.Type != webhook_module.GOGS && len(pushEvent.Commits) == 0 { return nil } @@ -215,7 +211,7 @@ func PrepareWebhook(ctx context.Context, w *webhook_model.Webhook, event webhook } // PrepareWebhooks adds new webhooks to task queue for given payload. -func PrepareWebhooks(ctx context.Context, source EventSource, event webhook_model.HookEventType, p api.Payloader) error { +func PrepareWebhooks(ctx context.Context, source EventSource, event webhook_module.HookEventType, p api.Payloader) error { owner := source.Owner var ws []*webhook_model.Webhook diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index a1f197d80..338b94360 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" ) @@ -32,12 +33,12 @@ func TestPrepareWebhooks(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) hookTasks := []*webhook_model.HookTask{ - {HookID: 1, EventType: webhook_model.HookEventPush}, + {HookID: 1, EventType: webhook_module.HookEventPush}, } for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_model.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) + assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) for _, hookTask := range hookTasks { unittest.AssertExistsAndLoadBean(t, hookTask) } @@ -48,13 +49,13 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) hookTasks := []*webhook_model.HookTask{ - {HookID: 4, EventType: webhook_model.HookEventPush}, + {HookID: 4, EventType: webhook_module.HookEventPush}, } for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } // this test also ensures that * doesn't handle / in any special way (like shell would) - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_model.HookEventPush, &api.PushPayload{Ref: "refs/heads/feature/7791", Commits: []*api.PayloadCommit{{}}})) + assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/feature/7791", Commits: []*api.PayloadCommit{{}}})) for _, hookTask := range hookTasks { unittest.AssertExistsAndLoadBean(t, hookTask) } @@ -65,12 +66,12 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) hookTasks := []*webhook_model.HookTask{ - {HookID: 4, EventType: webhook_model.HookEventPush}, + {HookID: 4, EventType: webhook_module.HookEventPush}, } for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_model.HookEventPush, &api.PushPayload{Ref: "refs/heads/fix_weird_bug"})) + assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/fix_weird_bug"})) for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) diff --git a/services/webhook/wechatwork.go b/services/webhook/wechatwork.go index a77d871dd..dc8810c4a 100644 --- a/services/webhook/wechatwork.go +++ b/services/webhook/wechatwork.go @@ -7,10 +7,10 @@ import ( "fmt" "strings" - webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" + webhook_module "code.gitea.io/gitea/modules/webhook" ) type ( @@ -135,7 +135,7 @@ func (f *WechatworkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloade } // Review implements PayloadConvertor Review method -func (f *WechatworkPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { +func (f *WechatworkPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) { var text, title string switch p.Action { case api.HookIssueReviewed: @@ -180,6 +180,6 @@ func (f *WechatworkPayload) Release(p *api.ReleasePayload) (api.Payloader, error } // GetWechatworkPayload GetWechatworkPayload converts a ding talk webhook into a WechatworkPayload -func GetWechatworkPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) { +func GetWechatworkPayload(p api.Payloader, event webhook_module.HookEventType, _ string) (api.Payloader, error) { return convertPayloader(new(WechatworkPayload), p, event) }