webhook.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. var hookContentTypes = map[string]HookContentType{
  24. "json": JSON,
  25. "form": FORM,
  26. }
  27. // ToHookContentType returns HookContentType by given name.
  28. func ToHookContentType(name string) HookContentType {
  29. return hookContentTypes[name]
  30. }
  31. func (t HookContentType) Name() string {
  32. switch t {
  33. case JSON:
  34. return "json"
  35. case FORM:
  36. return "form"
  37. }
  38. return ""
  39. }
  40. // IsValidHookContentType returns true if given name is a valid hook content type.
  41. func IsValidHookContentType(name string) bool {
  42. _, ok := hookContentTypes[name]
  43. return ok
  44. }
  45. // HookEvent represents events that will delivery hook.
  46. type HookEvent struct {
  47. PushOnly bool `json:"push_only"`
  48. }
  49. // Webhook represents a web hook object.
  50. type Webhook struct {
  51. Id int64
  52. RepoId int64
  53. Url string `xorm:"TEXT"`
  54. ContentType HookContentType
  55. Secret string `xorm:"TEXT"`
  56. Events string `xorm:"TEXT"`
  57. *HookEvent `xorm:"-"`
  58. IsSsl bool
  59. IsActive bool
  60. HookTaskType HookTaskType
  61. Meta string `xorm:"TEXT"` // store hook-specific attributes
  62. OrgId int64
  63. }
  64. // GetEvent handles conversion from Events to HookEvent.
  65. func (w *Webhook) GetEvent() {
  66. w.HookEvent = &HookEvent{}
  67. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  68. log.Error(4, "webhook.GetEvent(%d): %v", w.Id, err)
  69. }
  70. }
  71. func (w *Webhook) GetSlackHook() *Slack {
  72. s := &Slack{}
  73. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  74. log.Error(4, "webhook.GetSlackHook(%d): %v", w.Id, err)
  75. }
  76. return s
  77. }
  78. // UpdateEvent handles conversion from HookEvent to Events.
  79. func (w *Webhook) UpdateEvent() error {
  80. data, err := json.Marshal(w.HookEvent)
  81. w.Events = string(data)
  82. return err
  83. }
  84. // HasPushEvent returns true if hook enbaled push event.
  85. func (w *Webhook) HasPushEvent() bool {
  86. if w.PushOnly {
  87. return true
  88. }
  89. return false
  90. }
  91. // CreateWebhook creates a new web hook.
  92. func CreateWebhook(w *Webhook) error {
  93. _, err := x.Insert(w)
  94. return err
  95. }
  96. // GetWebhookById returns webhook by given ID.
  97. func GetWebhookById(hookId int64) (*Webhook, error) {
  98. w := &Webhook{Id: hookId}
  99. has, err := x.Get(w)
  100. if err != nil {
  101. return nil, err
  102. } else if !has {
  103. return nil, ErrWebhookNotExist
  104. }
  105. return w, nil
  106. }
  107. // GetActiveWebhooksByRepoId returns all active webhooks of repository.
  108. func GetActiveWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  109. err = x.Where("repo_id=?", repoId).And("is_active=?", true).Find(&ws)
  110. return ws, err
  111. }
  112. // GetWebhooksByRepoId returns all webhooks of repository.
  113. func GetWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
  114. err = x.Find(&ws, &Webhook{RepoId: repoId})
  115. return ws, err
  116. }
  117. // UpdateWebhook updates information of webhook.
  118. func UpdateWebhook(w *Webhook) error {
  119. _, err := x.Id(w.Id).AllCols().Update(w)
  120. return err
  121. }
  122. // DeleteWebhook deletes webhook of repository.
  123. func DeleteWebhook(hookId int64) error {
  124. _, err := x.Delete(&Webhook{Id: hookId})
  125. return err
  126. }
  127. // GetWebhooksByOrgId returns all webhooks for an organization.
  128. func GetWebhooksByOrgId(orgId int64) (ws []*Webhook, err error) {
  129. err = x.Find(&ws, &Webhook{OrgId: orgId})
  130. return ws, err
  131. }
  132. // GetActiveWebhooksByOrgId returns all active webhooks for an organization.
  133. func GetActiveWebhooksByOrgId(orgId int64) (ws []*Webhook, err error) {
  134. err = x.Where("org_id=?", orgId).And("is_active=?", true).Find(&ws)
  135. return ws, err
  136. }
  137. // ___ ___ __ ___________ __
  138. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  139. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  140. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  141. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  142. // \/ \/ \/ \/ \/
  143. type HookTaskType int
  144. const (
  145. GOGS HookTaskType = iota + 1
  146. SLACK
  147. )
  148. var hookTaskTypes = map[string]HookTaskType{
  149. "gogs": GOGS,
  150. "slack": SLACK,
  151. }
  152. // ToHookTaskType returns HookTaskType by given name.
  153. func ToHookTaskType(name string) HookTaskType {
  154. return hookTaskTypes[name]
  155. }
  156. func (t HookTaskType) Name() string {
  157. switch t {
  158. case GOGS:
  159. return "gogs"
  160. case SLACK:
  161. return "slack"
  162. }
  163. return ""
  164. }
  165. // IsValidHookTaskType returns true if given name is a valid hook task type.
  166. func IsValidHookTaskType(name string) bool {
  167. _, ok := hookTaskTypes[name]
  168. return ok
  169. }
  170. type HookEventType string
  171. const (
  172. PUSH HookEventType = "push"
  173. )
  174. type PayloadAuthor struct {
  175. Name string `json:"name"`
  176. Email string `json:"email"`
  177. UserName string `json:"username"`
  178. }
  179. type PayloadCommit struct {
  180. Id string `json:"id"`
  181. Message string `json:"message"`
  182. Url string `json:"url"`
  183. Author *PayloadAuthor `json:"author"`
  184. }
  185. type PayloadRepo struct {
  186. Id int64 `json:"id"`
  187. Name string `json:"name"`
  188. Url string `json:"url"`
  189. Description string `json:"description"`
  190. Website string `json:"website"`
  191. Watchers int `json:"watchers"`
  192. Owner *PayloadAuthor `json:"owner"`
  193. Private bool `json:"private"`
  194. }
  195. type BasePayload interface {
  196. GetJSONPayload() ([]byte, error)
  197. }
  198. // Payload represents a payload information of hook.
  199. type Payload struct {
  200. Secret string `json:"secret"`
  201. Ref string `json:"ref"`
  202. Commits []*PayloadCommit `json:"commits"`
  203. Repo *PayloadRepo `json:"repository"`
  204. Pusher *PayloadAuthor `json:"pusher"`
  205. Before string `json:"before"`
  206. After string `json:"after"`
  207. CompareUrl string `json:"compare_url"`
  208. }
  209. func (p Payload) GetJSONPayload() ([]byte, error) {
  210. data, err := json.Marshal(p)
  211. if err != nil {
  212. return []byte{}, err
  213. }
  214. return data, nil
  215. }
  216. // HookTask represents a hook task.
  217. type HookTask struct {
  218. Id int64
  219. Uuid string
  220. Type HookTaskType
  221. Url string
  222. BasePayload `xorm:"-"`
  223. PayloadContent string `xorm:"TEXT"`
  224. ContentType HookContentType
  225. EventType HookEventType
  226. IsSsl bool
  227. IsDelivered bool
  228. IsSucceed bool
  229. }
  230. // CreateHookTask creates a new hook task,
  231. // it handles conversion from Payload to PayloadContent.
  232. func CreateHookTask(t *HookTask) error {
  233. data, err := t.BasePayload.GetJSONPayload()
  234. if err != nil {
  235. return err
  236. }
  237. t.Uuid = uuid.NewV4().String()
  238. t.PayloadContent = string(data)
  239. _, err = x.Insert(t)
  240. return err
  241. }
  242. // UpdateHookTask updates information of hook task.
  243. func UpdateHookTask(t *HookTask) error {
  244. _, err := x.Id(t.Id).AllCols().Update(t)
  245. return err
  246. }
  247. var (
  248. // Prevent duplicate deliveries.
  249. // This happens with massive hook tasks cannot finish delivering
  250. // before next shooting starts.
  251. isShooting = false
  252. )
  253. // DeliverHooks checks and delivers undelivered hooks.
  254. // FIXME: maybe can use goroutine to shoot a number of them at same time?
  255. func DeliverHooks() {
  256. if isShooting {
  257. return
  258. }
  259. isShooting = true
  260. defer func() { isShooting = false }()
  261. tasks := make([]*HookTask, 0, 10)
  262. timeout := time.Duration(setting.WebhookDeliverTimeout) * time.Second
  263. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  264. func(idx int, bean interface{}) error {
  265. t := bean.(*HookTask)
  266. req := httplib.Post(t.Url).SetTimeout(timeout, timeout).
  267. Header("X-Gogs-Delivery", t.Uuid).
  268. Header("X-Gogs-Event", string(t.EventType))
  269. switch t.ContentType {
  270. case JSON:
  271. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  272. case FORM:
  273. req.Param("payload", t.PayloadContent)
  274. }
  275. t.IsDelivered = true
  276. // FIXME: record response.
  277. switch t.Type {
  278. case GOGS:
  279. {
  280. if _, err := req.Response(); err != nil {
  281. log.Error(4, "Delivery: %v", err)
  282. } else {
  283. t.IsSucceed = true
  284. }
  285. }
  286. case SLACK:
  287. {
  288. if res, err := req.Response(); err != nil {
  289. log.Error(4, "Delivery: %v", err)
  290. } else {
  291. defer res.Body.Close()
  292. contents, err := ioutil.ReadAll(res.Body)
  293. if err != nil {
  294. log.Error(4, "%s", err)
  295. } else {
  296. if string(contents) != "ok" {
  297. log.Error(4, "slack failed with: %s", string(contents))
  298. } else {
  299. t.IsSucceed = true
  300. }
  301. }
  302. }
  303. }
  304. }
  305. tasks = append(tasks, t)
  306. if t.IsSucceed {
  307. log.Trace("Hook delivered(%s): %s", t.Uuid, t.PayloadContent)
  308. }
  309. return nil
  310. })
  311. // Update hook task status.
  312. for _, t := range tasks {
  313. if err := UpdateHookTask(t); err != nil {
  314. log.Error(4, "UpdateHookTask(%d): %v", t.Id, err)
  315. }
  316. }
  317. }