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 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. "context"
  8. "fmt"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/modules/json"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. api "code.gitea.io/gitea/modules/structs"
  15. "code.gitea.io/gitea/modules/timeutil"
  16. "code.gitea.io/gitea/modules/util"
  17. gouuid "github.com/google/uuid"
  18. "xorm.io/builder"
  19. )
  20. // HookContentType is the content type of a web hook
  21. type HookContentType int
  22. const (
  23. // ContentTypeJSON is a JSON payload for web hooks
  24. ContentTypeJSON HookContentType = iota + 1
  25. // ContentTypeForm is an url-encoded form payload for web hook
  26. ContentTypeForm
  27. )
  28. var hookContentTypes = map[string]HookContentType{
  29. "json": ContentTypeJSON,
  30. "form": ContentTypeForm,
  31. }
  32. // ToHookContentType returns HookContentType by given name.
  33. func ToHookContentType(name string) HookContentType {
  34. return hookContentTypes[name]
  35. }
  36. // HookTaskCleanupType is the type of cleanup to perform on hook_task
  37. type HookTaskCleanupType int
  38. const (
  39. // OlderThan hook_task rows will be cleaned up by the age of the row
  40. OlderThan HookTaskCleanupType = iota
  41. // PerWebhook hook_task rows will be cleaned up by leaving the most recent deliveries for each webhook
  42. PerWebhook
  43. )
  44. var hookTaskCleanupTypes = map[string]HookTaskCleanupType{
  45. "OlderThan": OlderThan,
  46. "PerWebhook": PerWebhook,
  47. }
  48. // ToHookTaskCleanupType returns HookTaskCleanupType by given name.
  49. func ToHookTaskCleanupType(name string) HookTaskCleanupType {
  50. return hookTaskCleanupTypes[name]
  51. }
  52. // Name returns the name of a given web hook's content type
  53. func (t HookContentType) Name() string {
  54. switch t {
  55. case ContentTypeJSON:
  56. return "json"
  57. case ContentTypeForm:
  58. return "form"
  59. }
  60. return ""
  61. }
  62. // IsValidHookContentType returns true if given name is a valid hook content type.
  63. func IsValidHookContentType(name string) bool {
  64. _, ok := hookContentTypes[name]
  65. return ok
  66. }
  67. // HookEvents is a set of web hook events
  68. type HookEvents struct {
  69. Create bool `json:"create"`
  70. Delete bool `json:"delete"`
  71. Fork bool `json:"fork"`
  72. Issues bool `json:"issues"`
  73. IssueAssign bool `json:"issue_assign"`
  74. IssueLabel bool `json:"issue_label"`
  75. IssueMilestone bool `json:"issue_milestone"`
  76. IssueComment bool `json:"issue_comment"`
  77. Push bool `json:"push"`
  78. PullRequest bool `json:"pull_request"`
  79. PullRequestAssign bool `json:"pull_request_assign"`
  80. PullRequestLabel bool `json:"pull_request_label"`
  81. PullRequestMilestone bool `json:"pull_request_milestone"`
  82. PullRequestComment bool `json:"pull_request_comment"`
  83. PullRequestReview bool `json:"pull_request_review"`
  84. PullRequestSync bool `json:"pull_request_sync"`
  85. Repository bool `json:"repository"`
  86. Release bool `json:"release"`
  87. }
  88. // HookEvent represents events that will delivery hook.
  89. type HookEvent struct {
  90. PushOnly bool `json:"push_only"`
  91. SendEverything bool `json:"send_everything"`
  92. ChooseEvents bool `json:"choose_events"`
  93. BranchFilter string `json:"branch_filter"`
  94. HookEvents `json:"events"`
  95. }
  96. // HookType is the type of a webhook
  97. type HookType = string
  98. // Types of webhooks
  99. const (
  100. GITEA HookType = "gitea"
  101. GOGS HookType = "gogs"
  102. SLACK HookType = "slack"
  103. DISCORD HookType = "discord"
  104. DINGTALK HookType = "dingtalk"
  105. TELEGRAM HookType = "telegram"
  106. MSTEAMS HookType = "msteams"
  107. FEISHU HookType = "feishu"
  108. MATRIX HookType = "matrix"
  109. WECHATWORK HookType = "wechatwork"
  110. )
  111. // HookStatus is the status of a web hook
  112. type HookStatus int
  113. // Possible statuses of a web hook
  114. const (
  115. HookStatusNone = iota
  116. HookStatusSucceed
  117. HookStatusFail
  118. )
  119. // Webhook represents a web hook object.
  120. type Webhook struct {
  121. ID int64 `xorm:"pk autoincr"`
  122. RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook
  123. OrgID int64 `xorm:"INDEX"`
  124. IsSystemWebhook bool
  125. URL string `xorm:"url TEXT"`
  126. HTTPMethod string `xorm:"http_method"`
  127. ContentType HookContentType
  128. Secret string `xorm:"TEXT"`
  129. Events string `xorm:"TEXT"`
  130. *HookEvent `xorm:"-"`
  131. IsActive bool `xorm:"INDEX"`
  132. Type HookType `xorm:"VARCHAR(16) 'type'"`
  133. Meta string `xorm:"TEXT"` // store hook-specific attributes
  134. LastStatus HookStatus // Last delivery status
  135. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  136. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  137. }
  138. // AfterLoad updates the webhook object upon setting a column
  139. func (w *Webhook) AfterLoad() {
  140. w.HookEvent = &HookEvent{}
  141. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  142. log.Error("Unmarshal[%d]: %v", w.ID, err)
  143. }
  144. }
  145. // History returns history of webhook by given conditions.
  146. func (w *Webhook) History(page int) ([]*HookTask, error) {
  147. return HookTasks(w.ID, page)
  148. }
  149. // UpdateEvent handles conversion from HookEvent to Events.
  150. func (w *Webhook) UpdateEvent() error {
  151. data, err := json.Marshal(w.HookEvent)
  152. w.Events = string(data)
  153. return err
  154. }
  155. // HasCreateEvent returns true if hook enabled create event.
  156. func (w *Webhook) HasCreateEvent() bool {
  157. return w.SendEverything ||
  158. (w.ChooseEvents && w.HookEvents.Create)
  159. }
  160. // HasDeleteEvent returns true if hook enabled delete event.
  161. func (w *Webhook) HasDeleteEvent() bool {
  162. return w.SendEverything ||
  163. (w.ChooseEvents && w.HookEvents.Delete)
  164. }
  165. // HasForkEvent returns true if hook enabled fork event.
  166. func (w *Webhook) HasForkEvent() bool {
  167. return w.SendEverything ||
  168. (w.ChooseEvents && w.HookEvents.Fork)
  169. }
  170. // HasIssuesEvent returns true if hook enabled issues event.
  171. func (w *Webhook) HasIssuesEvent() bool {
  172. return w.SendEverything ||
  173. (w.ChooseEvents && w.HookEvents.Issues)
  174. }
  175. // HasIssuesAssignEvent returns true if hook enabled issues assign event.
  176. func (w *Webhook) HasIssuesAssignEvent() bool {
  177. return w.SendEverything ||
  178. (w.ChooseEvents && w.HookEvents.IssueAssign)
  179. }
  180. // HasIssuesLabelEvent returns true if hook enabled issues label event.
  181. func (w *Webhook) HasIssuesLabelEvent() bool {
  182. return w.SendEverything ||
  183. (w.ChooseEvents && w.HookEvents.IssueLabel)
  184. }
  185. // HasIssuesMilestoneEvent returns true if hook enabled issues milestone event.
  186. func (w *Webhook) HasIssuesMilestoneEvent() bool {
  187. return w.SendEverything ||
  188. (w.ChooseEvents && w.HookEvents.IssueMilestone)
  189. }
  190. // HasIssueCommentEvent returns true if hook enabled issue_comment event.
  191. func (w *Webhook) HasIssueCommentEvent() bool {
  192. return w.SendEverything ||
  193. (w.ChooseEvents && w.HookEvents.IssueComment)
  194. }
  195. // HasPushEvent returns true if hook enabled push event.
  196. func (w *Webhook) HasPushEvent() bool {
  197. return w.PushOnly || w.SendEverything ||
  198. (w.ChooseEvents && w.HookEvents.Push)
  199. }
  200. // HasPullRequestEvent returns true if hook enabled pull request event.
  201. func (w *Webhook) HasPullRequestEvent() bool {
  202. return w.SendEverything ||
  203. (w.ChooseEvents && w.HookEvents.PullRequest)
  204. }
  205. // HasPullRequestAssignEvent returns true if hook enabled pull request assign event.
  206. func (w *Webhook) HasPullRequestAssignEvent() bool {
  207. return w.SendEverything ||
  208. (w.ChooseEvents && w.HookEvents.PullRequestAssign)
  209. }
  210. // HasPullRequestLabelEvent returns true if hook enabled pull request label event.
  211. func (w *Webhook) HasPullRequestLabelEvent() bool {
  212. return w.SendEverything ||
  213. (w.ChooseEvents && w.HookEvents.PullRequestLabel)
  214. }
  215. // HasPullRequestMilestoneEvent returns true if hook enabled pull request milestone event.
  216. func (w *Webhook) HasPullRequestMilestoneEvent() bool {
  217. return w.SendEverything ||
  218. (w.ChooseEvents && w.HookEvents.PullRequestMilestone)
  219. }
  220. // HasPullRequestCommentEvent returns true if hook enabled pull_request_comment event.
  221. func (w *Webhook) HasPullRequestCommentEvent() bool {
  222. return w.SendEverything ||
  223. (w.ChooseEvents && w.HookEvents.PullRequestComment)
  224. }
  225. // HasPullRequestApprovedEvent returns true if hook enabled pull request review event.
  226. func (w *Webhook) HasPullRequestApprovedEvent() bool {
  227. return w.SendEverything ||
  228. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  229. }
  230. // HasPullRequestRejectedEvent returns true if hook enabled pull request review event.
  231. func (w *Webhook) HasPullRequestRejectedEvent() bool {
  232. return w.SendEverything ||
  233. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  234. }
  235. // HasPullRequestReviewCommentEvent returns true if hook enabled pull request review event.
  236. func (w *Webhook) HasPullRequestReviewCommentEvent() bool {
  237. return w.SendEverything ||
  238. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  239. }
  240. // HasPullRequestSyncEvent returns true if hook enabled pull request sync event.
  241. func (w *Webhook) HasPullRequestSyncEvent() bool {
  242. return w.SendEverything ||
  243. (w.ChooseEvents && w.HookEvents.PullRequestSync)
  244. }
  245. // HasReleaseEvent returns if hook enabled release event.
  246. func (w *Webhook) HasReleaseEvent() bool {
  247. return w.SendEverything ||
  248. (w.ChooseEvents && w.HookEvents.Release)
  249. }
  250. // HasRepositoryEvent returns if hook enabled repository event.
  251. func (w *Webhook) HasRepositoryEvent() bool {
  252. return w.SendEverything ||
  253. (w.ChooseEvents && w.HookEvents.Repository)
  254. }
  255. // EventCheckers returns event checkers
  256. func (w *Webhook) EventCheckers() []struct {
  257. Has func() bool
  258. Type HookEventType
  259. } {
  260. return []struct {
  261. Has func() bool
  262. Type HookEventType
  263. }{
  264. {w.HasCreateEvent, HookEventCreate},
  265. {w.HasDeleteEvent, HookEventDelete},
  266. {w.HasForkEvent, HookEventFork},
  267. {w.HasPushEvent, HookEventPush},
  268. {w.HasIssuesEvent, HookEventIssues},
  269. {w.HasIssuesAssignEvent, HookEventIssueAssign},
  270. {w.HasIssuesLabelEvent, HookEventIssueLabel},
  271. {w.HasIssuesMilestoneEvent, HookEventIssueMilestone},
  272. {w.HasIssueCommentEvent, HookEventIssueComment},
  273. {w.HasPullRequestEvent, HookEventPullRequest},
  274. {w.HasPullRequestAssignEvent, HookEventPullRequestAssign},
  275. {w.HasPullRequestLabelEvent, HookEventPullRequestLabel},
  276. {w.HasPullRequestMilestoneEvent, HookEventPullRequestMilestone},
  277. {w.HasPullRequestCommentEvent, HookEventPullRequestComment},
  278. {w.HasPullRequestApprovedEvent, HookEventPullRequestReviewApproved},
  279. {w.HasPullRequestRejectedEvent, HookEventPullRequestReviewRejected},
  280. {w.HasPullRequestCommentEvent, HookEventPullRequestReviewComment},
  281. {w.HasPullRequestSyncEvent, HookEventPullRequestSync},
  282. {w.HasRepositoryEvent, HookEventRepository},
  283. {w.HasReleaseEvent, HookEventRelease},
  284. }
  285. }
  286. // EventsArray returns an array of hook events
  287. func (w *Webhook) EventsArray() []string {
  288. events := make([]string, 0, 7)
  289. for _, c := range w.EventCheckers() {
  290. if c.Has() {
  291. events = append(events, string(c.Type))
  292. }
  293. }
  294. return events
  295. }
  296. // CreateWebhook creates a new web hook.
  297. func CreateWebhook(w *Webhook) error {
  298. return createWebhook(x, w)
  299. }
  300. func createWebhook(e Engine, w *Webhook) error {
  301. w.Type = strings.TrimSpace(w.Type)
  302. _, err := e.Insert(w)
  303. return err
  304. }
  305. // getWebhook uses argument bean as query condition,
  306. // ID must be specified and do not assign unnecessary fields.
  307. func getWebhook(bean *Webhook) (*Webhook, error) {
  308. has, err := x.Get(bean)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrWebhookNotExist{bean.ID}
  313. }
  314. return bean, nil
  315. }
  316. // GetWebhookByID returns webhook of repository by given ID.
  317. func GetWebhookByID(id int64) (*Webhook, error) {
  318. return getWebhook(&Webhook{
  319. ID: id,
  320. })
  321. }
  322. // GetWebhookByRepoID returns webhook of repository by given ID.
  323. func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
  324. return getWebhook(&Webhook{
  325. ID: id,
  326. RepoID: repoID,
  327. })
  328. }
  329. // GetWebhookByOrgID returns webhook of organization by given ID.
  330. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  331. return getWebhook(&Webhook{
  332. ID: id,
  333. OrgID: orgID,
  334. })
  335. }
  336. // ListWebhookOptions are options to filter webhooks on ListWebhooksByOpts
  337. type ListWebhookOptions struct {
  338. ListOptions
  339. RepoID int64
  340. OrgID int64
  341. IsActive util.OptionalBool
  342. }
  343. func (opts *ListWebhookOptions) toCond() builder.Cond {
  344. cond := builder.NewCond()
  345. if opts.RepoID != 0 {
  346. cond = cond.And(builder.Eq{"webhook.repo_id": opts.RepoID})
  347. }
  348. if opts.OrgID != 0 {
  349. cond = cond.And(builder.Eq{"webhook.org_id": opts.OrgID})
  350. }
  351. if !opts.IsActive.IsNone() {
  352. cond = cond.And(builder.Eq{"webhook.is_active": opts.IsActive.IsTrue()})
  353. }
  354. return cond
  355. }
  356. func listWebhooksByOpts(e Engine, opts *ListWebhookOptions) ([]*Webhook, error) {
  357. sess := e.Where(opts.toCond())
  358. if opts.Page != 0 {
  359. sess = opts.setSessionPagination(sess)
  360. webhooks := make([]*Webhook, 0, opts.PageSize)
  361. err := sess.Find(&webhooks)
  362. return webhooks, err
  363. }
  364. webhooks := make([]*Webhook, 0, 10)
  365. err := sess.Find(&webhooks)
  366. return webhooks, err
  367. }
  368. // ListWebhooksByOpts return webhooks based on options
  369. func ListWebhooksByOpts(opts *ListWebhookOptions) ([]*Webhook, error) {
  370. return listWebhooksByOpts(x, opts)
  371. }
  372. // CountWebhooksByOpts count webhooks based on options and ignore pagination
  373. func CountWebhooksByOpts(opts *ListWebhookOptions) (int64, error) {
  374. return x.Where(opts.toCond()).Count(&Webhook{})
  375. }
  376. // GetDefaultWebhooks returns all admin-default webhooks.
  377. func GetDefaultWebhooks() ([]*Webhook, error) {
  378. return getDefaultWebhooks(x)
  379. }
  380. func getDefaultWebhooks(e Engine) ([]*Webhook, error) {
  381. webhooks := make([]*Webhook, 0, 5)
  382. return webhooks, e.
  383. Where("repo_id=? AND org_id=? AND is_system_webhook=?", 0, 0, false).
  384. Find(&webhooks)
  385. }
  386. // GetSystemOrDefaultWebhook returns admin system or default webhook by given ID.
  387. func GetSystemOrDefaultWebhook(id int64) (*Webhook, error) {
  388. webhook := &Webhook{ID: id}
  389. has, err := x.
  390. Where("repo_id=? AND org_id=?", 0, 0).
  391. Get(webhook)
  392. if err != nil {
  393. return nil, err
  394. } else if !has {
  395. return nil, ErrWebhookNotExist{id}
  396. }
  397. return webhook, nil
  398. }
  399. // GetSystemWebhooks returns all admin system webhooks.
  400. func GetSystemWebhooks() ([]*Webhook, error) {
  401. return getSystemWebhooks(x)
  402. }
  403. func getSystemWebhooks(e Engine) ([]*Webhook, error) {
  404. webhooks := make([]*Webhook, 0, 5)
  405. return webhooks, e.
  406. Where("repo_id=? AND org_id=? AND is_system_webhook=?", 0, 0, true).
  407. Find(&webhooks)
  408. }
  409. // UpdateWebhook updates information of webhook.
  410. func UpdateWebhook(w *Webhook) error {
  411. _, err := x.ID(w.ID).AllCols().Update(w)
  412. return err
  413. }
  414. // UpdateWebhookLastStatus updates last status of webhook.
  415. func UpdateWebhookLastStatus(w *Webhook) error {
  416. _, err := x.ID(w.ID).Cols("last_status").Update(w)
  417. return err
  418. }
  419. // deleteWebhook uses argument bean as query condition,
  420. // ID must be specified and do not assign unnecessary fields.
  421. func deleteWebhook(bean *Webhook) (err error) {
  422. sess := x.NewSession()
  423. defer sess.Close()
  424. if err = sess.Begin(); err != nil {
  425. return err
  426. }
  427. if count, err := sess.Delete(bean); err != nil {
  428. return err
  429. } else if count == 0 {
  430. return ErrWebhookNotExist{ID: bean.ID}
  431. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  432. return err
  433. }
  434. return sess.Commit()
  435. }
  436. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  437. func DeleteWebhookByRepoID(repoID, id int64) error {
  438. return deleteWebhook(&Webhook{
  439. ID: id,
  440. RepoID: repoID,
  441. })
  442. }
  443. // DeleteWebhookByOrgID deletes webhook of organization by given ID.
  444. func DeleteWebhookByOrgID(orgID, id int64) error {
  445. return deleteWebhook(&Webhook{
  446. ID: id,
  447. OrgID: orgID,
  448. })
  449. }
  450. // DeleteDefaultSystemWebhook deletes an admin-configured default or system webhook (where Org and Repo ID both 0)
  451. func DeleteDefaultSystemWebhook(id int64) error {
  452. sess := x.NewSession()
  453. defer sess.Close()
  454. if err := sess.Begin(); err != nil {
  455. return err
  456. }
  457. count, err := sess.
  458. Where("repo_id=? AND org_id=?", 0, 0).
  459. Delete(&Webhook{ID: id})
  460. if err != nil {
  461. return err
  462. } else if count == 0 {
  463. return ErrWebhookNotExist{ID: id}
  464. }
  465. if _, err := sess.Delete(&HookTask{HookID: id}); err != nil {
  466. return err
  467. }
  468. return sess.Commit()
  469. }
  470. // copyDefaultWebhooksToRepo creates copies of the default webhooks in a new repo
  471. func copyDefaultWebhooksToRepo(e Engine, repoID int64) error {
  472. ws, err := getDefaultWebhooks(e)
  473. if err != nil {
  474. return fmt.Errorf("GetDefaultWebhooks: %v", err)
  475. }
  476. for _, w := range ws {
  477. w.ID = 0
  478. w.RepoID = repoID
  479. if err := createWebhook(e, w); err != nil {
  480. return fmt.Errorf("CreateWebhook: %v", err)
  481. }
  482. }
  483. return nil
  484. }
  485. // ___ ___ __ ___________ __
  486. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  487. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  488. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  489. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  490. // \/ \/ \/ \/ \/
  491. // HookEventType is the type of an hook event
  492. type HookEventType string
  493. // Types of hook events
  494. const (
  495. HookEventCreate HookEventType = "create"
  496. HookEventDelete HookEventType = "delete"
  497. HookEventFork HookEventType = "fork"
  498. HookEventPush HookEventType = "push"
  499. HookEventIssues HookEventType = "issues"
  500. HookEventIssueAssign HookEventType = "issue_assign"
  501. HookEventIssueLabel HookEventType = "issue_label"
  502. HookEventIssueMilestone HookEventType = "issue_milestone"
  503. HookEventIssueComment HookEventType = "issue_comment"
  504. HookEventPullRequest HookEventType = "pull_request"
  505. HookEventPullRequestAssign HookEventType = "pull_request_assign"
  506. HookEventPullRequestLabel HookEventType = "pull_request_label"
  507. HookEventPullRequestMilestone HookEventType = "pull_request_milestone"
  508. HookEventPullRequestComment HookEventType = "pull_request_comment"
  509. HookEventPullRequestReviewApproved HookEventType = "pull_request_review_approved"
  510. HookEventPullRequestReviewRejected HookEventType = "pull_request_review_rejected"
  511. HookEventPullRequestReviewComment HookEventType = "pull_request_review_comment"
  512. HookEventPullRequestSync HookEventType = "pull_request_sync"
  513. HookEventRepository HookEventType = "repository"
  514. HookEventRelease HookEventType = "release"
  515. )
  516. // Event returns the HookEventType as an event string
  517. func (h HookEventType) Event() string {
  518. switch h {
  519. case HookEventCreate:
  520. return "create"
  521. case HookEventDelete:
  522. return "delete"
  523. case HookEventFork:
  524. return "fork"
  525. case HookEventPush:
  526. return "push"
  527. case HookEventIssues, HookEventIssueAssign, HookEventIssueLabel, HookEventIssueMilestone:
  528. return "issues"
  529. case HookEventPullRequest, HookEventPullRequestAssign, HookEventPullRequestLabel, HookEventPullRequestMilestone,
  530. HookEventPullRequestSync:
  531. return "pull_request"
  532. case HookEventIssueComment, HookEventPullRequestComment:
  533. return "issue_comment"
  534. case HookEventPullRequestReviewApproved:
  535. return "pull_request_approved"
  536. case HookEventPullRequestReviewRejected:
  537. return "pull_request_rejected"
  538. case HookEventPullRequestReviewComment:
  539. return "pull_request_comment"
  540. case HookEventRepository:
  541. return "repository"
  542. case HookEventRelease:
  543. return "release"
  544. }
  545. return ""
  546. }
  547. // HookRequest represents hook task request information.
  548. type HookRequest struct {
  549. URL string `json:"url"`
  550. HTTPMethod string `json:"http_method"`
  551. Headers map[string]string `json:"headers"`
  552. }
  553. // HookResponse represents hook task response information.
  554. type HookResponse struct {
  555. Status int `json:"status"`
  556. Headers map[string]string `json:"headers"`
  557. Body string `json:"body"`
  558. }
  559. // HookTask represents a hook task.
  560. type HookTask struct {
  561. ID int64 `xorm:"pk autoincr"`
  562. RepoID int64 `xorm:"INDEX"`
  563. HookID int64
  564. UUID string
  565. api.Payloader `xorm:"-"`
  566. PayloadContent string `xorm:"TEXT"`
  567. EventType HookEventType
  568. IsDelivered bool
  569. Delivered int64
  570. DeliveredString string `xorm:"-"`
  571. // History info.
  572. IsSucceed bool
  573. RequestContent string `xorm:"TEXT"`
  574. RequestInfo *HookRequest `xorm:"-"`
  575. ResponseContent string `xorm:"TEXT"`
  576. ResponseInfo *HookResponse `xorm:"-"`
  577. }
  578. // BeforeUpdate will be invoked by XORM before updating a record
  579. // representing this object
  580. func (t *HookTask) BeforeUpdate() {
  581. if t.RequestInfo != nil {
  582. t.RequestContent = t.simpleMarshalJSON(t.RequestInfo)
  583. }
  584. if t.ResponseInfo != nil {
  585. t.ResponseContent = t.simpleMarshalJSON(t.ResponseInfo)
  586. }
  587. }
  588. // AfterLoad updates the webhook object upon setting a column
  589. func (t *HookTask) AfterLoad() {
  590. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  591. if len(t.RequestContent) == 0 {
  592. return
  593. }
  594. t.RequestInfo = &HookRequest{}
  595. if err := json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  596. log.Error("Unmarshal RequestContent[%d]: %v", t.ID, err)
  597. }
  598. if len(t.ResponseContent) > 0 {
  599. t.ResponseInfo = &HookResponse{}
  600. if err := json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  601. log.Error("Unmarshal ResponseContent[%d]: %v", t.ID, err)
  602. }
  603. }
  604. }
  605. func (t *HookTask) simpleMarshalJSON(v interface{}) string {
  606. p, err := json.Marshal(v)
  607. if err != nil {
  608. log.Error("Marshal [%d]: %v", t.ID, err)
  609. }
  610. return string(p)
  611. }
  612. // HookTasks returns a list of hook tasks by given conditions.
  613. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  614. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  615. return tasks, x.
  616. Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).
  617. Where("hook_id=?", hookID).
  618. Desc("id").
  619. Find(&tasks)
  620. }
  621. // CreateHookTask creates a new hook task,
  622. // it handles conversion from Payload to PayloadContent.
  623. func CreateHookTask(t *HookTask) error {
  624. return createHookTask(x, t)
  625. }
  626. func createHookTask(e Engine, t *HookTask) error {
  627. data, err := t.Payloader.JSONPayload()
  628. if err != nil {
  629. return err
  630. }
  631. t.UUID = gouuid.New().String()
  632. t.PayloadContent = string(data)
  633. _, err = e.Insert(t)
  634. return err
  635. }
  636. // UpdateHookTask updates information of hook task.
  637. func UpdateHookTask(t *HookTask) error {
  638. _, err := x.ID(t.ID).AllCols().Update(t)
  639. return err
  640. }
  641. // FindUndeliveredHookTasks represents find the undelivered hook tasks
  642. func FindUndeliveredHookTasks() ([]*HookTask, error) {
  643. tasks := make([]*HookTask, 0, 10)
  644. if err := x.Where("is_delivered=?", false).Find(&tasks); err != nil {
  645. return nil, err
  646. }
  647. return tasks, nil
  648. }
  649. // FindRepoUndeliveredHookTasks represents find the undelivered hook tasks of one repository
  650. func FindRepoUndeliveredHookTasks(repoID int64) ([]*HookTask, error) {
  651. tasks := make([]*HookTask, 0, 5)
  652. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  653. return nil, err
  654. }
  655. return tasks, nil
  656. }
  657. // CleanupHookTaskTable deletes rows from hook_task as needed.
  658. func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error {
  659. log.Trace("Doing: CleanupHookTaskTable")
  660. if cleanupType == OlderThan {
  661. deleteOlderThan := time.Now().Add(-olderThan).UnixNano()
  662. deletes, err := x.
  663. Where("is_delivered = ? and delivered < ?", true, deleteOlderThan).
  664. Delete(new(HookTask))
  665. if err != nil {
  666. return err
  667. }
  668. log.Trace("Deleted %d rows from hook_task", deletes)
  669. } else if cleanupType == PerWebhook {
  670. hookIDs := make([]int64, 0, 10)
  671. err := x.Table("webhook").
  672. Where("id > 0").
  673. Cols("id").
  674. Find(&hookIDs)
  675. if err != nil {
  676. return err
  677. }
  678. for _, hookID := range hookIDs {
  679. select {
  680. case <-ctx.Done():
  681. return ErrCancelledf("Before deleting hook_task records for hook id %d", hookID)
  682. default:
  683. }
  684. if err = deleteDeliveredHookTasksByWebhook(hookID, numberToKeep); err != nil {
  685. return err
  686. }
  687. }
  688. }
  689. log.Trace("Finished: CleanupHookTaskTable")
  690. return nil
  691. }
  692. func deleteDeliveredHookTasksByWebhook(hookID int64, numberDeliveriesToKeep int) error {
  693. log.Trace("Deleting hook_task rows for webhook %d, keeping the most recent %d deliveries", hookID, numberDeliveriesToKeep)
  694. deliveryDates := make([]int64, 0, 10)
  695. err := x.Table("hook_task").
  696. Where("hook_task.hook_id = ? AND hook_task.is_delivered = ? AND hook_task.delivered is not null", hookID, true).
  697. Cols("hook_task.delivered").
  698. Join("INNER", "webhook", "hook_task.hook_id = webhook.id").
  699. OrderBy("hook_task.delivered desc").
  700. Limit(1, int(numberDeliveriesToKeep)).
  701. Find(&deliveryDates)
  702. if err != nil {
  703. return err
  704. }
  705. if len(deliveryDates) > 0 {
  706. deletes, err := x.
  707. Where("hook_id = ? and is_delivered = ? and delivered <= ?", hookID, true, deliveryDates[0]).
  708. Delete(new(HookTask))
  709. if err != nil {
  710. return err
  711. }
  712. log.Trace("Deleted %d hook_task rows for webhook %d", deletes, hookID)
  713. } else {
  714. log.Trace("No hook_task rows to delete for webhook %d", hookID)
  715. }
  716. return nil
  717. }