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.

slack.go 10KB

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