webhook.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. "crypto/hmac"
  7. "crypto/sha256"
  8. "crypto/tls"
  9. "encoding/hex"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "strings"
  14. "time"
  15. "github.com/go-xorm/xorm"
  16. gouuid "github.com/satori/go.uuid"
  17. log "gopkg.in/clog.v1"
  18. api "github.com/gogits/go-gogs-client"
  19. "github.com/gogits/gogs/models/errors"
  20. "github.com/gogits/gogs/pkg/httplib"
  21. "github.com/gogits/gogs/pkg/setting"
  22. "github.com/gogits/gogs/pkg/sync"
  23. )
  24. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  25. type HookContentType int
  26. const (
  27. JSON HookContentType = iota + 1
  28. FORM
  29. )
  30. var hookContentTypes = map[string]HookContentType{
  31. "json": JSON,
  32. "form": FORM,
  33. }
  34. // ToHookContentType returns HookContentType by given name.
  35. func ToHookContentType(name string) HookContentType {
  36. return hookContentTypes[name]
  37. }
  38. func (t HookContentType) Name() string {
  39. switch t {
  40. case JSON:
  41. return "json"
  42. case FORM:
  43. return "form"
  44. }
  45. return ""
  46. }
  47. // IsValidHookContentType returns true if given name is a valid hook content type.
  48. func IsValidHookContentType(name string) bool {
  49. _, ok := hookContentTypes[name]
  50. return ok
  51. }
  52. type HookEvents struct {
  53. Create bool `json:"create"`
  54. Delete bool `json:"delete"`
  55. Fork bool `json:"fork"`
  56. Push bool `json:"push"`
  57. Issues bool `json:"issues"`
  58. IssueComment bool `json:"issue_comment"`
  59. PullRequest bool `json:"pull_request"`
  60. Release bool `json:"release"`
  61. }
  62. // HookEvent represents events that will delivery hook.
  63. type HookEvent struct {
  64. PushOnly bool `json:"push_only"`
  65. SendEverything bool `json:"send_everything"`
  66. ChooseEvents bool `json:"choose_events"`
  67. HookEvents `json:"events"`
  68. }
  69. type HookStatus int
  70. const (
  71. HOOK_STATUS_NONE = iota
  72. HOOK_STATUS_SUCCEED
  73. HOOK_STATUS_FAILED
  74. )
  75. // Webhook represents a web hook object.
  76. type Webhook struct {
  77. ID int64
  78. RepoID int64
  79. OrgID int64
  80. URL string `xorm:"url TEXT"`
  81. ContentType HookContentType
  82. Secret string `xorm:"TEXT"`
  83. Events string `xorm:"TEXT"`
  84. *HookEvent `xorm:"-"`
  85. IsSSL bool `xorm:"is_ssl"`
  86. IsActive bool
  87. HookTaskType HookTaskType
  88. Meta string `xorm:"TEXT"` // store hook-specific attributes
  89. LastStatus HookStatus // Last delivery status
  90. Created time.Time `xorm:"-"`
  91. CreatedUnix int64
  92. Updated time.Time `xorm:"-"`
  93. UpdatedUnix int64
  94. }
  95. func (w *Webhook) BeforeInsert() {
  96. w.CreatedUnix = time.Now().Unix()
  97. w.UpdatedUnix = w.CreatedUnix
  98. }
  99. func (w *Webhook) BeforeUpdate() {
  100. w.UpdatedUnix = time.Now().Unix()
  101. }
  102. func (w *Webhook) AfterSet(colName string, _ xorm.Cell) {
  103. var err error
  104. switch colName {
  105. case "events":
  106. w.HookEvent = &HookEvent{}
  107. if err = json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  108. log.Error(3, "Unmarshal [%d]: %v", w.ID, err)
  109. }
  110. case "created_unix":
  111. w.Created = time.Unix(w.CreatedUnix, 0).Local()
  112. case "updated_unix":
  113. w.Updated = time.Unix(w.UpdatedUnix, 0).Local()
  114. }
  115. }
  116. func (w *Webhook) GetSlackHook() *SlackMeta {
  117. s := &SlackMeta{}
  118. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  119. log.Error(2, "GetSlackHook [%d]: %v", w.ID, err)
  120. }
  121. return s
  122. }
  123. // History returns history of webhook by given conditions.
  124. func (w *Webhook) History(page int) ([]*HookTask, error) {
  125. return HookTasks(w.ID, page)
  126. }
  127. // UpdateEvent handles conversion from HookEvent to Events.
  128. func (w *Webhook) UpdateEvent() error {
  129. data, err := json.Marshal(w.HookEvent)
  130. w.Events = string(data)
  131. return err
  132. }
  133. // HasCreateEvent returns true if hook enabled create event.
  134. func (w *Webhook) HasCreateEvent() bool {
  135. return w.SendEverything ||
  136. (w.ChooseEvents && w.HookEvents.Create)
  137. }
  138. // HasDeleteEvent returns true if hook enabled delete event.
  139. func (w *Webhook) HasDeleteEvent() bool {
  140. return w.SendEverything ||
  141. (w.ChooseEvents && w.HookEvents.Delete)
  142. }
  143. // HasForkEvent returns true if hook enabled fork event.
  144. func (w *Webhook) HasForkEvent() bool {
  145. return w.SendEverything ||
  146. (w.ChooseEvents && w.HookEvents.Fork)
  147. }
  148. // HasPushEvent returns true if hook enabled push event.
  149. func (w *Webhook) HasPushEvent() bool {
  150. return w.PushOnly || w.SendEverything ||
  151. (w.ChooseEvents && w.HookEvents.Push)
  152. }
  153. // HasIssuesEvent returns true if hook enabled issues event.
  154. func (w *Webhook) HasIssuesEvent() bool {
  155. return w.SendEverything ||
  156. (w.ChooseEvents && w.HookEvents.Issues)
  157. }
  158. // HasIssueCommentEvent returns true if hook enabled issue comment event.
  159. func (w *Webhook) HasIssueCommentEvent() bool {
  160. return w.SendEverything ||
  161. (w.ChooseEvents && w.HookEvents.IssueComment)
  162. }
  163. // HasPullRequestEvent returns true if hook enabled pull request event.
  164. func (w *Webhook) HasPullRequestEvent() bool {
  165. return w.SendEverything ||
  166. (w.ChooseEvents && w.HookEvents.PullRequest)
  167. }
  168. // HasReleaseEvent returns true if hook enabled release event.
  169. func (w *Webhook) HasReleaseEvent() bool {
  170. return w.SendEverything ||
  171. (w.ChooseEvents && w.HookEvents.Release)
  172. }
  173. type eventChecker struct {
  174. checker func() bool
  175. typ HookEventType
  176. }
  177. func (w *Webhook) EventsArray() []string {
  178. events := make([]string, 0, 7)
  179. eventCheckers := []eventChecker{
  180. {w.HasCreateEvent, HOOK_EVENT_CREATE},
  181. {w.HasDeleteEvent, HOOK_EVENT_DELETE},
  182. {w.HasForkEvent, HOOK_EVENT_FORK},
  183. {w.HasPushEvent, HOOK_EVENT_PUSH},
  184. {w.HasIssuesEvent, HOOK_EVENT_ISSUES},
  185. {w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT},
  186. {w.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST},
  187. {w.HasReleaseEvent, HOOK_EVENT_RELEASE},
  188. }
  189. for _, c := range eventCheckers {
  190. if c.checker() {
  191. events = append(events, string(c.typ))
  192. }
  193. }
  194. return events
  195. }
  196. // CreateWebhook creates a new web hook.
  197. func CreateWebhook(w *Webhook) error {
  198. _, err := x.Insert(w)
  199. return err
  200. }
  201. // getWebhook uses argument bean as query condition,
  202. // ID must be specified and do not assign unnecessary fields.
  203. func getWebhook(bean *Webhook) (*Webhook, error) {
  204. has, err := x.Get(bean)
  205. if err != nil {
  206. return nil, err
  207. } else if !has {
  208. return nil, errors.WebhookNotExist{bean.ID}
  209. }
  210. return bean, nil
  211. }
  212. // GetWebhookByID returns webhook by given ID.
  213. // Use this function with caution of accessing unauthorized webhook,
  214. // which means should only be used in non-user interactive functions.
  215. func GetWebhookByID(id int64) (*Webhook, error) {
  216. return getWebhook(&Webhook{
  217. ID: id,
  218. })
  219. }
  220. // GetWebhookOfRepoByID returns webhook of repository by given ID.
  221. func GetWebhookOfRepoByID(repoID, id int64) (*Webhook, error) {
  222. return getWebhook(&Webhook{
  223. ID: id,
  224. RepoID: repoID,
  225. })
  226. }
  227. // GetWebhookByOrgID returns webhook of organization by given ID.
  228. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  229. return getWebhook(&Webhook{
  230. ID: id,
  231. OrgID: orgID,
  232. })
  233. }
  234. // getActiveWebhooksByRepoID returns all active webhooks of repository.
  235. func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
  236. webhooks := make([]*Webhook, 0, 5)
  237. return webhooks, e.Where("repo_id = ?", repoID).And("is_active = ?", true).Find(&webhooks)
  238. }
  239. // GetWebhooksByRepoID returns all webhooks of a repository.
  240. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  241. webhooks := make([]*Webhook, 0, 5)
  242. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  243. }
  244. // UpdateWebhook updates information of webhook.
  245. func UpdateWebhook(w *Webhook) error {
  246. _, err := x.Id(w.ID).AllCols().Update(w)
  247. return err
  248. }
  249. // deleteWebhook uses argument bean as query condition,
  250. // ID must be specified and do not assign unnecessary fields.
  251. func deleteWebhook(bean *Webhook) (err error) {
  252. sess := x.NewSession()
  253. defer sess.Close()
  254. if err = sess.Begin(); err != nil {
  255. return err
  256. }
  257. if _, err = sess.Delete(bean); err != nil {
  258. return err
  259. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  260. return err
  261. }
  262. return sess.Commit()
  263. }
  264. // DeleteWebhookOfRepoByID deletes webhook of repository by given ID.
  265. func DeleteWebhookOfRepoByID(repoID, id int64) error {
  266. return deleteWebhook(&Webhook{
  267. ID: id,
  268. RepoID: repoID,
  269. })
  270. }
  271. // DeleteWebhookOfOrgByID deletes webhook of organization by given ID.
  272. func DeleteWebhookOfOrgByID(orgID, id int64) error {
  273. return deleteWebhook(&Webhook{
  274. ID: id,
  275. OrgID: orgID,
  276. })
  277. }
  278. // GetWebhooksByOrgID returns all webhooks for an organization.
  279. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  280. err = x.Find(&ws, &Webhook{OrgID: orgID})
  281. return ws, err
  282. }
  283. // getActiveWebhooksByOrgID returns all active webhooks for an organization.
  284. func getActiveWebhooksByOrgID(e Engine, orgID int64) ([]*Webhook, error) {
  285. ws := make([]*Webhook, 0, 3)
  286. return ws, e.Where("org_id=?", orgID).And("is_active=?", true).Find(&ws)
  287. }
  288. // ___ ___ __ ___________ __
  289. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  290. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  291. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  292. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  293. // \/ \/ \/ \/ \/
  294. type HookTaskType int
  295. const (
  296. GOGS HookTaskType = iota + 1
  297. SLACK
  298. DISCORD
  299. DINGTALK
  300. )
  301. var hookTaskTypes = map[string]HookTaskType{
  302. "gogs": GOGS,
  303. "slack": SLACK,
  304. "discord": DISCORD,
  305. }
  306. // ToHookTaskType returns HookTaskType by given name.
  307. func ToHookTaskType(name string) HookTaskType {
  308. return hookTaskTypes[name]
  309. }
  310. func (t HookTaskType) Name() string {
  311. switch t {
  312. case GOGS:
  313. return "gogs"
  314. case SLACK:
  315. return "slack"
  316. case DISCORD:
  317. return "discord"
  318. }
  319. return ""
  320. }
  321. // IsValidHookTaskType returns true if given name is a valid hook task type.
  322. func IsValidHookTaskType(name string) bool {
  323. _, ok := hookTaskTypes[name]
  324. return ok
  325. }
  326. type HookEventType string
  327. const (
  328. HOOK_EVENT_CREATE HookEventType = "create"
  329. HOOK_EVENT_DELETE HookEventType = "delete"
  330. HOOK_EVENT_FORK HookEventType = "fork"
  331. HOOK_EVENT_PUSH HookEventType = "push"
  332. HOOK_EVENT_ISSUES HookEventType = "issues"
  333. HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment"
  334. HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request"
  335. HOOK_EVENT_RELEASE HookEventType = "release"
  336. )
  337. // HookRequest represents hook task request information.
  338. type HookRequest struct {
  339. Headers map[string]string `json:"headers"`
  340. }
  341. // HookResponse represents hook task response information.
  342. type HookResponse struct {
  343. Status int `json:"status"`
  344. Headers map[string]string `json:"headers"`
  345. Body string `json:"body"`
  346. }
  347. // HookTask represents a hook task.
  348. type HookTask struct {
  349. ID int64
  350. RepoID int64 `xorm:"INDEX"`
  351. HookID int64
  352. UUID string
  353. Type HookTaskType
  354. URL string `xorm:"TEXT"`
  355. Signature string `xorm:"TEXT"`
  356. api.Payloader `xorm:"-"`
  357. PayloadContent string `xorm:"TEXT"`
  358. ContentType HookContentType
  359. EventType HookEventType
  360. IsSSL bool
  361. IsDelivered bool
  362. Delivered int64
  363. DeliveredString string `xorm:"-"`
  364. // History info.
  365. IsSucceed bool
  366. RequestContent string `xorm:"TEXT"`
  367. RequestInfo *HookRequest `xorm:"-"`
  368. ResponseContent string `xorm:"TEXT"`
  369. ResponseInfo *HookResponse `xorm:"-"`
  370. }
  371. func (t *HookTask) BeforeUpdate() {
  372. if t.RequestInfo != nil {
  373. t.RequestContent = t.MarshalJSON(t.RequestInfo)
  374. }
  375. if t.ResponseInfo != nil {
  376. t.ResponseContent = t.MarshalJSON(t.ResponseInfo)
  377. }
  378. }
  379. func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
  380. var err error
  381. switch colName {
  382. case "delivered":
  383. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  384. case "request_content":
  385. if len(t.RequestContent) == 0 {
  386. return
  387. }
  388. t.RequestInfo = &HookRequest{}
  389. if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  390. log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
  391. }
  392. case "response_content":
  393. if len(t.ResponseContent) == 0 {
  394. return
  395. }
  396. t.ResponseInfo = &HookResponse{}
  397. if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  398. log.Error(3, "Unmarshal [%d]: %v", t.ID, err)
  399. }
  400. }
  401. }
  402. func (t *HookTask) MarshalJSON(v interface{}) string {
  403. p, err := json.Marshal(v)
  404. if err != nil {
  405. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  406. }
  407. return string(p)
  408. }
  409. // HookTasks returns a list of hook tasks by given conditions.
  410. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  411. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  412. return tasks, x.Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).Where("hook_id=?", hookID).Desc("id").Find(&tasks)
  413. }
  414. // createHookTask creates a new hook task,
  415. // it handles conversion from Payload to PayloadContent.
  416. func createHookTask(e Engine, t *HookTask) error {
  417. data, err := t.Payloader.JSONPayload()
  418. if err != nil {
  419. return err
  420. }
  421. t.UUID = gouuid.NewV4().String()
  422. t.PayloadContent = string(data)
  423. _, err = e.Insert(t)
  424. return err
  425. }
  426. // GetHookTaskOfWebhookByUUID returns hook task of given webhook by UUID.
  427. func GetHookTaskOfWebhookByUUID(webhookID int64, uuid string) (*HookTask, error) {
  428. hookTask := &HookTask{
  429. HookID: webhookID,
  430. UUID: uuid,
  431. }
  432. has, err := x.Get(hookTask)
  433. if err != nil {
  434. return nil, err
  435. } else if !has {
  436. return nil, errors.HookTaskNotExist{webhookID, uuid}
  437. }
  438. return hookTask, nil
  439. }
  440. // UpdateHookTask updates information of hook task.
  441. func UpdateHookTask(t *HookTask) error {
  442. _, err := x.Id(t.ID).AllCols().Update(t)
  443. return err
  444. }
  445. // prepareHookTasks adds list of webhooks to task queue.
  446. func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Payloader, webhooks []*Webhook) (err error) {
  447. if len(webhooks) == 0 {
  448. return nil
  449. }
  450. var payloader api.Payloader
  451. for _, w := range webhooks {
  452. switch event {
  453. case HOOK_EVENT_CREATE:
  454. if !w.HasCreateEvent() {
  455. continue
  456. }
  457. case HOOK_EVENT_DELETE:
  458. if !w.HasDeleteEvent() {
  459. continue
  460. }
  461. case HOOK_EVENT_FORK:
  462. if !w.HasForkEvent() {
  463. continue
  464. }
  465. case HOOK_EVENT_PUSH:
  466. if !w.HasPushEvent() {
  467. continue
  468. }
  469. case HOOK_EVENT_ISSUES:
  470. if !w.HasIssuesEvent() {
  471. continue
  472. }
  473. case HOOK_EVENT_ISSUE_COMMENT:
  474. if !w.HasIssueCommentEvent() {
  475. continue
  476. }
  477. case HOOK_EVENT_PULL_REQUEST:
  478. if !w.HasPullRequestEvent() {
  479. continue
  480. }
  481. case HOOK_EVENT_RELEASE:
  482. if !w.HasReleaseEvent() {
  483. continue
  484. }
  485. }
  486. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  487. switch w.HookTaskType {
  488. case SLACK:
  489. payloader, err = GetSlackPayload(p, event, w.Meta)
  490. if err != nil {
  491. return fmt.Errorf("GetSlackPayload: %v", err)
  492. }
  493. case DISCORD:
  494. payloader, err = GetDiscordPayload(p, event, w.Meta)
  495. if err != nil {
  496. return fmt.Errorf("GetDiscordPayload: %v", err)
  497. }
  498. case DINGTALK:
  499. payloader, err = GetDingtalkPayload(p, event)
  500. if err != nil {
  501. return fmt.Errorf("GetDingtalkPayload: %v", err)
  502. }
  503. default:
  504. payloader = p
  505. }
  506. var signature string
  507. if len(w.Secret) > 0 {
  508. data, err := payloader.JSONPayload()
  509. if err != nil {
  510. log.Error(2, "prepareWebhooks.JSONPayload: %v", err)
  511. }
  512. sig := hmac.New(sha256.New, []byte(w.Secret))
  513. sig.Write(data)
  514. signature = hex.EncodeToString(sig.Sum(nil))
  515. }
  516. if err = createHookTask(e, &HookTask{
  517. RepoID: repo.ID,
  518. HookID: w.ID,
  519. Type: w.HookTaskType,
  520. URL: w.URL,
  521. Signature: signature,
  522. Payloader: payloader,
  523. ContentType: w.ContentType,
  524. EventType: event,
  525. IsSSL: w.IsSSL,
  526. }); err != nil {
  527. return fmt.Errorf("createHookTask: %v", err)
  528. }
  529. }
  530. // It's safe to fail when the whole function is called during hook execution
  531. // because resource released after exit. Also, there is no process started to
  532. // consume this input during hook execution.
  533. go HookQueue.Add(repo.ID)
  534. return nil
  535. }
  536. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  537. webhooks, err := getActiveWebhooksByRepoID(e, repo.ID)
  538. if err != nil {
  539. return fmt.Errorf("getActiveWebhooksByRepoID [%d]: %v", repo.ID, err)
  540. }
  541. // check if repo belongs to org and append additional webhooks
  542. if repo.mustOwner(e).IsOrganization() {
  543. // get hooks for org
  544. orgws, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  545. if err != nil {
  546. return fmt.Errorf("getActiveWebhooksByOrgID [%d]: %v", repo.OwnerID, err)
  547. }
  548. webhooks = append(webhooks, orgws...)
  549. }
  550. return prepareHookTasks(e, repo, event, p, webhooks)
  551. }
  552. // PrepareWebhooks adds all active webhooks to task queue.
  553. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  554. return prepareWebhooks(x, repo, event, p)
  555. }
  556. // TestWebhook adds the test webhook matches the ID to task queue.
  557. func TestWebhook(repo *Repository, event HookEventType, p api.Payloader, webhookID int64) error {
  558. webhook, err := GetWebhookOfRepoByID(repo.ID, webhookID)
  559. if err != nil {
  560. return fmt.Errorf("GetWebhookOfRepoByID [repo_id: %d, id: %d]: %v", repo.ID, webhookID, err)
  561. }
  562. return prepareHookTasks(x, repo, event, p, []*Webhook{webhook})
  563. }
  564. func (t *HookTask) deliver() {
  565. t.IsDelivered = true
  566. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  567. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  568. Header("X-Gogs-Delivery", t.UUID).
  569. Header("X-Gogs-Signature", t.Signature).
  570. Header("X-Gogs-Event", string(t.EventType)).
  571. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  572. switch t.ContentType {
  573. case JSON:
  574. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  575. case FORM:
  576. req.Param("payload", t.PayloadContent)
  577. }
  578. // Record delivery information.
  579. t.RequestInfo = &HookRequest{
  580. Headers: map[string]string{},
  581. }
  582. for k, vals := range req.Headers() {
  583. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  584. }
  585. t.ResponseInfo = &HookResponse{
  586. Headers: map[string]string{},
  587. }
  588. defer func() {
  589. t.Delivered = time.Now().UnixNano()
  590. if t.IsSucceed {
  591. log.Trace("Hook delivered: %s", t.UUID)
  592. } else {
  593. log.Trace("Hook delivery failed: %s", t.UUID)
  594. }
  595. // Update webhook last delivery status.
  596. w, err := GetWebhookByID(t.HookID)
  597. if err != nil {
  598. log.Error(3, "GetWebhookByID: %v", err)
  599. return
  600. }
  601. if t.IsSucceed {
  602. w.LastStatus = HOOK_STATUS_SUCCEED
  603. } else {
  604. w.LastStatus = HOOK_STATUS_FAILED
  605. }
  606. if err = UpdateWebhook(w); err != nil {
  607. log.Error(3, "UpdateWebhook: %v", err)
  608. return
  609. }
  610. }()
  611. resp, err := req.Response()
  612. if err != nil {
  613. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  614. return
  615. }
  616. defer resp.Body.Close()
  617. // Status code is 20x can be seen as succeed.
  618. t.IsSucceed = resp.StatusCode/100 == 2
  619. t.ResponseInfo.Status = resp.StatusCode
  620. for k, vals := range resp.Header {
  621. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  622. }
  623. p, err := ioutil.ReadAll(resp.Body)
  624. if err != nil {
  625. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  626. return
  627. }
  628. t.ResponseInfo.Body = string(p)
  629. }
  630. // DeliverHooks checks and delivers undelivered hooks.
  631. // TODO: shoot more hooks at same time.
  632. func DeliverHooks() {
  633. tasks := make([]*HookTask, 0, 10)
  634. x.Where("is_delivered = ?", false).Iterate(new(HookTask),
  635. func(idx int, bean interface{}) error {
  636. t := bean.(*HookTask)
  637. t.deliver()
  638. tasks = append(tasks, t)
  639. return nil
  640. })
  641. // Update hook task status.
  642. for _, t := range tasks {
  643. if err := UpdateHookTask(t); err != nil {
  644. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  645. }
  646. }
  647. // Start listening on new hook requests.
  648. for repoID := range HookQueue.Queue() {
  649. log.Trace("DeliverHooks [repo_id: %v]", repoID)
  650. HookQueue.Remove(repoID)
  651. tasks = make([]*HookTask, 0, 5)
  652. if err := x.Where("repo_id = ?", repoID).And("is_delivered = ?", false).Find(&tasks); err != nil {
  653. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  654. continue
  655. }
  656. for _, t := range tasks {
  657. t.deliver()
  658. if err := UpdateHookTask(t); err != nil {
  659. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  660. continue
  661. }
  662. }
  663. }
  664. }
  665. func InitDeliverHooks() {
  666. go DeliverHooks()
  667. }