webhook.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. jsoniter "github.com/json-iterator/go"
  10. "github.com/unknwon/com"
  11. git "github.com/gogs/git-module"
  12. api "github.com/gogs/go-gogs-client"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/context"
  15. "gogs.io/gogs/internal/db"
  16. "gogs.io/gogs/internal/db/errors"
  17. "gogs.io/gogs/internal/form"
  18. )
  19. const (
  20. WEBHOOKS = "repo/settings/webhook/base"
  21. WEBHOOK_NEW = "repo/settings/webhook/new"
  22. ORG_WEBHOOK_NEW = "org/settings/webhook_new"
  23. )
  24. func Webhooks(c *context.Context) {
  25. c.Data["Title"] = c.Tr("repo.settings.hooks")
  26. c.Data["PageIsSettingsHooks"] = true
  27. c.Data["BaseLink"] = c.Repo.RepoLink
  28. c.Data["Description"] = c.Tr("repo.settings.hooks_desc", "https://github.com/gogs/docs-api/blob/master/Repositories/Webhooks.md")
  29. c.Data["Types"] = conf.Webhook.Types
  30. ws, err := db.GetWebhooksByRepoID(c.Repo.Repository.ID)
  31. if err != nil {
  32. c.Error(err, "get webhooks by repository ID")
  33. return
  34. }
  35. c.Data["Webhooks"] = ws
  36. c.Success(WEBHOOKS)
  37. }
  38. type OrgRepoCtx struct {
  39. OrgID int64
  40. RepoID int64
  41. Link string
  42. NewTemplate string
  43. }
  44. // getOrgRepoCtx determines whether this is a repo context or organization context.
  45. func getOrgRepoCtx(c *context.Context) (*OrgRepoCtx, error) {
  46. if len(c.Repo.RepoLink) > 0 {
  47. c.Data["PageIsRepositoryContext"] = true
  48. return &OrgRepoCtx{
  49. RepoID: c.Repo.Repository.ID,
  50. Link: c.Repo.RepoLink,
  51. NewTemplate: WEBHOOK_NEW,
  52. }, nil
  53. }
  54. if len(c.Org.OrgLink) > 0 {
  55. c.Data["PageIsOrganizationContext"] = true
  56. return &OrgRepoCtx{
  57. OrgID: c.Org.Organization.ID,
  58. Link: c.Org.OrgLink,
  59. NewTemplate: ORG_WEBHOOK_NEW,
  60. }, nil
  61. }
  62. return nil, errors.New("Unable to set OrgRepo context")
  63. }
  64. func checkHookType(c *context.Context) string {
  65. hookType := strings.ToLower(c.Params(":type"))
  66. if !com.IsSliceContainsStr(conf.Webhook.Types, hookType) {
  67. c.NotFound()
  68. return ""
  69. }
  70. return hookType
  71. }
  72. func WebhooksNew(c *context.Context) {
  73. c.Data["Title"] = c.Tr("repo.settings.add_webhook")
  74. c.Data["PageIsSettingsHooks"] = true
  75. c.Data["PageIsSettingsHooksNew"] = true
  76. c.Data["Webhook"] = db.Webhook{HookEvent: &db.HookEvent{}}
  77. orCtx, err := getOrgRepoCtx(c)
  78. if err != nil {
  79. c.Error(err, "get organization repository context")
  80. return
  81. }
  82. c.Data["HookType"] = checkHookType(c)
  83. if c.Written() {
  84. return
  85. }
  86. c.Data["BaseLink"] = orCtx.Link
  87. c.Success(orCtx.NewTemplate)
  88. }
  89. func ParseHookEvent(f form.Webhook) *db.HookEvent {
  90. return &db.HookEvent{
  91. PushOnly: f.PushOnly(),
  92. SendEverything: f.SendEverything(),
  93. ChooseEvents: f.ChooseEvents(),
  94. HookEvents: db.HookEvents{
  95. Create: f.Create,
  96. Delete: f.Delete,
  97. Fork: f.Fork,
  98. Push: f.Push,
  99. Issues: f.Issues,
  100. IssueComment: f.IssueComment,
  101. PullRequest: f.PullRequest,
  102. Release: f.Release,
  103. },
  104. }
  105. }
  106. func WebHooksNewPost(c *context.Context, f form.NewWebhook) {
  107. c.Data["Title"] = c.Tr("repo.settings.add_webhook")
  108. c.Data["PageIsSettingsHooks"] = true
  109. c.Data["PageIsSettingsHooksNew"] = true
  110. c.Data["Webhook"] = db.Webhook{HookEvent: &db.HookEvent{}}
  111. c.Data["HookType"] = "gogs"
  112. orCtx, err := getOrgRepoCtx(c)
  113. if err != nil {
  114. c.Error(err, "get organization repository context")
  115. return
  116. }
  117. c.Data["BaseLink"] = orCtx.Link
  118. if c.HasError() {
  119. c.Success(orCtx.NewTemplate)
  120. return
  121. }
  122. contentType := db.JSON
  123. if db.HookContentType(f.ContentType) == db.FORM {
  124. contentType = db.FORM
  125. }
  126. w := &db.Webhook{
  127. RepoID: orCtx.RepoID,
  128. URL: f.PayloadURL,
  129. ContentType: contentType,
  130. Secret: f.Secret,
  131. HookEvent: ParseHookEvent(f.Webhook),
  132. IsActive: f.Active,
  133. HookTaskType: db.GOGS,
  134. OrgID: orCtx.OrgID,
  135. }
  136. if err := w.UpdateEvent(); err != nil {
  137. c.Error(err, "update event")
  138. return
  139. } else if err := db.CreateWebhook(w); err != nil {
  140. c.Error(err, "create webhook")
  141. return
  142. }
  143. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  144. c.Redirect(orCtx.Link + "/settings/hooks")
  145. }
  146. func SlackHooksNewPost(c *context.Context, f form.NewSlackHook) {
  147. c.Data["Title"] = c.Tr("repo.settings")
  148. c.Data["PageIsSettingsHooks"] = true
  149. c.Data["PageIsSettingsHooksNew"] = true
  150. c.Data["Webhook"] = db.Webhook{HookEvent: &db.HookEvent{}}
  151. orCtx, err := getOrgRepoCtx(c)
  152. if err != nil {
  153. c.Error(err, "get organization repository context")
  154. return
  155. }
  156. if c.HasError() {
  157. c.Success(orCtx.NewTemplate)
  158. return
  159. }
  160. meta, err := jsoniter.Marshal(&db.SlackMeta{
  161. Channel: f.Channel,
  162. Username: f.Username,
  163. IconURL: f.IconURL,
  164. Color: f.Color,
  165. })
  166. if err != nil {
  167. c.Error(err, "marshal JSON")
  168. return
  169. }
  170. w := &db.Webhook{
  171. RepoID: orCtx.RepoID,
  172. URL: f.PayloadURL,
  173. ContentType: db.JSON,
  174. HookEvent: ParseHookEvent(f.Webhook),
  175. IsActive: f.Active,
  176. HookTaskType: db.SLACK,
  177. Meta: string(meta),
  178. OrgID: orCtx.OrgID,
  179. }
  180. if err := w.UpdateEvent(); err != nil {
  181. c.Error(err, "update event")
  182. return
  183. } else if err := db.CreateWebhook(w); err != nil {
  184. c.Error(err, "create webhook")
  185. return
  186. }
  187. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  188. c.Redirect(orCtx.Link + "/settings/hooks")
  189. }
  190. // FIXME: merge logic to Slack
  191. func DiscordHooksNewPost(c *context.Context, f form.NewDiscordHook) {
  192. c.Data["Title"] = c.Tr("repo.settings")
  193. c.Data["PageIsSettingsHooks"] = true
  194. c.Data["PageIsSettingsHooksNew"] = true
  195. c.Data["Webhook"] = db.Webhook{HookEvent: &db.HookEvent{}}
  196. orCtx, err := getOrgRepoCtx(c)
  197. if err != nil {
  198. c.Error(err, "get organization repository context")
  199. return
  200. }
  201. if c.HasError() {
  202. c.Success(orCtx.NewTemplate)
  203. return
  204. }
  205. meta, err := jsoniter.Marshal(&db.SlackMeta{
  206. Username: f.Username,
  207. IconURL: f.IconURL,
  208. Color: f.Color,
  209. })
  210. if err != nil {
  211. c.Error(err, "marshal JSON")
  212. return
  213. }
  214. w := &db.Webhook{
  215. RepoID: orCtx.RepoID,
  216. URL: f.PayloadURL,
  217. ContentType: db.JSON,
  218. HookEvent: ParseHookEvent(f.Webhook),
  219. IsActive: f.Active,
  220. HookTaskType: db.DISCORD,
  221. Meta: string(meta),
  222. OrgID: orCtx.OrgID,
  223. }
  224. if err := w.UpdateEvent(); err != nil {
  225. c.Error(err, "update event")
  226. return
  227. } else if err := db.CreateWebhook(w); err != nil {
  228. c.Error(err, "create webhook")
  229. return
  230. }
  231. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  232. c.Redirect(orCtx.Link + "/settings/hooks")
  233. }
  234. func DingtalkHooksNewPost(c *context.Context, f form.NewDingtalkHook) {
  235. c.Data["Title"] = c.Tr("repo.settings")
  236. c.Data["PageIsSettingsHooks"] = true
  237. c.Data["PageIsSettingsHooksNew"] = true
  238. c.Data["Webhook"] = db.Webhook{HookEvent: &db.HookEvent{}}
  239. orCtx, err := getOrgRepoCtx(c)
  240. if err != nil {
  241. c.Error(err, "get organization repository context")
  242. return
  243. }
  244. if c.HasError() {
  245. c.Success(orCtx.NewTemplate)
  246. return
  247. }
  248. w := &db.Webhook{
  249. RepoID: orCtx.RepoID,
  250. URL: f.PayloadURL,
  251. ContentType: db.JSON,
  252. HookEvent: ParseHookEvent(f.Webhook),
  253. IsActive: f.Active,
  254. HookTaskType: db.DINGTALK,
  255. OrgID: orCtx.OrgID,
  256. }
  257. if err := w.UpdateEvent(); err != nil {
  258. c.Error(err, "update event")
  259. return
  260. } else if err := db.CreateWebhook(w); err != nil {
  261. c.Error(err, "create webhook")
  262. return
  263. }
  264. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  265. c.Redirect(orCtx.Link + "/settings/hooks")
  266. }
  267. func checkWebhook(c *context.Context) (*OrgRepoCtx, *db.Webhook) {
  268. c.Data["RequireHighlightJS"] = true
  269. orCtx, err := getOrgRepoCtx(c)
  270. if err != nil {
  271. c.Error(err, "get organization repository context")
  272. return nil, nil
  273. }
  274. c.Data["BaseLink"] = orCtx.Link
  275. var w *db.Webhook
  276. if orCtx.RepoID > 0 {
  277. w, err = db.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  278. } else {
  279. w, err = db.GetWebhookByOrgID(c.Org.Organization.ID, c.ParamsInt64(":id"))
  280. }
  281. if err != nil {
  282. c.NotFoundOrError(err, "get webhook")
  283. return nil, nil
  284. }
  285. switch w.HookTaskType {
  286. case db.SLACK:
  287. c.Data["SlackHook"] = w.GetSlackHook()
  288. c.Data["HookType"] = "slack"
  289. case db.DISCORD:
  290. c.Data["SlackHook"] = w.GetSlackHook()
  291. c.Data["HookType"] = "discord"
  292. case db.DINGTALK:
  293. c.Data["HookType"] = "dingtalk"
  294. default:
  295. c.Data["HookType"] = "gogs"
  296. }
  297. c.Data["History"], err = w.History(1)
  298. if err != nil {
  299. c.Error(err, "get history")
  300. return nil, nil
  301. }
  302. return orCtx, w
  303. }
  304. func WebHooksEdit(c *context.Context) {
  305. c.Data["Title"] = c.Tr("repo.settings.update_webhook")
  306. c.Data["PageIsSettingsHooks"] = true
  307. c.Data["PageIsSettingsHooksEdit"] = true
  308. orCtx, w := checkWebhook(c)
  309. if c.Written() {
  310. return
  311. }
  312. c.Data["Webhook"] = w
  313. c.Success(orCtx.NewTemplate)
  314. }
  315. func WebHooksEditPost(c *context.Context, f form.NewWebhook) {
  316. c.Data["Title"] = c.Tr("repo.settings.update_webhook")
  317. c.Data["PageIsSettingsHooks"] = true
  318. c.Data["PageIsSettingsHooksEdit"] = true
  319. orCtx, w := checkWebhook(c)
  320. if c.Written() {
  321. return
  322. }
  323. c.Data["Webhook"] = w
  324. if c.HasError() {
  325. c.Success(orCtx.NewTemplate)
  326. return
  327. }
  328. contentType := db.JSON
  329. if db.HookContentType(f.ContentType) == db.FORM {
  330. contentType = db.FORM
  331. }
  332. w.URL = f.PayloadURL
  333. w.ContentType = contentType
  334. w.Secret = f.Secret
  335. w.HookEvent = ParseHookEvent(f.Webhook)
  336. w.IsActive = f.Active
  337. if err := w.UpdateEvent(); err != nil {
  338. c.Error(err, "update event")
  339. return
  340. } else if err := db.UpdateWebhook(w); err != nil {
  341. c.Error(err, "update webhook")
  342. return
  343. }
  344. c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
  345. c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  346. }
  347. func SlackHooksEditPost(c *context.Context, f form.NewSlackHook) {
  348. c.Data["Title"] = c.Tr("repo.settings")
  349. c.Data["PageIsSettingsHooks"] = true
  350. c.Data["PageIsSettingsHooksEdit"] = true
  351. orCtx, w := checkWebhook(c)
  352. if c.Written() {
  353. return
  354. }
  355. c.Data["Webhook"] = w
  356. if c.HasError() {
  357. c.Success(orCtx.NewTemplate)
  358. return
  359. }
  360. meta, err := jsoniter.Marshal(&db.SlackMeta{
  361. Channel: f.Channel,
  362. Username: f.Username,
  363. IconURL: f.IconURL,
  364. Color: f.Color,
  365. })
  366. if err != nil {
  367. c.Error(err, "marshal JSON")
  368. return
  369. }
  370. w.URL = f.PayloadURL
  371. w.Meta = string(meta)
  372. w.HookEvent = ParseHookEvent(f.Webhook)
  373. w.IsActive = f.Active
  374. if err := w.UpdateEvent(); err != nil {
  375. c.Error(err, "update event")
  376. return
  377. } else if err := db.UpdateWebhook(w); err != nil {
  378. c.Error(err, "update webhook")
  379. return
  380. }
  381. c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
  382. c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  383. }
  384. // FIXME: merge logic to Slack
  385. func DiscordHooksEditPost(c *context.Context, f form.NewDiscordHook) {
  386. c.Data["Title"] = c.Tr("repo.settings")
  387. c.Data["PageIsSettingsHooks"] = true
  388. c.Data["PageIsSettingsHooksEdit"] = true
  389. orCtx, w := checkWebhook(c)
  390. if c.Written() {
  391. return
  392. }
  393. c.Data["Webhook"] = w
  394. if c.HasError() {
  395. c.Success(orCtx.NewTemplate)
  396. return
  397. }
  398. meta, err := jsoniter.Marshal(&db.SlackMeta{
  399. Username: f.Username,
  400. IconURL: f.IconURL,
  401. Color: f.Color,
  402. })
  403. if err != nil {
  404. c.Error(err, "marshal JSON")
  405. return
  406. }
  407. w.URL = f.PayloadURL
  408. w.Meta = string(meta)
  409. w.HookEvent = ParseHookEvent(f.Webhook)
  410. w.IsActive = f.Active
  411. if err := w.UpdateEvent(); err != nil {
  412. c.Error(err, "update event")
  413. return
  414. } else if err := db.UpdateWebhook(w); err != nil {
  415. c.Error(err, "update webhook")
  416. return
  417. }
  418. c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
  419. c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  420. }
  421. func DingtalkHooksEditPost(c *context.Context, f form.NewDingtalkHook) {
  422. c.Data["Title"] = c.Tr("repo.settings")
  423. c.Data["PageIsSettingsHooks"] = true
  424. c.Data["PageIsSettingsHooksEdit"] = true
  425. orCtx, w := checkWebhook(c)
  426. if c.Written() {
  427. return
  428. }
  429. c.Data["Webhook"] = w
  430. if c.HasError() {
  431. c.Success(orCtx.NewTemplate)
  432. return
  433. }
  434. w.URL = f.PayloadURL
  435. w.HookEvent = ParseHookEvent(f.Webhook)
  436. w.IsActive = f.Active
  437. if err := w.UpdateEvent(); err != nil {
  438. c.Error(err, "update event")
  439. return
  440. } else if err := db.UpdateWebhook(w); err != nil {
  441. c.Error(err, "update webhook")
  442. return
  443. }
  444. c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
  445. c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  446. }
  447. func TestWebhook(c *context.Context) {
  448. var (
  449. commitID string
  450. commitMessage string
  451. author *git.Signature
  452. committer *git.Signature
  453. authorUsername string
  454. committerUsername string
  455. nameStatus *git.NameStatus
  456. )
  457. // Grab latest commit or fake one if it's empty repository.
  458. if c.Repo.Commit == nil {
  459. commitID = git.EmptyID
  460. commitMessage = "This is a fake commit"
  461. ghost := db.NewGhostUser()
  462. author = ghost.NewGitSig()
  463. committer = ghost.NewGitSig()
  464. authorUsername = ghost.Name
  465. committerUsername = ghost.Name
  466. nameStatus = &git.NameStatus{}
  467. } else {
  468. commitID = c.Repo.Commit.ID.String()
  469. commitMessage = c.Repo.Commit.Message
  470. author = c.Repo.Commit.Author
  471. committer = c.Repo.Commit.Committer
  472. // Try to match email with a real user.
  473. author, err := db.GetUserByEmail(c.Repo.Commit.Author.Email)
  474. if err == nil {
  475. authorUsername = author.Name
  476. } else if !db.IsErrUserNotExist(err) {
  477. c.Error(err, "get user by email")
  478. return
  479. }
  480. user, err := db.GetUserByEmail(c.Repo.Commit.Committer.Email)
  481. if err == nil {
  482. committerUsername = user.Name
  483. } else if !db.IsErrUserNotExist(err) {
  484. c.Error(err, "get user by email")
  485. return
  486. }
  487. nameStatus, err = c.Repo.Commit.ShowNameStatus()
  488. if err != nil {
  489. c.Error(err, "get changed files")
  490. return
  491. }
  492. }
  493. apiUser := c.User.APIFormat()
  494. p := &api.PushPayload{
  495. Ref: git.RefsHeads + c.Repo.Repository.DefaultBranch,
  496. Before: commitID,
  497. After: commitID,
  498. Commits: []*api.PayloadCommit{
  499. {
  500. ID: commitID,
  501. Message: commitMessage,
  502. URL: c.Repo.Repository.HTMLURL() + "/commit/" + commitID,
  503. Author: &api.PayloadUser{
  504. Name: author.Name,
  505. Email: author.Email,
  506. UserName: authorUsername,
  507. },
  508. Committer: &api.PayloadUser{
  509. Name: committer.Name,
  510. Email: committer.Email,
  511. UserName: committerUsername,
  512. },
  513. Added: nameStatus.Added,
  514. Removed: nameStatus.Removed,
  515. Modified: nameStatus.Modified,
  516. },
  517. },
  518. Repo: c.Repo.Repository.APIFormat(nil),
  519. Pusher: apiUser,
  520. Sender: apiUser,
  521. }
  522. if err := db.TestWebhook(c.Repo.Repository, db.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil {
  523. c.Error(err, "test webhook")
  524. return
  525. }
  526. c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success"))
  527. c.Status(http.StatusOK)
  528. }
  529. func RedeliveryWebhook(c *context.Context) {
  530. webhook, err := db.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  531. if err != nil {
  532. c.NotFoundOrError(err, "get webhook")
  533. return
  534. }
  535. hookTask, err := db.GetHookTaskOfWebhookByUUID(webhook.ID, c.Query("uuid"))
  536. if err != nil {
  537. c.NotFoundOrError(err, "get hook task by UUID")
  538. return
  539. }
  540. hookTask.IsDelivered = false
  541. if err = db.UpdateHookTask(hookTask); err != nil {
  542. c.Error(err, "update hook task")
  543. return
  544. }
  545. go db.HookQueue.Add(c.Repo.Repository.ID)
  546. c.Flash.Info(c.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
  547. c.Status(http.StatusOK)
  548. }
  549. func DeleteWebhook(c *context.Context) {
  550. if err := db.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  551. c.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
  552. } else {
  553. c.Flash.Success(c.Tr("repo.settings.webhook_deletion_success"))
  554. }
  555. c.JSONSuccess(map[string]interface{}{
  556. "redirect": c.Repo.RepoLink + "/settings/hooks",
  557. })
  558. }