gitea源码

slack.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package webhook
  4. import (
  5. "context"
  6. "fmt"
  7. "net/http"
  8. "regexp"
  9. "strings"
  10. webhook_model "code.gitea.io/gitea/models/webhook"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/json"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. api "code.gitea.io/gitea/modules/structs"
  16. webhook_module "code.gitea.io/gitea/modules/webhook"
  17. )
  18. // SlackMeta contains the slack metadata
  19. type SlackMeta struct {
  20. Channel string `json:"channel"`
  21. Username string `json:"username"`
  22. IconURL string `json:"icon_url"`
  23. Color string `json:"color"`
  24. }
  25. // GetSlackHook returns slack metadata
  26. func GetSlackHook(w *webhook_model.Webhook) *SlackMeta {
  27. s := &SlackMeta{}
  28. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  29. log.Error("webhook.GetSlackHook(%d): %v", w.ID, err)
  30. }
  31. return s
  32. }
  33. // SlackPayload contains the information about the slack channel
  34. type SlackPayload struct {
  35. Channel string `json:"channel"`
  36. Text string `json:"text"`
  37. Username string `json:"username"`
  38. IconURL string `json:"icon_url"`
  39. UnfurlLinks int `json:"unfurl_links"`
  40. LinkNames int `json:"link_names"`
  41. Attachments []SlackAttachment `json:"attachments"`
  42. }
  43. // SlackAttachment contains the slack message
  44. type SlackAttachment struct {
  45. Fallback string `json:"fallback"`
  46. Color string `json:"color"`
  47. Title string `json:"title"`
  48. TitleLink string `json:"title_link"`
  49. Text string `json:"text"`
  50. }
  51. // SlackTextFormatter replaces &, <, > with HTML characters
  52. // see: https://api.slack.com/docs/formatting
  53. func SlackTextFormatter(s string) string {
  54. // replace & < >
  55. s = strings.ReplaceAll(s, "&", "&amp;")
  56. s = strings.ReplaceAll(s, "<", "&lt;")
  57. s = strings.ReplaceAll(s, ">", "&gt;")
  58. return s
  59. }
  60. // SlackShortTextFormatter replaces &, <, > with HTML characters
  61. func SlackShortTextFormatter(s string) string {
  62. s = strings.Split(s, "\n")[0]
  63. // replace & < >
  64. s = strings.ReplaceAll(s, "&", "&amp;")
  65. s = strings.ReplaceAll(s, "<", "&lt;")
  66. s = strings.ReplaceAll(s, ">", "&gt;")
  67. return s
  68. }
  69. // SlackLinkFormatter creates a link compatible with slack
  70. func SlackLinkFormatter(url, text string) string {
  71. return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
  72. }
  73. // SlackLinkToRef slack-formatter link to a repo ref
  74. func SlackLinkToRef(repoURL, ref string) string {
  75. // FIXME: SHA1 hardcoded here
  76. refName := git.RefName(ref)
  77. url := repoURL + "/src/" + refName.RefWebLinkPath()
  78. return SlackLinkFormatter(url, refName.ShortName())
  79. }
  80. // Create implements payloadConvertor Create method
  81. func (s slackConvertor) Create(p *api.CreatePayload) (SlackPayload, error) {
  82. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  83. refLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  84. text := fmt.Sprintf("[%s:%s] %s created by %s", repoLink, refLink, p.RefType, p.Sender.UserName)
  85. return s.createPayload(text, nil), nil
  86. }
  87. // Delete composes Slack payload for delete a branch or tag.
  88. func (s slackConvertor) Delete(p *api.DeletePayload) (SlackPayload, error) {
  89. refName := git.RefName(p.Ref).ShortName()
  90. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  91. text := fmt.Sprintf("[%s:%s] %s deleted by %s", repoLink, refName, p.RefType, p.Sender.UserName)
  92. return s.createPayload(text, nil), nil
  93. }
  94. // Fork composes Slack payload for forked by a repository.
  95. func (s slackConvertor) Fork(p *api.ForkPayload) (SlackPayload, error) {
  96. baseLink := SlackLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName)
  97. forkLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  98. text := fmt.Sprintf("%s is forked to %s", baseLink, forkLink)
  99. return s.createPayload(text, nil), nil
  100. }
  101. // Issue implements payloadConvertor Issue method
  102. func (s slackConvertor) Issue(p *api.IssuePayload) (SlackPayload, error) {
  103. text, issueTitle, extraMarkdown, color := getIssuesPayloadInfo(p, SlackLinkFormatter, true)
  104. var attachments []SlackAttachment
  105. if extraMarkdown != "" {
  106. extraMarkdown = SlackTextFormatter(extraMarkdown)
  107. issueTitle = SlackTextFormatter(issueTitle)
  108. attachments = append(attachments, SlackAttachment{
  109. Color: fmt.Sprintf("%x", color),
  110. Title: issueTitle,
  111. TitleLink: p.Issue.HTMLURL,
  112. Text: extraMarkdown,
  113. })
  114. }
  115. return s.createPayload(text, attachments), nil
  116. }
  117. // IssueComment implements payloadConvertor IssueComment method
  118. func (s slackConvertor) IssueComment(p *api.IssueCommentPayload) (SlackPayload, error) {
  119. text, issueTitle, color := getIssueCommentPayloadInfo(p, SlackLinkFormatter, true)
  120. return s.createPayload(text, []SlackAttachment{{
  121. Color: fmt.Sprintf("%x", color),
  122. Title: issueTitle,
  123. TitleLink: p.Comment.HTMLURL,
  124. Text: SlackTextFormatter(p.Comment.Body),
  125. }}), nil
  126. }
  127. // Wiki implements payloadConvertor Wiki method
  128. func (s slackConvertor) Wiki(p *api.WikiPayload) (SlackPayload, error) {
  129. text, _, _ := getWikiPayloadInfo(p, SlackLinkFormatter, true)
  130. return s.createPayload(text, nil), nil
  131. }
  132. // Release implements payloadConvertor Release method
  133. func (s slackConvertor) Release(p *api.ReleasePayload) (SlackPayload, error) {
  134. text, _ := getReleasePayloadInfo(p, SlackLinkFormatter, true)
  135. return s.createPayload(text, nil), nil
  136. }
  137. func (s slackConvertor) Package(p *api.PackagePayload) (SlackPayload, error) {
  138. text, _ := getPackagePayloadInfo(p, SlackLinkFormatter, true)
  139. return s.createPayload(text, nil), nil
  140. }
  141. func (s slackConvertor) Status(p *api.CommitStatusPayload) (SlackPayload, error) {
  142. text, _ := getStatusPayloadInfo(p, SlackLinkFormatter, true)
  143. return s.createPayload(text, nil), nil
  144. }
  145. func (s slackConvertor) WorkflowRun(p *api.WorkflowRunPayload) (SlackPayload, error) {
  146. text, _ := getWorkflowRunPayloadInfo(p, SlackLinkFormatter, true)
  147. return s.createPayload(text, nil), nil
  148. }
  149. func (s slackConvertor) WorkflowJob(p *api.WorkflowJobPayload) (SlackPayload, error) {
  150. text, _ := getWorkflowJobPayloadInfo(p, SlackLinkFormatter, true)
  151. return s.createPayload(text, nil), nil
  152. }
  153. // Push implements payloadConvertor Push method
  154. func (s slackConvertor) Push(p *api.PushPayload) (SlackPayload, error) {
  155. // n new commits
  156. var (
  157. commitDesc string
  158. commitString string
  159. )
  160. if p.TotalCommits == 1 {
  161. commitDesc = "1 new commit"
  162. } else {
  163. commitDesc = fmt.Sprintf("%d new commits", p.TotalCommits)
  164. }
  165. if len(p.CompareURL) > 0 {
  166. commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
  167. } else {
  168. commitString = commitDesc
  169. }
  170. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  171. branchLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  172. text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
  173. var attachmentText string
  174. // for each commit, generate attachment text
  175. for i, commit := range p.Commits {
  176. attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
  177. // add linebreak to each commit but the last
  178. if i < len(p.Commits)-1 {
  179. attachmentText += "\n"
  180. }
  181. }
  182. return s.createPayload(text, []SlackAttachment{{
  183. Color: s.Color,
  184. Title: p.Repo.HTMLURL,
  185. TitleLink: p.Repo.HTMLURL,
  186. Text: attachmentText,
  187. }}), nil
  188. }
  189. // PullRequest implements payloadConvertor PullRequest method
  190. func (s slackConvertor) PullRequest(p *api.PullRequestPayload) (SlackPayload, error) {
  191. text, issueTitle, extraMarkdown, color := getPullRequestPayloadInfo(p, SlackLinkFormatter, true)
  192. var attachments []SlackAttachment
  193. if extraMarkdown != "" {
  194. extraMarkdown = SlackTextFormatter(p.PullRequest.Body)
  195. issueTitle = SlackTextFormatter(issueTitle)
  196. attachments = append(attachments, SlackAttachment{
  197. Color: fmt.Sprintf("%x", color),
  198. Title: issueTitle,
  199. TitleLink: p.PullRequest.HTMLURL,
  200. Text: extraMarkdown,
  201. })
  202. }
  203. return s.createPayload(text, attachments), nil
  204. }
  205. // Review implements payloadConvertor Review method
  206. func (s slackConvertor) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (SlackPayload, error) {
  207. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  208. title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)
  209. titleLink := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index)
  210. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  211. var text string
  212. switch p.Action {
  213. case api.HookIssueReviewed:
  214. action, err := parseHookPullRequestEventType(event)
  215. if err != nil {
  216. return SlackPayload{}, err
  217. }
  218. text = fmt.Sprintf("[%s] Pull request review %s: [%s](%s) by %s", repoLink, action, title, titleLink, senderLink)
  219. }
  220. return s.createPayload(text, nil), nil
  221. }
  222. // Repository implements payloadConvertor Repository method
  223. func (s slackConvertor) Repository(p *api.RepositoryPayload) (SlackPayload, error) {
  224. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  225. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  226. var text string
  227. switch p.Action {
  228. case api.HookRepoCreated:
  229. text = fmt.Sprintf("[%s] Repository created by %s", repoLink, senderLink)
  230. case api.HookRepoDeleted:
  231. text = fmt.Sprintf("[%s] Repository deleted by %s", repoLink, senderLink)
  232. }
  233. return s.createPayload(text, nil), nil
  234. }
  235. func (s slackConvertor) createPayload(text string, attachments []SlackAttachment) SlackPayload {
  236. return SlackPayload{
  237. Channel: s.Channel,
  238. Text: text,
  239. Username: s.Username,
  240. IconURL: s.IconURL,
  241. Attachments: attachments,
  242. }
  243. }
  244. type slackConvertor struct {
  245. Channel string
  246. Username string
  247. IconURL string
  248. Color string
  249. }
  250. func newSlackRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) {
  251. meta := &SlackMeta{}
  252. if err := json.Unmarshal([]byte(w.Meta), meta); err != nil {
  253. return nil, nil, fmt.Errorf("newSlackRequest meta json: %w", err)
  254. }
  255. var pc payloadConvertor[SlackPayload] = slackConvertor{
  256. Channel: meta.Channel,
  257. Username: meta.Username,
  258. IconURL: meta.IconURL,
  259. Color: meta.Color,
  260. }
  261. return newJSONRequest(pc, w, t, true)
  262. }
  263. func init() {
  264. RegisterWebhookRequester(webhook_module.SLACK, newSlackRequest)
  265. }
  266. var slackChannel = regexp.MustCompile(`^#?[a-z0-9_-]{1,80}$`)
  267. // IsValidSlackChannel validates a channel name conforms to what slack expects:
  268. // https://api.slack.com/methods/conversations.rename#naming
  269. // Conversation names can only contain lowercase letters, numbers, hyphens, and underscores, and must be 80 characters or less.
  270. // Gitea accepts if it starts with a #.
  271. func IsValidSlackChannel(name string) bool {
  272. return slackChannel.MatchString(name)
  273. }