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

webhook.go 22 kB

11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
9 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. return createWebhook(x, w)
  210. }
  211. func createWebhook(e Engine, w *Webhook) error {
  212. _, err := e.Insert(w)
  213. return err
  214. }
  215. // getWebhook uses argument bean as query condition,
  216. // ID must be specified and do not assign unnecessary fields.
  217. func getWebhook(bean *Webhook) (*Webhook, error) {
  218. has, err := x.Get(bean)
  219. if err != nil {
  220. return nil, err
  221. } else if !has {
  222. return nil, ErrWebhookNotExist{bean.ID}
  223. }
  224. return bean, nil
  225. }
  226. // GetWebhookByID returns webhook of repository by given ID.
  227. func GetWebhookByID(id int64) (*Webhook, error) {
  228. return getWebhook(&Webhook{
  229. ID: id,
  230. })
  231. }
  232. // GetWebhookByRepoID returns webhook of repository by given ID.
  233. func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
  234. return getWebhook(&Webhook{
  235. ID: id,
  236. RepoID: repoID,
  237. })
  238. }
  239. // GetWebhookByOrgID returns webhook of organization by given ID.
  240. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  241. return getWebhook(&Webhook{
  242. ID: id,
  243. OrgID: orgID,
  244. })
  245. }
  246. // GetActiveWebhooksByRepoID returns all active webhooks of repository.
  247. func GetActiveWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  248. return getActiveWebhooksByRepoID(x, repoID)
  249. }
  250. func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
  251. webhooks := make([]*Webhook, 0, 5)
  252. return webhooks, e.Where("is_active=?", true).
  253. Find(&webhooks, &Webhook{RepoID: repoID})
  254. }
  255. // GetWebhooksByRepoID returns all webhooks of a repository.
  256. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  257. webhooks := make([]*Webhook, 0, 5)
  258. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  259. }
  260. // GetActiveWebhooksByOrgID returns all active webhooks for an organization.
  261. func GetActiveWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  262. return getActiveWebhooksByOrgID(x, orgID)
  263. }
  264. func getActiveWebhooksByOrgID(e Engine, orgID int64) (ws []*Webhook, err error) {
  265. err = e.
  266. Where("org_id=?", orgID).
  267. And("is_active=?", true).
  268. Find(&ws)
  269. return ws, err
  270. }
  271. // GetWebhooksByOrgID returns all webhooks for an organization.
  272. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  273. err = x.Find(&ws, &Webhook{OrgID: orgID})
  274. return ws, err
  275. }
  276. // GetDefaultWebhook returns admin-default webhook by given ID.
  277. func GetDefaultWebhook(id int64) (*Webhook, error) {
  278. webhook := &Webhook{ID: id}
  279. has, err := x.
  280. Where("repo_id=? AND org_id=?", 0, 0).
  281. Get(webhook)
  282. if err != nil {
  283. return nil, err
  284. } else if !has {
  285. return nil, ErrWebhookNotExist{id}
  286. }
  287. return webhook, nil
  288. }
  289. // GetDefaultWebhooks returns all admin-default webhooks.
  290. func GetDefaultWebhooks() ([]*Webhook, error) {
  291. return getDefaultWebhooks(x)
  292. }
  293. func getDefaultWebhooks(e Engine) ([]*Webhook, error) {
  294. webhooks := make([]*Webhook, 0, 5)
  295. return webhooks, e.
  296. Where("repo_id=? AND org_id=?", 0, 0).
  297. Find(&webhooks)
  298. }
  299. // UpdateWebhook updates information of webhook.
  300. func UpdateWebhook(w *Webhook) error {
  301. _, err := x.ID(w.ID).AllCols().Update(w)
  302. return err
  303. }
  304. // UpdateWebhookLastStatus updates last status of webhook.
  305. func UpdateWebhookLastStatus(w *Webhook) error {
  306. _, err := x.ID(w.ID).Cols("last_status").Update(w)
  307. return err
  308. }
  309. // deleteWebhook uses argument bean as query condition,
  310. // ID must be specified and do not assign unnecessary fields.
  311. func deleteWebhook(bean *Webhook) (err error) {
  312. sess := x.NewSession()
  313. defer sess.Close()
  314. if err = sess.Begin(); err != nil {
  315. return err
  316. }
  317. if count, err := sess.Delete(bean); err != nil {
  318. return err
  319. } else if count == 0 {
  320. return ErrWebhookNotExist{ID: bean.ID}
  321. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  322. return err
  323. }
  324. return sess.Commit()
  325. }
  326. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  327. func DeleteWebhookByRepoID(repoID, id int64) error {
  328. return deleteWebhook(&Webhook{
  329. ID: id,
  330. RepoID: repoID,
  331. })
  332. }
  333. // DeleteWebhookByOrgID deletes webhook of organization by given ID.
  334. func DeleteWebhookByOrgID(orgID, id int64) error {
  335. return deleteWebhook(&Webhook{
  336. ID: id,
  337. OrgID: orgID,
  338. })
  339. }
  340. // DeleteDefaultWebhook deletes an admin-default webhook by given ID.
  341. func DeleteDefaultWebhook(id int64) error {
  342. sess := x.NewSession()
  343. defer sess.Close()
  344. if err := sess.Begin(); err != nil {
  345. return err
  346. }
  347. count, err := sess.
  348. Where("repo_id=? AND org_id=?", 0, 0).
  349. Delete(&Webhook{ID: id})
  350. if err != nil {
  351. return err
  352. } else if count == 0 {
  353. return ErrWebhookNotExist{ID: id}
  354. }
  355. if _, err := sess.Delete(&HookTask{HookID: id}); err != nil {
  356. return err
  357. }
  358. return sess.Commit()
  359. }
  360. // copyDefaultWebhooksToRepo creates copies of the default webhooks in a new repo
  361. func copyDefaultWebhooksToRepo(e Engine, repoID int64) error {
  362. ws, err := getDefaultWebhooks(e)
  363. if err != nil {
  364. return fmt.Errorf("GetDefaultWebhooks: %v", err)
  365. }
  366. for _, w := range ws {
  367. w.ID = 0
  368. w.RepoID = repoID
  369. if err := createWebhook(e, w); err != nil {
  370. return fmt.Errorf("CreateWebhook: %v", err)
  371. }
  372. }
  373. return nil
  374. }
  375. // ___ ___ __ ___________ __
  376. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  377. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  378. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  379. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  380. // \/ \/ \/ \/ \/
  381. // HookTaskType is the type of an hook task
  382. type HookTaskType int
  383. // Types of hook tasks
  384. const (
  385. GOGS HookTaskType = iota + 1
  386. SLACK
  387. GITEA
  388. DISCORD
  389. DINGTALK
  390. )
  391. var hookTaskTypes = map[string]HookTaskType{
  392. "gitea": GITEA,
  393. "gogs": GOGS,
  394. "slack": SLACK,
  395. "discord": DISCORD,
  396. "dingtalk": DINGTALK,
  397. }
  398. // ToHookTaskType returns HookTaskType by given name.
  399. func ToHookTaskType(name string) HookTaskType {
  400. return hookTaskTypes[name]
  401. }
  402. // Name returns the name of an hook task type
  403. func (t HookTaskType) Name() string {
  404. switch t {
  405. case GITEA:
  406. return "gitea"
  407. case GOGS:
  408. return "gogs"
  409. case SLACK:
  410. return "slack"
  411. case DISCORD:
  412. return "discord"
  413. case DINGTALK:
  414. return "dingtalk"
  415. }
  416. return ""
  417. }
  418. // IsValidHookTaskType returns true if given name is a valid hook task type.
  419. func IsValidHookTaskType(name string) bool {
  420. _, ok := hookTaskTypes[name]
  421. return ok
  422. }
  423. // HookEventType is the type of an hook event
  424. type HookEventType string
  425. // Types of hook events
  426. const (
  427. HookEventCreate HookEventType = "create"
  428. HookEventDelete HookEventType = "delete"
  429. HookEventFork HookEventType = "fork"
  430. HookEventPush HookEventType = "push"
  431. HookEventIssues HookEventType = "issues"
  432. HookEventIssueComment HookEventType = "issue_comment"
  433. HookEventPullRequest HookEventType = "pull_request"
  434. HookEventRepository HookEventType = "repository"
  435. HookEventRelease HookEventType = "release"
  436. HookEventPullRequestApproved HookEventType = "pull_request_approved"
  437. HookEventPullRequestRejected HookEventType = "pull_request_rejected"
  438. HookEventPullRequestComment HookEventType = "pull_request_comment"
  439. )
  440. // HookRequest represents hook task request information.
  441. type HookRequest struct {
  442. Headers map[string]string `json:"headers"`
  443. }
  444. // HookResponse represents hook task response information.
  445. type HookResponse struct {
  446. Status int `json:"status"`
  447. Headers map[string]string `json:"headers"`
  448. Body string `json:"body"`
  449. }
  450. // HookTask represents a hook task.
  451. type HookTask struct {
  452. ID int64 `xorm:"pk autoincr"`
  453. RepoID int64 `xorm:"INDEX"`
  454. HookID int64
  455. UUID string
  456. Type HookTaskType
  457. URL string `xorm:"TEXT"`
  458. api.Payloader `xorm:"-"`
  459. PayloadContent string `xorm:"TEXT"`
  460. ContentType HookContentType
  461. EventType HookEventType
  462. IsSSL bool
  463. IsDelivered bool
  464. Delivered int64
  465. DeliveredString string `xorm:"-"`
  466. // History info.
  467. IsSucceed bool
  468. RequestContent string `xorm:"TEXT"`
  469. RequestInfo *HookRequest `xorm:"-"`
  470. ResponseContent string `xorm:"TEXT"`
  471. ResponseInfo *HookResponse `xorm:"-"`
  472. }
  473. // BeforeUpdate will be invoked by XORM before updating a record
  474. // representing this object
  475. func (t *HookTask) BeforeUpdate() {
  476. if t.RequestInfo != nil {
  477. t.RequestContent = t.simpleMarshalJSON(t.RequestInfo)
  478. }
  479. if t.ResponseInfo != nil {
  480. t.ResponseContent = t.simpleMarshalJSON(t.ResponseInfo)
  481. }
  482. }
  483. // AfterLoad updates the webhook object upon setting a column
  484. func (t *HookTask) AfterLoad() {
  485. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  486. if len(t.RequestContent) == 0 {
  487. return
  488. }
  489. t.RequestInfo = &HookRequest{}
  490. if err := json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  491. log.Error(3, "Unmarshal RequestContent[%d]: %v", t.ID, err)
  492. }
  493. if len(t.ResponseContent) > 0 {
  494. t.ResponseInfo = &HookResponse{}
  495. if err := json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  496. log.Error(3, "Unmarshal ResponseContent[%d]: %v", t.ID, err)
  497. }
  498. }
  499. }
  500. func (t *HookTask) simpleMarshalJSON(v interface{}) string {
  501. p, err := json.Marshal(v)
  502. if err != nil {
  503. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  504. }
  505. return string(p)
  506. }
  507. // HookTasks returns a list of hook tasks by given conditions.
  508. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  509. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  510. return tasks, x.
  511. Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).
  512. Where("hook_id=?", hookID).
  513. Desc("id").
  514. Find(&tasks)
  515. }
  516. // CreateHookTask creates a new hook task,
  517. // it handles conversion from Payload to PayloadContent.
  518. func CreateHookTask(t *HookTask) error {
  519. return createHookTask(x, t)
  520. }
  521. func createHookTask(e Engine, t *HookTask) error {
  522. data, err := t.Payloader.JSONPayload()
  523. if err != nil {
  524. return err
  525. }
  526. t.UUID = gouuid.NewV4().String()
  527. t.PayloadContent = string(data)
  528. _, err = e.Insert(t)
  529. return err
  530. }
  531. // UpdateHookTask updates information of hook task.
  532. func UpdateHookTask(t *HookTask) error {
  533. _, err := x.ID(t.ID).AllCols().Update(t)
  534. return err
  535. }
  536. // PrepareWebhook adds special webhook to task queue for given payload.
  537. func PrepareWebhook(w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  538. return prepareWebhook(x, w, repo, event, p)
  539. }
  540. func prepareWebhook(e Engine, w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  541. for _, e := range w.eventCheckers() {
  542. if event == e.typ {
  543. if !e.has() {
  544. return nil
  545. }
  546. }
  547. }
  548. var payloader api.Payloader
  549. var err error
  550. // Use separate objects so modifications won't be made on payload on non-Gogs/Gitea type hooks.
  551. switch w.HookTaskType {
  552. case SLACK:
  553. payloader, err = GetSlackPayload(p, event, w.Meta)
  554. if err != nil {
  555. return fmt.Errorf("GetSlackPayload: %v", err)
  556. }
  557. case DISCORD:
  558. payloader, err = GetDiscordPayload(p, event, w.Meta)
  559. if err != nil {
  560. return fmt.Errorf("GetDiscordPayload: %v", err)
  561. }
  562. case DINGTALK:
  563. payloader, err = GetDingtalkPayload(p, event, w.Meta)
  564. if err != nil {
  565. return fmt.Errorf("GetDingtalkPayload: %v", err)
  566. }
  567. default:
  568. p.SetSecret(w.Secret)
  569. payloader = p
  570. }
  571. if err = createHookTask(e, &HookTask{
  572. RepoID: repo.ID,
  573. HookID: w.ID,
  574. Type: w.HookTaskType,
  575. URL: w.URL,
  576. Payloader: payloader,
  577. ContentType: w.ContentType,
  578. EventType: event,
  579. IsSSL: w.IsSSL,
  580. }); err != nil {
  581. return fmt.Errorf("CreateHookTask: %v", err)
  582. }
  583. return nil
  584. }
  585. // PrepareWebhooks adds new webhooks to task queue for given payload.
  586. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  587. return prepareWebhooks(x, repo, event, p)
  588. }
  589. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  590. ws, err := getActiveWebhooksByRepoID(e, repo.ID)
  591. if err != nil {
  592. return fmt.Errorf("GetActiveWebhooksByRepoID: %v", err)
  593. }
  594. // check if repo belongs to org and append additional webhooks
  595. if repo.mustOwner(e).IsOrganization() {
  596. // get hooks for org
  597. orgHooks, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  598. if err != nil {
  599. return fmt.Errorf("GetActiveWebhooksByOrgID: %v", err)
  600. }
  601. ws = append(ws, orgHooks...)
  602. }
  603. if len(ws) == 0 {
  604. return nil
  605. }
  606. for _, w := range ws {
  607. if err = prepareWebhook(e, w, repo, event, p); err != nil {
  608. return err
  609. }
  610. }
  611. return nil
  612. }
  613. func (t *HookTask) deliver() {
  614. t.IsDelivered = true
  615. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  616. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  617. Header("X-Gitea-Delivery", t.UUID).
  618. Header("X-Gitea-Event", string(t.EventType)).
  619. Header("X-Gogs-Delivery", t.UUID).
  620. Header("X-Gogs-Event", string(t.EventType)).
  621. HeaderWithSensitiveCase("X-GitHub-Delivery", t.UUID).
  622. HeaderWithSensitiveCase("X-GitHub-Event", string(t.EventType)).
  623. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  624. switch t.ContentType {
  625. case ContentTypeJSON:
  626. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  627. case ContentTypeForm:
  628. req.Param("payload", t.PayloadContent)
  629. }
  630. // Record delivery information.
  631. t.RequestInfo = &HookRequest{
  632. Headers: map[string]string{},
  633. }
  634. for k, vals := range req.Headers() {
  635. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  636. }
  637. t.ResponseInfo = &HookResponse{
  638. Headers: map[string]string{},
  639. }
  640. defer func() {
  641. t.Delivered = time.Now().UnixNano()
  642. if t.IsSucceed {
  643. log.Trace("Hook delivered: %s", t.UUID)
  644. } else {
  645. log.Trace("Hook delivery failed: %s", t.UUID)
  646. }
  647. if err := UpdateHookTask(t); err != nil {
  648. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  649. }
  650. // Update webhook last delivery status.
  651. w, err := GetWebhookByID(t.HookID)
  652. if err != nil {
  653. log.Error(5, "GetWebhookByID: %v", err)
  654. return
  655. }
  656. if t.IsSucceed {
  657. w.LastStatus = HookStatusSucceed
  658. } else {
  659. w.LastStatus = HookStatusFail
  660. }
  661. if err = UpdateWebhookLastStatus(w); err != nil {
  662. log.Error(5, "UpdateWebhookLastStatus: %v", err)
  663. return
  664. }
  665. }()
  666. resp, err := req.Response()
  667. if err != nil {
  668. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  669. return
  670. }
  671. defer resp.Body.Close()
  672. // Status code is 20x can be seen as succeed.
  673. t.IsSucceed = resp.StatusCode/100 == 2
  674. t.ResponseInfo.Status = resp.StatusCode
  675. for k, vals := range resp.Header {
  676. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  677. }
  678. p, err := ioutil.ReadAll(resp.Body)
  679. if err != nil {
  680. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  681. return
  682. }
  683. t.ResponseInfo.Body = string(p)
  684. }
  685. // DeliverHooks checks and delivers undelivered hooks.
  686. // TODO: shoot more hooks at same time.
  687. func DeliverHooks() {
  688. tasks := make([]*HookTask, 0, 10)
  689. err := x.Where("is_delivered=?", false).Find(&tasks)
  690. if err != nil {
  691. log.Error(4, "DeliverHooks: %v", err)
  692. return
  693. }
  694. // Update hook task status.
  695. for _, t := range tasks {
  696. t.deliver()
  697. }
  698. // Start listening on new hook requests.
  699. for repoIDStr := range HookQueue.Queue() {
  700. log.Trace("DeliverHooks [repo_id: %v]", repoIDStr)
  701. HookQueue.Remove(repoIDStr)
  702. repoID, err := com.StrTo(repoIDStr).Int64()
  703. if err != nil {
  704. log.Error(4, "Invalid repo ID: %s", repoIDStr)
  705. continue
  706. }
  707. tasks = make([]*HookTask, 0, 5)
  708. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  709. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  710. continue
  711. }
  712. for _, t := range tasks {
  713. t.deliver()
  714. }
  715. }
  716. }
  717. // InitDeliverHooks starts the hooks delivery thread
  718. func InitDeliverHooks() {
  719. go DeliverHooks()
  720. }