aboutsummaryrefslogtreecommitdiffstats
path: root/routers/api/v1/utils/hook.go
blob: 0b00e59ade4e0ec0f7bcff95cc4593b5c8b42f22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2016 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package utils

import (
	"encoding/json"
	"net/http"
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"
	api "code.gitea.io/gitea/modules/structs"
	"code.gitea.io/gitea/routers/api/v1/convert"
	"code.gitea.io/gitea/routers/utils"

	"github.com/unknwon/com"
)

// GetOrgHook get an organization's webhook. If there is an error, write to
// `ctx` accordingly and return the error
func GetOrgHook(ctx *context.APIContext, orgID, hookID int64) (*models.Webhook, error) {
	w, err := models.GetWebhookByOrgID(orgID, hookID)
	if err != nil {
		if models.IsErrWebhookNotExist(err) {
			ctx.NotFound()
		} else {
			ctx.Error(500, "GetWebhookByOrgID", err)
		}
		return nil, err
	}
	return w, nil
}

// GetRepoHook get a repo's webhook. If there is an error, write to `ctx`
// accordingly and return the error
func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*models.Webhook, error) {
	w, err := models.GetWebhookByRepoID(repoID, hookID)
	if err != nil {
		if models.IsErrWebhookNotExist(err) {
			ctx.NotFound()
		} else {
			ctx.Error(500, "GetWebhookByID", err)
		}
		return nil, err
	}
	return w, nil
}

// CheckCreateHookOption check if a CreateHookOption form is valid. If invalid,
// write the appropriate error to `ctx`. Return whether the form is valid
func CheckCreateHookOption(ctx *context.APIContext, form *api.CreateHookOption) bool {
	if !models.IsValidHookTaskType(form.Type) {
		ctx.Error(422, "", "Invalid hook type")
		return false
	}
	for _, name := range []string{"url", "content_type"} {
		if _, ok := form.Config[name]; !ok {
			ctx.Error(422, "", "Missing config option: "+name)
			return false
		}
	}
	if !models.IsValidHookContentType(form.Config["content_type"]) {
		ctx.Error(422, "", "Invalid content type")
		return false
	}
	return true
}

// AddOrgHook add a hook to an organization. Writes to `ctx` accordingly
func AddOrgHook(ctx *context.APIContext, form *api.CreateHookOption) {
	org := ctx.Org.Organization
	hook, ok := addHook(ctx, form, org.ID, 0)
	if ok {
		ctx.JSON(http.StatusCreated, convert.ToHook(org.HomeLink(), hook))
	}
}

// AddRepoHook add a hook to a repo. Writes to `ctx` accordingly
func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) {
	repo := ctx.Repo
	hook, ok := addHook(ctx, form, 0, repo.Repository.ID)
	if ok {
		ctx.JSON(http.StatusCreated, convert.ToHook(repo.RepoLink, hook))
	}
}

// addHook add the hook specified by `form`, `orgID` and `repoID`. If there is
// an error, write to `ctx` accordingly. Return (webhook, ok)
func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID int64) (*models.Webhook, bool) {
	if len(form.Events) == 0 {
		form.Events = []string{"push"}
	}
	w := &models.Webhook{
		OrgID:       orgID,
		RepoID:      repoID,
		URL:         form.Config["url"],
		ContentType: models.ToHookContentType(form.Config["content_type"]),
		Secret:      form.Config["secret"],
		HTTPMethod:  "POST",
		HookEvent: &models.HookEvent{
			ChooseEvents: true,
			HookEvents: models.HookEvents{
				Create:       com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)),
				Delete:       com.IsSliceContainsStr(form.Events, string(models.HookEventDelete)),
				Fork:         com.IsSliceContainsStr(form.Events, string(models.HookEventFork)),
				Issues:       com.IsSliceContainsStr(form.Events, string(models.HookEventIssues)),
				IssueComment: com.IsSliceContainsStr(form.Events, string(models.HookEventIssueComment)),
				Push:         com.IsSliceContainsStr(form.Events, string(models.HookEventPush)),
				PullRequest:  com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest)),
				Repository:   com.IsSliceContainsStr(form.Events, string(models.HookEventRepository)),
				Release:      com.IsSliceContainsStr(form.Events, string(models.HookEventRelease)),
			},
		},
		IsActive:     form.Active,
		HookTaskType: models.ToHookTaskType(form.Type),
	}
	if w.HookTaskType == models.SLACK {
		channel, ok := form.Config["channel"]
		if !ok {
			ctx.Error(422, "", "Missing config option: channel")
			return nil, false
		}

		if !utils.IsValidSlackChannel(channel) {
			ctx.Error(400, "", "Invalid slack channel name")
			return nil, false
		}

		meta, err := json.Marshal(&models.SlackMeta{
			Channel:  strings.TrimSpace(channel),
			Username: form.Config["username"],
			IconURL:  form.Config["icon_url"],
			Color:    form.Config["color"],
		})
		if err != nil {
			ctx.Error(500, "slack: JSON marshal failed", err)
			return nil, false
		}
		w.Meta = string(meta)
	}

	if err := w.UpdateEvent(); err != nil {
		ctx.Error(500, "UpdateEvent", err)
		return nil, false
	} else if err := models.CreateWebhook(w); err != nil {
		ctx.Error(500, "CreateWebhook", err)
		return nil, false
	}
	return w, true
}

