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.

webhook.go 20KB

10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
8 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/modules/httplib"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/sync"
  17. "code.gitea.io/gitea/modules/util"
  18. api "code.gitea.io/sdk/gitea"
  19. "github.com/Unknwon/com"
  20. gouuid "github.com/satori/go.uuid"
  21. )
  22. // HookQueue is a global queue of web hooks
  23. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  24. // HookContentType is the content type of a web hook
  25. type HookContentType int
  26. const (
  27. // ContentTypeJSON is a JSON payload for web hooks
  28. ContentTypeJSON HookContentType = iota + 1
  29. // ContentTypeForm is an url-encoded form payload for web hook
  30. ContentTypeForm
  31. )
  32. var hookContentTypes = map[string]HookContentType{
  33. "json": ContentTypeJSON,
  34. "form": ContentTypeForm,
  35. }
  36. // ToHookContentType returns HookContentType by given name.
  37. func ToHookContentType(name string) HookContentType {
  38. return hookContentTypes[name]
  39. }
  40. // Name returns the name of a given web hook's content type
  41. func (t HookContentType) Name() string {
  42. switch t {
  43. case ContentTypeJSON:
  44. return "json"
  45. case ContentTypeForm:
  46. return "form"
  47. }
  48. return ""
  49. }
  50. // IsValidHookContentType returns true if given name is a valid hook content type.
  51. func IsValidHookContentType(name string) bool {
  52. _, ok := hookContentTypes[name]
  53. return ok
  54. }
  55. // HookEvents is a set of web hook events
  56. type HookEvents struct {
  57. Create bool `json:"create"`
  58. Delete bool `json:"delete"`
  59. Fork bool `json:"fork"`
  60. Issues bool `json:"issues"`
  61. IssueComment bool `json:"issue_comment"`
  62. Push bool `json:"push"`
  63. PullRequest bool `json:"pull_request"`
  64. Repository bool `json:"repository"`
  65. Release bool `json:"release"`
  66. }
  67. // HookEvent represents events that will delivery hook.
  68. type HookEvent struct {
  69. PushOnly bool `json:"push_only"`
  70. SendEverything bool `json:"send_everything"`
  71. ChooseEvents bool `json:"choose_events"`
  72. HookEvents `json:"events"`
  73. }
  74. // HookStatus is the status of a web hook
  75. type HookStatus int
  76. // Possible statuses of a web hook
  77. const (
  78. HookStatusNone = iota
  79. HookStatusSucceed
  80. HookStatusFail
  81. )
  82. // Webhook represents a web hook object.
  83. type Webhook struct {
  84. ID int64 `xorm:"pk autoincr"`
  85. RepoID int64 `xorm:"INDEX"`
  86. OrgID int64 `xorm:"INDEX"`
  87. URL string `xorm:"url TEXT"`
  88. ContentType HookContentType
  89. Secret string `xorm:"TEXT"`
  90. Events string `xorm:"TEXT"`
  91. *HookEvent `xorm:"-"`
  92. IsSSL bool `xorm:"is_ssl"`
  93. IsActive bool `xorm:"INDEX"`
  94. HookTaskType HookTaskType
  95. Meta string `xorm:"TEXT"` // store hook-specific attributes
  96. LastStatus HookStatus // Last delivery status
  97. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  98. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  99. }
  100. // AfterLoad updates the webhook object upon setting a column
  101. func (w *Webhook) AfterLoad() {
  102. w.HookEvent = &HookEvent{}
  103. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  104. log.Error(3, "Unmarshal[%d]: %v", w.ID, err)
  105. }
  106. }
  107. // GetSlackHook returns slack metadata
  108. func (w *Webhook) GetSlackHook() *SlackMeta {
  109. s := &SlackMeta{}
  110. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  111. log.Error(4, "webhook.GetSlackHook(%d): %v", w.ID, err)
  112. }
  113. return s
  114. }
  115. // GetDiscordHook returns discord metadata
  116. func (w *Webhook) GetDiscordHook() *DiscordMeta {
  117. s := &DiscordMeta{}
  118. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  119. log.Error(4, "webhook.GetDiscordHook(%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. // HasIssuesEvent returns true if hook enabled issues event.
  149. func (w *Webhook) HasIssuesEvent() bool {
  150. return w.SendEverything ||
  151. (w.ChooseEvents && w.HookEvents.Issues)
  152. }
  153. // HasIssueCommentEvent returns true if hook enabled issue_comment event.
  154. func (w *Webhook) HasIssueCommentEvent() bool {
  155. return w.SendEverything ||
  156. (w.ChooseEvents && w.HookEvents.IssueComment)
  157. }
  158. // HasPushEvent returns true if hook enabled push event.
  159. func (w *Webhook) HasPushEvent() bool {
  160. return w.PushOnly || w.SendEverything ||
  161. (w.ChooseEvents && w.HookEvents.Push)
  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 if hook enabled release event.
  169. func (w *Webhook) HasReleaseEvent() bool {
  170. return w.SendEverything ||
  171. (w.ChooseEvents && w.HookEvents.Release)
  172. }
  173. // HasRepositoryEvent returns if hook enabled repository event.
  174. func (w *Webhook) HasRepositoryEvent() bool {
  175. return w.SendEverything ||
  176. (w.ChooseEvents && w.HookEvents.Repository)
  177. }
  178. func (w *Webhook) eventCheckers() []struct {
  179. has func() bool
  180. typ HookEventType
  181. } {
  182. return []struct {
  183. has func() bool
  184. typ HookEventType
  185. }{
  186. {w.HasCreateEvent, HookEventCreate},
  187. {w.HasDeleteEvent, HookEventDelete},
  188. {w.HasForkEvent, HookEventFork},
  189. {w.HasPushEvent, HookEventPush},
  190. {w.HasIssuesEvent, HookEventIssues},
  191. {w.HasIssueCommentEvent, HookEventIssueComment},
  192. {w.HasPullRequestEvent, HookEventPullRequest},
  193. {w.HasRepositoryEvent, HookEventRepository},
  194. {w.HasReleaseEvent, HookEventRelease},
  195. }
  196. }
  197. // EventsArray returns an array of hook events
  198. func (w *Webhook) EventsArray() []string {
  199. events := make([]string, 0, 7)
  200. for _, c := range w.eventCheckers() {
  201. if c.has() {
  202. events = append(events, string(c.typ))
  203. }
  204. }
  205. return events
  206. }
  207. // CreateWebhook creates a new web hook.
  208. func CreateWebhook(w *Webhook) error {
  209. _, err := x.Insert(w)
  210. return err
  211. }
  212. // getWebhook uses argument bean as query condition,
  213. // ID must be specified and do not assign unnecessary fields.
  214. func getWebhook(bean *Webhook) (*Webhook, error) {
  215. has, err := x.Get(bean)
  216. if err != nil {
  217. return nil, err
  218. } else if !has {
  219. return nil, ErrWebhookNotExist{bean.ID}
  220. }
  221. return bean, nil
  222. }
  223. // GetWebhookByID returns webhook of repository by given ID.
  224. func GetWebhookByID(id int64) (*Webhook, error) {
  225. return getWebhook(&Webhook{
  226. ID: id,
  227. })
  228. }
  229. // GetWebhookByRepoID returns webhook of repository by given ID.
  230. func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
  231. return getWebhook(&Webhook{
  232. ID: id,
  233. RepoID: repoID,
  234. })
  235. }
  236. // GetWebhookByOrgID returns webhook of organization by given ID.
  237. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  238. return getWebhook(&Webhook{
  239. ID: id,
  240. OrgID: orgID,
  241. })
  242. }
  243. // GetActiveWebhooksByRepoID returns all active webhooks of repository.
  244. func GetActiveWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  245. return getActiveWebhooksByRepoID(x, repoID)
  246. }
  247. func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
  248. webhooks := make([]*Webhook, 0, 5)
  249. return webhooks, e.Where("is_active=?", true).
  250. Find(&webhooks, &Webhook{RepoID: repoID})
  251. }
  252. // GetWebhooksByRepoID returns all webhooks of a repository.
  253. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  254. webhooks := make([]*Webhook, 0, 5)
  255. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  256. }
  257. // GetActiveWebhooksByOrgID returns all active webhooks for an organization.
  258. func GetActiveWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  259. return getActiveWebhooksByOrgID(x, orgID)
  260. }
  261. func getActiveWebhooksByOrgID(e Engine, orgID int64) (ws []*Webhook, err error) {
  262. err = e.
  263. Where("org_id=?", orgID).
  264. And("is_active=?", true).
  265. Find(&ws)
  266. return ws, err
  267. }
  268. // GetWebhooksByOrgID returns all webhooks for an organization.
  269. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  270. err = x.Find(&ws, &Webhook{OrgID: orgID})
  271. return ws, err
  272. }
  273. // UpdateWebhook updates information of webhook.
  274. func UpdateWebhook(w *Webhook) error {
  275. _, err := x.ID(w.ID).AllCols().Update(w)
  276. return err
  277. }
  278. // UpdateWebhookLastStatus updates last status of webhook.
  279. func UpdateWebhookLastStatus(w *Webhook) error {
  280. _, err := x.ID(w.ID).Cols("last_status").Update(w)
  281. return err
  282. }
  283. // deleteWebhook uses argument bean as query condition,
  284. // ID must be specified and do not assign unnecessary fields.
  285. func deleteWebhook(bean *Webhook) (err error) {
  286. sess := x.NewSession()
  287. defer sess.Close()
  288. if err = sess.Begin(); err != nil {
  289. return err
  290. }
  291. if count, err := sess.Delete(bean); err != nil {
  292. return err
  293. } else if count == 0 {
  294. return ErrWebhookNotExist{ID: bean.ID}
  295. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  296. return err
  297. }
  298. return sess.Commit()
  299. }
  300. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  301. func DeleteWebhookByRepoID(repoID, id int64) error {
  302. return deleteWebhook(&Webhook{
  303. ID: id,
  304. RepoID: repoID,
  305. })
  306. }
  307. // DeleteWebhookByOrgID deletes webhook of organization by given ID.
  308. func DeleteWebhookByOrgID(orgID, id int64) error {
  309. return deleteWebhook(&Webhook{
  310. ID: id,
  311. OrgID: orgID,
  312. })
  313. }
  314. // ___ ___ __ ___________ __
  315. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  316. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  317. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  318. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  319. // \/ \/ \/ \/ \/
  320. // HookTaskType is the type of an hook task
  321. type HookTaskType int
  322. // Types of hook tasks
  323. const (
  324. GOGS HookTaskType = iota + 1
  325. SLACK
  326. GITEA
  327. DISCORD
  328. DINGTALK
  329. )
  330. var hookTaskTypes = map[string]HookTaskType{
  331. "gitea": GITEA,
  332. "gogs": GOGS,
  333. "slack": SLACK,
  334. "discord": DISCORD,
  335. "dingtalk": DINGTALK,
  336. }
  337. // ToHookTaskType returns HookTaskType by given name.
  338. func ToHookTaskType(name string) HookTaskType {
  339. return hookTaskTypes[name]
  340. }
  341. // Name returns the name of an hook task type
  342. func (t HookTaskType) Name() string {
  343. switch t {
  344. case GITEA:
  345. return "gitea"
  346. case GOGS:
  347. return "gogs"
  348. case SLACK:
  349. return "slack"
  350. case DISCORD:
  351. return "discord"
  352. case DINGTALK:
  353. return "dingtalk"
  354. }
  355. return ""
  356. }
  357. // IsValidHookTaskType returns true if given name is a valid hook task type.
  358. func IsValidHookTaskType(name string) bool {
  359. _, ok := hookTaskTypes[name]
  360. return ok
  361. }
  362. // HookEventType is the type of an hook event
  363. type HookEventType string
  364. // Types of hook events
  365. const (
  366. HookEventCreate HookEventType = "create"
  367. HookEventDelete HookEventType = "delete"
  368. HookEventFork HookEventType = "fork"
  369. HookEventPush HookEventType = "push"
  370. HookEventIssues HookEventType = "issues"
  371. HookEventIssueComment HookEventType = "issue_comment"
  372. HookEventPullRequest HookEventType = "pull_request"
  373. HookEventRepository HookEventType = "repository"
  374. HookEventRelease HookEventType = "release"
  375. )
  376. // HookRequest represents hook task request information.
  377. type HookRequest struct {
  378. Headers map[string]string `json:"headers"`
  379. }
  380. // HookResponse represents hook task response information.
  381. type HookResponse struct {
  382. Status int `json:"status"`
  383. Headers map[string]string `json:"headers"`
  384. Body string `json:"body"`
  385. }
  386. // HookTask represents a hook task.
  387. type HookTask struct {
  388. ID int64 `xorm:"pk autoincr"`
  389. RepoID int64 `xorm:"INDEX"`
  390. HookID int64
  391. UUID string
  392. Type HookTaskType
  393. URL string `xorm:"TEXT"`
  394. api.Payloader `xorm:"-"`
  395. PayloadContent string `xorm:"TEXT"`
  396. ContentType HookContentType
  397. EventType HookEventType
  398. IsSSL bool
  399. IsDelivered bool
  400. Delivered int64
  401. DeliveredString string `xorm:"-"`
  402. // History info.
  403. IsSucceed bool
  404. RequestContent string `xorm:"TEXT"`
  405. RequestInfo *HookRequest `xorm:"-"`
  406. ResponseContent string `xorm:"TEXT"`
  407. ResponseInfo *HookResponse `xorm:"-"`
  408. }
  409. // BeforeUpdate will be invoked by XORM before updating a record
  410. // representing this object
  411. func (t *HookTask) BeforeUpdate() {
  412. if t.RequestInfo != nil {
  413. t.RequestContent = t.simpleMarshalJSON(t.RequestInfo)
  414. }
  415. if t.ResponseInfo != nil {
  416. t.ResponseContent = t.simpleMarshalJSON(t.ResponseInfo)
  417. }
  418. }
  419. // AfterLoad updates the webhook object upon setting a column
  420. func (t *HookTask) AfterLoad() {
  421. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  422. if len(t.RequestContent) == 0 {
  423. return
  424. }
  425. t.RequestInfo = &HookRequest{}
  426. if err := json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  427. log.Error(3, "Unmarshal RequestContent[%d]: %v", t.ID, err)
  428. }
  429. if len(t.ResponseContent) > 0 {
  430. t.ResponseInfo = &HookResponse{}
  431. if err := json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  432. log.Error(3, "Unmarshal ResponseContent[%d]: %v", t.ID, err)
  433. }
  434. }
  435. }
  436. func (t *HookTask) simpleMarshalJSON(v interface{}) string {
  437. p, err := json.Marshal(v)
  438. if err != nil {
  439. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  440. }
  441. return string(p)
  442. }
  443. // HookTasks returns a list of hook tasks by given conditions.
  444. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  445. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  446. return tasks, x.
  447. Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).
  448. Where("hook_id=?", hookID).
  449. Desc("id").
  450. Find(&tasks)
  451. }
  452. // CreateHookTask creates a new hook task,
  453. // it handles conversion from Payload to PayloadContent.
  454. func CreateHookTask(t *HookTask) error {
  455. return createHookTask(x, t)
  456. }
  457. func createHookTask(e Engine, t *HookTask) error {
  458. data, err := t.Payloader.JSONPayload()
  459. if err != nil {
  460. return err
  461. }
  462. t.UUID = gouuid.NewV4().String()
  463. t.PayloadContent = string(data)
  464. _, err = e.Insert(t)
  465. return err
  466. }
  467. // UpdateHookTask updates information of hook task.
  468. func UpdateHookTask(t *HookTask) error {
  469. _, err := x.ID(t.ID).AllCols().Update(t)
  470. return err
  471. }
  472. // PrepareWebhook adds special webhook to task queue for given payload.
  473. func PrepareWebhook(w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  474. return prepareWebhook(x, w, repo, event, p)
  475. }
  476. func prepareWebhook(e Engine, w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  477. for _, e := range w.eventCheckers() {
  478. if event == e.typ {
  479. if !e.has() {
  480. return nil
  481. }
  482. }
  483. }
  484. var payloader api.Payloader
  485. var err error
  486. // Use separate objects so modifications won't be made on payload on non-Gogs/Gitea 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, w.Meta)
  500. if err != nil {
  501. return fmt.Errorf("GetDingtalkPayload: %v", err)
  502. }
  503. default:
  504. p.SetSecret(w.Secret)
  505. payloader = p
  506. }
  507. if err = createHookTask(e, &HookTask{
  508. RepoID: repo.ID,
  509. HookID: w.ID,
  510. Type: w.HookTaskType,
  511. URL: w.URL,
  512. Payloader: payloader,
  513. ContentType: w.ContentType,
  514. EventType: event,
  515. IsSSL: w.IsSSL,
  516. }); err != nil {
  517. return fmt.Errorf("CreateHookTask: %v", err)
  518. }
  519. return nil
  520. }
  521. // PrepareWebhooks adds new webhooks to task queue for given payload.
  522. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  523. return prepareWebhooks(x, repo, event, p)
  524. }
  525. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  526. ws, err := getActiveWebhooksByRepoID(e, repo.ID)
  527. if err != nil {
  528. return fmt.Errorf("GetActiveWebhooksByRepoID: %v", err)
  529. }
  530. // check if repo belongs to org and append additional webhooks
  531. if repo.mustOwner(e).IsOrganization() {
  532. // get hooks for org
  533. orgHooks, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  534. if err != nil {
  535. return fmt.Errorf("GetActiveWebhooksByOrgID: %v", err)
  536. }
  537. ws = append(ws, orgHooks...)
  538. }
  539. if len(ws) == 0 {
  540. return nil
  541. }
  542. for _, w := range ws {
  543. if err = prepareWebhook(e, w, repo, event, p); err != nil {
  544. return err
  545. }
  546. }
  547. return nil
  548. }
  549. func (t *HookTask) deliver() {
  550. t.IsDelivered = true
  551. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  552. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  553. Header("X-Gitea-Delivery", t.UUID).
  554. Header("X-Gitea-Event", string(t.EventType)).
  555. Header("X-Gogs-Delivery", t.UUID).
  556. Header("X-Gogs-Event", string(t.EventType)).
  557. HeaderWithSensitiveCase("X-GitHub-Delivery", t.UUID).
  558. HeaderWithSensitiveCase("X-GitHub-Event", string(t.EventType)).
  559. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  560. switch t.ContentType {
  561. case ContentTypeJSON:
  562. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  563. case ContentTypeForm:
  564. req.Param("payload", t.PayloadContent)
  565. }
  566. // Record delivery information.
  567. t.RequestInfo = &HookRequest{
  568. Headers: map[string]string{},
  569. }
  570. for k, vals := range req.Headers() {
  571. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  572. }
  573. t.ResponseInfo = &HookResponse{
  574. Headers: map[string]string{},
  575. }
  576. defer func() {
  577. t.Delivered = time.Now().UnixNano()
  578. if t.IsSucceed {
  579. log.Trace("Hook delivered: %s", t.UUID)
  580. } else {
  581. log.Trace("Hook delivery failed: %s", t.UUID)
  582. }
  583. if err := UpdateHookTask(t); err != nil {
  584. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  585. }
  586. // Update webhook last delivery status.
  587. w, err := GetWebhookByID(t.HookID)
  588. if err != nil {
  589. log.Error(5, "GetWebhookByID: %v", err)
  590. return
  591. }
  592. if t.IsSucceed {
  593. w.LastStatus = HookStatusSucceed
  594. } else {
  595. w.LastStatus = HookStatusFail
  596. }
  597. if err = UpdateWebhookLastStatus(w); err != nil {
  598. log.Error(5, "UpdateWebhookLastStatus: %v", err)
  599. return
  600. }
  601. }()
  602. resp, err := req.Response()
  603. if err != nil {
  604. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  605. return
  606. }
  607. defer resp.Body.Close()
  608. // Status code is 20x can be seen as succeed.
  609. t.IsSucceed = resp.StatusCode/100 == 2
  610. t.ResponseInfo.Status = resp.StatusCode
  611. for k, vals := range resp.Header {
  612. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  613. }
  614. p, err := ioutil.ReadAll(resp.Body)
  615. if err != nil {
  616. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  617. return
  618. }
  619. t.ResponseInfo.Body = string(p)
  620. }
  621. // DeliverHooks checks and delivers undelivered hooks.
  622. // TODO: shoot more hooks at same time.
  623. func DeliverHooks() {
  624. tasks := make([]*HookTask, 0, 10)
  625. err := x.Where("is_delivered=?", false).Find(&tasks)
  626. if err != nil {
  627. log.Error(4, "DeliverHooks: %v", err)
  628. return
  629. }
  630. // Update hook task status.
  631. for _, t := range tasks {
  632. t.deliver()
  633. }
  634. // Start listening on new hook requests.
  635. for repoIDStr := range HookQueue.Queue() {
  636. log.Trace("DeliverHooks [repo_id: %v]", repoIDStr)
  637. HookQueue.Remove(repoIDStr)
  638. repoID, err := com.StrTo(repoIDStr).Int64()
  639. if err != nil {
  640. log.Error(4, "Invalid repo ID: %s", repoIDStr)
  641. continue
  642. }
  643. tasks = make([]*HookTask, 0, 5)
  644. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  645. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  646. continue
  647. }
  648. for _, t := range tasks {
  649. t.deliver()
  650. }
  651. }
  652. }
  653. // InitDeliverHooks starts the hooks delivery thread
  654. func InitDeliverHooks() {
  655. go DeliverHooks()
  656. }