code.gitea.io/gitea@v1.21.7/models/webhook/webhook_system.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package webhook 5 6 import ( 7 "context" 8 "fmt" 9 10 "code.gitea.io/gitea/models/db" 11 "code.gitea.io/gitea/modules/util" 12 ) 13 14 // GetDefaultWebhooks returns all admin-default webhooks. 15 func GetDefaultWebhooks(ctx context.Context) ([]*Webhook, error) { 16 webhooks := make([]*Webhook, 0, 5) 17 return webhooks, db.GetEngine(ctx). 18 Where("repo_id=? AND owner_id=? AND is_system_webhook=?", 0, 0, false). 19 Find(&webhooks) 20 } 21 22 // GetSystemOrDefaultWebhook returns admin system or default webhook by given ID. 23 func GetSystemOrDefaultWebhook(ctx context.Context, id int64) (*Webhook, error) { 24 webhook := &Webhook{ID: id} 25 has, err := db.GetEngine(ctx). 26 Where("repo_id=? AND owner_id=?", 0, 0). 27 Get(webhook) 28 if err != nil { 29 return nil, err 30 } else if !has { 31 return nil, ErrWebhookNotExist{ID: id} 32 } 33 return webhook, nil 34 } 35 36 // GetSystemWebhooks returns all admin system webhooks. 37 func GetSystemWebhooks(ctx context.Context, isActive util.OptionalBool) ([]*Webhook, error) { 38 webhooks := make([]*Webhook, 0, 5) 39 if isActive.IsNone() { 40 return webhooks, db.GetEngine(ctx). 41 Where("repo_id=? AND owner_id=? AND is_system_webhook=?", 0, 0, true). 42 Find(&webhooks) 43 } 44 return webhooks, db.GetEngine(ctx). 45 Where("repo_id=? AND owner_id=? AND is_system_webhook=? AND is_active = ?", 0, 0, true, isActive.IsTrue()). 46 Find(&webhooks) 47 } 48 49 // DeleteDefaultSystemWebhook deletes an admin-configured default or system webhook (where Org and Repo ID both 0) 50 func DeleteDefaultSystemWebhook(ctx context.Context, id int64) error { 51 return db.WithTx(ctx, func(ctx context.Context) error { 52 count, err := db.GetEngine(ctx). 53 Where("repo_id=? AND owner_id=?", 0, 0). 54 Delete(&Webhook{ID: id}) 55 if err != nil { 56 return err 57 } else if count == 0 { 58 return ErrWebhookNotExist{ID: id} 59 } 60 61 _, err = db.DeleteByBean(ctx, &HookTask{HookID: id}) 62 return err 63 }) 64 } 65 66 // CopyDefaultWebhooksToRepo creates copies of the default webhooks in a new repo 67 func CopyDefaultWebhooksToRepo(ctx context.Context, repoID int64) error { 68 ws, err := GetDefaultWebhooks(ctx) 69 if err != nil { 70 return fmt.Errorf("GetDefaultWebhooks: %v", err) 71 } 72 73 for _, w := range ws { 74 w.ID = 0 75 w.RepoID = repoID 76 if err := CreateWebhook(ctx, w); err != nil { 77 return fmt.Errorf("CreateWebhook: %v", err) 78 } 79 } 80 return nil 81 }