webhook.go 8.9 KB

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