action.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "regexp"
  10. "strings"
  11. "time"
  12. "unicode"
  13. "github.com/gogits/git"
  14. "github.com/gogits/gogs/modules/base"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. // Operation types of user action.
  19. const (
  20. OP_CREATE_REPO = iota + 1
  21. OP_DELETE_REPO
  22. OP_STAR_REPO
  23. OP_FOLLOW_REPO
  24. OP_COMMIT_REPO
  25. OP_CREATE_ISSUE
  26. OP_PULL_REQUEST
  27. OP_TRANSFER_REPO
  28. OP_PUSH_TAG
  29. OP_COMMENT_ISSUE
  30. )
  31. var (
  32. ErrNotImplemented = errors.New("Not implemented yet")
  33. )
  34. var (
  35. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  36. IssueKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  37. IssueKeywordsPat *regexp.Regexp
  38. )
  39. func init() {
  40. IssueKeywordsPat = regexp.MustCompile(fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(IssueKeywords, "|")))
  41. }
  42. // Action represents user operation type and other information to repository.,
  43. // it implemented interface base.Actioner so that can be used in template render.
  44. type Action struct {
  45. Id int64
  46. UserId int64 // Receiver user id.
  47. OpType int
  48. ActUserId int64 // Action user id.
  49. ActUserName string // Action user name.
  50. ActEmail string
  51. RepoId int64
  52. RepoUserName string
  53. RepoName string
  54. RefName string
  55. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  56. Content string `xorm:"TEXT"`
  57. Created time.Time `xorm:"created"`
  58. }
  59. func (a Action) GetOpType() int {
  60. return a.OpType
  61. }
  62. func (a Action) GetActUserName() string {
  63. return a.ActUserName
  64. }
  65. func (a Action) GetActEmail() string {
  66. return a.ActEmail
  67. }
  68. func (a Action) GetRepoUserName() string {
  69. return a.RepoUserName
  70. }
  71. func (a Action) GetRepoName() string {
  72. return a.RepoName
  73. }
  74. func (a Action) GetBranch() string {
  75. return a.RefName
  76. }
  77. func (a Action) GetContent() string {
  78. return a.Content
  79. }
  80. func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, commits []*base.PushCommit) error {
  81. for _, c := range commits {
  82. refs := IssueKeywordsPat.FindAllString(c.Message, -1)
  83. for _, ref := range refs {
  84. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  85. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  86. return !unicode.IsDigit(c)
  87. })
  88. if len(ref) == 0 {
  89. continue
  90. }
  91. // Add repo name if missing
  92. if ref[0] == '#' {
  93. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  94. } else if strings.Contains(ref, "/") == false {
  95. // We don't support User#ID syntax yet
  96. // return ErrNotImplemented
  97. continue
  98. }
  99. issue, err := GetIssueByRef(ref)
  100. if err != nil {
  101. return err
  102. }
  103. url := fmt.Sprintf("/%s/%s/commit/%s", repoUserName, repoName, c.Sha1)
  104. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  105. if _, err = CreateComment(userId, issue.RepoId, issue.Id, 0, 0, COMMIT, message, nil); err != nil {
  106. return err
  107. }
  108. if issue.RepoId == repoId {
  109. if issue.IsClosed {
  110. continue
  111. }
  112. issue.IsClosed = true
  113. if err = UpdateIssue(issue); err != nil {
  114. return err
  115. }
  116. issue.Repo, err = GetRepositoryById(issue.RepoId)
  117. if err != nil {
  118. return err
  119. }
  120. issue.Repo.NumClosedIssues++
  121. if err = UpdateRepository(issue.Repo); err != nil {
  122. return err
  123. }
  124. if err = ChangeMilestoneIssueStats(issue); err != nil {
  125. return err
  126. }
  127. // If commit happened in the referenced repository, it means the issue can be closed.
  128. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, CLOSE, "", nil); err != nil {
  129. return err
  130. }
  131. }
  132. }
  133. }
  134. return nil
  135. }
  136. // CommitRepoAction adds new action for committing repository.
  137. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  138. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits) error {
  139. // log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName)
  140. opType := OP_COMMIT_REPO
  141. // Check it's tag push or branch.
  142. if strings.HasPrefix(refFullName, "refs/tags/") {
  143. opType = OP_PUSH_TAG
  144. commit = &base.PushCommits{}
  145. }
  146. refName := git.RefEndName(refFullName)
  147. bs, err := json.Marshal(commit)
  148. if err != nil {
  149. return errors.New("action.CommitRepoAction(json): " + err.Error())
  150. }
  151. // Change repository bare status and update last updated time.
  152. repo, err := GetRepositoryByName(repoUserId, repoName)
  153. if err != nil {
  154. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  155. }
  156. repo.IsBare = false
  157. if err = UpdateRepository(repo); err != nil {
  158. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  159. }
  160. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  161. if err != nil {
  162. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  163. }
  164. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  165. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  166. RepoName: repoName, RefName: refName,
  167. IsPrivate: repo.IsPrivate}); err != nil {
  168. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  169. }
  170. //qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName)
  171. // New push event hook.
  172. if err := repo.GetOwner(); err != nil {
  173. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  174. }
  175. ws, err := GetActiveWebhooksByRepoId(repoId)
  176. if err != nil {
  177. return errors.New("action.CommitRepoAction(GetWebhooksByRepoId): " + err.Error())
  178. } else if len(ws) == 0 {
  179. return nil
  180. }
  181. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  182. commits := make([]*PayloadCommit, len(commit.Commits))
  183. for i, cmt := range commit.Commits {
  184. commits[i] = &PayloadCommit{
  185. Id: cmt.Sha1,
  186. Message: cmt.Message,
  187. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  188. Author: &PayloadAuthor{
  189. Name: cmt.AuthorName,
  190. Email: cmt.AuthorEmail,
  191. },
  192. }
  193. }
  194. p := &Payload{
  195. Ref: refFullName,
  196. Commits: commits,
  197. Repo: &PayloadRepo{
  198. Id: repo.Id,
  199. Name: repo.LowerName,
  200. Url: repoLink,
  201. Description: repo.Description,
  202. Website: repo.Website,
  203. Watchers: repo.NumWatches,
  204. Owner: &PayloadAuthor{
  205. Name: repoUserName,
  206. Email: actEmail,
  207. },
  208. Private: repo.IsPrivate,
  209. },
  210. Pusher: &PayloadAuthor{
  211. Name: repo.Owner.LowerName,
  212. Email: repo.Owner.Email,
  213. },
  214. }
  215. for _, w := range ws {
  216. w.GetEvent()
  217. if !w.HasPushEvent() {
  218. continue
  219. }
  220. p.Secret = w.Secret
  221. CreateHookTask(&HookTask{
  222. Type: WEBHOOK,
  223. Url: w.Url,
  224. Payload: p,
  225. ContentType: w.ContentType,
  226. IsSsl: w.IsSsl,
  227. })
  228. }
  229. return nil
  230. }
  231. // NewRepoAction adds new action for creating repository.
  232. func NewRepoAction(u *User, repo *Repository) (err error) {
  233. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  234. OpType: OP_CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  235. IsPrivate: repo.IsPrivate}); err != nil {
  236. log.Error("action.NewRepoAction(notify watchers): %d/%s", u.Id, repo.Name)
  237. return err
  238. }
  239. log.Trace("action.NewRepoAction: %s/%s", u.LowerName, repo.LowerName)
  240. return err
  241. }
  242. // TransferRepoAction adds new action for transfering repository.
  243. func TransferRepoAction(user, newUser *User, repo *Repository) (err error) {
  244. if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, ActEmail: user.Email,
  245. OpType: OP_TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name,
  246. IsPrivate: repo.IsPrivate}); err != nil {
  247. log.Error("action.TransferRepoAction(notify watchers): %d/%s", user.Id, repo.Name)
  248. return err
  249. }
  250. log.Trace("action.TransferRepoAction: %s/%s", user.LowerName, repo.LowerName)
  251. return err
  252. }
  253. // GetFeeds returns action list of given user in given context.
  254. func GetFeeds(userid, offset int64, isProfile bool) ([]*Action, error) {
  255. actions := make([]*Action, 0, 20)
  256. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", userid)
  257. if isProfile {
  258. sess.Where("is_private=?", false).And("act_user_id=?", userid)
  259. } else {
  260. sess.And("act_user_id!=?", userid)
  261. }
  262. err := sess.Find(&actions)
  263. return actions, err
  264. }