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