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_slack.go 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 models
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "strings"
  10. "code.gitea.io/git"
  11. api "code.gitea.io/sdk/gitea"
  12. "code.gitea.io/gitea/modules/setting"
  13. )
  14. // SlackMeta contains the slack metadata
  15. type SlackMeta struct {
  16. Channel string `json:"channel"`
  17. Username string `json:"username"`
  18. IconURL string `json:"icon_url"`
  19. Color string `json:"color"`
  20. }
  21. // SlackPayload contains the information about the slack channel
  22. type SlackPayload struct {
  23. Channel string `json:"channel"`
  24. Text string `json:"text"`
  25. Username string `json:"username"`
  26. IconURL string `json:"icon_url"`
  27. UnfurlLinks int `json:"unfurl_links"`
  28. LinkNames int `json:"link_names"`
  29. Attachments []SlackAttachment `json:"attachments"`
  30. }
  31. // SlackAttachment contains the slack message
  32. type SlackAttachment struct {
  33. Fallback string `json:"fallback"`
  34. Color string `json:"color"`
  35. Title string `json:"title"`
  36. Text string `json:"text"`
  37. }
  38. // SetSecret sets the slack secret
  39. func (p *SlackPayload) SetSecret(_ string) {}
  40. // JSONPayload Marshals the SlackPayload to json
  41. func (p *SlackPayload) JSONPayload() ([]byte, error) {
  42. data, err := json.MarshalIndent(p, "", " ")
  43. if err != nil {
  44. return []byte{}, err
  45. }
  46. return data, nil
  47. }
  48. // SlackTextFormatter replaces &, <, > with HTML characters
  49. // see: https://api.slack.com/docs/formatting
  50. func SlackTextFormatter(s string) string {
  51. // replace & < >
  52. s = strings.Replace(s, "&", "&amp;", -1)
  53. s = strings.Replace(s, "<", "&lt;", -1)
  54. s = strings.Replace(s, ">", "&gt;", -1)
  55. return s
  56. }
  57. // SlackShortTextFormatter replaces &, <, > with HTML characters
  58. func SlackShortTextFormatter(s string) string {
  59. s = strings.Split(s, "\n")[0]
  60. // replace & < >
  61. s = strings.Replace(s, "&", "&amp;", -1)
  62. s = strings.Replace(s, "<", "&lt;", -1)
  63. s = strings.Replace(s, ">", "&gt;", -1)
  64. return s
  65. }
  66. // SlackLinkFormatter creates a link compatible with slack
  67. func SlackLinkFormatter(url string, text string) string {
  68. return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
  69. }
  70. // SlackLinkToRef slack-formatter link to a repo ref
  71. func SlackLinkToRef(repoURL, ref string) string {
  72. refName := git.RefEndName(ref)
  73. switch {
  74. case strings.HasPrefix(ref, git.BranchPrefix):
  75. return SlackLinkFormatter(repoURL+"/src/branch/"+refName, refName)
  76. case strings.HasPrefix(ref, git.TagPrefix):
  77. return SlackLinkFormatter(repoURL+"/src/tag/"+refName, refName)
  78. default:
  79. return SlackLinkFormatter(repoURL+"/src/commit/"+refName, refName)
  80. }
  81. }
  82. func getSlackCreatePayload(p *api.CreatePayload, slack *SlackMeta) (*SlackPayload, error) {
  83. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
  84. refLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  85. text := fmt.Sprintf("[%s:%s] %s created by %s", repoLink, refLink, p.RefType, p.Sender.UserName)
  86. return &SlackPayload{
  87. Channel: slack.Channel,
  88. Text: text,
  89. Username: slack.Username,
  90. IconURL: slack.IconURL,
  91. }, nil
  92. }
  93. func getSlackPushPayload(p *api.PushPayload, slack *SlackMeta) (*SlackPayload, error) {
  94. // n new commits
  95. var (
  96. commitDesc string
  97. commitString string
  98. )
  99. if len(p.Commits) == 1 {
  100. commitDesc = "1 new commit"
  101. } else {
  102. commitDesc = fmt.Sprintf("%d new commits", len(p.Commits))
  103. }
  104. if len(p.CompareURL) > 0 {
  105. commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
  106. } else {
  107. commitString = commitDesc
  108. }
  109. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
  110. branchLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  111. text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
  112. var attachmentText string
  113. // for each commit, generate attachment text
  114. for i, commit := range p.Commits {
  115. attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
  116. // add linebreak to each commit but the last
  117. if i < len(p.Commits)-1 {
  118. attachmentText += "\n"
  119. }
  120. }
  121. return &SlackPayload{
  122. Channel: slack.Channel,
  123. Text: text,
  124. Username: slack.Username,
  125. IconURL: slack.IconURL,
  126. Attachments: []SlackAttachment{{
  127. Color: slack.Color,
  128. Text: attachmentText,
  129. }},
  130. }, nil
  131. }
  132. func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*SlackPayload, error) {
  133. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  134. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  135. fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
  136. var text, title, attachmentText string
  137. switch p.Action {
  138. case api.HookIssueOpened:
  139. text = fmt.Sprintf("[%s] Pull request submitted by %s", p.Repository.FullName, senderLink)
  140. title = titleLink
  141. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  142. case api.HookIssueClosed:
  143. if p.PullRequest.HasMerged {
  144. text = fmt.Sprintf("[%s] Pull request merged: %s by %s", p.Repository.FullName, titleLink, senderLink)
  145. } else {
  146. text = fmt.Sprintf("[%s] Pull request closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
  147. }
  148. case api.HookIssueReOpened:
  149. text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
  150. case api.HookIssueEdited:
  151. text = fmt.Sprintf("[%s] Pull request edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
  152. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  153. case api.HookIssueAssigned:
  154. text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName,
  155. SlackLinkFormatter(setting.AppURL+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName),
  156. titleLink, senderLink)
  157. case api.HookIssueUnassigned:
  158. text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
  159. case api.HookIssueLabelUpdated:
  160. text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
  161. case api.HookIssueLabelCleared:
  162. text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
  163. case api.HookIssueSynchronized:
  164. text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink)
  165. }
  166. return &SlackPayload{
  167. Channel: slack.Channel,
  168. Text: text,
  169. Username: slack.Username,
  170. IconURL: slack.IconURL,
  171. Attachments: []SlackAttachment{{
  172. Color: slack.Color,
  173. Title: title,
  174. Text: attachmentText,
  175. }},
  176. }, nil
  177. }
  178. func getSlackRepositoryPayload(p *api.RepositoryPayload, slack *SlackMeta) (*SlackPayload, error) {
  179. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  180. var text, title, attachmentText string
  181. switch p.Action {
  182. case api.HookRepoCreated:
  183. text = fmt.Sprintf("[%s] Repository created by %s", p.Repository.FullName, senderLink)
  184. title = p.Repository.HTMLURL
  185. case api.HookRepoDeleted:
  186. text = fmt.Sprintf("[%s] Repository deleted by %s", p.Repository.FullName, senderLink)
  187. }
  188. return &SlackPayload{
  189. Channel: slack.Channel,
  190. Text: text,
  191. Username: slack.Username,
  192. IconURL: slack.IconURL,
  193. Attachments: []SlackAttachment{{
  194. Color: slack.Color,
  195. Title: title,
  196. Text: attachmentText,
  197. }},
  198. }, nil
  199. }
  200. // GetSlackPayload converts a slack webhook into a SlackPayload
  201. func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (*SlackPayload, error) {
  202. s := new(SlackPayload)
  203. slack := &SlackMeta{}
  204. if err := json.Unmarshal([]byte(meta), &slack); err != nil {
  205. return s, errors.New("GetSlackPayload meta json:" + err.Error())
  206. }
  207. switch event {
  208. case HookEventCreate:
  209. return getSlackCreatePayload(p.(*api.CreatePayload), slack)
  210. case HookEventPush:
  211. return getSlackPushPayload(p.(*api.PushPayload), slack)
  212. case HookEventPullRequest:
  213. return getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
  214. case HookEventRepository:
  215. return getSlackRepositoryPayload(p.(*api.RepositoryPayload), slack)
  216. }
  217. return s, nil
  218. }