You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

webhook.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package setting
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "strings"
  12. "code.gitea.io/gitea/models/perm"
  13. access_model "code.gitea.io/gitea/models/perm/access"
  14. user_model "code.gitea.io/gitea/models/user"
  15. "code.gitea.io/gitea/models/webhook"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/json"
  20. "code.gitea.io/gitea/modules/setting"
  21. api "code.gitea.io/gitea/modules/structs"
  22. "code.gitea.io/gitea/modules/util"
  23. "code.gitea.io/gitea/modules/web"
  24. webhook_module "code.gitea.io/gitea/modules/webhook"
  25. "code.gitea.io/gitea/services/convert"
  26. "code.gitea.io/gitea/services/forms"
  27. webhook_service "code.gitea.io/gitea/services/webhook"
  28. )
  29. const (
  30. tplHooks base.TplName = "repo/settings/webhook/base"
  31. tplHookNew base.TplName = "repo/settings/webhook/new"
  32. tplOrgHookNew base.TplName = "org/settings/hook_new"
  33. tplUserHookNew base.TplName = "user/settings/hook_new"
  34. tplAdminHookNew base.TplName = "admin/hook_new"
  35. )
  36. // Webhooks render web hooks list page
  37. func Webhooks(ctx *context.Context) {
  38. ctx.Data["Title"] = ctx.Tr("repo.settings.hooks")
  39. ctx.Data["PageIsSettingsHooks"] = true
  40. ctx.Data["BaseLink"] = ctx.Repo.RepoLink + "/settings/hooks"
  41. ctx.Data["BaseLinkNew"] = ctx.Repo.RepoLink + "/settings/hooks"
  42. ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://docs.gitea.com/usage/webhooks")
  43. ws, err := webhook.ListWebhooksByOpts(ctx, &webhook.ListWebhookOptions{RepoID: ctx.Repo.Repository.ID})
  44. if err != nil {
  45. ctx.ServerError("GetWebhooksByRepoID", err)
  46. return
  47. }
  48. ctx.Data["Webhooks"] = ws
  49. ctx.HTML(http.StatusOK, tplHooks)
  50. }
  51. type ownerRepoCtx struct {
  52. OwnerID int64
  53. RepoID int64
  54. IsAdmin bool
  55. IsSystemWebhook bool
  56. Link string
  57. LinkNew string
  58. NewTemplate base.TplName
  59. }
  60. // getOwnerRepoCtx determines whether this is a repo, owner, or admin (both default and system) context.
  61. func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
  62. if ctx.Data["PageIsRepoSettings"] == true {
  63. return &ownerRepoCtx{
  64. RepoID: ctx.Repo.Repository.ID,
  65. Link: path.Join(ctx.Repo.RepoLink, "settings/hooks"),
  66. LinkNew: path.Join(ctx.Repo.RepoLink, "settings/hooks"),
  67. NewTemplate: tplHookNew,
  68. }, nil
  69. }
  70. if ctx.Data["PageIsOrgSettings"] == true {
  71. return &ownerRepoCtx{
  72. OwnerID: ctx.ContextUser.ID,
  73. Link: path.Join(ctx.Org.OrgLink, "settings/hooks"),
  74. LinkNew: path.Join(ctx.Org.OrgLink, "settings/hooks"),
  75. NewTemplate: tplOrgHookNew,
  76. }, nil
  77. }
  78. if ctx.Data["PageIsUserSettings"] == true {
  79. return &ownerRepoCtx{
  80. OwnerID: ctx.Doer.ID,
  81. Link: path.Join(setting.AppSubURL, "/user/settings/hooks"),
  82. LinkNew: path.Join(setting.AppSubURL, "/user/settings/hooks"),
  83. NewTemplate: tplUserHookNew,
  84. }, nil
  85. }
  86. if ctx.Data["PageIsAdmin"] == true {
  87. return &ownerRepoCtx{
  88. IsAdmin: true,
  89. IsSystemWebhook: ctx.Params(":configType") == "system-hooks",
  90. Link: path.Join(setting.AppSubURL, "/admin/hooks"),
  91. LinkNew: path.Join(setting.AppSubURL, "/admin/", ctx.Params(":configType")),
  92. NewTemplate: tplAdminHookNew,
  93. }, nil
  94. }
  95. return nil, errors.New("unable to set OwnerRepo context")
  96. }
  97. func checkHookType(ctx *context.Context) string {
  98. hookType := strings.ToLower(ctx.Params(":type"))
  99. if !util.SliceContainsString(setting.Webhook.Types, hookType, true) {
  100. ctx.NotFound("checkHookType", nil)
  101. return ""
  102. }
  103. return hookType
  104. }
  105. // WebhooksNew render creating webhook page
  106. func WebhooksNew(ctx *context.Context) {
  107. ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
  108. ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}}
  109. orCtx, err := getOwnerRepoCtx(ctx)
  110. if err != nil {
  111. ctx.ServerError("getOwnerRepoCtx", err)
  112. return
  113. }
  114. if orCtx.IsAdmin && orCtx.IsSystemWebhook {
  115. ctx.Data["PageIsAdminSystemHooks"] = true
  116. ctx.Data["PageIsAdminSystemHooksNew"] = true
  117. } else if orCtx.IsAdmin {
  118. ctx.Data["PageIsAdminDefaultHooks"] = true
  119. ctx.Data["PageIsAdminDefaultHooksNew"] = true
  120. } else {
  121. ctx.Data["PageIsSettingsHooks"] = true
  122. ctx.Data["PageIsSettingsHooksNew"] = true
  123. }
  124. hookType := checkHookType(ctx)
  125. ctx.Data["HookType"] = hookType
  126. if ctx.Written() {
  127. return
  128. }
  129. if hookType == "discord" {
  130. ctx.Data["DiscordHook"] = map[string]any{
  131. "Username": "Gitea",
  132. }
  133. }
  134. ctx.Data["BaseLink"] = orCtx.LinkNew
  135. ctx.HTML(http.StatusOK, orCtx.NewTemplate)
  136. }
  137. // ParseHookEvent convert web form content to webhook.HookEvent
  138. func ParseHookEvent(form forms.WebhookForm) *webhook_module.HookEvent {
  139. return &webhook_module.HookEvent{
  140. PushOnly: form.PushOnly(),
  141. SendEverything: form.SendEverything(),
  142. ChooseEvents: form.ChooseEvents(),
  143. HookEvents: webhook_module.HookEvents{
  144. Create: form.Create,
  145. Delete: form.Delete,
  146. Fork: form.Fork,
  147. Issues: form.Issues,
  148. IssueAssign: form.IssueAssign,
  149. IssueLabel: form.IssueLabel,
  150. IssueMilestone: form.IssueMilestone,
  151. IssueComment: form.IssueComment,
  152. Release: form.Release,
  153. Push: form.Push,
  154. PullRequest: form.PullRequest,
  155. PullRequestAssign: form.PullRequestAssign,
  156. PullRequestLabel: form.PullRequestLabel,
  157. PullRequestMilestone: form.PullRequestMilestone,
  158. PullRequestComment: form.PullRequestComment,
  159. PullRequestReview: form.PullRequestReview,
  160. PullRequestSync: form.PullRequestSync,
  161. PullRequestReviewRequest: form.PullRequestReviewRequest,
  162. Wiki: form.Wiki,
  163. Repository: form.Repository,
  164. Package: form.Package,
  165. },
  166. BranchFilter: form.BranchFilter,
  167. }
  168. }
  169. type webhookParams struct {
  170. // Type should be imported from webhook package (webhook.XXX)
  171. Type string
  172. URL string
  173. ContentType webhook.HookContentType
  174. Secret string
  175. HTTPMethod string
  176. WebhookForm forms.WebhookForm
  177. Meta any
  178. }
  179. func createWebhook(ctx *context.Context, params webhookParams) {
  180. ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
  181. ctx.Data["PageIsSettingsHooks"] = true
  182. ctx.Data["PageIsSettingsHooksNew"] = true
  183. ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}}
  184. ctx.Data["HookType"] = params.Type
  185. orCtx, err := getOwnerRepoCtx(ctx)
  186. if err != nil {
  187. ctx.ServerError("getOwnerRepoCtx", err)
  188. return
  189. }
  190. ctx.Data["BaseLink"] = orCtx.LinkNew
  191. if ctx.HasError() {
  192. ctx.HTML(http.StatusOK, orCtx.NewTemplate)
  193. return
  194. }
  195. var meta []byte
  196. if params.Meta != nil {
  197. meta, err = json.Marshal(params.Meta)
  198. if err != nil {
  199. ctx.ServerError("Marshal", err)
  200. return
  201. }
  202. }
  203. w := &webhook.Webhook{
  204. RepoID: orCtx.RepoID,
  205. URL: params.URL,
  206. HTTPMethod: params.HTTPMethod,
  207. ContentType: params.ContentType,
  208. Secret: params.Secret,
  209. HookEvent: ParseHookEvent(params.WebhookForm),
  210. IsActive: params.WebhookForm.Active,
  211. Type: params.Type,
  212. Meta: string(meta),
  213. OwnerID: orCtx.OwnerID,
  214. IsSystemWebhook: orCtx.IsSystemWebhook,
  215. }
  216. err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
  217. if err != nil {
  218. ctx.ServerError("SetHeaderAuthorization", err)
  219. return
  220. }
  221. if err := w.UpdateEvent(); err != nil {
  222. ctx.ServerError("UpdateEvent", err)
  223. return
  224. } else if err := webhook.CreateWebhook(ctx, w); err != nil {
  225. ctx.ServerError("CreateWebhook", err)
  226. return
  227. }
  228. ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
  229. ctx.Redirect(orCtx.Link)
  230. }
  231. func editWebhook(ctx *context.Context, params webhookParams) {
  232. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  233. ctx.Data["PageIsSettingsHooks"] = true
  234. ctx.Data["PageIsSettingsHooksEdit"] = true
  235. orCtx, w := checkWebhook(ctx)
  236. if ctx.Written() {
  237. return
  238. }
  239. ctx.Data["Webhook"] = w
  240. if ctx.HasError() {
  241. ctx.HTML(http.StatusOK, orCtx.NewTemplate)
  242. return
  243. }
  244. var meta []byte
  245. var err error
  246. if params.Meta != nil {
  247. meta, err = json.Marshal(params.Meta)
  248. if err != nil {
  249. ctx.ServerError("Marshal", err)
  250. return
  251. }
  252. }
  253. w.URL = params.URL
  254. w.ContentType = params.ContentType
  255. w.Secret = params.Secret
  256. w.HookEvent = ParseHookEvent(params.WebhookForm)
  257. w.IsActive = params.WebhookForm.Active
  258. w.HTTPMethod = params.HTTPMethod
  259. w.Meta = string(meta)
  260. err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
  261. if err != nil {
  262. ctx.ServerError("SetHeaderAuthorization", err)
  263. return
  264. }
  265. if err := w.UpdateEvent(); err != nil {
  266. ctx.ServerError("UpdateEvent", err)
  267. return
  268. } else if err := webhook.UpdateWebhook(w); err != nil {
  269. ctx.ServerError("UpdateWebhook", err)
  270. return
  271. }
  272. ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
  273. ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
  274. }
  275. // GiteaHooksNewPost response for creating Gitea webhook
  276. func GiteaHooksNewPost(ctx *context.Context) {
  277. createWebhook(ctx, giteaHookParams(ctx))
  278. }
  279. // GiteaHooksEditPost response for editing Gitea webhook
  280. func GiteaHooksEditPost(ctx *context.Context) {
  281. editWebhook(ctx, giteaHookParams(ctx))
  282. }
  283. func giteaHookParams(ctx *context.Context) webhookParams {
  284. form := web.GetForm(ctx).(*forms.NewWebhookForm)
  285. contentType := webhook.ContentTypeJSON
  286. if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
  287. contentType = webhook.ContentTypeForm
  288. }
  289. return webhookParams{
  290. Type: webhook_module.GITEA,
  291. URL: form.PayloadURL,
  292. ContentType: contentType,
  293. Secret: form.Secret,
  294. HTTPMethod: form.HTTPMethod,
  295. WebhookForm: form.WebhookForm,
  296. }
  297. }
  298. // GogsHooksNewPost response for creating Gogs webhook
  299. func GogsHooksNewPost(ctx *context.Context) {
  300. createWebhook(ctx, gogsHookParams(ctx))
  301. }
  302. // GogsHooksEditPost response for editing Gogs webhook
  303. func GogsHooksEditPost(ctx *context.Context) {
  304. editWebhook(ctx, gogsHookParams(ctx))
  305. }
  306. func gogsHookParams(ctx *context.Context) webhookParams {
  307. form := web.GetForm(ctx).(*forms.NewGogshookForm)
  308. contentType := webhook.ContentTypeJSON
  309. if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
  310. contentType = webhook.ContentTypeForm
  311. }
  312. return webhookParams{
  313. Type: webhook_module.GOGS,
  314. URL: form.PayloadURL,
  315. ContentType: contentType,
  316. Secret: form.Secret,
  317. WebhookForm: form.WebhookForm,
  318. }
  319. }
  320. // DiscordHooksNewPost response for creating Discord webhook
  321. func DiscordHooksNewPost(ctx *context.Context) {
  322. createWebhook(ctx, discordHookParams(ctx))
  323. }
  324. // DiscordHooksEditPost response for editing Discord webhook
  325. func DiscordHooksEditPost(ctx *context.Context) {
  326. editWebhook(ctx, discordHookParams(ctx))
  327. }
  328. func discordHookParams(ctx *context.Context) webhookParams {
  329. form := web.GetForm(ctx).(*forms.NewDiscordHookForm)
  330. return webhookParams{
  331. Type: webhook_module.DISCORD,
  332. URL: form.PayloadURL,
  333. ContentType: webhook.ContentTypeJSON,
  334. WebhookForm: form.WebhookForm,
  335. Meta: &webhook_service.DiscordMeta{
  336. Username: form.Username,
  337. IconURL: form.IconURL,
  338. },
  339. }
  340. }
  341. // DingtalkHooksNewPost response for creating Dingtalk webhook
  342. func DingtalkHooksNewPost(ctx *context.Context) {
  343. createWebhook(ctx, dingtalkHookParams(ctx))
  344. }
  345. // DingtalkHooksEditPost response for editing Dingtalk webhook
  346. func DingtalkHooksEditPost(ctx *context.Context) {
  347. editWebhook(ctx, dingtalkHookParams(ctx))
  348. }
  349. func dingtalkHookParams(ctx *context.Context) webhookParams {
  350. form := web.GetForm(ctx).(*forms.NewDingtalkHookForm)
  351. return webhookParams{
  352. Type: webhook_module.DINGTALK,
  353. URL: form.PayloadURL,
  354. ContentType: webhook.ContentTypeJSON,
  355. WebhookForm: form.WebhookForm,
  356. }
  357. }
  358. // TelegramHooksNewPost response for creating Telegram webhook
  359. func TelegramHooksNewPost(ctx *context.Context) {
  360. createWebhook(ctx, telegramHookParams(ctx))
  361. }
  362. // TelegramHooksEditPost response for editing Telegram webhook
  363. func TelegramHooksEditPost(ctx *context.Context) {
  364. editWebhook(ctx, telegramHookParams(ctx))
  365. }
  366. func telegramHookParams(ctx *context.Context) webhookParams {
  367. form := web.GetForm(ctx).(*forms.NewTelegramHookForm)
  368. return webhookParams{
  369. Type: webhook_module.TELEGRAM,
  370. URL: fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s&message_thread_id=%s", url.PathEscape(form.BotToken), url.QueryEscape(form.ChatID), url.QueryEscape(form.ThreadID)),
  371. ContentType: webhook.ContentTypeJSON,
  372. WebhookForm: form.WebhookForm,
  373. Meta: &webhook_service.TelegramMeta{
  374. BotToken: form.BotToken,
  375. ChatID: form.ChatID,
  376. ThreadID: form.ThreadID,
  377. },
  378. }
  379. }
  380. // MatrixHooksNewPost response for creating Matrix webhook
  381. func MatrixHooksNewPost(ctx *context.Context) {
  382. createWebhook(ctx, matrixHookParams(ctx))
  383. }
  384. // MatrixHooksEditPost response for editing Matrix webhook
  385. func MatrixHooksEditPost(ctx *context.Context) {
  386. editWebhook(ctx, matrixHookParams(ctx))
  387. }
  388. func matrixHookParams(ctx *context.Context) webhookParams {
  389. form := web.GetForm(ctx).(*forms.NewMatrixHookForm)
  390. return webhookParams{
  391. Type: webhook_module.MATRIX,
  392. URL: fmt.Sprintf("%s/_matrix/client/r0/rooms/%s/send/m.room.message", form.HomeserverURL, url.PathEscape(form.RoomID)),
  393. ContentType: webhook.ContentTypeJSON,
  394. HTTPMethod: http.MethodPut,
  395. WebhookForm: form.WebhookForm,
  396. Meta: &webhook_service.MatrixMeta{
  397. HomeserverURL: form.HomeserverURL,
  398. Room: form.RoomID,
  399. MessageType: form.MessageType,
  400. },
  401. }
  402. }
  403. // MSTeamsHooksNewPost response for creating MSTeams webhook
  404. func MSTeamsHooksNewPost(ctx *context.Context) {
  405. createWebhook(ctx, mSTeamsHookParams(ctx))
  406. }
  407. // MSTeamsHooksEditPost response for editing MSTeams webhook
  408. func MSTeamsHooksEditPost(ctx *context.Context) {
  409. editWebhook(ctx, mSTeamsHookParams(ctx))
  410. }
  411. func mSTeamsHookParams(ctx *context.Context) webhookParams {
  412. form := web.GetForm(ctx).(*forms.NewMSTeamsHookForm)
  413. return webhookParams{
  414. Type: webhook_module.MSTEAMS,
  415. URL: form.PayloadURL,
  416. ContentType: webhook.ContentTypeJSON,
  417. WebhookForm: form.WebhookForm,
  418. }
  419. }
  420. // SlackHooksNewPost response for creating Slack webhook
  421. func SlackHooksNewPost(ctx *context.Context) {
  422. createWebhook(ctx, slackHookParams(ctx))
  423. }
  424. // SlackHooksEditPost response for editing Slack webhook
  425. func SlackHooksEditPost(ctx *context.Context) {
  426. editWebhook(ctx, slackHookParams(ctx))
  427. }
  428. func slackHookParams(ctx *context.Context) webhookParams {
  429. form := web.GetForm(ctx).(*forms.NewSlackHookForm)
  430. return webhookParams{
  431. Type: webhook_module.SLACK,
  432. URL: form.PayloadURL,
  433. ContentType: webhook.ContentTypeJSON,
  434. WebhookForm: form.WebhookForm,
  435. Meta: &webhook_service.SlackMeta{
  436. Channel: strings.TrimSpace(form.Channel),
  437. Username: form.Username,
  438. IconURL: form.IconURL,
  439. Color: form.Color,
  440. },
  441. }
  442. }
  443. // FeishuHooksNewPost response for creating Feishu webhook
  444. func FeishuHooksNewPost(ctx *context.Context) {
  445. createWebhook(ctx, feishuHookParams(ctx))
  446. }
  447. // FeishuHooksEditPost response for editing Feishu webhook
  448. func FeishuHooksEditPost(ctx *context.Context) {
  449. editWebhook(ctx, feishuHookParams(ctx))
  450. }
  451. func feishuHookParams(ctx *context.Context) webhookParams {
  452. form := web.GetForm(ctx).(*forms.NewFeishuHookForm)
  453. return webhookParams{
  454. Type: webhook_module.FEISHU,
  455. URL: form.PayloadURL,
  456. ContentType: webhook.ContentTypeJSON,
  457. WebhookForm: form.WebhookForm,
  458. }
  459. }
  460. // WechatworkHooksNewPost response for creating Wechatwork webhook
  461. func WechatworkHooksNewPost(ctx *context.Context) {
  462. createWebhook(ctx, wechatworkHookParams(ctx))
  463. }
  464. // WechatworkHooksEditPost response for editing Wechatwork webhook
  465. func WechatworkHooksEditPost(ctx *context.Context) {
  466. editWebhook(ctx, wechatworkHookParams(ctx))
  467. }
  468. func wechatworkHookParams(ctx *context.Context) webhookParams {
  469. form := web.GetForm(ctx).(*forms.NewWechatWorkHookForm)
  470. return webhookParams{
  471. Type: webhook_module.WECHATWORK,
  472. URL: form.PayloadURL,
  473. ContentType: webhook.ContentTypeJSON,
  474. WebhookForm: form.WebhookForm,
  475. }
  476. }
  477. // PackagistHooksNewPost response for creating Packagist webhook
  478. func PackagistHooksNewPost(ctx *context.Context) {
  479. createWebhook(ctx, packagistHookParams(ctx))
  480. }
  481. // PackagistHooksEditPost response for editing Packagist webhook
  482. func PackagistHooksEditPost(ctx *context.Context) {
  483. editWebhook(ctx, packagistHookParams(ctx))
  484. }
  485. func packagistHookParams(ctx *context.Context) webhookParams {
  486. form := web.GetForm(ctx).(*forms.NewPackagistHookForm)
  487. return webhookParams{
  488. Type: webhook_module.PACKAGIST,
  489. URL: fmt.Sprintf("https://packagist.org/api/update-package?username=%s&apiToken=%s", url.QueryEscape(form.Username), url.QueryEscape(form.APIToken)),
  490. ContentType: webhook.ContentTypeJSON,
  491. WebhookForm: form.WebhookForm,
  492. Meta: &webhook_service.PackagistMeta{
  493. Username: form.Username,
  494. APIToken: form.APIToken,
  495. PackageURL: form.PackageURL,
  496. },
  497. }
  498. }
  499. func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) {
  500. orCtx, err := getOwnerRepoCtx(ctx)
  501. if err != nil {
  502. ctx.ServerError("getOwnerRepoCtx", err)
  503. return nil, nil
  504. }
  505. ctx.Data["BaseLink"] = orCtx.Link
  506. var w *webhook.Webhook
  507. if orCtx.RepoID > 0 {
  508. w, err = webhook.GetWebhookByRepoID(orCtx.RepoID, ctx.ParamsInt64(":id"))
  509. } else if orCtx.OwnerID > 0 {
  510. w, err = webhook.GetWebhookByOwnerID(orCtx.OwnerID, ctx.ParamsInt64(":id"))
  511. } else if orCtx.IsAdmin {
  512. w, err = webhook.GetSystemOrDefaultWebhook(ctx, ctx.ParamsInt64(":id"))
  513. }
  514. if err != nil || w == nil {
  515. if webhook.IsErrWebhookNotExist(err) {
  516. ctx.NotFound("GetWebhookByID", nil)
  517. } else {
  518. ctx.ServerError("GetWebhookByID", err)
  519. }
  520. return nil, nil
  521. }
  522. ctx.Data["HookType"] = w.Type
  523. switch w.Type {
  524. case webhook_module.SLACK:
  525. ctx.Data["SlackHook"] = webhook_service.GetSlackHook(w)
  526. case webhook_module.DISCORD:
  527. ctx.Data["DiscordHook"] = webhook_service.GetDiscordHook(w)
  528. case webhook_module.TELEGRAM:
  529. ctx.Data["TelegramHook"] = webhook_service.GetTelegramHook(w)
  530. case webhook_module.MATRIX:
  531. ctx.Data["MatrixHook"] = webhook_service.GetMatrixHook(w)
  532. case webhook_module.PACKAGIST:
  533. ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w)
  534. }
  535. ctx.Data["History"], err = w.History(1)
  536. if err != nil {
  537. ctx.ServerError("History", err)
  538. }
  539. return orCtx, w
  540. }
  541. // WebHooksEdit render editing web hook page
  542. func WebHooksEdit(ctx *context.Context) {
  543. ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
  544. ctx.Data["PageIsSettingsHooks"] = true
  545. ctx.Data["PageIsSettingsHooksEdit"] = true
  546. orCtx, w := checkWebhook(ctx)
  547. if ctx.Written() {
  548. return
  549. }
  550. ctx.Data["Webhook"] = w
  551. ctx.HTML(http.StatusOK, orCtx.NewTemplate)
  552. }
  553. // TestWebhook test if web hook is work fine
  554. func TestWebhook(ctx *context.Context) {
  555. hookID := ctx.ParamsInt64(":id")
  556. w, err := webhook.GetWebhookByRepoID(ctx.Repo.Repository.ID, hookID)
  557. if err != nil {
  558. ctx.Flash.Error("GetWebhookByRepoID: " + err.Error())
  559. ctx.Status(http.StatusInternalServerError)
  560. return
  561. }
  562. // Grab latest commit or fake one if it's empty repository.
  563. commit := ctx.Repo.Commit
  564. if commit == nil {
  565. ghost := user_model.NewGhostUser()
  566. commit = &git.Commit{
  567. ID: git.MustIDFromString(git.EmptySHA),
  568. Author: ghost.NewGitSig(),
  569. Committer: ghost.NewGitSig(),
  570. CommitMessage: "This is a fake commit",
  571. }
  572. }
  573. apiUser := convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone)
  574. apiCommit := &api.PayloadCommit{
  575. ID: commit.ID.String(),
  576. Message: commit.Message(),
  577. URL: ctx.Repo.Repository.HTMLURL() + "/commit/" + url.PathEscape(commit.ID.String()),
  578. Author: &api.PayloadUser{
  579. Name: commit.Author.Name,
  580. Email: commit.Author.Email,
  581. },
  582. Committer: &api.PayloadUser{
  583. Name: commit.Committer.Name,
  584. Email: commit.Committer.Email,
  585. },
  586. }
  587. commitID := commit.ID.String()
  588. p := &api.PushPayload{
  589. Ref: git.BranchPrefix + ctx.Repo.Repository.DefaultBranch,
  590. Before: commitID,
  591. After: commitID,
  592. CompareURL: setting.AppURL + ctx.Repo.Repository.ComposeCompareURL(commitID, commitID),
  593. Commits: []*api.PayloadCommit{apiCommit},
  594. TotalCommits: 1,
  595. HeadCommit: apiCommit,
  596. Repo: convert.ToRepo(ctx, ctx.Repo.Repository, access_model.Permission{AccessMode: perm.AccessModeNone}),
  597. Pusher: apiUser,
  598. Sender: apiUser,
  599. }
  600. if err := webhook_service.PrepareWebhook(ctx, w, webhook_module.HookEventPush, p); err != nil {
  601. ctx.Flash.Error("PrepareWebhook: " + err.Error())
  602. ctx.Status(http.StatusInternalServerError)
  603. } else {
  604. ctx.Flash.Info(ctx.Tr("repo.settings.webhook.delivery.success"))
  605. ctx.Status(http.StatusOK)
  606. }
  607. }
  608. // ReplayWebhook replays a webhook
  609. func ReplayWebhook(ctx *context.Context) {
  610. hookTaskUUID := ctx.Params(":uuid")
  611. orCtx, w := checkWebhook(ctx)
  612. if ctx.Written() {
  613. return
  614. }
  615. if err := webhook_service.ReplayHookTask(ctx, w, hookTaskUUID); err != nil {
  616. if webhook.IsErrHookTaskNotExist(err) {
  617. ctx.NotFound("ReplayHookTask", nil)
  618. } else {
  619. ctx.ServerError("ReplayHookTask", err)
  620. }
  621. return
  622. }
  623. ctx.Flash.Success(ctx.Tr("repo.settings.webhook.delivery.success"))
  624. ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
  625. }
  626. // DeleteWebhook delete a webhook
  627. func DeleteWebhook(ctx *context.Context) {
  628. if err := webhook.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil {
  629. ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
  630. } else {
  631. ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
  632. }
  633. ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/hooks")
  634. }