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.

matrix.go 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package webhook
  4. import (
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "html"
  10. "net/url"
  11. "regexp"
  12. "strings"
  13. webhook_model "code.gitea.io/gitea/models/webhook"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/json"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. api "code.gitea.io/gitea/modules/structs"
  19. "code.gitea.io/gitea/modules/util"
  20. webhook_module "code.gitea.io/gitea/modules/webhook"
  21. )
  22. const matrixPayloadSizeLimit = 1024 * 64
  23. // MatrixMeta contains the Matrix metadata
  24. type MatrixMeta struct {
  25. HomeserverURL string `json:"homeserver_url"`
  26. Room string `json:"room_id"`
  27. MessageType int `json:"message_type"`
  28. }
  29. var messageTypeText = map[int]string{
  30. 1: "m.notice",
  31. 2: "m.text",
  32. }
  33. // GetMatrixHook returns Matrix metadata
  34. func GetMatrixHook(w *webhook_model.Webhook) *MatrixMeta {
  35. s := &MatrixMeta{}
  36. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  37. log.Error("webhook.GetMatrixHook(%d): %v", w.ID, err)
  38. }
  39. return s
  40. }
  41. var _ PayloadConvertor = &MatrixPayload{}
  42. // MatrixPayload contains payload for a Matrix room
  43. type MatrixPayload struct {
  44. Body string `json:"body"`
  45. MsgType string `json:"msgtype"`
  46. Format string `json:"format"`
  47. FormattedBody string `json:"formatted_body"`
  48. Commits []*api.PayloadCommit `json:"io.gitea.commits,omitempty"`
  49. }
  50. // JSONPayload Marshals the MatrixPayload to json
  51. func (m *MatrixPayload) JSONPayload() ([]byte, error) {
  52. data, err := json.MarshalIndent(m, "", " ")
  53. if err != nil {
  54. return []byte{}, err
  55. }
  56. return data, nil
  57. }
  58. // MatrixLinkFormatter creates a link compatible with Matrix
  59. func MatrixLinkFormatter(url, text string) string {
  60. return fmt.Sprintf(`<a href="%s">%s</a>`, html.EscapeString(url), html.EscapeString(text))
  61. }
  62. // MatrixLinkToRef Matrix-formatter link to a repo ref
  63. func MatrixLinkToRef(repoURL, ref string) string {
  64. refName := git.RefName(ref).ShortName()
  65. switch {
  66. case strings.HasPrefix(ref, git.BranchPrefix):
  67. return MatrixLinkFormatter(repoURL+"/src/branch/"+util.PathEscapeSegments(refName), refName)
  68. case strings.HasPrefix(ref, git.TagPrefix):
  69. return MatrixLinkFormatter(repoURL+"/src/tag/"+util.PathEscapeSegments(refName), refName)
  70. default:
  71. return MatrixLinkFormatter(repoURL+"/src/commit/"+util.PathEscapeSegments(refName), refName)
  72. }
  73. }
  74. // Create implements PayloadConvertor Create method
  75. func (m *MatrixPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
  76. repoLink := MatrixLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  77. refLink := MatrixLinkToRef(p.Repo.HTMLURL, p.Ref)
  78. text := fmt.Sprintf("[%s:%s] %s created by %s", repoLink, refLink, p.RefType, p.Sender.UserName)
  79. return getMatrixPayload(text, nil, m.MsgType), nil
  80. }
  81. // Delete composes Matrix payload for delete a branch or tag.
  82. func (m *MatrixPayload) Delete(p *api.DeletePayload) (api.Payloader, error) {
  83. refName := git.RefName(p.Ref).ShortName()
  84. repoLink := MatrixLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  85. text := fmt.Sprintf("[%s:%s] %s deleted by %s", repoLink, refName, p.RefType, p.Sender.UserName)
  86. return getMatrixPayload(text, nil, m.MsgType), nil
  87. }
  88. // Fork composes Matrix payload for forked by a repository.
  89. func (m *MatrixPayload) Fork(p *api.ForkPayload) (api.Payloader, error) {
  90. baseLink := MatrixLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName)
  91. forkLink := MatrixLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  92. text := fmt.Sprintf("%s is forked to %s", baseLink, forkLink)
  93. return getMatrixPayload(text, nil, m.MsgType), nil
  94. }
  95. // Issue implements PayloadConvertor Issue method
  96. func (m *MatrixPayload) Issue(p *api.IssuePayload) (api.Payloader, error) {
  97. text, _, _, _ := getIssuesPayloadInfo(p, MatrixLinkFormatter, true)
  98. return getMatrixPayload(text, nil, m.MsgType), nil
  99. }
  100. // IssueComment implements PayloadConvertor IssueComment method
  101. func (m *MatrixPayload) IssueComment(p *api.IssueCommentPayload) (api.Payloader, error) {
  102. text, _, _ := getIssueCommentPayloadInfo(p, MatrixLinkFormatter, true)
  103. return getMatrixPayload(text, nil, m.MsgType), nil
  104. }
  105. // Wiki implements PayloadConvertor Wiki method
  106. func (m *MatrixPayload) Wiki(p *api.WikiPayload) (api.Payloader, error) {
  107. text, _, _ := getWikiPayloadInfo(p, MatrixLinkFormatter, true)
  108. return getMatrixPayload(text, nil, m.MsgType), nil
  109. }
  110. // Release implements PayloadConvertor Release method
  111. func (m *MatrixPayload) Release(p *api.ReleasePayload) (api.Payloader, error) {
  112. text, _ := getReleasePayloadInfo(p, MatrixLinkFormatter, true)
  113. return getMatrixPayload(text, nil, m.MsgType), nil
  114. }
  115. // Push implements PayloadConvertor Push method
  116. func (m *MatrixPayload) Push(p *api.PushPayload) (api.Payloader, error) {
  117. var commitDesc string
  118. if p.TotalCommits == 1 {
  119. commitDesc = "1 commit"
  120. } else {
  121. commitDesc = fmt.Sprintf("%d commits", p.TotalCommits)
  122. }
  123. repoLink := MatrixLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)
  124. branchLink := MatrixLinkToRef(p.Repo.HTMLURL, p.Ref)
  125. text := fmt.Sprintf("[%s] %s pushed %s to %s:<br>", repoLink, p.Pusher.UserName, commitDesc, branchLink)
  126. // for each commit, generate a new line text
  127. for i, commit := range p.Commits {
  128. text += fmt.Sprintf("%s: %s - %s", MatrixLinkFormatter(commit.URL, commit.ID[:7]), commit.Message, commit.Author.Name)
  129. // add linebreak to each commit but the last
  130. if i < len(p.Commits)-1 {
  131. text += "<br>"
  132. }
  133. }
  134. return getMatrixPayload(text, p.Commits, m.MsgType), nil
  135. }
  136. // PullRequest implements PayloadConvertor PullRequest method
  137. func (m *MatrixPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, error) {
  138. text, _, _, _ := getPullRequestPayloadInfo(p, MatrixLinkFormatter, true)
  139. return getMatrixPayload(text, nil, m.MsgType), nil
  140. }
  141. // Review implements PayloadConvertor Review method
  142. func (m *MatrixPayload) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (api.Payloader, error) {
  143. senderLink := MatrixLinkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)
  144. title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)
  145. titleLink := MatrixLinkFormatter(p.PullRequest.HTMLURL, title)
  146. repoLink := MatrixLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  147. var text string
  148. switch p.Action {
  149. case api.HookIssueReviewed:
  150. action, err := parseHookPullRequestEventType(event)
  151. if err != nil {
  152. return nil, err
  153. }
  154. text = fmt.Sprintf("[%s] Pull request review %s: %s by %s", repoLink, action, titleLink, senderLink)
  155. }
  156. return getMatrixPayload(text, nil, m.MsgType), nil
  157. }
  158. // Repository implements PayloadConvertor Repository method
  159. func (m *MatrixPayload) Repository(p *api.RepositoryPayload) (api.Payloader, error) {
  160. senderLink := MatrixLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  161. repoLink := MatrixLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)
  162. var text string
  163. switch p.Action {
  164. case api.HookRepoCreated:
  165. text = fmt.Sprintf("[%s] Repository created by %s", repoLink, senderLink)
  166. case api.HookRepoDeleted:
  167. text = fmt.Sprintf("[%s] Repository deleted by %s", repoLink, senderLink)
  168. }
  169. return getMatrixPayload(text, nil, m.MsgType), nil
  170. }
  171. func (m *MatrixPayload) Package(p *api.PackagePayload) (api.Payloader, error) {
  172. senderLink := MatrixLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)
  173. packageLink := MatrixLinkFormatter(p.Package.HTMLURL, p.Package.Name)
  174. var text string
  175. switch p.Action {
  176. case api.HookPackageCreated:
  177. text = fmt.Sprintf("[%s] Package published by %s", packageLink, senderLink)
  178. case api.HookPackageDeleted:
  179. text = fmt.Sprintf("[%s] Package deleted by %s", packageLink, senderLink)
  180. }
  181. return getMatrixPayload(text, nil, m.MsgType), nil
  182. }
  183. // GetMatrixPayload converts a Matrix webhook into a MatrixPayload
  184. func GetMatrixPayload(p api.Payloader, event webhook_module.HookEventType, meta string) (api.Payloader, error) {
  185. s := new(MatrixPayload)
  186. matrix := &MatrixMeta{}
  187. if err := json.Unmarshal([]byte(meta), &matrix); err != nil {
  188. return s, errors.New("GetMatrixPayload meta json:" + err.Error())
  189. }
  190. s.MsgType = messageTypeText[matrix.MessageType]
  191. return convertPayloader(s, p, event)
  192. }
  193. func getMatrixPayload(text string, commits []*api.PayloadCommit, msgType string) *MatrixPayload {
  194. p := MatrixPayload{}
  195. p.FormattedBody = text
  196. p.Body = getMessageBody(text)
  197. p.Format = "org.matrix.custom.html"
  198. p.MsgType = msgType
  199. p.Commits = commits
  200. return &p
  201. }
  202. var urlRegex = regexp.MustCompile(`<a [^>]*?href="([^">]*?)">(.*?)</a>`)
  203. func getMessageBody(htmlText string) string {
  204. htmlText = urlRegex.ReplaceAllString(htmlText, "[$2]($1)")
  205. htmlText = strings.ReplaceAll(htmlText, "<br>", "\n")
  206. return htmlText
  207. }
  208. // getMatrixTxnID computes the transaction ID to ensure idempotency
  209. func getMatrixTxnID(payload []byte) (string, error) {
  210. if len(payload) >= matrixPayloadSizeLimit {
  211. return "", fmt.Errorf("getMatrixTxnID: payload size %d > %d", len(payload), matrixPayloadSizeLimit)
  212. }
  213. h := sha1.New()
  214. _, err := h.Write(payload)
  215. if err != nil {
  216. return "", err
  217. }
  218. return hex.EncodeToString(h.Sum(nil)), nil
  219. }