// EditOrgHook edit webhook `w` according to `form`. Writes to `ctx` accordingly
func EditOrgHook(ctx *context.APIContext, form *api.EditHookOption, hookID int64) {
	org := ctx.Org.Organization
	hook, err := GetOrgHook(ctx, org.ID, hookID)
	if err != nil {
		return
	}
	if !editHook(ctx, form, hook) {
		return
	}
	updated, err := GetOrgHook(ctx, org.ID, hookID)
	if err != nil {
		return
	}
	ctx.JSON(200, convert.ToHook(org.HomeLink(), updated))
}

// EditRepoHook edit webhook `w` according to `form`. Writes to `ctx` accordingly
func EditRepoHook(ctx *context.APIContext, form *api.EditHookOption, hookID int64) {
	repo := ctx.Repo
	hook, err := GetRepoHook(ctx, repo.Repository.ID, hookID)
	if err != nil {
		return
	}
	if !editHook(ctx, form, hook) {
		return
	}
	updated, err := GetRepoHook(ctx, repo.Repository.ID, hookID)
	if err != nil {
		return
	}
	ctx.JSON(200, convert.ToHook(repo.RepoLink, updated))
}

// editHook edit the webhook `w` according to `form`. If an error occurs, write
// to `ctx` accordingly and return the error. Return whether successful
func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webhook) bool {
	if form.Config != nil {
		if url, ok := form.Config["url"]; ok {
			w.URL = url
		}
		if ct, ok := form.Config["content_type"]; ok {
			if !models.IsValidHookContentType(ct) {
				ctx.Error(422, "", "Invalid content type")
				return false
			}
			w.ContentType = models.ToHookContentType(ct)
		}

		if w.HookTaskType == models.SLACK {
			if channel, ok := form.Config["channel"]; ok {
				meta, err := json.Marshal(&models.SlackMeta{
					Channel:  channel,
					Username: form.Config["username"],
					IconURL:  form.Config["icon_url"],
					Color:    form.Config["color"],
				})
				if err != nil {
					ctx.Error(500, "slack: JSON marshal failed", err)
					return false
				}
				w.Meta = string(meta)
			}
		}
	}

	// Update events
	if len(form.Events) == 0 {
		form.Events = []string{"push"}
	}
	w.PushOnly = false
	w.SendEverything = false
	w.ChooseEvents = true
	w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate))
	w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush))
	w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest))
	w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate))
	w.Delete = com.IsSliceContainsStr(form.Events, string(models.HookEventDelete))
	w.Fork = com.IsSliceContainsStr(form.Events, string(models.HookEventFork))
	w.Issues = com.IsSliceContainsStr(form.Events, string(models.HookEventIssues))
	w.IssueComment = com.IsSliceContainsStr(form.Events, string(models.HookEventIssueComment))
	w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush))
	w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest))
	w.Repository = com.IsSliceContainsStr(form.Events, string(models.HookEventRepository))
	w.Release = com.IsSliceContainsStr(form.Events, string(models.HookEventRelease))

	if err := w.UpdateEvent(); err != nil {
		ctx.Error(500, "UpdateEvent", err)
		return false
	}

	if form.Active != nil {
		w.IsActive = *form.Active
	}

	if err := models.UpdateWebhook(w); err != nil {
		ctx.Error(500, "UpdateWebhook", err)
		return false
	}
	return true
}