webhook.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. "io/ioutil"
  9. "time"
  10. "github.com/gogits/gogs/modules/httplib"
  11. "github.com/gogits/gogs/modules/log"
  12. "github.com/gogits/gogs/modules/setting"
  13. "github.com/gogits/gogs/modules/uuid"
  14. )
  15. var (
  16. ErrWebhookNotExist = errors.New("Webhook does not exist")
  17. )
  18. type HookContentType int
  19. const (
  20. JSON HookContentType = iota + 1
  21. FORM
  22. )
  23. // HookEvent represents events that will delivery hook.
  24. type HookEvent struct {
  25. PushOnly bool `json:"push_only"`
  26. }
  27. // Webhook represents a web hook object.
  28. type Webhook struct {
  29. Id int64
  30. RepoId int64
  31. Url string `xorm:"TEXT"`
  32. ContentType HookContentType
  33. Secret string `xorm:"TEXT"`
  34. Events string `xorm:"TEXT"`
  35. *HookEvent `xorm:"-"`
  36. IsSsl bool
  37. IsActive bool
  38. HookTaskType HookTaskType
  39. Meta string `xorm:"TEXT"` // store hook-specific attributes
  40. OrgId int64
  41. }
  42. // GetEvent handles conversion from Events to HookEvent.
  43. func (w *Webhook) GetEvent() {
  44. w.HookEvent = &HookEvent{}
  45. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  46. log.Error(4, "webhook.GetEvent(%d): %v", w.Id, err)
  47. }
  48. }
  49. func (w *Webhook) GetSlackHook() *Slack {
  50. s := &Slack{}
  51. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  52. log.Error(4, "webhook.GetSlackHook(%d): %v", w.Id, err)
  53. }
  54. return s
  55. }
  56. // UpdateEvent handles conversion from HookEvent to Events.
  57. func (w *Webhook) UpdateEvent() error {
  58. data, err := json.Marshal(w.HookEvent)
  59. w.Events = string(data)
  60. return err
  61. }
  62. // HasPushEvent returns true if hook enbaled push event.
  63. func (w *Webhook) HasPushEvent() bool {
  64. if w.PushOnly {
  65. return true
  66. }
  67. return false
  68. }
  69. // CreateWebhook creates a new web hook.
  70. func CreateWebhook(w *Webhook) error {
  71. _, err := x.Insert(w)
  72. return err
  73. }
  74. // GetWebhookById returns webhook by given ID.
  75. func GetWebhookById(hookId int64) (*Webhook, error) {
  76. w := &Webhook{Id: hookId}
  77. has, err := x.Get(w)
  78. if err != nil {
  79. return nil, err
  80. } else if !has {
  81. return nil, ErrWebhookNotExist
  82. }
  83. return w, nil
  84. }
  85. // GetActiveWebhooksByRepoId returns all active webhooks of repository.
  86. func GetActiveWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  87. err = x.Find(&ws, &Webhook{RepoId: repoId, IsActive: true})
  88. return ws, err
  89. }
  90. // GetWebhooksByRepoId returns all webhooks of repository.
  91. func GetWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  92. err = x.Find(&ws, &Webhook{RepoId: repoId})
  93. return ws, err
  94. }
  95. // UpdateWebhook updates information of webhook.
  96. func UpdateWebhook(w *Webhook) error {
  97. _, err := x.Id(w.Id).AllCols().Update(w)
  98. return err
  99. }
  100. // DeleteWebhook deletes webhook of repository.
  101. func DeleteWebhook(hookId int64) error {
  102. _, err := x.Delete(&Webhook{Id: hookId})
  103. return err
  104. }
  105. // GetWebhooksByOrgId returns all webhooks for an organization.
  106. func GetWebhooksByOrgId(orgId int64) (ws []*Webhook, err error) {
  107. err = x.Find(&ws, &Webhook{OrgId: orgId})
  108. return ws, err
  109. }
  110. // GetActiveWebhooksByOrgId returns all active webhooks for an organization.
  111. func GetActiveWebhooksByOrgId(orgId int64) (ws []*Webhook, err error) {
  112. err = x.Find(&ws, &Webhook{OrgId: orgId, IsActive: true})
  113. return ws, err
  114. }
  115. // ___ ___ __ ___________ __
  116. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  117. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  118. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  119. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  120. // \/ \/ \/ \/ \/
  121. type HookTaskType int
  122. const (
  123. GOGS HookTaskType = iota + 1
  124. SLACK
  125. )
  126. type HookEventType string
  127. const (
  128. PUSH HookEventType = "push"
  129. )
  130. type PayloadAuthor struct {
  131. Name string `json:"name"`
  132. Email string `json:"email"`
  133. }
  134. type PayloadCommit struct {
  135. Id string `json:"id"`
  136. Message string `json:"message"`
  137. Url string `json:"url"`
  138. Author *PayloadAuthor `json:"author"`
  139. }
  140. type PayloadRepo struct {
  141. Id int64 `json:"id"`
  142. Name string `json:"name"`
  143. Url string `json:"url"`
  144. Description string `json:"description"`
  145. Website string `json:"website"`
  146. Watchers int `json:"watchers"`
  147. Owner *PayloadAuthor `json:"author"`
  148. Private bool `json:"private"`
  149. }
  150. type BasePayload interface {
  151. GetJSONPayload() ([]byte, error)
  152. }
  153. // Payload represents a payload information of hook.
  154. type Payload struct {
  155. Secret string `json:"secret"`
  156. Ref string `json:"ref"`
  157. Commits []*PayloadCommit `json:"commits"`
  158. Repo *PayloadRepo `json:"repository"`
  159. Pusher *PayloadAuthor `json:"pusher"`
  160. Before string `json:"before"`
  161. After string `json:"after"`
  162. CompareUrl string `json:"compare_url"`
  163. }
  164. func (p Payload) GetJSONPayload() ([]byte, error) {
  165. data, err := json.Marshal(p)
  166. if err != nil {
  167. return []byte{}, err
  168. }
  169. return data, nil
  170. }
  171. // HookTask represents a hook task.
  172. type HookTask struct {
  173. Id int64
  174. Uuid string
  175. Type HookTaskType
  176. Url string
  177. BasePayload `xorm:"-"`
  178. PayloadContent string `xorm:"TEXT"`
  179. ContentType HookContentType
  180. EventType HookEventType
  181. IsSsl bool
  182. IsDelivered bool
  183. IsSucceed bool
  184. }
  185. // CreateHookTask creates a new hook task,
  186. // it handles conversion from Payload to PayloadContent.
  187. func CreateHookTask(t *HookTask) error {
  188. data, err := t.BasePayload.GetJSONPayload()
  189. if err != nil {
  190. return err
  191. }
  192. t.Uuid = uuid.NewV4().String()
  193. t.PayloadContent = string(data)
  194. _, err = x.Insert(t)
  195. return err
  196. }
  197. // UpdateHookTask updates information of hook task.
  198. func UpdateHookTask(t *HookTask) error {
  199. _, err := x.AllCols().Update(t)
  200. return err
  201. }
  202. // DeliverHooks checks and delivers undelivered hooks.
  203. func DeliverHooks() {
  204. timeout := time.Duration(setting.WebhookDeliverTimeout) * time.Second
  205. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  206. func(idx int, bean interface{}) error {
  207. t := bean.(*HookTask)
  208. req := httplib.Post(t.Url).SetTimeout(timeout, timeout).
  209. Header("X-Gogs-Delivery", t.Uuid).
  210. Header("X-Gogs-Event", string(t.EventType))
  211. switch t.ContentType {
  212. case JSON:
  213. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  214. case FORM:
  215. req.Param("payload", t.PayloadContent)
  216. }
  217. t.IsDelivered = true
  218. // TODO: record response.
  219. switch t.Type {
  220. case GOGS:
  221. {
  222. if _, err := req.Response(); err != nil {
  223. log.Error(4, "Delivery: %v", err)
  224. } else {
  225. t.IsSucceed = true
  226. }
  227. }
  228. case SLACK:
  229. {
  230. if res, err := req.Response(); err != nil {
  231. log.Error(4, "Delivery: %v", err)
  232. } else {
  233. defer res.Body.Close()
  234. contents, err := ioutil.ReadAll(res.Body)
  235. if err != nil {
  236. log.Error(4, "%s", err)
  237. } else {
  238. if string(contents) != "ok" {
  239. log.Error(4, "slack failed with: %s", string(contents))
  240. } else {
  241. t.IsSucceed = true
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if err := UpdateHookTask(t); err != nil {
  248. log.Error(4, "UpdateHookTask: %v", err)
  249. return nil
  250. }
  251. log.Trace("Hook delivered(%s): %s", t.Uuid, t.PayloadContent)
  252. return nil
  253. })
  254. }