webhook.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "github.com/gogits/gogs/modules/log"
  9. )
  10. var (
  11. ErrWebhookNotExist = errors.New("Webhook does not exist")
  12. )
  13. // Content types.
  14. const (
  15. CT_JSON = iota + 1
  16. CT_FORM
  17. )
  18. type HookEvent struct {
  19. PushOnly bool `json:"push_only"`
  20. }
  21. type Webhook struct {
  22. Id int64
  23. RepoId int64
  24. Url string `xorm:"TEXT"`
  25. ContentType int
  26. Secret string `xorm:"TEXT"`
  27. Events string `xorm:"TEXT"`
  28. *HookEvent `xorm:"-"`
  29. IsSsl bool
  30. IsActive bool
  31. }
  32. func (w *Webhook) GetEvent() {
  33. w.HookEvent = &HookEvent{}
  34. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  35. log.Error("webhook.GetEvent(%d): %v", w.Id, err)
  36. }
  37. }
  38. func (w *Webhook) SaveEvent() error {
  39. data, err := json.Marshal(w.HookEvent)
  40. w.Events = string(data)
  41. return err
  42. }
  43. func (w *Webhook) HasPushEvent() bool {
  44. if w.PushOnly {
  45. return true
  46. }
  47. return false
  48. }
  49. // CreateWebhook creates new webhook.
  50. func CreateWebhook(w *Webhook) error {
  51. _, err := orm.Insert(w)
  52. return err
  53. }
  54. // UpdateWebhook updates information of webhook.
  55. func UpdateWebhook(w *Webhook) error {
  56. _, err := orm.AllCols().Update(w)
  57. return err
  58. }
  59. // GetWebhookById returns webhook by given ID.
  60. func GetWebhookById(hookId int64) (*Webhook, error) {
  61. w := &Webhook{Id: hookId}
  62. has, err := orm.Get(w)
  63. if err != nil {
  64. return nil, err
  65. } else if !has {
  66. return nil, ErrWebhookNotExist
  67. }
  68. return w, nil
  69. }
  70. // GetActiveWebhooksByRepoId returns all active webhooks of repository.
  71. func GetActiveWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  72. err = orm.Find(&ws, &Webhook{RepoId: repoId, IsActive: true})
  73. return ws, err
  74. }
  75. // GetWebhooksByRepoId returns all webhooks of repository.
  76. func GetWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  77. err = orm.Find(&ws, &Webhook{RepoId: repoId})
  78. return ws, err
  79. }
  80. // DeleteWebhook deletes webhook of repository.
  81. func DeleteWebhook(hookId int64) error {
  82. _, err := orm.Delete(&Webhook{Id: hookId})
  83. return err
  84. }