webhook.go 13 KB

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