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.

386 lines
14 KiB

9 years ago
9 years ago
9 years ago
  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. // getSlackDeletePayload composes Slack payload for delete a branch or tag.
  94. func getSlackDeletePayload(p *api.DeletePayload, slack *SlackMeta) (*SlackPayload, error) {
  95. refName := git.RefEndName(p.Ref)
  96. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
  97. text := fmt.Sprintf("[%s:%s] %s deleted by %s", repoLink, refName, p.RefType, p.Sender.UserName)
  98. return &SlackPayload{
  99. Channel: slack.Channel,
  100. Text: text,
  101. Username: slack.Username,
  102. IconURL: slack.IconURL,
  103. }, nil
  104. }
  105. // getSlackForkPayload composes Slack payload for forked by a repository.
  106. func getSlackForkPayload(p *api.ForkPayload, slack *SlackMeta) (*SlackPayload, error) {
  107. baseLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
  108. forkLink := SlackLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName)
  109. text := fmt.Sprintf("%s is forked to %s", baseLink, forkLink)
  110. return &SlackPayload{
  111. Channel: slack.Channel,
  112. Text: text,
  113. Username: slack.Username,
  114. IconURL: slack.IconURL,
  115. }, nil
  116. }
  117. func getSlackIssuesPayload(p *api.IssuePayload, slack *SlackMeta) (*SlackPayload, error) {
  118. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  119. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  120. fmt.Sprintf("#%d %s", p.Index, p.Issue.Title))
  121. var text, title, attachmentText string
  122. switch p.Action {
  123. case api.HookIssueOpened:
  124. text = fmt.Sprintf("[%s] Issue submitted by %s", p.Repository.FullName, senderLink)
  125. title = titleLink
  126. attachmentText = SlackTextFormatter(p.Issue.Body)
  127. case api.HookIssueClosed:
  128. text = fmt.Sprintf("[%s] Issue closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
  129. case api.HookIssueReOpened:
  130. text = fmt.Sprintf("[%s] Issue re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
  131. case api.HookIssueEdited:
  132. text = fmt.Sprintf("[%s] Issue edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
  133. attachmentText = SlackTextFormatter(p.Issue.Body)
  134. case api.HookIssueAssigned:
  135. text = fmt.Sprintf("[%s] Issue assigned to %s: %s by %s", p.Repository.FullName,
  136. SlackLinkFormatter(setting.AppURL+p.Issue.Assignee.UserName, p.Issue.Assignee.UserName),
  137. titleLink, senderLink)
  138. case api.HookIssueUnassigned:
  139. text = fmt.Sprintf("[%s] Issue unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
  140. case api.HookIssueLabelUpdated:
  141. text = fmt.Sprintf("[%s] Issue labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
  142. case api.HookIssueLabelCleared:
  143. text = fmt.Sprintf("[%s] Issue labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
  144. case api.HookIssueSynchronized:
  145. text = fmt.Sprintf("[%s] Issue synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink)
  146. }
  147. return &SlackPayload{
  148. Channel: slack.Channel,
  149. Text: text,
  150. Username: slack.Username,
  151. IconURL: slack.IconURL,
  152. Attachments: []SlackAttachment{{
  153. Color: slack.Color,
  154. Title: title,
  155. Text: attachmentText,
  156. }},
  157. }, nil
  158. }
  159. func getSlackIssueCommentPayload(p *api.IssueCommentPayload, slack *SlackMeta) (*SlackPayload, error) {
  160. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  161. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/issues/%d#%s", p.Repository.HTMLURL, p.Issue.Index, CommentHashTag(p.Comment.ID)),
  162. fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
  163. var text, title, attachmentText string
  164. switch p.Action {
  165. case api.HookIssueCommentCreated:
  166. text = fmt.Sprintf("[%s] New comment created by %s", p.Repository.FullName, senderLink)
  167. title = titleLink
  168. attachmentText = SlackTextFormatter(p.Comment.Body)
  169. case api.HookIssueCommentEdited:
  170. text = fmt.Sprintf("[%s] Comment edited by %s", p.Repository.FullName, senderLink)
  171. title = titleLink
  172. attachmentText = SlackTextFormatter(p.Comment.Body)
  173. case api.HookIssueCommentDeleted:
  174. text = fmt.Sprintf("[%s] Comment deleted by %s", p.Repository.FullName, senderLink)
  175. title = SlackLinkFormatter(fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index),
  176. fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
  177. attachmentText = SlackTextFormatter(p.Comment.Body)
  178. }
  179. return &SlackPayload{
  180. Channel: slack.Channel,
  181. Text: text,
  182. Username: slack.Username,
  183. IconURL: slack.IconURL,
  184. Attachments: []SlackAttachment{{
  185. Color: slack.Color,
  186. Title: title,
  187. Text: attachmentText,
  188. }},
  189. }, nil
  190. }
  191. func getSlackReleasePayload(p *api.ReleasePayload, slack *SlackMeta) (*SlackPayload, error) {
  192. repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.Name)
  193. refLink := SlackLinkFormatter(p.Repository.HTMLURL+"/src/"+p.Release.TagName, p.Release.TagName)
  194. var text string
  195. switch p.Action {
  196. case api.HookReleasePublished:
  197. text = fmt.Sprintf("[%s] new release %s published by %s", repoLink, refLink, p.Sender.UserName)
  198. case api.HookReleaseUpdated:
  199. text = fmt.Sprintf("[%s] new release %s updated by %s", repoLink, refLink, p.Sender.UserName)
  200. case api.HookReleaseDeleted:
  201. text = fmt.Sprintf("[%s] new release %s deleted by %s", repoLink, refLink, p.Sender.UserName)
  202. }
  203. return &SlackPayload{
  204. Channel: slack.Channel,
  205. Text: text,
  206. Username: slack.Username,
  207. IconURL: slack.IconURL,
  208. }, nil
  209. }
  210. func getSlackPushPayload(p *api.PushPayload, slack *SlackMeta) (*SlackPayload, error) {
  211. // n new commits
  212. var (
  213. commitDesc string
  214. commitString string
  215. )
  216. if len(p.Commits) == 1 {
  217. commitDesc = "1 new commit"
  218. } else {
  219. commitDesc = fmt.Sprintf("%d new commits", len(p.Commits))
  220. }
  221. if len(p.CompareURL) > 0 {
  222. commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
  223. } else {
  224. commitString = commitDesc
  225. }
  226. repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
  227. branchLink := SlackLinkToRef(p.Repo.HTMLURL, p.Ref)
  228. text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
  229. var attachmentText string
  230. // for each commit, generate attachment text
  231. for i, commit := range p.Commits {
  232. attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
  233. // add linebreak to each commit but the last
  234. if i < len(p.Commits)-1 {
  235. attachmentText += "\n"
  236. }
  237. }
  238. return &SlackPayload{
  239. Channel: slack.Channel,
  240. Text: text,
  241. Username: slack.Username,
  242. IconURL: slack.IconURL,
  243. Attachments: []SlackAttachment{{
  244. Color: slack.Color,
  245. Text: attachmentText,
  246. }},
  247. }, nil
  248. }
  249. func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*SlackPayload, error) {
  250. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  251. titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
  252. fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
  253. var text, title, attachmentText string
  254. switch p.Action {
  255. case api.HookIssueOpened:
  256. text = fmt.Sprintf("[%s] Pull request submitted by %s", p.Repository.FullName, senderLink)
  257. title = titleLink
  258. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  259. case api.HookIssueClosed:
  260. if p.PullRequest.HasMerged {
  261. text = fmt.Sprintf("[%s] Pull request merged: %s by %s", p.Repository.FullName, titleLink, senderLink)
  262. } else {
  263. text = fmt.Sprintf("[%s] Pull request closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
  264. }
  265. case api.HookIssueReOpened:
  266. text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
  267. case api.HookIssueEdited:
  268. text = fmt.Sprintf("[%s] Pull request edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
  269. attachmentText = SlackTextFormatter(p.PullRequest.Body)
  270. case api.HookIssueAssigned:
  271. list, err := MakeAssigneeList(&Issue{ID: p.PullRequest.ID})
  272. if err != nil {
  273. return &SlackPayload{}, err
  274. }
  275. text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName,
  276. SlackLinkFormatter(setting.AppURL+list, list),
  277. titleLink, senderLink)
  278. case api.HookIssueUnassigned:
  279. text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
  280. case api.HookIssueLabelUpdated:
  281. text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
  282. case api.HookIssueLabelCleared:
  283. text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
  284. case api.HookIssueSynchronized:
  285. text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink)
  286. }
  287. return &SlackPayload{
  288. Channel: slack.Channel,
  289. Text: text,
  290. Username: slack.Username,
  291. IconURL: slack.IconURL,
  292. Attachments: []SlackAttachment{{
  293. Color: slack.Color,
  294. Title: title,
  295. Text: attachmentText,
  296. }},
  297. }, nil
  298. }
  299. func getSlackRepositoryPayload(p *api.RepositoryPayload, slack *SlackMeta) (*SlackPayload, error) {
  300. senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  301. var text, title, attachmentText string
  302. switch p.Action {
  303. case api.HookRepoCreated:
  304. text = fmt.Sprintf("[%s] Repository created by %s", p.Repository.FullName, senderLink)
  305. title = p.Repository.HTMLURL
  306. case api.HookRepoDeleted:
  307. text = fmt.Sprintf("[%s] Repository deleted by %s", p.Repository.FullName, senderLink)
  308. }
  309. return &SlackPayload{
  310. Channel: slack.Channel,
  311. Text: text,
  312. Username: slack.Username,
  313. IconURL: slack.IconURL,
  314. Attachments: []SlackAttachment{{
  315. Color: slack.Color,
  316. Title: title,
  317. Text: attachmentText,
  318. }},
  319. }, nil
  320. }
  321. // GetSlackPayload converts a slack webhook into a SlackPayload
  322. func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (*SlackPayload, error) {
  323. s := new(SlackPayload)
  324. slack := &SlackMeta{}
  325. if err := json.Unmarshal([]byte(meta), &slack); err != nil {
  326. return s, errors.New("GetSlackPayload meta json:" + err.Error())
  327. }
  328. switch event {
  329. case HookEventCreate:
  330. return getSlackCreatePayload(p.(*api.CreatePayload), slack)
  331. case HookEventDelete:
  332. return getSlackDeletePayload(p.(*api.DeletePayload), slack)
  333. case HookEventFork:
  334. return getSlackForkPayload(p.(*api.ForkPayload), slack)
  335. case HookEventIssues:
  336. return getSlackIssuesPayload(p.(*api.IssuePayload), slack)
  337. case HookEventIssueComment:
  338. return getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
  339. case HookEventPush:
  340. return getSlackPushPayload(p.(*api.PushPayload), slack)
  341. case HookEventPullRequest:
  342. return getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
  343. case HookEventRepository:
  344. return getSlackRepositoryPayload(p.(*api.RepositoryPayload), slack)
  345. case HookEventRelease:
  346. return getSlackReleasePayload(p.(*api.ReleasePayload), slack)
  347. }
  348. return s, nil
  349. }