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