webhook.go 13 KB

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