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.

390 lines
10 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
  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. ActAvatar string `xorm:"-"`
  53. RepoId int64
  54. RepoUserName string
  55. RepoName string
  56. RefName string
  57. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  58. Content string `xorm:"TEXT"`
  59. Created time.Time `xorm:"created"`
  60. }
  61. func (a Action) GetOpType() int {
  62. return int(a.OpType)
  63. }
  64. func (a Action) GetActUserName() string {
  65. return a.ActUserName
  66. }
  67. func (a Action) GetActEmail() string {
  68. return a.ActEmail
  69. }
  70. func (a Action) GetRepoUserName() string {
  71. return a.RepoUserName
  72. }
  73. func (a Action) GetRepoName() string {
  74. return a.RepoName
  75. }
  76. func (a Action) GetRepoLink() string {
  77. return path.Join(a.RepoUserName, a.RepoName)
  78. }
  79. func (a Action) GetBranch() string {
  80. return a.RefName
  81. }
  82. func (a Action) GetContent() string {
  83. return a.Content
  84. }
  85. func (a Action) GetCreate() time.Time {
  86. return a.Created
  87. }
  88. func (a Action) GetIssueInfos() []string {
  89. return strings.SplitN(a.Content, "|", 2)
  90. }
  91. func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, commits []*base.PushCommit) error {
  92. for _, c := range commits {
  93. refs := IssueKeywordsPat.FindAllString(c.Message, -1)
  94. for _, ref := range refs {
  95. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  96. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  97. return !unicode.IsDigit(c)
  98. })
  99. if len(ref) == 0 {
  100. continue
  101. }
  102. // Add repo name if missing
  103. if ref[0] == '#' {
  104. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  105. } else if strings.Contains(ref, "/") == false {
  106. // We don't support User#ID syntax yet
  107. // return ErrNotImplemented
  108. continue
  109. }
  110. issue, err := GetIssueByRef(ref)
  111. if err != nil {
  112. return err
  113. }
  114. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  115. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  116. if _, err = CreateComment(userId, issue.RepoId, issue.Id, 0, 0, COMMIT, message, nil); err != nil {
  117. return err
  118. }
  119. if issue.RepoId == repoId {
  120. if issue.IsClosed {
  121. continue
  122. }
  123. issue.IsClosed = true
  124. if err = UpdateIssue(issue); err != nil {
  125. return err
  126. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  127. return err
  128. }
  129. if err = ChangeMilestoneIssueStats(issue); err != nil {
  130. return err
  131. }
  132. // If commit happened in the referenced repository, it means the issue can be closed.
  133. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, CLOSE, "", nil); err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. }
  139. return nil
  140. }
  141. // CommitRepoAction adds new action for committing repository.
  142. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  143. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitId string, newCommitId string) error {
  144. opType := COMMIT_REPO
  145. // Check it's tag push or branch.
  146. if strings.HasPrefix(refFullName, "refs/tags/") {
  147. opType = PUSH_TAG
  148. commit = &base.PushCommits{}
  149. }
  150. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  151. // if not the first commit, set the compareUrl
  152. if !strings.HasPrefix(oldCommitId, "0000000") {
  153. commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
  154. }
  155. bs, err := json.Marshal(commit)
  156. if err != nil {
  157. return errors.New("action.CommitRepoAction(json): " + err.Error())
  158. }
  159. refName := git.RefEndName(refFullName)
  160. // Change repository bare status and update last updated time.
  161. repo, err := GetRepositoryByName(repoUserId, repoName)
  162. if err != nil {
  163. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  164. }
  165. repo.IsBare = false
  166. if err = UpdateRepository(repo); err != nil {
  167. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  168. }
  169. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  170. if err != nil {
  171. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  172. }
  173. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  174. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  175. RepoName: repoName, RefName: refName,
  176. IsPrivate: repo.IsPrivate}); err != nil {
  177. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  178. }
  179. // New push event hook.
  180. if err := repo.GetOwner(); err != nil {
  181. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  182. }
  183. ws, err := GetActiveWebhooksByRepoId(repoId)
  184. if err != nil {
  185. return errors.New("action.CommitRepoAction(GetActiveWebhooksByRepoId): " + err.Error())
  186. }
  187. // check if repo belongs to org and append additional webhooks
  188. if repo.Owner.IsOrganization() {
  189. // get hooks for org
  190. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId)
  191. if err != nil {
  192. return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error())
  193. }
  194. ws = append(ws, orgws...)
  195. }
  196. if len(ws) == 0 {
  197. return nil
  198. }
  199. pusher_email, pusher_name := "", ""
  200. pusher, err := GetUserByName(userName)
  201. if err == nil {
  202. pusher_email = pusher.Email
  203. pusher_name = pusher.GetFullNameFallback()
  204. }
  205. commits := make([]*PayloadCommit, len(commit.Commits))
  206. for i, cmt := range commit.Commits {
  207. author_username := ""
  208. author, err := GetUserByEmail(cmt.AuthorEmail)
  209. if err == nil {
  210. author_username = author.Name
  211. }
  212. commits[i] = &PayloadCommit{
  213. Id: cmt.Sha1,
  214. Message: cmt.Message,
  215. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  216. Author: &PayloadAuthor{
  217. Name: cmt.AuthorName,
  218. Email: cmt.AuthorEmail,
  219. UserName: author_username,
  220. },
  221. }
  222. }
  223. p := &Payload{
  224. Ref: refFullName,
  225. Commits: commits,
  226. Repo: &PayloadRepo{
  227. Id: repo.Id,
  228. Name: repo.LowerName,
  229. Url: repoLink,
  230. Description: repo.Description,
  231. Website: repo.Website,
  232. Watchers: repo.NumWatches,
  233. Owner: &PayloadAuthor{
  234. Name: repo.Owner.GetFullNameFallback(),
  235. Email: repo.Owner.Email,
  236. UserName: repo.Owner.Name,
  237. },
  238. Private: repo.IsPrivate,
  239. },
  240. Pusher: &PayloadAuthor{
  241. Name: pusher_name,
  242. Email: pusher_email,
  243. UserName: userName,
  244. },
  245. Before: oldCommitId,
  246. After: newCommitId,
  247. CompareUrl: commit.CompareUrl,
  248. }
  249. for _, w := range ws {
  250. w.GetEvent()
  251. if !w.HasPushEvent() {
  252. continue
  253. }
  254. switch w.HookTaskType {
  255. case SLACK:
  256. {
  257. s, err := GetSlackPayload(p, w.Meta)
  258. if err != nil {
  259. return errors.New("action.GetSlackPayload: " + err.Error())
  260. }
  261. CreateHookTask(&HookTask{
  262. Type: w.HookTaskType,
  263. Url: w.Url,
  264. BasePayload: s,
  265. ContentType: w.ContentType,
  266. IsSsl: w.IsSsl,
  267. })
  268. }
  269. default:
  270. {
  271. p.Secret = w.Secret
  272. CreateHookTask(&HookTask{
  273. Type: w.HookTaskType,
  274. Url: w.Url,
  275. BasePayload: p,
  276. ContentType: w.ContentType,
  277. IsSsl: w.IsSsl,
  278. })
  279. }
  280. }
  281. }
  282. go DeliverHooks()
  283. return nil
  284. }
  285. // NewRepoAction adds new action for creating repository.
  286. func NewRepoAction(u *User, repo *Repository) (err error) {
  287. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  288. OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  289. IsPrivate: repo.IsPrivate}); err != nil {
  290. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  291. return err
  292. }
  293. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  294. return err
  295. }
  296. // TransferRepoAction adds new action for transferring repository.
  297. func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
  298. action := &Action{
  299. ActUserId: u.Id,
  300. ActUserName: u.Name,
  301. ActEmail: u.Email,
  302. OpType: TRANSFER_REPO,
  303. RepoId: repo.Id,
  304. RepoUserName: newUser.Name,
  305. RepoName: repo.Name,
  306. IsPrivate: repo.IsPrivate,
  307. Content: path.Join(repo.Owner.LowerName, repo.LowerName),
  308. }
  309. if err = NotifyWatchers(action); err != nil {
  310. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  311. return err
  312. }
  313. // Remove watch for organization.
  314. if repo.Owner.IsOrganization() {
  315. if err = WatchRepo(repo.Owner.Id, repo.Id, false); err != nil {
  316. log.Error(4, "WatchRepo", err)
  317. }
  318. }
  319. log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name)
  320. return err
  321. }
  322. // GetFeeds returns action list of given user in given context.
  323. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  324. actions := make([]*Action, 0, 20)
  325. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  326. if isProfile {
  327. sess.And("is_private=?", false).And("act_user_id=?", uid)
  328. }
  329. err := sess.Find(&actions)
  330. return actions, err
  331. }