Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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