action.go 8.3 KB

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