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.

718 lines
18 KiB

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