Merge remote-tracking branch 'upstream/main' into limit-repo-size

This commit is contained in:
DmitryFrolovTri committed 2023-03-13 08:45:22 +00:00
commit 4b09713aed
419 files changed
+9967 -6026

No files matched your search

+5 -3
View File
@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/actions"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
actions_service "code.gitea.io/gitea/services/actions"
runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
@@ -51,13 +52,14 @@ func (s *Service) Register(
}
if runnerToken.IsActive {
return nil, errors.New("runner token has already activated")
return nil, errors.New("runner token has already been activated")
}
// create new runner
name, _ := util.SplitStringAtByteN(req.Msg.Name, 255)
runner := &actions_model.ActionRunner{
UUID: gouuid.New().String(),
Name: req.Msg.Name,
Name: name,
OwnerID: runnerToken.OwnerID,
RepoID: runnerToken.RepoID,
AgentLabels: req.Msg.AgentLabels,
@@ -148,7 +150,7 @@ func (s *Service) UpdateTask(
}
if err := actions_service.CreateCommitStatus(ctx, task.Job); err != nil {
log.Error("Update commit status failed: %v", err)
log.Error("Update commit status for job %v failed: %v", task.Job.ID, err)
// go on
}
+3 -3
View File
@@ -45,7 +45,7 @@ func ListUnadoptedRepositories(ctx *context.APIContext) {
if listOptions.Page == 0 {
listOptions.Page = 1
}
repoNames, count, err := repo_service.ListUnadoptedRepositories(ctx.FormString("query"), &listOptions)
repoNames, count, err := repo_service.ListUnadoptedRepositories(ctx, ctx.FormString("query"), &listOptions)
if err != nil {
ctx.InternalServerError(err)
return
@@ -109,7 +109,7 @@ func AdoptRepository(ctx *context.APIContext) {
ctx.NotFound()
return
}
if _, err := repo_service.AdoptRepository(ctx.Doer, ctxUser, repo_module.CreateRepoOptions{
if _, err := repo_service.AdoptRepository(ctx, ctx.Doer, ctxUser, repo_module.CreateRepoOptions{
Name: repoName,
IsPrivate: true,
}); err != nil {
@@ -172,7 +172,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
return
}
if err := repo_service.DeleteUnadoptedRepository(ctx.Doer, ctxUser, repoName); err != nil {
if err := repo_service.DeleteUnadoptedRepository(ctx, ctx.Doer, ctxUser, repoName); err != nil {
ctx.InternalServerError(err)
return
}
+1 -4
View File
@@ -105,10 +105,7 @@ func CreateHook(ctx *context.APIContext) {
// "$ref": "#/responses/Hook"
form := web.GetForm(ctx).(*api.CreateHookOption)
// TODO in body params
if !utils.CheckCreateHookOption(ctx, form) {
return
}
utils.AddSystemHook(ctx, form)
}
+7
View File
@@ -835,6 +835,13 @@ func Routes(ctx gocontext.Context) *web.Route {
m.Get("/stopwatches", reqToken(auth_model.AccessTokenScopeRepo), repo.GetStopwatches)
m.Get("/subscriptions", reqToken(auth_model.AccessTokenScopeRepo), user.GetMyWatchedRepos)
m.Get("/teams", reqToken(auth_model.AccessTokenScopeRepo), org.ListUserTeams)
m.Group("/hooks", func() {
m.Combo("").Get(user.ListHooks).
Post(bind(api.CreateHookOption{}), user.CreateHook)
m.Combo("/{id}").Get(user.GetHook).
Patch(bind(api.EditHookOption{}), user.EditHook).
Delete(user.DeleteHook)
}, reqToken(auth_model.AccessTokenScopeAdminUserHook), reqWebhooksEnabled())
}, reqToken(""))
// Repositories
+23 -56
View File
@@ -6,7 +6,6 @@ package org
import (
"net/http"
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"
@@ -39,34 +38,10 @@ func ListHooks(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/HookList"
opts := &webhook_model.ListWebhookOptions{
ListOptions: utils.GetListOptions(ctx),
OrgID: ctx.Org.Organization.ID,
}
count, err := webhook_model.CountWebhooksByOpts(opts)
if err != nil {
ctx.InternalServerError(err)
return
}
orgHooks, err := webhook_model.ListWebhooksByOpts(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
}
hooks := make([]*api.Hook, len(orgHooks))
for i, hook := range orgHooks {
hooks[i], err = webhook_service.ToHook(ctx.Org.Organization.AsUser().HomeLink(), hook)
if err != nil {
ctx.InternalServerError(err)
return
}
}
ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, hooks)
utils.ListOwnerHooks(
ctx,
ctx.ContextUser,
)
}
// GetHook get an organization's hook by id
@@ -92,14 +67,12 @@ func GetHook(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/Hook"
org := ctx.Org.Organization
hookID := ctx.ParamsInt64(":id")
hook, err := utils.GetOrgHook(ctx, org.ID, hookID)
hook, err := utils.GetOwnerHook(ctx, ctx.ContextUser.ID, ctx.ParamsInt64("id"))
if err != nil {
return
}
apiHook, err := webhook_service.ToHook(org.AsUser().HomeLink(), hook)
apiHook, err := webhook_service.ToHook(ctx.ContextUser.HomeLink(), hook)
if err != nil {
ctx.InternalServerError(err)
return
@@ -131,15 +104,14 @@ func CreateHook(ctx *context.APIContext) {
// "201":
// "$ref": "#/responses/Hook"
form := web.GetForm(ctx).(*api.CreateHookOption)
// TODO in body params
if !utils.CheckCreateHookOption(ctx, form) {
return
}
utils.AddOrgHook(ctx, form)
utils.AddOwnerHook(
ctx,
ctx.ContextUser,
web.GetForm(ctx).(*api.CreateHookOption),
)
}
// EditHook modify a hook of a repository
// EditHook modify a hook of an organization
func EditHook(ctx *context.APIContext) {
// swagger:operation PATCH /orgs/{org}/hooks/{id} organization orgEditHook
// ---
@@ -168,11 +140,12 @@ func EditHook(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/Hook"
form := web.GetForm(ctx).(*api.EditHookOption)
// TODO in body params
hookID := ctx.ParamsInt64(":id")
utils.EditOrgHook(ctx, form, hookID)
utils.EditOwnerHook(
ctx,
ctx.ContextUser,
web.GetForm(ctx).(*api.EditHookOption),
ctx.ParamsInt64("id"),
)
}
// DeleteHook delete a hook of an organization
@@ -198,15 +171,9 @@ func DeleteHook(ctx *context.APIContext) {
// "204":
// "$ref": "#/responses/empty"
org := ctx.Org.Organization
hookID := ctx.ParamsInt64(":id")
if err := webhook_model.DeleteWebhookByOrgID(org.ID, hookID); err != nil {
if webhook_model.IsErrWebhookNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "DeleteWebhookByOrgID", err)
}
return
}
ctx.Status(http.StatusNoContent)
utils.DeleteOwnerHook(
ctx,
ctx.ContextUser,
ctx.ParamsInt64("id"),
)
}
+15 -18
View File
@@ -4,13 +4,13 @@
package org
import (
"fmt"
"net/http"
"strconv"
"strings"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/label"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/api/v1/utils"
@@ -84,13 +84,12 @@ func CreateLabel(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.CreateLabelOption)
form.Color = strings.Trim(form.Color, " ")
if len(form.Color) == 6 {
form.Color = "#" + form.Color
}
if !issues_model.LabelColorPattern.MatchString(form.Color) {
ctx.Error(http.StatusUnprocessableEntity, "ColorPattern", fmt.Errorf("bad color code: %s", form.Color))
color, err := label.NormalizeColor(form.Color)
if err != nil {
ctx.Error(http.StatusUnprocessableEntity, "Color", err)
return
}
form.Color = color
label := &issues_model.Label{
Name: form.Name,
@@ -183,7 +182,7 @@ func EditLabel(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption)
label, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
l, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
if err != nil {
if issues_model.IsErrOrgLabelNotExist(err) {
ctx.NotFound()
@@ -194,30 +193,28 @@ func EditLabel(ctx *context.APIContext) {
}
if form.Name != nil {
label.Name = *form.Name
l.Name = *form.Name
}
if form.Exclusive != nil {
label.Exclusive = *form.Exclusive
l.Exclusive = *form.Exclusive
}
if form.Color != nil {
label.Color = strings.Trim(*form.Color, " ")
if len(label.Color) == 6 {
label.Color = "#" + label.Color
}
if !issues_model.LabelColorPattern.MatchString(label.Color) {
ctx.Error(http.StatusUnprocessableEntity, "ColorPattern", fmt.Errorf("bad color code: %s", label.Color))
color, err := label.NormalizeColor(*form.Color)
if err != nil {
ctx.Error(http.StatusUnprocessableEntity, "Color", err)
return
}
l.Color = color
}
if form.Description != nil {
label.Description = *form.Description
l.Description = *form.Description
}
if err := issues_model.UpdateLabel(label); err != nil {
if err := issues_model.UpdateLabel(l); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateLabel", err)
return
}
ctx.JSON(http.StatusOK, convert.ToLabel(label, nil, ctx.Org.Organization.AsUser()))
ctx.JSON(http.StatusOK, convert.ToLabel(l, nil, ctx.Org.Organization.AsUser()))
}
// DeleteLabel delete a label for an organization
+1 -1
View File
@@ -118,7 +118,7 @@ func DeleteBranch(ctx *context.APIContext) {
branchName := ctx.Params("*")
if err := repo_service.DeleteBranch(ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, branchName); err != nil {
if err := repo_service.DeleteBranch(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, branchName); err != nil {
switch {
case git.IsErrBranchNotExist(err):
ctx.NotFound(err)
+1 -5
View File
@@ -223,12 +223,8 @@ func CreateHook(ctx *context.APIContext) {
// responses:
// "201":
// "$ref": "#/responses/Hook"
form := web.GetForm(ctx).(*api.CreateHookOption)
if !utils.CheckCreateHookOption(ctx, form) {
return
}
utils.AddRepoHook(ctx, form)
utils.AddRepoHook(ctx, web.GetForm(ctx).(*api.CreateHookOption))
}
// EditHook modify a hook of a repository
+1 -1
View File
@@ -176,7 +176,7 @@ func CreateIssueAttachment(ctx *context.APIContext) {
filename = query
}
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, &repo_model.Attachment{
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename,
UploaderID: ctx.Doer.ID,
RepoID: ctx.Repo.Repository.ID,
@@ -180,7 +180,7 @@ func CreateIssueCommentAttachment(ctx *context.APIContext) {
filename = query
}
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, &repo_model.Attachment{
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename,
UploaderID: ctx.Doer.ID,
RepoID: ctx.Repo.Repository.ID,
+24 -28
View File
@@ -5,13 +5,12 @@
package repo
import (
"fmt"
"net/http"
"strconv"
"strings"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/label"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/api/v1/utils"
@@ -93,14 +92,14 @@ func GetLabel(ctx *context.APIContext) {
// "$ref": "#/responses/Label"
var (
label *issues_model.Label
err error
l *issues_model.Label
err error
)
strID := ctx.Params(":id")
if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil {
label, err = issues_model.GetLabelInRepoByName(ctx, ctx.Repo.Repository.ID, strID)
l, err = issues_model.GetLabelInRepoByName(ctx, ctx.Repo.Repository.ID, strID)
} else {
label, err = issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, intID)
l, err = issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, intID)
}
if err != nil {
if issues_model.IsErrRepoLabelNotExist(err) {
@@ -111,7 +110,7 @@ func GetLabel(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusOK, convert.ToLabel(label, ctx.Repo.Repository, nil))
ctx.JSON(http.StatusOK, convert.ToLabel(l, ctx.Repo.Repository, nil))
}
// CreateLabel create a label for a repository
@@ -145,28 +144,27 @@ func CreateLabel(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.CreateLabelOption)
form.Color = strings.Trim(form.Color, " ")
if len(form.Color) == 6 {
form.Color = "#" + form.Color
}
if !issues_model.LabelColorPattern.MatchString(form.Color) {
ctx.Error(http.StatusUnprocessableEntity, "ColorPattern", fmt.Errorf("bad color code: %s", form.Color))
color, err := label.NormalizeColor(form.Color)
if err != nil {
ctx.Error(http.StatusUnprocessableEntity, "StringToColor", err)
return
}
form.Color = color
label := &issues_model.Label{
l := &issues_model.Label{
Name: form.Name,
Exclusive: form.Exclusive,
Color: form.Color,
RepoID: ctx.Repo.Repository.ID,
Description: form.Description,
}
if err := issues_model.NewLabel(ctx, label); err != nil {
if err := issues_model.NewLabel(ctx, l); err != nil {
ctx.Error(http.StatusInternalServerError, "NewLabel", err)
return
}
ctx.JSON(http.StatusCreated, convert.ToLabel(label, ctx.Repo.Repository, nil))
ctx.JSON(http.StatusCreated, convert.ToLabel(l, ctx.Repo.Repository, nil))
}
// EditLabel modify a label for a repository
@@ -206,7 +204,7 @@ func EditLabel(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption)
label, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
l, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
if err != nil {
if issues_model.IsErrRepoLabelNotExist(err) {
ctx.NotFound()
@@ -217,30 +215,28 @@ func EditLabel(ctx *context.APIContext) {
}
if form.Name != nil {
label.Name = *form.Name
l.Name = *form.Name
}
if form.Exclusive != nil {
label.Exclusive = *form.Exclusive
l.Exclusive = *form.Exclusive
}
if form.Color != nil {
label.Color = strings.Trim(*form.Color, " ")
if len(label.Color) == 6 {
label.Color = "#" + label.Color
}
if !issues_model.LabelColorPattern.MatchString(label.Color) {
ctx.Error(http.StatusUnprocessableEntity, "ColorPattern", fmt.Errorf("bad color code: %s", label.Color))
color, err := label.NormalizeColor(*form.Color)
if err != nil {
ctx.Error(http.StatusUnprocessableEntity, "StringToColor", err)
return
}
l.Color = color
}
if form.Description != nil {
label.Description = *form.Description
l.Description = *form.Description
}
if err := issues_model.UpdateLabel(label); err != nil {
if err := issues_model.UpdateLabel(l); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateLabel", err)
return
}
ctx.JSON(http.StatusOK, convert.ToLabel(label, ctx.Repo.Repository, nil))
ctx.JSON(http.StatusOK, convert.ToLabel(l, ctx.Repo.Repository, nil))
}
// DeleteLabel delete a label for a repository
+11 -1
View File
@@ -58,8 +58,18 @@ func getNote(ctx *context.APIContext, identifier string) {
return
}
commitSHA, err := ctx.Repo.GitRepo.ConvertToSHA1(identifier)
if err != nil {
if git.IsErrNotExist(err) {
ctx.NotFound(err)
} else {
ctx.Error(http.StatusInternalServerError, "ConvertToSHA1", err)
}
return
}
var note git.Note
if err := git.GetNote(ctx, ctx.Repo.GitRepo, identifier, &note); err != nil {
if err := git.GetNote(ctx, ctx.Repo.GitRepo, commitSHA.String(), &note); err != nil {
if git.IsErrNotExist(err) {
ctx.NotFound(identifier)
return
+1 -1
View File
@@ -904,7 +904,7 @@ func MergePullRequest(ctx *context.APIContext) {
}
defer headRepo.Close()
}
if err := repo_service.DeleteBranch(ctx.Doer, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
if err := repo_service.DeleteBranch(ctx, ctx.Doer, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
switch {
case git.IsErrBranchNotExist(err):
ctx.NotFound(err)
+2 -2
View File
@@ -268,7 +268,7 @@ func DeletePullReview(ctx *context.APIContext) {
ctx.Status(http.StatusNoContent)
}
// CreatePullReview create a review to an pull request
// CreatePullReview create a review to a pull request
func CreatePullReview(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews repository repoCreatePullReview
// ---
@@ -360,7 +360,7 @@ func CreatePullReview(ctx *context.APIContext) {
line,
c.Body,
c.Path,
true, // is review
true, // pending review
0, // no reply
opts.CommitID,
); err != nil {
+1 -1
View File
@@ -194,7 +194,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
}
// Create a new attachment and save the file
attach, err := attachment.UploadAttachment(file, setting.Repository.Release.AllowedTypes, &repo_model.Attachment{
attach, err := attachment.UploadAttachment(file, setting.Repository.Release.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename,
UploaderID: ctx.Doer.ID,
RepoID: release.RepoID,
+6 -5
View File
@@ -19,6 +19,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/label"
"code.gitea.io/gitea/modules/log"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@@ -230,7 +231,7 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
if opt.AutoInit && opt.Readme == "" {
opt.Readme = "Default"
}
repo, err := repo_service.CreateRepository(ctx.Doer, owner, repo_module.CreateRepoOptions{
repo, err := repo_service.CreateRepository(ctx, ctx.Doer, owner, repo_module.CreateRepoOptions{
Name: opt.Name,
Description: opt.Description,
IssueLabels: opt.IssueLabels,
@@ -249,7 +250,7 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
} else if db.IsErrNameReserved(err) ||
db.IsErrNamePatternNotAllowed(err) ||
repo_module.IsErrIssueLabelTemplateLoad(err) {
label.IsErrTemplateLoad(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err)
} else {
ctx.Error(http.StatusInternalServerError, "CreateRepository", err)
@@ -394,7 +395,7 @@ func Generate(ctx *context.APIContext) {
}
}
repo, err := repo_service.GenerateRepository(ctx.Doer, ctxUser, ctx.Repo.Repository, opts)
repo, err := repo_service.GenerateRepository(ctx, ctx.Doer, ctxUser, ctx.Repo.Repository, opts)
if err != nil {
if repo_model.IsErrRepoAlreadyExist(err) {
ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
@@ -638,7 +639,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
}
// Check if repository name has been changed and not just a case change
if repo.LowerName != strings.ToLower(newRepoName) {
if err := repo_service.ChangeRepositoryName(ctx.Doer, repo, newRepoName); err != nil {
if err := repo_service.ChangeRepositoryName(ctx, ctx.Doer, repo, newRepoName); err != nil {
switch {
case repo_model.IsErrRepoAlreadyExist(err):
ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err)
@@ -719,7 +720,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
repo.SizeLimit = *opts.SizeLimit
}
if err := repo_service.UpdateRepository(repo, visibilityChanged); err != nil {
if err := repo_service.UpdateRepository(ctx, repo, visibilityChanged); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRepository", err)
return err
}
+154
View File
@@ -0,0 +1,154 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"net/http"
"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"
webhook_service "code.gitea.io/gitea/services/webhook"
)
// ListHooks list the authenticated user's webhooks
func ListHooks(ctx *context.APIContext) {
// swagger:operation GET /user/hooks user userListHooks
// ---
// summary: List the authenticated user's webhooks
// produces:
// - application/json
// parameters:
// - name: page
// in: query
// description: page number of results to return (1-based)
// type: integer
// - name: limit
// in: query
// description: page size of results
// type: integer
// responses:
// "200":
// "$ref": "#/responses/HookList"
utils.ListOwnerHooks(
ctx,
ctx.Doer,
)
}
// GetHook get the authenticated user's hook by id
func GetHook(ctx *context.APIContext) {
// swagger:operation GET /user/hooks/{id} user userGetHook
// ---
// summary: Get a hook
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of the hook to get
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/Hook"
hook, err := utils.GetOwnerHook(ctx, ctx.Doer.ID, ctx.ParamsInt64("id"))
if err != nil {
return
}
apiHook, err := webhook_service.ToHook(ctx.Doer.HomeLink(), hook)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiHook)
}
// CreateHook create a hook for the authenticated user
func CreateHook(ctx *context.APIContext) {
// swagger:operation POST /user/hooks user userCreateHook
// ---
// summary: Create a hook
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/CreateHookOption"
// responses:
// "201":
// "$ref": "#/responses/Hook"
utils.AddOwnerHook(
ctx,
ctx.Doer,
web.GetForm(ctx).(*api.CreateHookOption),
)
}
// EditHook modify a hook of the authenticated user
func EditHook(ctx *context.APIContext) {
// swagger:operation PATCH /user/hooks/{id} user userEditHook
// ---
// summary: Update a hook
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of the hook to update
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/EditHookOption"
// responses:
// "200":
// "$ref": "#/responses/Hook"
utils.EditOwnerHook(
ctx,
ctx.Doer,
web.GetForm(ctx).(*api.EditHookOption),
ctx.ParamsInt64("id"),
)
}
// DeleteHook delete a hook of the authenticated user
func DeleteHook(ctx *context.APIContext) {
// swagger:operation DELETE /user/hooks/{id} user userDeleteHook
// ---
// summary: Delete a hook
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of the hook to delete
// type: integer
// format: int64
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
utils.DeleteOwnerHook(
ctx,
ctx.Doer,
ctx.ParamsInt64("id"),
)
}
+68 -21
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"strings"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/json"
@@ -18,15 +19,46 @@ import (
webhook_service "code.gitea.io/gitea/services/webhook"
)
// 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) (*webhook.Webhook, error) {
w, err := webhook.GetWebhookByOrgID(orgID, hookID)
// ListOwnerHooks lists the webhooks of the provided owner
func ListOwnerHooks(ctx *context.APIContext, owner *user_model.User) {
opts := &webhook.ListWebhookOptions{
ListOptions: GetListOptions(ctx),
OwnerID: owner.ID,
}
count, err := webhook.CountWebhooksByOpts(opts)
if err != nil {
ctx.InternalServerError(err)
return
}
hooks, err := webhook.ListWebhooksByOpts(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
}
apiHooks := make([]*api.Hook, len(hooks))
for i, hook := range hooks {
apiHooks[i], err = webhook_service.ToHook(owner.HomeLink(), hook)
if err != nil {
ctx.InternalServerError(err)
return
}
}
ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiHooks)
}
// GetOwnerHook gets an user or organization webhook. Errors are written to ctx.
func GetOwnerHook(ctx *context.APIContext, ownerID, hookID int64) (*webhook.Webhook, error) {
w, err := webhook.GetWebhookByOwnerID(ownerID, hookID)
if err != nil {
if webhook.IsErrWebhookNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "GetWebhookByOrgID", err)
ctx.Error(http.StatusInternalServerError, "GetWebhookByOwnerID", err)
}
return nil, err
}
@@ -48,9 +80,9 @@ func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*webhook.Webhoo
return w, nil
}
// CheckCreateHookOption check if a CreateHookOption form is valid. If invalid,
// 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 {
func checkCreateHookOption(ctx *context.APIContext, form *api.CreateHookOption) bool {
if !webhook_service.IsValidHookTaskType(form.Type) {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Invalid hook type: %s", form.Type))
return false
@@ -81,14 +113,13 @@ func AddSystemHook(ctx *context.APIContext, form *api.CreateHookOption) {
}
}
// 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)
// AddOwnerHook adds a hook to an user or organization
func AddOwnerHook(ctx *context.APIContext, owner *user_model.User, form *api.CreateHookOption) {
hook, ok := addHook(ctx, form, owner.ID, 0)
if !ok {
return
}
apiHook, ok := toAPIHook(ctx, org.AsUser().HomeLink(), hook)
apiHook, ok := toAPIHook(ctx, owner.HomeLink(), hook)
if !ok {
return
}
@@ -128,14 +159,18 @@ func pullHook(events []string, event string) bool {
return util.SliceContainsString(events, event, true) || util.SliceContainsString(events, string(webhook_module.HookEventPullRequest), true)
}
// addHook add the hook specified by `form`, `orgID` and `repoID`. If there is
// addHook add the hook specified by `form`, `ownerID` 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) (*webhook.Webhook, bool) {
func addHook(ctx *context.APIContext, form *api.CreateHookOption, ownerID, repoID int64) (*webhook.Webhook, bool) {
if !checkCreateHookOption(ctx, form) {
return nil, false
}
if len(form.Events) == 0 {
form.Events = []string{"push"}
}
w := &webhook.Webhook{
OrgID: orgID,
OwnerID: ownerID,
RepoID: repoID,
URL: form.Config["url"],
ContentType: webhook.ToHookContentType(form.Config["content_type"]),
@@ -234,21 +269,20 @@ func EditSystemHook(ctx *context.APIContext, form *api.EditHookOption, hookID in
ctx.JSON(http.StatusOK, h)
}
// 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)
// EditOwnerHook updates a webhook of an user or organization
func EditOwnerHook(ctx *context.APIContext, owner *user_model.User, form *api.EditHookOption, hookID int64) {
hook, err := GetOwnerHook(ctx, owner.ID, hookID)
if err != nil {
return
}
if !editHook(ctx, form, hook) {
return
}
updated, err := GetOrgHook(ctx, org.ID, hookID)
updated, err := GetOwnerHook(ctx, owner.ID, hookID)
if err != nil {
return
}
apiHook, ok := toAPIHook(ctx, org.AsUser().HomeLink(), updated)
apiHook, ok := toAPIHook(ctx, owner.HomeLink(), updated)
if !ok {
return
}
@@ -362,3 +396,16 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh
}
return true
}
// DeleteOwnerHook deletes the hook owned by the owner.
func DeleteOwnerHook(ctx *context.APIContext, owner *user_model.User, hookID int64) {
if err := webhook.DeleteWebhookByOwnerID(owner.ID, hookID); err != nil {
if webhook.IsErrWebhookNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "DeleteWebhookByOwnerID", err)
}
return
}
ctx.Status(http.StatusNoContent)
}