webhook.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. "encoding/json"
  7. "fmt"
  8. "strings"
  9. "github.com/Unknwon/com"
  10. git "github.com/gogits/git-module"
  11. api "github.com/gogits/go-gogs-client"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/models/errors"
  14. "github.com/gogits/gogs/pkg/context"
  15. "github.com/gogits/gogs/pkg/form"
  16. "github.com/gogits/gogs/pkg/setting"
  17. )
  18. const (
  19. WEBHOOKS = "repo/settings/webhook/base"
  20. WEBHOOK_NEW = "repo/settings/webhook/new"
  21. ORG_WEBHOOK_NEW = "org/settings/webhook_new"
  22. )
  23. func Webhooks(c *context.Context) {
  24. c.Data["Title"] = c.Tr("repo.settings.hooks")
  25. c.Data["PageIsSettingsHooks"] = true
  26. c.Data["BaseLink"] = c.Repo.RepoLink
  27. c.Data["Description"] = c.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks")
  28. c.Data["Types"] = setting.Webhook.Types
  29. ws, err := models.GetWebhooksByRepoID(c.Repo.Repository.ID)
  30. if err != nil {
  31. c.Handle(500, "GetWebhooksByRepoID", err)
  32. return
  33. }
  34. c.Data["Webhooks"] = ws
  35. c.HTML(200, WEBHOOKS)
  36. }
  37. type OrgRepoCtx struct {
  38. OrgID int64
  39. RepoID int64
  40. Link string
  41. NewTemplate string
  42. }
  43. // getOrgRepoCtx determines whether this is a repo context or organization context.
  44. func getOrgRepoCtx(c *context.Context) (*OrgRepoCtx, error) {
  45. if len(c.Repo.RepoLink) > 0 {
  46. c.Data["PageIsRepositoryContext"] = true
  47. return &OrgRepoCtx{
  48. RepoID: c.Repo.Repository.ID,
  49. Link: c.Repo.RepoLink,
  50. NewTemplate: WEBHOOK_NEW,
  51. }, nil
  52. }
  53. if len(c.Org.OrgLink) > 0 {
  54. c.Data["PageIsOrganizationContext"] = true
  55. return &OrgRepoCtx{
  56. OrgID: c.Org.Organization.ID,
  57. Link: c.Org.OrgLink,
  58. NewTemplate: ORG_WEBHOOK_NEW,
  59. }, nil
  60. }
  61. return nil, errors.New("Unable to set OrgRepo context")
  62. }
  63. func checkHookType(c *context.Context) string {
  64. hookType := strings.ToLower(c.Params(":type"))
  65. if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) {
  66. c.Handle(404, "checkHookType", nil)
  67. return ""
  68. }
  69. return hookType
  70. }
  71. func WebhooksNew(c *context.Context) {
  72. c.Data["Title"] = c.Tr("repo.settings.add_webhook")
  73. c.Data["PageIsSettingsHooks"] = true
  74. c.Data["PageIsSettingsHooksNew"] = true
  75. c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  76. orCtx, err := getOrgRepoCtx(c)
  77. if err != nil {
  78. c.Handle(500, "getOrgRepoCtx", err)
  79. return
  80. }
  81. c.Data["HookType"] = checkHookType(c)
  82. if c.Written() {
  83. return
  84. }
  85. c.Data["BaseLink"] = orCtx.Link
  86. c.HTML(200, orCtx.NewTemplate)
  87. }
  88. func ParseHookEvent(f form.Webhook) *models.HookEvent {
  89. return &models.HookEvent{
  90. PushOnly: f.PushOnly(),
  91. SendEverything: f.SendEverything(),
  92. ChooseEvents: f.ChooseEvents(),
  93. HookEvents: models.HookEvents{
  94. Create: f.Create,
  95. Delete: f.Delete,
  96. Fork: f.Fork,
  97. Push: f.Push,
  98. Issues: f.Issues,
  99. IssueComment: f.IssueComment,
  100. PullRequest: f.PullRequest,
  101. Release: f.Release,
  102. },
  103. }
  104. }
  105. func WebHooksNewPost(c *context.Context, f form.NewWebhook) {
  106. c.Data["Title"] = c.Tr("repo.settings.add_webhook")
  107. c.Data["PageIsSettingsHooks"] = true
  108. c.Data["PageIsSettingsHooksNew"] = true
  109. c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  110. c.Data["HookType"] = "gogs"
  111. orCtx, err := getOrgRepoCtx(c)
  112. if err != nil {
  113. c.Handle(500, "getOrgRepoCtx", err)
  114. return
  115. }
  116. c.Data["BaseLink"] = orCtx.Link
  117. if c.HasError() {
  118. c.HTML(200, orCtx.NewTemplate)
  119. return
  120. }
  121. contentType := models.JSON
  122. if models.HookContentType(f.ContentType) == models.FORM {
  123. contentType = models.FORM
  124. }
  125. w := &models.Webhook{
  126. RepoID: orCtx.RepoID,
  127. URL: f.PayloadURL,
  128. ContentType: contentType,
  129. Secret: f.Secret,
  130. HookEvent: ParseHookEvent(f.Webhook),
  131. IsActive: f.Active,
  132. HookTaskType: models.GOGS,
  133. OrgID: orCtx.OrgID,
  134. }
  135. if err := w.UpdateEvent(); err != nil {
  136. c.Handle(500, "UpdateEvent", err)
  137. return
  138. } else if err := models.CreateWebhook(w); err != nil {
  139. c.Handle(500, "CreateWebhook", err)
  140. return
  141. }
  142. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  143. c.Redirect(orCtx.Link + "/settings/hooks")
  144. }
  145. func SlackHooksNewPost(c *context.Context, f form.NewSlackHook) {
  146. c.Data["Title"] = c.Tr("repo.settings")
  147. c.Data["PageIsSettingsHooks"] = true
  148. c.Data["PageIsSettingsHooksNew"] = true
  149. c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  150. orCtx, err := getOrgRepoCtx(c)
  151. if err != nil {
  152. c.Handle(500, "getOrgRepoCtx", err)
  153. return
  154. }
  155. if c.HasError() {
  156. c.HTML(200, orCtx.NewTemplate)
  157. return
  158. }
  159. meta, err := json.Marshal(&models.SlackMeta{
  160. Channel: f.Channel,
  161. Username: f.Username,
  162. IconURL: f.IconURL,
  163. Color: f.Color,
  164. })
  165. if err != nil {
  166. c.Handle(500, "Marshal", err)
  167. return
  168. }
  169. w := &models.Webhook{
  170. RepoID: orCtx.RepoID,
  171. URL: f.PayloadURL,
  172. ContentType: models.JSON,
  173. HookEvent: ParseHookEvent(f.Webhook),
  174. IsActive: f.Active,
  175. HookTaskType: models.SLACK,
  176. Meta: string(meta),
  177. OrgID: orCtx.OrgID,
  178. }
  179. if err := w.UpdateEvent(); err != nil {
  180. c.Handle(500, "UpdateEvent", err)
  181. return
  182. } else if err := models.CreateWebhook(w); err != nil {
  183. c.Handle(500, "CreateWebhook", err)
  184. return
  185. }
  186. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  187. c.Redirect(orCtx.Link + "/settings/hooks")
  188. }
  189. // FIXME: merge logic to Slack
  190. func DiscordHooksNewPost(c *context.Context, f form.NewDiscordHook) {
  191. c.Data["Title"] = c.Tr("repo.settings")
  192. c.Data["PageIsSettingsHooks"] = true
  193. c.Data["PageIsSettingsHooksNew"] = true
  194. c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  195. orCtx, err := getOrgRepoCtx(c)
  196. if err != nil {
  197. c.Handle(500, "getOrgRepoCtx", err)
  198. return
  199. }
  200. if c.HasError() {
  201. c.HTML(200, orCtx.NewTemplate)
  202. return
  203. }
  204. meta, err := json.Marshal(&models.SlackMeta{
  205. Username: f.Username,
  206. IconURL: f.IconURL,
  207. Color: f.Color,
  208. })
  209. if err != nil {
  210. c.Handle(500, "Marshal", err)
  211. return
  212. }
  213. w := &models.Webhook{
  214. RepoID: orCtx.RepoID,
  215. URL: f.PayloadURL,
  216. ContentType: models.JSON,
  217. HookEvent: ParseHookEvent(f.Webhook),
  218. IsActive: f.Active,
  219. HookTaskType: models.DISCORD,
  220. Meta: string(meta),
  221. OrgID: orCtx.OrgID,
  222. }
  223. if err := w.UpdateEvent(); err != nil {
  224. c.Handle(500, "UpdateEvent", err)
  225. return
  226. } else if err := models.CreateWebhook(w); err != nil {
  227. c.Handle(500, "CreateWebhook", err)
  228. return
  229. }
  230. c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
  231. c.Redirect(orCtx.Link + "/settings/hooks")
  232. }
  233. func checkWebhook(c *context.Context) (*OrgRepoCtx, *models.Webhook) {
  234. c.Data["RequireHighlightJS"] = true
  235. orCtx, err := getOrgRepoCtx(c)
  236. if err != nil {
  237. c.Handle(500, "getOrgRepoCtx", err)
  238. return nil, nil
  239. }
  240. c.Data["BaseLink"] = orCtx.Link
  241. var w *models.Webhook
  242. if orCtx.RepoID > 0 {
  243. w, err = models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  244. } else {
  245. w, err = models.GetWebhookByOrgID(c.Org.Organization.ID, c.ParamsInt64(":id"))
  246. }
  247. if err != nil {
  248. c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
  249. return nil, nil
  250. }
  251. switch w.HookTaskType {
  252. case models.SLACK:
  253. c.Data["SlackHook"] = w.GetSlackHook()
  254. c.Data["HookType"] = "slack"
  255. case models.DISCORD:
  256. c.Data["SlackHook"] = w.GetSlackHook()
  257. c.Data["HookType"] = "discord"
  258. default:
  259. c.Data["HookType"] = "gogs"
  260. }
  261. c.Data["History"], err = w.History(1)
  262. if err != nil {
  263. c.Handle(500, "History", err)
  264. }
  265. return orCtx, w
  266. }
  267. func WebHooksEdit(c *context.Context) {
  268. c.Data["Title"] = c.Tr("repo.settings.update_webhook")
  269. c.Data["PageIsSettingsHooks"] = true
  270. c.Data["PageIsSettingsHooksEdit"] = true
  271. orCtx, w := checkWebhook(c)
  272. if c.Written() {
  273. return
  274. }
  275. c.Data["Webhook"] = w
  276. c.HTML(200, orCtx.NewTemplate)
  277. }
  278. func WebHooksEditPost(c *context.Context, f form.NewWebhook) {
  279. c.Data["Title"] = c.Tr("repo.settings.update_webhook")
  280. c.Data["PageIsSettingsHooks"] = true
  281. c.Data["PageIsSettingsHooksEdit"] = true
  282. orCtx, w := checkWebhook(c)
  283. if c.Written() {
  284. return
  285. }
  286. c.Data["Webhook"] = w
  287. if c.HasError() {
  288. c.HTML(200, orCtx.NewTemplate)
  289. return
  290. }
  291. contentType := models.JSON
  292. if models.HookContentType(f.ContentType) == models.FORM {
  293. contentType = models.FORM
  294. }
  295. w.URL = f.PayloadURL
  296. w.ContentType = contentType
  297. w.Secret = f.Secret
  298. w.HookEvent = ParseHookEvent(f.Webhook)
  299. w.IsActive = f.Active
  300. if err := w.UpdateEvent(); err != nil {
  301. c.Handle(500, "UpdateEvent", err)
  302. return
  303. } else if err := models.UpdateWebhook(w); err != nil {
  304. c.Handle(500, "WebHooksEditPost", err)
  305. return
  306. }
  307. c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
  308. c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  309. }
  310. func SlackHooksEditPost(c *context.Context, f form.NewSlackHook) {
  311. c.Data["Title"] = c.Tr("repo.settings")
  312. c.Data["PageIsSettingsHooks"] = true
  313. c.Data["PageIsSettingsHooksEdit"] = true
  314. orCtx, w := checkWebhook(c)
  315. if c.Written() {
  316. return
  317. }
  318. c.Data["Webhook"] = w
  319. if c.HasError() {
  320. c.HTML(200, orCtx.NewTemplate)
  321. return
  322. }
  323. meta, err := json.Marshal(&models.SlackMeta{
  324. Channel: f.Channel,
  325. Username: f.Username,
  326. IconURL: f.IconURL,
  327. Color: f.Color,
  328. })
  329. if err != nil {
  330. c.Handle(500, "Marshal", err)
  331. return
  332. }
  333. w.URL = f.PayloadURL
  334. w.Meta = string(meta)
  335. w.HookEvent = ParseHookEvent(f.Webhook)
  336. w.IsActive = f.Active
  337. if err := w.UpdateEvent(); err != nil {
  338. c.Handle(500, "UpdateEvent", err)
  339. return
  340. } else if err := models.UpdateWebhook(w); err != nil {
  341. c.Handle(500, "UpdateWebhook", err)
  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. // FIXME: merge logic to Slack
  348. func DiscordHooksEditPost(c *context.Context, f form.NewDiscordHook) {
  349. c.Data["Title"] = c.Tr("repo.settings")
  350. c.Data["PageIsSettingsHooks"] = true
  351. c.Data["PageIsSettingsHooksEdit"] = true
  352. orCtx, w := checkWebhook(c)
  353. if c.Written() {
  354. return
  355. }
  356. c.Data["Webhook"] = w
  357. if c.HasError() {
  358. c.HTML(200, orCtx.NewTemplate)
  359. return
  360. }
  361. meta, err := json.Marshal(&models.SlackMeta{
  362. Username: f.Username,
  363. IconURL: f.IconURL,
  364. Color: f.Color,
  365. })
  366. if err != nil {
  367. c.Handle(500, "Marshal", err)
  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.Handle(500, "UpdateEvent", err)
  376. return
  377. } else if err := models.UpdateWebhook(w); err != nil {
  378. c.Handle(500, "UpdateWebhook", err)
  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. func TestWebhook(c *context.Context) {
  385. var authorUsername, committerUsername string
  386. // Grab latest commit or fake one if it's empty repository.
  387. commit := c.Repo.Commit
  388. if commit == nil {
  389. ghost := models.NewGhostUser()
  390. commit = &git.Commit{
  391. ID: git.MustIDFromString(git.EMPTY_SHA),
  392. Author: ghost.NewGitSig(),
  393. Committer: ghost.NewGitSig(),
  394. CommitMessage: "This is a fake commit",
  395. }
  396. authorUsername = ghost.Name
  397. committerUsername = ghost.Name
  398. } else {
  399. // Try to match email with a real user.
  400. author, err := models.GetUserByEmail(commit.Author.Email)
  401. if err == nil {
  402. authorUsername = author.Name
  403. } else if !errors.IsUserNotExist(err) {
  404. c.Handle(500, "GetUserByEmail.(author)", err)
  405. return
  406. }
  407. committer, err := models.GetUserByEmail(commit.Committer.Email)
  408. if err == nil {
  409. committerUsername = committer.Name
  410. } else if !errors.IsUserNotExist(err) {
  411. c.Handle(500, "GetUserByEmail.(committer)", err)
  412. return
  413. }
  414. }
  415. fileStatus, err := commit.FileStatus()
  416. if err != nil {
  417. c.Handle(500, "FileStatus", err)
  418. return
  419. }
  420. apiUser := c.User.APIFormat()
  421. p := &api.PushPayload{
  422. Ref: git.BRANCH_PREFIX + c.Repo.Repository.DefaultBranch,
  423. Before: commit.ID.String(),
  424. After: commit.ID.String(),
  425. Commits: []*api.PayloadCommit{
  426. {
  427. ID: commit.ID.String(),
  428. Message: commit.Message(),
  429. URL: c.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(),
  430. Author: &api.PayloadUser{
  431. Name: commit.Author.Name,
  432. Email: commit.Author.Email,
  433. UserName: authorUsername,
  434. },
  435. Committer: &api.PayloadUser{
  436. Name: commit.Committer.Name,
  437. Email: commit.Committer.Email,
  438. UserName: committerUsername,
  439. },
  440. Added: fileStatus.Added,
  441. Removed: fileStatus.Removed,
  442. Modified: fileStatus.Modified,
  443. },
  444. },
  445. Repo: c.Repo.Repository.APIFormat(nil),
  446. Pusher: apiUser,
  447. Sender: apiUser,
  448. }
  449. if err := models.TestWebhook(c.Repo.Repository, models.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil {
  450. c.Handle(500, "TestWebhook", err)
  451. } else {
  452. c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success"))
  453. c.Status(200)
  454. }
  455. }
  456. func RedeliveryWebhook(c *context.Context) {
  457. webhook, err := models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  458. if err != nil {
  459. c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
  460. return
  461. }
  462. hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, c.Query("uuid"))
  463. if err != nil {
  464. c.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err)
  465. return
  466. }
  467. hookTask.IsDelivered = false
  468. if err = models.UpdateHookTask(hookTask); err != nil {
  469. c.Handle(500, "UpdateHookTask", err)
  470. } else {
  471. go models.HookQueue.Add(c.Repo.Repository.ID)
  472. c.Flash.Info(c.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
  473. c.Status(200)
  474. }
  475. }
  476. func DeleteWebhook(c *context.Context) {
  477. if err := models.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  478. c.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
  479. } else {
  480. c.Flash.Success(c.Tr("repo.settings.webhook_deletion_success"))
  481. }
  482. c.JSON(200, map[string]interface{}{
  483. "redirect": c.Repo.RepoLink + "/settings/hooks",
  484. })
  485. }