You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.1 KiB

  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 hooks
  5. import (
  6. "encoding/json"
  7. "time"
  8. "github.com/gogits/gogs/modules/httplib"
  9. "github.com/gogits/gogs/modules/log"
  10. )
  11. // Hook task types.
  12. const (
  13. HTT_WEBHOOK = iota + 1
  14. HTT_SERVICE
  15. )
  16. type PayloadAuthor struct {
  17. Name string `json:"name"`
  18. Email string `json:"email"`
  19. }
  20. type PayloadCommit struct {
  21. Id string `json:"id"`
  22. Message string `json:"message"`
  23. Url string `json:"url"`
  24. Author *PayloadAuthor `json:"author"`
  25. }
  26. type PayloadRepo struct {
  27. Id int64 `json:"id"`
  28. Name string `json:"name"`
  29. Url string `json:"url"`
  30. Description string `json:"description"`
  31. Website string `json:"website"`
  32. Watchers int `json:"watchers"`
  33. Owner *PayloadAuthor `json:"author"`
  34. Private bool `json:"private"`
  35. }
  36. // Payload represents payload information of hook.
  37. type Payload struct {
  38. Secret string `json:"secret"`
  39. Ref string `json:"ref"`
  40. Commits []*PayloadCommit `json:"commits"`
  41. Repo *PayloadRepo `json:"repository"`
  42. Pusher *PayloadAuthor `json:"pusher"`
  43. }
  44. // HookTask represents hook task.
  45. type HookTask struct {
  46. Type int
  47. Url string
  48. *Payload
  49. ContentType int
  50. IsSsl bool
  51. }
  52. var (
  53. taskQueue = make(chan *HookTask, 1000)
  54. )
  55. // AddHookTask adds new hook task to task queue.
  56. func AddHookTask(t *HookTask) {
  57. taskQueue <- t
  58. }
  59. func init() {
  60. go handleQueue()
  61. }
  62. func handleQueue() {
  63. for {
  64. select {
  65. case t := <-taskQueue:
  66. // Only support JSON now.
  67. data, err := json.MarshalIndent(t.Payload, "", "\t")
  68. if err != nil {
  69. log.Error("hooks.handleQueue(json): %v", err)
  70. continue
  71. }
  72. _, err = httplib.Post(t.Url).SetTimeout(5*time.Second, 5*time.Second).
  73. Body(data).Response()
  74. if err != nil {
  75. log.Error("hooks.handleQueue: Fail to deliver hook: %v", err)
  76. continue
  77. }
  78. log.Info("Hook delivered: %s", string(data))
  79. }
  80. }
  81. }