action.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. if err = ChangeMilestoneIssueStats(issue); err != nil {
  117. return err
  118. }
  119. // If commit happened in the referenced repository, it means the issue can be closed.
  120. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, CLOSE, "", nil); err != nil {
  121. return err
  122. }
  123. }
  124. }
  125. }
  126. return nil
  127. }
  128. // CommitRepoAction adds new action for committing repository.
  129. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  130. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits) error {
  131. // log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName)
  132. opType := OP_COMMIT_REPO
  133. // Check it's tag push or branch.
  134. if strings.HasPrefix(refFullName, "refs/tags/") {
  135. opType = OP_PUSH_TAG
  136. commit = &base.PushCommits{}
  137. }
  138. refName := git.RefEndName(refFullName)
  139. bs, err := json.Marshal(commit)
  140. if err != nil {
  141. return errors.New("action.CommitRepoAction(json): " + err.Error())
  142. }
  143. // Change repository bare status and update last updated time.
  144. repo, err := GetRepositoryByName(repoUserId, repoName)
  145. if err != nil {
  146. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  147. }
  148. repo.IsBare = false
  149. if err = UpdateRepository(repo); err != nil {
  150. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  151. }
  152. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  153. if err != nil {
  154. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  155. }
  156. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  157. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  158. RepoName: repoName, RefName: refName,
  159. IsPrivate: repo.IsPrivate}); err != nil {
  160. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  161. }
  162. //qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName)
  163. // New push event hook.
  164. if err := repo.GetOwner(); err != nil {
  165. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  166. }
  167. ws, err := GetActiveWebhooksByRepoId(repoId)
  168. if err != nil {
  169. return errors.New("action.CommitRepoAction(GetWebhooksByRepoId): " + err.Error())
  170. } else if len(ws) == 0 {
  171. return nil
  172. }
  173. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  174. commits := make([]*PayloadCommit, len(commit.Commits))
  175. for i, cmt := range commit.Commits {
  176. commits[i] = &PayloadCommit{
  177. Id: cmt.Sha1,
  178. Message: cmt.Message,
  179. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  180. Author: &PayloadAuthor{
  181. Name: cmt.AuthorName,
  182. Email: cmt.AuthorEmail,
  183. },
  184. }
  185. }
  186. p := &Payload{
  187. Ref: refFullName,
  188. Commits: commits,
  189. Repo: &PayloadRepo{
  190. Id: repo.Id,
  191. Name: repo.LowerName,
  192. Url: repoLink,
  193. Description: repo.Description,
  194. Website: repo.Website,
  195. Watchers: repo.NumWatches,
  196. Owner: &PayloadAuthor{
  197. Name: repoUserName,
  198. Email: actEmail,
  199. },
  200. Private: repo.IsPrivate,
  201. },
  202. Pusher: &PayloadAuthor{
  203. Name: repo.Owner.LowerName,
  204. Email: repo.Owner.Email,
  205. },
  206. }
  207. for _, w := range ws {
  208. w.GetEvent()
  209. if !w.HasPushEvent() {
  210. continue
  211. }
  212. p.Secret = w.Secret
  213. CreateHookTask(&HookTask{
  214. Type: WEBHOOK,
  215. Url: w.Url,
  216. Payload: p,
  217. ContentType: w.ContentType,
  218. IsSsl: w.IsSsl,
  219. })
  220. }
  221. return nil
  222. }
  223. // NewRepoAction adds new action for creating repository.
  224. func NewRepoAction(u *User, repo *Repository) (err error) {
  225. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  226. OpType: OP_CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  227. IsPrivate: repo.IsPrivate}); err != nil {
  228. log.Error("action.NewRepoAction(notify watchers): %d/%s", u.Id, repo.Name)
  229. return err
  230. }
  231. log.Trace("action.NewRepoAction: %s/%s", u.LowerName, repo.LowerName)
  232. return err
  233. }
  234. // TransferRepoAction adds new action for transfering repository.
  235. func TransferRepoAction(user, newUser *User, repo *Repository) (err error) {
  236. if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, ActEmail: user.Email,
  237. OpType: OP_TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name,
  238. IsPrivate: repo.IsPrivate}); err != nil {
  239. log.Error("action.TransferRepoAction(notify watchers): %d/%s", user.Id, repo.Name)
  240. return err
  241. }
  242. log.Trace("action.TransferRepoAction: %s/%s", user.LowerName, repo.LowerName)
  243. return err
  244. }
  245. // GetFeeds returns action list of given user in given context.
  246. func GetFeeds(userid, offset int64, isProfile bool) ([]*Action, error) {
  247. actions := make([]*Action, 0, 20)
  248. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", userid)
  249. if isProfile {
  250. sess.Where("is_private=?", false).And("act_user_id=?", userid)
  251. } else {
  252. sess.And("act_user_id!=?", userid)
  253. }
  254. err := sess.Find(&actions)
  255. return actions, err
  256. }