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.

355 lines
9.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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. "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, oldCommitId string, newCommitId string) 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(GetActiveWebhooksByRepoId): " + err.Error())
  179. }
  180. // check if repo belongs to org and append additional webhooks
  181. if repo.Owner.IsOrganization() {
  182. // get hooks for org
  183. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId)
  184. if err != nil {
  185. return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error())
  186. }
  187. ws = append(ws, orgws...)
  188. }
  189. if len(ws) == 0 {
  190. return nil
  191. }
  192. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  193. compareUrl := ""
  194. // if not the first commit, set the compareUrl
  195. if !strings.HasPrefix(oldCommitId, "0000000") {
  196. compareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
  197. }
  198. commits := make([]*PayloadCommit, len(commit.Commits))
  199. for i, cmt := range commit.Commits {
  200. commits[i] = &PayloadCommit{
  201. Id: cmt.Sha1,
  202. Message: cmt.Message,
  203. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  204. Author: &PayloadAuthor{
  205. Name: cmt.AuthorName,
  206. Email: cmt.AuthorEmail,
  207. },
  208. }
  209. }
  210. p := &Payload{
  211. Ref: refFullName,
  212. Commits: commits,
  213. Repo: &PayloadRepo{
  214. Id: repo.Id,
  215. Name: repo.LowerName,
  216. Url: repoLink,
  217. Description: repo.Description,
  218. Website: repo.Website,
  219. Watchers: repo.NumWatches,
  220. Owner: &PayloadAuthor{
  221. Name: repoUserName,
  222. Email: actEmail,
  223. },
  224. Private: repo.IsPrivate,
  225. },
  226. Pusher: &PayloadAuthor{
  227. Name: repo.Owner.LowerName,
  228. Email: repo.Owner.Email,
  229. },
  230. Before: oldCommitId,
  231. After: newCommitId,
  232. CompareUrl: compareUrl,
  233. }
  234. for _, w := range ws {
  235. w.GetEvent()
  236. if !w.HasPushEvent() {
  237. continue
  238. }
  239. switch w.HookTaskType {
  240. case SLACK:
  241. {
  242. s, err := GetSlackPayload(p, w.Meta)
  243. if err != nil {
  244. return errors.New("action.GetSlackPayload: " + err.Error())
  245. }
  246. CreateHookTask(&HookTask{
  247. Type: w.HookTaskType,
  248. Url: w.Url,
  249. BasePayload: s,
  250. ContentType: w.ContentType,
  251. IsSsl: w.IsSsl,
  252. })
  253. }
  254. default:
  255. {
  256. p.Secret = w.Secret
  257. CreateHookTask(&HookTask{
  258. Type: w.HookTaskType,
  259. Url: w.Url,
  260. BasePayload: p,
  261. ContentType: w.ContentType,
  262. IsSsl: w.IsSsl,
  263. })
  264. }
  265. }
  266. }
  267. return nil
  268. }
  269. // NewRepoAction adds new action for creating repository.
  270. func NewRepoAction(u *User, repo *Repository) (err error) {
  271. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  272. OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  273. IsPrivate: repo.IsPrivate}); err != nil {
  274. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  275. return err
  276. }
  277. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  278. return err
  279. }
  280. // TransferRepoAction adds new action for transfering repository.
  281. func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
  282. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  283. OpType: TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name,
  284. IsPrivate: repo.IsPrivate}); err != nil {
  285. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  286. return err
  287. }
  288. log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name)
  289. return err
  290. }
  291. // GetFeeds returns action list of given user in given context.
  292. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  293. actions := make([]*Action, 0, 20)
  294. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  295. if isProfile {
  296. sess.Where("is_private=?", false).And("act_user_id=?", uid)
  297. }
  298. err := sess.Find(&actions)
  299. return actions, err
  300. }