webhook.go 13 KB

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