webhook.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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(ctx *context.Context) {
  24. ctx.Data["Title"] = ctx.Tr("repo.settings.hooks")
  25. ctx.Data["PageIsSettingsHooks"] = true
  26. ctx.Data["BaseLink"] = ctx.Repo.RepoLink
  27. ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks")
  28. ctx.Data["Types"] = setting.Webhook.Types
  29. ws, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID)
  30. if err != nil {
  31. ctx.Handle(500, "GetWebhooksByRepoID", err)
  32. return
  33. }
  34. ctx.Data["Webhooks"] = ws
  35. ctx.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(ctx *context.Context) (*OrgRepoCtx, error) {
  45. if len(ctx.Repo.RepoLink) > 0 {
  46. ctx.Data["PageIsRepositoryContext"] = true
  47. return &OrgRepoCtx{
  48. RepoID: ctx.Repo.Repository.ID,
  49. Link: ctx.Repo.RepoLink,
  50. NewTemplate: WEBHOOK_NEW,
  51. }, nil
  52. }
  53. if len(ctx.Org.OrgLink) > 0 {
  54. ctx.Data["PageIsOrganizationContext"] = true
  55. return &OrgRepoCtx{
  56. OrgID: ctx.Org.Organization.ID,
  57. Link: ctx.Org.OrgLink,
  58. NewTemplate: ORG_WEBHOOK_NEW,
  59. }, nil
  60. }
  61. return nil, errors.New("Unable to set OrgRepo context")
  62. }
  63. func checkHookType(ctx *context.Context) string {
  64. hookType := strings.ToLower(ctx.Params(":type"))
  65. if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) {
  66. ctx.Handle(404, "checkHookType", nil)
  67. return ""
  68. }
  69. return hookType
  70. }
  71. func WebhooksNew(ctx *context.Context) {
  72. ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
  73. ctx.Data["PageIsSettingsHooks"] = true
  74. ctx.Data["PageIsSettingsHooksNew"] = true
  75. ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  76. orCtx, err := getOrgRepoCtx(ctx)
  77. if err != nil {
  78. ctx.Handle(500, "getOrgRepoCtx", err)
  79. return
  80. }
  81. ctx.Data["HookType"] = checkHookType(ctx)
  82. if ctx.Written() {
  83. return
  84. }
  85. ctx.Data["BaseLink"] = orCtx.Link
  86. ctx.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(ctx *context.Context, f form.NewWebhook) {
  106. ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
  107. ctx.Data["PageIsSettingsHooks"] = true
  108. ctx.Data["PageIsSettingsHooksNew"] = true
  109. ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  110. ctx.Data["HookType"] = "gogs"
  111. orCtx, err := getOrgRepoCtx(ctx)
  112. if err != nil {
  113. ctx.Handle(500, "getOrgRepoCtx", err)
  114. return
  115. }
  116. ctx.Data["BaseLink"] = orCtx.Link
  117. if ctx.HasError() {
  118. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  137. return
  138. } else if err := models.CreateWebhook(w); err != nil {
  139. ctx.Handle(500, "CreateWebhook", err)
  140. return
  141. }
  142. ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
  143. ctx.Redirect(orCtx.Link + "/settings/hooks")
  144. }
  145. func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
  146. ctx.Data["Title"] = ctx.Tr("repo.settings")
  147. ctx.Data["PageIsSettingsHooks"] = true
  148. ctx.Data["PageIsSettingsHooksNew"] = true
  149. ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  150. orCtx, err := getOrgRepoCtx(ctx)
  151. if err != nil {
  152. ctx.Handle(500, "getOrgRepoCtx", err)
  153. return
  154. }
  155. if ctx.HasError() {
  156. ctx.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. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  181. return
  182. } else if err := models.CreateWebhook(w); err != nil {
  183. ctx.Handle(500, "CreateWebhook", err)
  184. return
  185. }
  186. ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
  187. ctx.Redirect(orCtx.Link + "/settings/hooks")
  188. }
  189. // FIXME: merge logic to Slack
  190. func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
  191. ctx.Data["Title"] = ctx.Tr("repo.settings")
  192. ctx.Data["PageIsSettingsHooks"] = true
  193. ctx.Data["PageIsSettingsHooksNew"] = true
  194. ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
  195. orCtx, err := getOrgRepoCtx(ctx)
  196. if err != nil {
  197. ctx.Handle(500, "getOrgRepoCtx", err)
  198. return
  199. }
  200. if ctx.HasError() {
  201. ctx.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. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  225. return
  226. } else if err := models.CreateWebhook(w); err != nil {
  227. ctx.Handle(500, "CreateWebhook", err)
  228. return
  229. }
  230. ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
  231. ctx.Redirect(orCtx.Link + "/settings/hooks")
  232. }
  233. func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) {
  234. ctx.Data["RequireHighlightJS"] = true
  235. orCtx, err := getOrgRepoCtx(ctx)
  236. if err != nil {
  237. ctx.Handle(500, "getOrgRepoCtx", err)
  238. return nil, nil
  239. }
  240. ctx.Data["BaseLink"] = orCtx.Link
  241. var w *models.Webhook
  242. if orCtx.RepoID > 0 {
  243. w, err = models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  244. } else {
  245. w, err = models.GetWebhookByOrgID(ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
  246. }
  247. if err != nil {
  248. ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
  249. return nil, nil
  250. }
  251. switch w.HookTaskType {
  252. case models.SLACK:
  253. ctx.Data["SlackHook"] = w.GetSlackHook()
  254. ctx.Data["HookType"] = "slack"
  255. case models.DISCORD:
  256. ctx.Data["SlackHook"] = w.GetSlackHook()
  257. ctx.Data["HookType"] = "discord"
  258. default:
  259. ctx.Data["HookType"] = "gogs"
  260. }
  261. ctx.Data["History"], err = w.History(1)
  262. if err != nil {
  263. ctx.Handle(500, "History", err)
  264. }
  265. return orCtx, w
  266. }
  267. func WebHooksEdit(ctx *context.Context) {
  268. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  269. ctx.Data["PageIsSettingsHooks"] = true
  270. ctx.Data["PageIsSettingsHooksEdit"] = true
  271. orCtx, w := checkWebhook(ctx)
  272. if ctx.Written() {
  273. return
  274. }
  275. ctx.Data["Webhook"] = w
  276. ctx.HTML(200, orCtx.NewTemplate)
  277. }
  278. func WebHooksEditPost(ctx *context.Context, f form.NewWebhook) {
  279. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  280. ctx.Data["PageIsSettingsHooks"] = true
  281. ctx.Data["PageIsSettingsHooksEdit"] = true
  282. orCtx, w := checkWebhook(ctx)
  283. if ctx.Written() {
  284. return
  285. }
  286. ctx.Data["Webhook"] = w
  287. if ctx.HasError() {
  288. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  302. return
  303. } else if err := models.UpdateWebhook(w); err != nil {
  304. ctx.Handle(500, "WebHooksEditPost", err)
  305. return
  306. }
  307. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  308. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  309. }
  310. func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
  311. ctx.Data["Title"] = ctx.Tr("repo.settings")
  312. ctx.Data["PageIsSettingsHooks"] = true
  313. ctx.Data["PageIsSettingsHooksEdit"] = true
  314. orCtx, w := checkWebhook(ctx)
  315. if ctx.Written() {
  316. return
  317. }
  318. ctx.Data["Webhook"] = w
  319. if ctx.HasError() {
  320. ctx.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. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  339. return
  340. } else if err := models.UpdateWebhook(w); err != nil {
  341. ctx.Handle(500, "UpdateWebhook", err)
  342. return
  343. }
  344. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  345. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  346. }
  347. // FIXME: merge logic to Slack
  348. func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
  349. ctx.Data["Title"] = ctx.Tr("repo.settings")
  350. ctx.Data["PageIsSettingsHooks"] = true
  351. ctx.Data["PageIsSettingsHooksEdit"] = true
  352. orCtx, w := checkWebhook(ctx)
  353. if ctx.Written() {
  354. return
  355. }
  356. ctx.Data["Webhook"] = w
  357. if ctx.HasError() {
  358. ctx.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. ctx.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. ctx.Handle(500, "UpdateEvent", err)
  376. return
  377. } else if err := models.UpdateWebhook(w); err != nil {
  378. ctx.Handle(500, "UpdateWebhook", err)
  379. return
  380. }
  381. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  382. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  383. }
  384. func TestWebhook(ctx *context.Context) {
  385. var authorUsername, committerUsername string
  386. // Grab latest commit or fake one if it's empty repository.
  387. commit := ctx.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. ctx.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. ctx.Handle(500, "GetUserByEmail.(committer)", err)
  412. return
  413. }
  414. }
  415. fileStatus, err := commit.FileStatus()
  416. if err != nil {
  417. ctx.Handle(500, "FileStatus", err)
  418. return
  419. }
  420. apiUser := ctx.User.APIFormat()
  421. p := &api.PushPayload{
  422. Ref: git.BRANCH_PREFIX + ctx.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: ctx.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: ctx.Repo.Repository.APIFormat(nil),
  446. Pusher: apiUser,
  447. Sender: apiUser,
  448. }
  449. if err := models.TestWebhook(ctx.Repo.Repository, models.HOOK_EVENT_PUSH, p, ctx.ParamsInt64("id")); err != nil {
  450. ctx.Handle(500, "TestWebhook", err)
  451. } else {
  452. ctx.Flash.Info(ctx.Tr("repo.settings.webhook.test_delivery_success"))
  453. ctx.Status(200)
  454. }
  455. }
  456. func RedeliveryWebhook(ctx *context.Context) {
  457. webhook, err := models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  458. if err != nil {
  459. ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
  460. return
  461. }
  462. hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, ctx.Query("uuid"))
  463. if err != nil {
  464. ctx.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err)
  465. return
  466. }
  467. hookTask.IsDelivered = false
  468. if err = models.UpdateHookTask(hookTask); err != nil {
  469. ctx.Handle(500, "UpdateHookTask", err)
  470. } else {
  471. go models.HookQueue.Add(ctx.Repo.Repository.ID)
  472. ctx.Flash.Info(ctx.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
  473. ctx.Status(200)
  474. }
  475. }
  476. func DeleteWebhook(ctx *context.Context) {
  477. if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  478. ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
  479. } else {
  480. ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
  481. }
  482. ctx.JSON(200, map[string]interface{}{
  483. "redirect": ctx.Repo.RepoLink + "/settings/hooks",
  484. })
  485. }