You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

slack.go 16 kB

10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. api "code.gitea.io/gitea/modules/structs"
  15. )
  16. // SlackMeta contains the slack metadata
  17. type SlackMeta struct {
  18. Channel string `json:"channel"`
  19. Username string `json:"username"`
  20. IconURL string `json:"icon_url"`
  21. Color string `json:"color"`
  22. }
  23. // GetSlackHook returns slack metadata
  24. func GetSlackHook(w *models.Webhook) *SlackMeta {
  25. s := &SlackMeta{}
  26. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  27. log.Error("webhook.GetSlackHook(%d): %v", w.ID, err)
  28. }
  29. return s
  30. }
  31. // SlackPayload contains the information about the slack channel
  32. type SlackPayload struct {
  33. Channel string `json:"channel"`
  34. Text string `json:"text"`
  35. Username string `json:"username"`
  36. IconURL string `json:"icon_url"`
  37. UnfurlLinks int `json:"unfurl_links"`
  38. LinkNames int `json:"link_names"`
  39. Attachments []SlackAttachment `json:"attachments"`
  40. }
  41. // SlackAttachment contains the slack message
  42. type SlackAttachment struct {
  43. Fallback string `json:"fallback"`
  44. Color string `json:"color"`
  45. Title string `json:"title"`
  46. Text string `json:"text"`
  47. }
  48. // SetSecret sets the slack secret
  49. func (p *SlackPayload) SetSecret(_ string) {}
  50. // JSONPayload Marshals the SlackPayload to json
  51. func (p *SlackPayload) JSONPayload() ([]byte, error) {
  52. data, err := json.MarshalIndent(p, "", " ")
  53. if err != nil {
  54. return []byte{}, err
  55. }
  56. return data, nil
  57. }
  58. // SlackTextFormatter replaces &, <, > with HTML characters
  59. // see: https://api.slack.com/docs/formatting
  60. func SlackTextFormatter(s string) string {
  61. // replace & < >
  62. s = strings.Replace(s, "&", "&amp;", -1)
  63. s = strings.Replace(s, "<", "&lt;", -1)
  64. s = strings.Replace(s, ">", "&gt;", -1)
  65. return s
  66. }
  67. // SlackShortTextFormatter replaces &, <, > with HTML characters
  68. func SlackShortTextFormatter(s string) string {
  69. s = strings.Split(s, "\n")[0]
  70. // replace & < >
  71. s = strings.Replace(s, "&", "&amp;", -1)
  72. s = strings.Replace(s, "<", "&lt;", -1)
  73. s = strings.Replace(s, ">", "&gt;", -1)
  74. return s
  75. }
  76. // SlackLinkFormatter creates a link compatible with slack
  77. func SlackLinkFormatter(url string, text string) string {
  78. return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
  79. }
  80. // SlackLinkToRef slack-formatter link to a repo ref
  81. func SlackLinkToRef(repoURL, ref string) string {
  82. refName := git.RefEndName(ref)
  83. switch {
  84. case strings.HasPrefix(ref, git.BranchPrefix):
  85. return SlackLinkFormatter(repoURL+"/src/branch/"+refName, refName)
  86. case strings.HasPrefix(ref, git.TagPrefix):
  87. return SlackLinkFormatter(repoURL+"/src/tag/"+refName, refName)
  88. default:
  89. return SlackLinkFormatter(repoURL+"/src/commit/"+refName, refName)
  90. }
  91. }
  92. func getSlackCreatePayload(p *api.CreatePayload, slack *SlackMeta) (*SlackPayload, error) {
  93. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  94. refLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  95. text := fmt.Sprintf("[%s:%s] %s created by %s", repoLink, refLink, p.RefType, p.Sender.UserName)
  96. return &SlackPayload{
  97. Channel: slack.Channel,
  98. Text: text,
  99. Username: slack.Username,
  100. IconURL: slack.IconURL,
  101. }, nil
  102. }
  103. // getSlackDeletePayload composes Slack payload for delete a branch or tag.
  104. func getSlackDeletePayload(p *api.DeletePayload, slack *SlackMeta) (*SlackPayload, error) {
  105. refName := git.RefEndName(p.Ref)
  106. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  107. text := fmt.Sprintf("[%s:%s] %s deleted by %s", repoLink, refName, p.RefType, p.Sender.UserName)
  108. return &SlackPayload{
  109. Channel: slack.Channel,
  110. Text: text,
  111. Username: slack.Username,
  112. IconURL: slack.IconURL,
  113. }, nil
  114. }
  115. // getSlackForkPayload composes Slack payload for forked by a repository.
  116. func getSlackForkPayload(p *api.ForkPayload, slack *SlackMeta) (*SlackPayload, error) {
  117. baseLink := SlackLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName)
  118. forkLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  119. text := fmt.Sprintf("%s is forked to %s", baseLink, forkLink)
  120. return &SlackPayload{
  121. Channel: slack.Channel,
  122. Text: text,
  123. Username: slack.Username,
  124. IconURL: slack.IconURL,
  125. }, nil
  126. }
  127. func getSlackIssuesPayload(p *api.IssuePayload, slack *SlackMeta) (*SlackPayload, error) {
  128. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  129. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  130. fmt.Sprintf("#%d %s", p.Index, p.Issue.Title))
  131. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  132. var text, title, attachmentText string
  133. switch p.Action {
  134. case api.HookIssueOpened:
  135. text = fmt.Sprintf("[%s] Issue submitted by %s", repoLink, senderLink)
  136. title = titleLink
  137. attachmentText = SlackTextFormatter(p.Issue.Body)
  138. case api.HookIssueClosed:
  139. text = fmt.Sprintf("[%s] Issue closed: %s by %s", repoLink, titleLink, senderLink)
  140. case api.HookIssueReOpened:
  141. text = fmt.Sprintf("[%s] Issue re-opened: %s by %s", repoLink, titleLink, senderLink)
  142. case api.HookIssueEdited:
  143. text = fmt.Sprintf("[%s] Issue edited: %s by %s", repoLink, titleLink, senderLink)
  144. attachmentText = SlackTextFormatter(p.Issue.Body)
  145. case api.HookIssueAssigned:
  146. text = fmt.Sprintf("[%s] Issue assigned to %s: %s by %s", repoLink,
  147. SlackLinkFormatter(setting.AppURL+p.Issue.Assignee.UserName, p.Issue.Assignee.UserName),
  148. titleLink, senderLink)
  149. case api.HookIssueUnassigned:
  150. text = fmt.Sprintf("[%s] Issue unassigned: %s by %s", repoLink, titleLink, senderLink)
  151. case api.HookIssueLabelUpdated:
  152. text = fmt.Sprintf("[%s] Issue labels updated: %s by %s", repoLink, titleLink, senderLink)
  153. case api.HookIssueLabelCleared:
  154. text = fmt.Sprintf("[%s] Issue labels cleared: %s by %s", repoLink, titleLink, senderLink)
  155. case api.HookIssueSynchronized:
  156. text = fmt.Sprintf("[%s] Issue synchronized: %s by %s", repoLink, titleLink, senderLink)
  157. case api.HookIssueMilestoned:
  158. text = fmt.Sprintf("[%s] Issue milestoned: #%s %s", repoLink, titleLink, senderLink)
  159. case api.HookIssueDemilestoned:
  160. text = fmt.Sprintf("[%s] Issue milestone cleared: #%s %s", repoLink, titleLink, senderLink)
  161. }
  162. return &SlackPayload{
  163. Channel: slack.Channel,
  164. Text: text,
  165. Username: slack.Username,
  166. IconURL: slack.IconURL,
  167. Attachments: []SlackAttachment{{
  168. Color: slack.Color,
  169. Title: title,
  170. Text: attachmentText,
  171. }},
  172. }, nil
  173. }
  174. func getSlackIssueCommentPayload(p *api.IssueCommentPayload, slack *SlackMeta) (*SlackPayload, error) {
  175. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  176. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/issues/%d#%s", p.Repository.HTMLURL, p.Issue.Index, models.CommentHashTag(p.Comment.ID)),
  177. fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
  178. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  179. var text, title, attachmentText string
  180. switch p.Action {
  181. case api.HookIssueCommentCreated:
  182. text = fmt.Sprintf("[%s] New comment created by %s", repoLink, senderLink)
  183. title = titleLink
  184. attachmentText = SlackTextFormatter(p.Comment.Body)
  185. case api.HookIssueCommentEdited:
  186. text = fmt.Sprintf("[%s] Comment edited by %s", repoLink, senderLink)
  187. title = titleLink
  188. attachmentText = SlackTextFormatter(p.Comment.Body)
  189. case api.HookIssueCommentDeleted:
  190. text = fmt.Sprintf("[%s] Comment deleted by %s", repoLink, senderLink)
  191. title = SlackLinkFormatter(fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index),
  192. fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
  193. attachmentText = SlackTextFormatter(p.Comment.Body)
  194. }
  195. return &SlackPayload{
  196. Channel: slack.Channel,
  197. Text: text,
  198. Username: slack.Username,
  199. IconURL: slack.IconURL,
  200. Attachments: []SlackAttachment{{
  201. Color: slack.Color,
  202. Title: title,
  203. Text: attachmentText,
  204. }},
  205. }, nil
  206. }
  207. func getSlackReleasePayload(p *api.ReleasePayload, slack *SlackMeta) (*SlackPayload, error) {
  208. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  209. refLink := SlackLinkFormatter(p.Repository.HTMLURL+"/src/"+p.Release.TagName, p.Release.TagName)
  210. var text string
  211. switch p.Action {
  212. case api.HookReleasePublished:
  213. text = fmt.Sprintf("[%s] new release %s published by %s", repoLink, refLink, p.Sender.UserName)
  214. case api.HookReleaseUpdated:
  215. text = fmt.Sprintf("[%s] new release %s updated by %s", repoLink, refLink, p.Sender.UserName)
  216. case api.HookReleaseDeleted:
  217. text = fmt.Sprintf("[%s] new release %s deleted by %s", repoLink, refLink, p.Sender.UserName)
  218. }
  219. return &SlackPayload{
  220. Channel: slack.Channel,
  221. Text: text,
  222. Username: slack.Username,
  223. IconURL: slack.IconURL,
  224. }, nil
  225. }
  226. func getSlackPushPayload(p *api.PushPayload, slack *SlackMeta) (*SlackPayload, error) {
  227. // n new commits
  228. var (
  229. commitDesc string
  230. commitString string
  231. )
  232. if len(p.Commits) == 1 {
  233. commitDesc = "1 new commit"
  234. } else {
  235. commitDesc = fmt.Sprintf("%d new commits", len(p.Commits))
  236. }
  237. if len(p.CompareURL) > 0 {
  238. commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
  239. } else {
  240. commitString = commitDesc
  241. }
  242. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  243. branchLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  244. text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
  245. var attachmentText string
  246. // for each commit, generate attachment text
  247. for i, commit := range p.Commits {
  248. attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
  249. // add linebreak to each commit but the last
  250. if i < len(p.Commits)-1 {
  251. attachmentText += "\n"
  252. }
  253. }
  254. return &SlackPayload{
  255. Channel: slack.Channel,
  256. Text: text,
  257. Username: slack.Username,
  258. IconURL: slack.IconURL,
  259. Attachments: []SlackAttachment{{
  260. Color: slack.Color,
  261. Text: attachmentText,
  262. }},
  263. }, nil
  264. }
  265. func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*SlackPayload, error) {
  266. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  267. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  268. fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
  269. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  270. var text, title, attachmentText string
  271. switch p.Action {
  272. case api.HookIssueOpened:
  273. text = fmt.Sprintf("[%s] Pull request submitted by %s", repoLink, senderLink)
  274. title = titleLink
  275. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  276. case api.HookIssueClosed:
  277. if p.PullRequest.HasMerged {
  278. text = fmt.Sprintf("[%s] Pull request merged: %s by %s", repoLink, titleLink, senderLink)
  279. } else {
  280. text = fmt.Sprintf("[%s] Pull request closed: %s by %s", repoLink, titleLink, senderLink)
  281. }
  282. case api.HookIssueReOpened:
  283. text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", repoLink, titleLink, senderLink)
  284. case api.HookIssueEdited:
  285. text = fmt.Sprintf("[%s] Pull request edited: %s by %s", repoLink, titleLink, senderLink)
  286. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  287. case api.HookIssueAssigned:
  288. list := make([]string, len(p.PullRequest.Assignees))
  289. for i, user := range p.PullRequest.Assignees {
  290. list[i] = SlackLinkFormatter(setting.AppURL+user.UserName, user.UserName)
  291. }
  292. text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", repoLink,
  293. strings.Join(list, ", "),
  294. titleLink, senderLink)
  295. case api.HookIssueUnassigned:
  296. text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", repoLink, titleLink, senderLink)
  297. case api.HookIssueLabelUpdated:
  298. text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", repoLink, titleLink, senderLink)
  299. case api.HookIssueLabelCleared:
  300. text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", repoLink, titleLink, senderLink)
  301. case api.HookIssueSynchronized:
  302. text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", repoLink, titleLink, senderLink)
  303. case api.HookIssueMilestoned:
  304. text = fmt.Sprintf("[%s] Pull request milestoned: #%s %s", repoLink, titleLink, senderLink)
  305. case api.HookIssueDemilestoned:
  306. text = fmt.Sprintf("[%s] Pull request milestone cleared: #%s %s", repoLink, titleLink, senderLink)
  307. }
  308. return &SlackPayload{
  309. Channel: slack.Channel,
  310. Text: text,
  311. Username: slack.Username,
  312. IconURL: slack.IconURL,
  313. Attachments: []SlackAttachment{{
  314. Color: slack.Color,
  315. Title: title,
  316. Text: attachmentText,
  317. }},
  318. }, nil
  319. }
  320. func getSlackPullRequestApprovalPayload(p *api.PullRequestPayload, slack *SlackMeta, event models.HookEventType) (*SlackPayload, error) {
  321. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  322. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  323. fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
  324. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  325. var text, title, attachmentText string
  326. switch p.Action {
  327. case api.HookIssueSynchronized:
  328. action, err := parseHookPullRequestEventType(event)
  329. if err != nil {
  330. return nil, err
  331. }
  332. text = fmt.Sprintf("[%s] Pull request review %s : %s by %s", repoLink, action, titleLink, senderLink)
  333. }
  334. return &SlackPayload{
  335. Channel: slack.Channel,
  336. Text: text,
  337. Username: slack.Username,
  338. IconURL: slack.IconURL,
  339. Attachments: []SlackAttachment{{
  340. Color: slack.Color,
  341. Title: title,
  342. Text: attachmentText,
  343. }},
  344. }, nil
  345. }
  346. func getSlackRepositoryPayload(p *api.RepositoryPayload, slack *SlackMeta) (*SlackPayload, error) {
  347. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  348. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  349. var text, title, attachmentText string
  350. switch p.Action {
  351. case api.HookRepoCreated:
  352. text = fmt.Sprintf("[%s] Repository created by %s", repoLink, senderLink)
  353. title = p.Repository.HTMLURL
  354. case api.HookRepoDeleted:
  355. text = fmt.Sprintf("[%s] Repository deleted by %s", repoLink, senderLink)
  356. }
  357. return &SlackPayload{
  358. Channel: slack.Channel,
  359. Text: text,
  360. Username: slack.Username,
  361. IconURL: slack.IconURL,
  362. Attachments: []SlackAttachment{{
  363. Color: slack.Color,
  364. Title: title,
  365. Text: attachmentText,
  366. }},
  367. }, nil
  368. }
  369. // GetSlackPayload converts a slack webhook into a SlackPayload
  370. func GetSlackPayload(p api.Payloader, event models.HookEventType, meta string) (*SlackPayload, error) {
  371. s := new(SlackPayload)
  372. slack := &SlackMeta{}
  373. if err := json.Unmarshal([]byte(meta), &slack); err != nil {
  374. return s, errors.New("GetSlackPayload meta json:" + err.Error())
  375. }
  376. switch event {
  377. case models.HookEventCreate:
  378. return getSlackCreatePayload(p.(*api.CreatePayload), slack)
  379. case models.HookEventDelete:
  380. return getSlackDeletePayload(p.(*api.DeletePayload), slack)
  381. case models.HookEventFork:
  382. return getSlackForkPayload(p.(*api.ForkPayload), slack)
  383. case models.HookEventIssues:
  384. return getSlackIssuesPayload(p.(*api.IssuePayload), slack)
  385. case models.HookEventIssueComment:
  386. return getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
  387. case models.HookEventPush:
  388. return getSlackPushPayload(p.(*api.PushPayload), slack)
  389. case models.HookEventPullRequest:
  390. return getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
  391. case models.HookEventPullRequestRejected, models.HookEventPullRequestApproved, models.HookEventPullRequestComment:
  392. return getSlackPullRequestApprovalPayload(p.(*api.PullRequestPayload), slack, event)
  393. case models.HookEventRepository:
  394. return getSlackRepositoryPayload(p.(*api.RepositoryPayload), slack)
  395. case models.HookEventRelease:
  396. return getSlackReleasePayload(p.(*api.ReleasePayload), slack)
  397. }
  398. return s, nil
  399. }