webhook.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. })
  201. if err != nil {
  202. ctx.Handle(500, "Marshal", err)
  203. return
  204. }
  205. w := &models.Webhook{
  206. RepoID: orCtx.RepoID,
  207. URL: form.PayloadURL,
  208. ContentType: models.JSON,
  209. HookEvent: ParseHookEvent(form.WebhookForm),
  210. IsActive: form.Active,
  211. HookTaskType: models.DISCORD,
  212. Meta: string(meta),
  213. OrgID: orCtx.OrgID,
  214. }
  215. if err := w.UpdateEvent(); err != nil {
  216. ctx.Handle(500, "UpdateEvent", err)
  217. return
  218. } else if err := models.CreateWebhook(w); err != nil {
  219. ctx.Handle(500, "CreateWebhook", err)
  220. return
  221. }
  222. ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
  223. ctx.Redirect(orCtx.Link + "/settings/hooks")
  224. }
  225. func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) {
  226. ctx.Data["RequireHighlightJS"] = true
  227. orCtx, err := getOrgRepoCtx(ctx)
  228. if err != nil {
  229. ctx.Handle(500, "getOrgRepoCtx", err)
  230. return nil, nil
  231. }
  232. ctx.Data["BaseLink"] = orCtx.Link
  233. var w *models.Webhook
  234. if orCtx.RepoID > 0 {
  235. w, err = models.GetWebhookByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  236. } else {
  237. w, err = models.GetWebhookByOrgID(ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
  238. }
  239. if err != nil {
  240. if models.IsErrWebhookNotExist(err) {
  241. ctx.Handle(404, "GetWebhookByID", nil)
  242. } else {
  243. ctx.Handle(500, "GetWebhookByID", err)
  244. }
  245. return nil, nil
  246. }
  247. switch w.HookTaskType {
  248. case models.SLACK:
  249. ctx.Data["SlackHook"] = w.GetSlackHook()
  250. ctx.Data["HookType"] = "slack"
  251. case models.DISCORD:
  252. ctx.Data["SlackHook"] = w.GetSlackHook()
  253. ctx.Data["HookType"] = "discord"
  254. default:
  255. ctx.Data["HookType"] = "gogs"
  256. }
  257. ctx.Data["History"], err = w.History(1)
  258. if err != nil {
  259. ctx.Handle(500, "History", err)
  260. }
  261. return orCtx, w
  262. }
  263. func WebHooksEdit(ctx *context.Context) {
  264. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  265. ctx.Data["PageIsSettingsHooks"] = true
  266. ctx.Data["PageIsSettingsHooksEdit"] = true
  267. orCtx, w := checkWebhook(ctx)
  268. if ctx.Written() {
  269. return
  270. }
  271. ctx.Data["Webhook"] = w
  272. ctx.HTML(200, orCtx.NewTemplate)
  273. }
  274. func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) {
  275. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  276. ctx.Data["PageIsSettingsHooks"] = true
  277. ctx.Data["PageIsSettingsHooksEdit"] = true
  278. orCtx, w := checkWebhook(ctx)
  279. if ctx.Written() {
  280. return
  281. }
  282. ctx.Data["Webhook"] = w
  283. if ctx.HasError() {
  284. ctx.HTML(200, orCtx.NewTemplate)
  285. return
  286. }
  287. contentType := models.JSON
  288. if models.HookContentType(form.ContentType) == models.FORM {
  289. contentType = models.FORM
  290. }
  291. w.URL = form.PayloadURL
  292. w.ContentType = contentType
  293. w.Secret = form.Secret
  294. w.HookEvent = ParseHookEvent(form.WebhookForm)
  295. w.IsActive = form.Active
  296. if err := w.UpdateEvent(); err != nil {
  297. ctx.Handle(500, "UpdateEvent", err)
  298. return
  299. } else if err := models.UpdateWebhook(w); err != nil {
  300. ctx.Handle(500, "WebHooksEditPost", err)
  301. return
  302. }
  303. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  304. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  305. }
  306. func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) {
  307. ctx.Data["Title"] = ctx.Tr("repo.settings")
  308. ctx.Data["PageIsSettingsHooks"] = true
  309. ctx.Data["PageIsSettingsHooksEdit"] = true
  310. orCtx, w := checkWebhook(ctx)
  311. if ctx.Written() {
  312. return
  313. }
  314. ctx.Data["Webhook"] = w
  315. if ctx.HasError() {
  316. ctx.HTML(200, orCtx.NewTemplate)
  317. return
  318. }
  319. meta, err := json.Marshal(&models.SlackMeta{
  320. Channel: form.Channel,
  321. Username: form.Username,
  322. IconURL: form.IconURL,
  323. Color: form.Color,
  324. })
  325. if err != nil {
  326. ctx.Handle(500, "Marshal", err)
  327. return
  328. }
  329. w.URL = form.PayloadURL
  330. w.Meta = string(meta)
  331. w.HookEvent = ParseHookEvent(form.WebhookForm)
  332. w.IsActive = form.Active
  333. if err := w.UpdateEvent(); err != nil {
  334. ctx.Handle(500, "UpdateEvent", err)
  335. return
  336. } else if err := models.UpdateWebhook(w); err != nil {
  337. ctx.Handle(500, "UpdateWebhook", err)
  338. return
  339. }
  340. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  341. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  342. }
  343. // FIXME: merge logic to Slack
  344. func DiscordHooksEditPost(ctx *context.Context, form auth.NewDiscordHookForm) {
  345. ctx.Data["Title"] = ctx.Tr("repo.settings")
  346. ctx.Data["PageIsSettingsHooks"] = true
  347. ctx.Data["PageIsSettingsHooksEdit"] = true
  348. orCtx, w := checkWebhook(ctx)
  349. if ctx.Written() {
  350. return
  351. }
  352. ctx.Data["Webhook"] = w
  353. if ctx.HasError() {
  354. ctx.HTML(200, orCtx.NewTemplate)
  355. return
  356. }
  357. meta, err := json.Marshal(&models.SlackMeta{
  358. Username: form.Username,
  359. IconURL: form.IconURL,
  360. })
  361. if err != nil {
  362. ctx.Handle(500, "Marshal", err)
  363. return
  364. }
  365. w.URL = form.PayloadURL
  366. w.Meta = string(meta)
  367. w.HookEvent = ParseHookEvent(form.WebhookForm)
  368. w.IsActive = form.Active
  369. if err := w.UpdateEvent(); err != nil {
  370. ctx.Handle(500, "UpdateEvent", err)
  371. return
  372. } else if err := models.UpdateWebhook(w); err != nil {
  373. ctx.Handle(500, "UpdateWebhook", err)
  374. return
  375. }
  376. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  377. ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
  378. }
  379. func TestWebhook(ctx *context.Context) {
  380. var authorUsername, committerUsername string
  381. // Grab latest commit or fake one if it's empty repository.
  382. commit := ctx.Repo.Commit
  383. if commit == nil {
  384. ghost := models.NewGhostUser()
  385. commit = &git.Commit{
  386. ID: git.MustIDFromString(git.EMPTY_SHA),
  387. Author: ghost.NewGitSig(),
  388. Committer: ghost.NewGitSig(),
  389. CommitMessage: "This is a fake commit",
  390. }
  391. authorUsername = ghost.Name
  392. committerUsername = ghost.Name
  393. } else {
  394. // Try to match email with a real user.
  395. author, err := models.GetUserByEmail(commit.Author.Email)
  396. if err == nil {
  397. authorUsername = author.Name
  398. } else if !models.IsErrUserNotExist(err) {
  399. ctx.Flash.Error(fmt.Sprintf("GetUserByEmail.(author) [%s]: %v", commit.Author.Email, err))
  400. ctx.Status(500)
  401. return
  402. }
  403. committer, err := models.GetUserByEmail(commit.Committer.Email)
  404. if err == nil {
  405. committerUsername = committer.Name
  406. } else if !models.IsErrUserNotExist(err) {
  407. ctx.Flash.Error(fmt.Sprintf("GetUserByEmail.(committer) [%s]: %v", commit.Committer.Email, err))
  408. ctx.Status(500)
  409. return
  410. }
  411. }
  412. apiUser := ctx.User.APIFormat()
  413. p := &api.PushPayload{
  414. Ref: git.BRANCH_PREFIX + ctx.Repo.Repository.DefaultBranch,
  415. Before: commit.ID.String(),
  416. After: commit.ID.String(),
  417. Commits: []*api.PayloadCommit{
  418. {
  419. ID: commit.ID.String(),
  420. Message: commit.Message(),
  421. URL: ctx.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(),
  422. Author: &api.PayloadUser{
  423. Name: commit.Author.Name,
  424. Email: commit.Author.Email,
  425. UserName: authorUsername,
  426. },
  427. Committer: &api.PayloadUser{
  428. Name: commit.Committer.Name,
  429. Email: commit.Committer.Email,
  430. UserName: committerUsername,
  431. },
  432. },
  433. },
  434. Repo: ctx.Repo.Repository.APIFormat(nil),
  435. Pusher: apiUser,
  436. Sender: apiUser,
  437. }
  438. if err := models.PrepareWebhooks(ctx.Repo.Repository, models.HOOK_EVENT_PUSH, p); err != nil {
  439. ctx.Flash.Error("PrepareWebhooks: " + err.Error())
  440. ctx.Status(500)
  441. } else {
  442. go models.HookQueue.Add(ctx.Repo.Repository.ID)
  443. ctx.Flash.Info(ctx.Tr("repo.settings.webhook.test_delivery_success"))
  444. ctx.Status(200)
  445. }
  446. }
  447. func DeleteWebhook(ctx *context.Context) {
  448. if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  449. ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
  450. } else {
  451. ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
  452. }
  453. ctx.JSON(200, map[string]interface{}{
  454. "redirect": ctx.Repo.RepoLink + "/settings/hooks",
  455. })
  456. }