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

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