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 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2014 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 webhook
  5. import (
  6. "errors"
  7. "fmt"
  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. )
  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.RefEndName(ref)
  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.RefEndName(p.Ref)
  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. // Push implements PayloadConvertor Push method
  146. func (s *SlackPayload) Push(p *api.PushPayload) (api.Payloader, error) {
  147. // n new commits
  148. var (
  149. commitDesc string
  150. commitString string
  151. )
  152. if len(p.Commits) == 1 {
  153. commitDesc = "1 new commit"
  154. } else {
  155. commitDesc = fmt.Sprintf("%d new commits", len(p.Commits))
  156. }
  157. if len(p.CompareURL) > 0 {
  158. commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
  159. } else {
  160. commitString = commitDesc
  161. }
  162. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  163. branchLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  164. text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
  165. var attachmentText string
  166. // for each commit, generate attachment text
  167. for i, commit := range p.Commits {
  168. attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
  169. // add linebreak to each commit but the last
  170. if i < len(p.Commits)-1 {
  171. attachmentText += "\n"
  172. }
  173. }
  174. return s.createPayload(text, []SlackAttachment{{
  175. Color: s.Color,
  176. Title: p.Repo.HTMLURL,
  177. TitleLink: p.Repo.HTMLURL,
  178. Text: attachmentText,
  179. }}), nil
  180. }
  181. // PullRequest implements PayloadConvertor PullRequest method
  182. func (s *SlackPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, error) {
  183. text, issueTitle, attachmentText, color := getPullRequestPayloadInfo(p, SlackLinkFormatter, true)
  184. var attachments []SlackAttachment
  185. if attachmentText != "" {
  186. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  187. issueTitle = SlackTextFormatter(issueTitle)
  188. attachments = append(attachments, SlackAttachment{
  189. Color: fmt.Sprintf("%x", color),
  190. Title: issueTitle,
  191. TitleLink: p.PullRequest.URL,
  192. Text: attachmentText,
  193. })
  194. }
  195. return s.createPayload(text, attachments), nil
  196. }
  197. // Review implements PayloadConvertor Review method
  198. func (s *SlackPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) {
  199. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  200. title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)
  201. titleLink := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index)
  202. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  203. var text string
  204. switch p.Action {
  205. case api.HookIssueReviewed:
  206. action, err := parseHookPullRequestEventType(event)
  207. if err != nil {
  208. return nil, err
  209. }
  210. text = fmt.Sprintf("[%s] Pull request review %s: [%s](%s) by %s", repoLink, action, title, titleLink, senderLink)
  211. }
  212. return s.createPayload(text, nil), nil
  213. }
  214. // Repository implements PayloadConvertor Repository method
  215. func (s *SlackPayload) Repository(p *api.RepositoryPayload) (api.Payloader, error) {
  216. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  217. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  218. var text string
  219. switch p.Action {
  220. case api.HookRepoCreated:
  221. text = fmt.Sprintf("[%s] Repository created by %s", repoLink, senderLink)
  222. case api.HookRepoDeleted:
  223. text = fmt.Sprintf("[%s] Repository deleted by %s", repoLink, senderLink)
  224. }
  225. return s.createPayload(text, nil), nil
  226. }
  227. func (s *SlackPayload) createPayload(text string, attachments []SlackAttachment) *SlackPayload {
  228. return &SlackPayload{
  229. Channel: s.Channel,
  230. Text: text,
  231. Username: s.Username,
  232. IconURL: s.IconURL,
  233. Attachments: attachments,
  234. }
  235. }
  236. // GetSlackPayload converts a slack webhook into a SlackPayload
  237. func GetSlackPayload(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) {
  238. s := new(SlackPayload)
  239. slack := &SlackMeta{}
  240. if err := json.Unmarshal([]byte(meta), &slack); err != nil {
  241. return s, errors.New("GetSlackPayload meta json:" + err.Error())
  242. }
  243. s.Channel = slack.Channel
  244. s.Username = slack.Username
  245. s.IconURL = slack.IconURL
  246. s.Color = slack.Color
  247. return convertPayloader(s, p, event)
  248. }
  249. var slackChannel = regexp.MustCompile(`^#?[a-z0-9_-]{1,80}$`)
  250. // IsValidSlackChannel validates a channel name conforms to what slack expects:
  251. // https://api.slack.com/methods/conversations.rename#naming
  252. // Conversation names can only contain lowercase letters, numbers, hyphens, and underscores, and must be 80 characters or less.
  253. // Gitea accepts if it starts with a #.
  254. func IsValidSlackChannel(name string) bool {
  255. return slackChannel.MatchString(name)
  256. }