webhook.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 db
  5. import (
  6. "crypto/hmac"
  7. "crypto/sha256"
  8. "crypto/tls"
  9. "encoding/hex"
  10. "fmt"
  11. "io/ioutil"
  12. "strings"
  13. "time"
  14. "github.com/json-iterator/go"
  15. gouuid "github.com/satori/go.uuid"
  16. log "gopkg.in/clog.v1"
  17. "xorm.io/xorm"
  18. api "github.com/gogs/go-gogs-client"
  19. "gogs.io/gogs/internal/db/errors"
  20. "gogs.io/gogs/internal/httplib"
  21. "gogs.io/gogs/internal/setting"
  22. "gogs.io/gogs/internal/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. PullRequest bool `json:"pull_request"`
  59. IssueComment bool `json:"issue_comment"`
  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:"-"` // LEGACY [1.0]: Cannot ignore JSON here, it breaks old backup archive
  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:"-" json:"-"`
  91. CreatedUnix int64
  92. Updated time.Time `xorm:"-" json:"-"`
  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 = jsoniter.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 := jsoniter.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 := jsoniter.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. // HasPullRequestEvent returns true if hook enabled pull request event.
  159. func (w *Webhook) HasPullRequestEvent() bool {
  160. return w.SendEverything ||
  161. (w.ChooseEvents && w.HookEvents.PullRequest)
  162. }
  163. // HasIssueCommentEvent returns true if hook enabled issue comment event.
  164. func (w *Webhook) HasIssueCommentEvent() bool {
  165. return w.SendEverything ||
  166. (w.ChooseEvents && w.HookEvents.IssueComment)
  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, 8)
  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.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST},
  186. {w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT},
  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. "dingtalk": DINGTALK,
  306. }
  307. // ToHookTaskType returns HookTaskType by given name.
  308. func ToHookTaskType(name string) HookTaskType {
  309. return hookTaskTypes[name]
  310. }
  311. func (t HookTaskType) Name() string {
  312. switch t {
  313. case GOGS:
  314. return "gogs"
  315. case SLACK:
  316. return "slack"
  317. case DISCORD:
  318. return "discord"
  319. case DINGTALK:
  320. return "dingtalk"
  321. }
  322. return ""
  323. }
  324. // IsValidHookTaskType returns true if given name is a valid hook task type.
  325. func IsValidHookTaskType(name string) bool {
  326. _, ok := hookTaskTypes[name]
  327. return ok
  328. }
  329. type HookEventType string
  330. const (
  331. HOOK_EVENT_CREATE HookEventType = "create"
  332. HOOK_EVENT_DELETE HookEventType = "delete"
  333. HOOK_EVENT_FORK HookEventType = "fork"
  334. HOOK_EVENT_PUSH HookEventType = "push"
  335. HOOK_EVENT_ISSUES HookEventType = "issues"
  336. HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request"
  337. HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment"
  338. HOOK_EVENT_RELEASE HookEventType = "release"
  339. )
  340. // HookRequest represents hook task request information.
  341. type HookRequest struct {
  342. Headers map[string]string `json:"headers"`
  343. }
  344. // HookResponse represents hook task response information.
  345. type HookResponse struct {
  346. Status int `json:"status"`
  347. Headers map[string]string `json:"headers"`
  348. Body string `json:"body"`
  349. }
  350. // HookTask represents a hook task.
  351. type HookTask struct {
  352. ID int64
  353. RepoID int64 `xorm:"INDEX"`
  354. HookID int64
  355. UUID string
  356. Type HookTaskType
  357. URL string `xorm:"TEXT"`
  358. Signature string `xorm:"TEXT"`
  359. api.Payloader `xorm:"-" json:"-"`
  360. PayloadContent string `xorm:"TEXT"`
  361. ContentType HookContentType
  362. EventType HookEventType
  363. IsSSL bool
  364. IsDelivered bool
  365. Delivered int64
  366. DeliveredString string `xorm:"-" json:"-"`
  367. // History info.
  368. IsSucceed bool
  369. RequestContent string `xorm:"TEXT"`
  370. RequestInfo *HookRequest `xorm:"-" json:"-"`
  371. ResponseContent string `xorm:"TEXT"`
  372. ResponseInfo *HookResponse `xorm:"-" json:"-"`
  373. }
  374. func (t *HookTask) BeforeUpdate() {
  375. if t.RequestInfo != nil {
  376. t.RequestContent = t.MarshalJSON(t.RequestInfo)
  377. }
  378. if t.ResponseInfo != nil {
  379. t.ResponseContent = t.MarshalJSON(t.ResponseInfo)
  380. }
  381. }
  382. func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
  383. var err error
  384. switch colName {
  385. case "delivered":
  386. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  387. case "request_content":
  388. if len(t.RequestContent) == 0 {
  389. return
  390. }
  391. t.RequestInfo = &HookRequest{}
  392. if err = jsoniter.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  393. log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
  394. }
  395. case "response_content":
  396. if len(t.ResponseContent) == 0 {
  397. return
  398. }
  399. t.ResponseInfo = &HookResponse{}
  400. if err = jsoniter.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  401. log.Error(3, "Unmarshal [%d]: %v", t.ID, err)
  402. }
  403. }
  404. }
  405. func (t *HookTask) MarshalJSON(v interface{}) string {
  406. p, err := jsoniter.Marshal(v)
  407. if err != nil {
  408. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  409. }
  410. return string(p)
  411. }
  412. // HookTasks returns a list of hook tasks by given conditions.
  413. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  414. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  415. return tasks, x.Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).Where("hook_id=?", hookID).Desc("id").Find(&tasks)
  416. }
  417. // createHookTask creates a new hook task,
  418. // it handles conversion from Payload to PayloadContent.
  419. func createHookTask(e Engine, t *HookTask) error {
  420. data, err := t.Payloader.JSONPayload()
  421. if err != nil {
  422. return err
  423. }
  424. t.UUID = gouuid.NewV4().String()
  425. t.PayloadContent = string(data)
  426. _, err = e.Insert(t)
  427. return err
  428. }
  429. // GetHookTaskOfWebhookByUUID returns hook task of given webhook by UUID.
  430. func GetHookTaskOfWebhookByUUID(webhookID int64, uuid string) (*HookTask, error) {
  431. hookTask := &HookTask{
  432. HookID: webhookID,
  433. UUID: uuid,
  434. }
  435. has, err := x.Get(hookTask)
  436. if err != nil {
  437. return nil, err
  438. } else if !has {
  439. return nil, errors.HookTaskNotExist{webhookID, uuid}
  440. }
  441. return hookTask, nil
  442. }
  443. // UpdateHookTask updates information of hook task.
  444. func UpdateHookTask(t *HookTask) error {
  445. _, err := x.Id(t.ID).AllCols().Update(t)
  446. return err
  447. }
  448. // prepareHookTasks adds list of webhooks to task queue.
  449. func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Payloader, webhooks []*Webhook) (err error) {
  450. if len(webhooks) == 0 {
  451. return nil
  452. }
  453. var payloader api.Payloader
  454. for _, w := range webhooks {
  455. switch event {
  456. case HOOK_EVENT_CREATE:
  457. if !w.HasCreateEvent() {
  458. continue
  459. }
  460. case HOOK_EVENT_DELETE:
  461. if !w.HasDeleteEvent() {
  462. continue
  463. }
  464. case HOOK_EVENT_FORK:
  465. if !w.HasForkEvent() {
  466. continue
  467. }
  468. case HOOK_EVENT_PUSH:
  469. if !w.HasPushEvent() {
  470. continue
  471. }
  472. case HOOK_EVENT_ISSUES:
  473. if !w.HasIssuesEvent() {
  474. continue
  475. }
  476. case HOOK_EVENT_PULL_REQUEST:
  477. if !w.HasPullRequestEvent() {
  478. continue
  479. }
  480. case HOOK_EVENT_ISSUE_COMMENT:
  481. if !w.HasIssueCommentEvent() {
  482. continue
  483. }
  484. case HOOK_EVENT_RELEASE:
  485. if !w.HasReleaseEvent() {
  486. continue
  487. }
  488. }
  489. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  490. switch w.HookTaskType {
  491. case SLACK:
  492. payloader, err = GetSlackPayload(p, event, w.Meta)
  493. if err != nil {
  494. return fmt.Errorf("GetSlackPayload: %v", err)
  495. }
  496. case DISCORD:
  497. payloader, err = GetDiscordPayload(p, event, w.Meta)
  498. if err != nil {
  499. return fmt.Errorf("GetDiscordPayload: %v", err)
  500. }
  501. case DINGTALK:
  502. payloader, err = GetDingtalkPayload(p, event)
  503. if err != nil {
  504. return fmt.Errorf("GetDingtalkPayload: %v", err)
  505. }
  506. default:
  507. payloader = p
  508. }
  509. var signature string
  510. if len(w.Secret) > 0 {
  511. data, err := payloader.JSONPayload()
  512. if err != nil {
  513. log.Error(2, "prepareWebhooks.JSONPayload: %v", err)
  514. }
  515. sig := hmac.New(sha256.New, []byte(w.Secret))
  516. sig.Write(data)
  517. signature = hex.EncodeToString(sig.Sum(nil))
  518. }
  519. if err = createHookTask(e, &HookTask{
  520. RepoID: repo.ID,
  521. HookID: w.ID,
  522. Type: w.HookTaskType,
  523. URL: w.URL,
  524. Signature: signature,
  525. Payloader: payloader,
  526. ContentType: w.ContentType,
  527. EventType: event,
  528. IsSSL: w.IsSSL,
  529. }); err != nil {
  530. return fmt.Errorf("createHookTask: %v", err)
  531. }
  532. }
  533. // It's safe to fail when the whole function is called during hook execution
  534. // because resource released after exit. Also, there is no process started to
  535. // consume this input during hook execution.
  536. go HookQueue.Add(repo.ID)
  537. return nil
  538. }
  539. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  540. webhooks, err := getActiveWebhooksByRepoID(e, repo.ID)
  541. if err != nil {
  542. return fmt.Errorf("getActiveWebhooksByRepoID [%d]: %v", repo.ID, err)
  543. }
  544. // check if repo belongs to org and append additional webhooks
  545. if repo.mustOwner(e).IsOrganization() {
  546. // get hooks for org
  547. orgws, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  548. if err != nil {
  549. return fmt.Errorf("getActiveWebhooksByOrgID [%d]: %v", repo.OwnerID, err)
  550. }
  551. webhooks = append(webhooks, orgws...)
  552. }
  553. return prepareHookTasks(e, repo, event, p, webhooks)
  554. }
  555. // PrepareWebhooks adds all active webhooks to task queue.
  556. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  557. return prepareWebhooks(x, repo, event, p)
  558. }
  559. // TestWebhook adds the test webhook matches the ID to task queue.
  560. func TestWebhook(repo *Repository, event HookEventType, p api.Payloader, webhookID int64) error {
  561. webhook, err := GetWebhookOfRepoByID(repo.ID, webhookID)
  562. if err != nil {
  563. return fmt.Errorf("GetWebhookOfRepoByID [repo_id: %d, id: %d]: %v", repo.ID, webhookID, err)
  564. }
  565. return prepareHookTasks(x, repo, event, p, []*Webhook{webhook})
  566. }
  567. func (t *HookTask) deliver() {
  568. t.IsDelivered = true
  569. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  570. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  571. Header("X-Github-Delivery", t.UUID).
  572. Header("X-Github-Event", string(t.EventType)).
  573. Header("X-Gogs-Delivery", t.UUID).
  574. Header("X-Gogs-Signature", t.Signature).
  575. Header("X-Gogs-Event", string(t.EventType)).
  576. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  577. switch t.ContentType {
  578. case JSON:
  579. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  580. case FORM:
  581. req.Param("payload", t.PayloadContent)
  582. }
  583. // Record delivery information.
  584. t.RequestInfo = &HookRequest{
  585. Headers: map[string]string{},
  586. }
  587. for k, vals := range req.Headers() {
  588. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  589. }
  590. t.ResponseInfo = &HookResponse{
  591. Headers: map[string]string{},
  592. }
  593. defer func() {
  594. t.Delivered = time.Now().UnixNano()
  595. if t.IsSucceed {
  596. log.Trace("Hook delivered: %s", t.UUID)
  597. } else {
  598. log.Trace("Hook delivery failed: %s", t.UUID)
  599. }
  600. // Update webhook last delivery status.
  601. w, err := GetWebhookByID(t.HookID)
  602. if err != nil {
  603. log.Error(3, "GetWebhookByID: %v", err)
  604. return
  605. }
  606. if t.IsSucceed {
  607. w.LastStatus = HOOK_STATUS_SUCCEED
  608. } else {
  609. w.LastStatus = HOOK_STATUS_FAILED
  610. }
  611. if err = UpdateWebhook(w); err != nil {
  612. log.Error(3, "UpdateWebhook: %v", err)
  613. return
  614. }
  615. }()
  616. resp, err := req.Response()
  617. if err != nil {
  618. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  619. return
  620. }
  621. defer resp.Body.Close()
  622. // Status code is 20x can be seen as succeed.
  623. t.IsSucceed = resp.StatusCode/100 == 2
  624. t.ResponseInfo.Status = resp.StatusCode
  625. for k, vals := range resp.Header {
  626. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  627. }
  628. p, err := ioutil.ReadAll(resp.Body)
  629. if err != nil {
  630. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  631. return
  632. }
  633. t.ResponseInfo.Body = string(p)
  634. }
  635. // DeliverHooks checks and delivers undelivered hooks.
  636. // TODO: shoot more hooks at same time.
  637. func DeliverHooks() {
  638. tasks := make([]*HookTask, 0, 10)
  639. x.Where("is_delivered = ?", false).Iterate(new(HookTask),
  640. func(idx int, bean interface{}) error {
  641. t := bean.(*HookTask)
  642. t.deliver()
  643. tasks = append(tasks, t)
  644. return nil
  645. })
  646. // Update hook task status.
  647. for _, t := range tasks {
  648. if err := UpdateHookTask(t); err != nil {
  649. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  650. }
  651. }
  652. // Start listening on new hook requests.
  653. for repoID := range HookQueue.Queue() {
  654. log.Trace("DeliverHooks [repo_id: %v]", repoID)
  655. HookQueue.Remove(repoID)
  656. tasks = make([]*HookTask, 0, 5)
  657. if err := x.Where("repo_id = ?", repoID).And("is_delivered = ?", false).Find(&tasks); err != nil {
  658. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  659. continue
  660. }
  661. for _, t := range tasks {
  662. t.deliver()
  663. if err := UpdateHookTask(t); err != nil {
  664. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  665. continue
  666. }
  667. }
  668. }
  669. }
  670. func InitDeliverHooks() {
  671. go DeliverHooks()
  672. }