webhook.go 13 KB

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