webhook.go 13 KB

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