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 17 kB

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