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.

538 lines
14 KiB

10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 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/go-xorm/xorm"
  15. api "github.com/gogits/go-gogs-client"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/git"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. type ActionType int
  22. const (
  23. CREATE_REPO ActionType = iota + 1 // 1
  24. RENAME_REPO // 2
  25. STAR_REPO // 3
  26. FOLLOW_REPO // 4
  27. COMMIT_REPO // 5
  28. CREATE_ISSUE // 6
  29. CREATE_PULL_REQUEST // 7
  30. TRANSFER_REPO // 8
  31. PUSH_TAG // 9
  32. COMMENT_ISSUE // 10
  33. MERGE_PULL_REQUEST // 11
  34. )
  35. var (
  36. ErrNotImplemented = errors.New("Not implemented yet")
  37. )
  38. var (
  39. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  40. IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  41. IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  42. IssueCloseKeywordsPat, IssueReopenKeywordsPat *regexp.Regexp
  43. IssueReferenceKeywordsPat *regexp.Regexp
  44. )
  45. func assembleKeywordsPattern(words []string) string {
  46. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  47. }
  48. func init() {
  49. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  50. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  51. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  52. }
  53. // Action represents user operation type and other information to repository.,
  54. // it implemented interface base.Actioner so that can be used in template render.
  55. type Action struct {
  56. ID int64 `xorm:"pk autoincr"`
  57. UserID int64 // Receiver user id.
  58. OpType ActionType
  59. ActUserID int64 // Action user id.
  60. ActUserName string // Action user name.
  61. ActEmail string
  62. ActAvatar string `xorm:"-"`
  63. RepoID int64
  64. RepoUserName string
  65. RepoName string
  66. RefName string
  67. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  68. Content string `xorm:"TEXT"`
  69. Created time.Time `xorm:"created"`
  70. }
  71. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  72. switch colName {
  73. case "created":
  74. a.Created = regulateTimeZone(a.Created)
  75. }
  76. }
  77. func (a Action) GetOpType() int {
  78. return int(a.OpType)
  79. }
  80. func (a Action) GetActUserName() string {
  81. return a.ActUserName
  82. }
  83. func (a Action) GetActEmail() string {
  84. return a.ActEmail
  85. }
  86. func (a Action) GetRepoUserName() string {
  87. return a.RepoUserName
  88. }
  89. func (a Action) GetRepoName() string {
  90. return a.RepoName
  91. }
  92. func (a Action) GetRepoPath() string {
  93. return path.Join(a.RepoUserName, a.RepoName)
  94. }
  95. func (a Action) GetRepoLink() string {
  96. if len(setting.AppSubUrl) > 0 {
  97. return path.Join(setting.AppSubUrl, a.GetRepoPath())
  98. }
  99. return "/" + a.GetRepoPath()
  100. }
  101. func (a Action) GetBranch() string {
  102. return a.RefName
  103. }
  104. func (a Action) GetContent() string {
  105. return a.Content
  106. }
  107. func (a Action) GetCreate() time.Time {
  108. return a.Created
  109. }
  110. func (a Action) GetIssueInfos() []string {
  111. return strings.SplitN(a.Content, "|", 2)
  112. }
  113. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  114. if err = notifyWatchers(e, &Action{
  115. ActUserID: u.Id,
  116. ActUserName: u.Name,
  117. ActEmail: u.Email,
  118. OpType: CREATE_REPO,
  119. RepoID: repo.ID,
  120. RepoUserName: repo.Owner.Name,
  121. RepoName: repo.Name,
  122. IsPrivate: repo.IsPrivate,
  123. }); err != nil {
  124. return fmt.Errorf("notify watchers '%d/%s': %v", u.Id, repo.ID, err)
  125. }
  126. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  127. return err
  128. }
  129. // NewRepoAction adds new action for creating repository.
  130. func NewRepoAction(u *User, repo *Repository) (err error) {
  131. return newRepoAction(x, u, repo)
  132. }
  133. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  134. if err = notifyWatchers(e, &Action{
  135. ActUserID: actUser.Id,
  136. ActUserName: actUser.Name,
  137. ActEmail: actUser.Email,
  138. OpType: RENAME_REPO,
  139. RepoID: repo.ID,
  140. RepoUserName: repo.Owner.Name,
  141. RepoName: repo.Name,
  142. IsPrivate: repo.IsPrivate,
  143. Content: oldRepoName,
  144. }); err != nil {
  145. return fmt.Errorf("notify watchers: %v", err)
  146. }
  147. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  148. return nil
  149. }
  150. // RenameRepoAction adds new action for renaming a repository.
  151. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  152. return renameRepoAction(x, actUser, oldRepoName, repo)
  153. }
  154. func issueIndexTrimRight(c rune) bool {
  155. return !unicode.IsDigit(c)
  156. }
  157. // updateIssuesCommit checks if issues are manipulated by commit message.
  158. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*base.PushCommit) error {
  159. // Commits are appended in the reverse order.
  160. for i := len(commits) - 1; i >= 0; i-- {
  161. c := commits[i]
  162. refMarked := make(map[int64]bool)
  163. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  164. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  165. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  166. if len(ref) == 0 {
  167. continue
  168. }
  169. // Add repo name if missing
  170. if ref[0] == '#' {
  171. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  172. } else if !strings.Contains(ref, "/") {
  173. // FIXME: We don't support User#ID syntax yet
  174. // return ErrNotImplemented
  175. continue
  176. }
  177. issue, err := GetIssueByRef(ref)
  178. if err != nil {
  179. if IsErrIssueNotExist(err) {
  180. continue
  181. }
  182. return err
  183. }
  184. if refMarked[issue.ID] {
  185. continue
  186. }
  187. refMarked[issue.ID] = true
  188. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  189. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  190. if err = CreateRefComment(u, repo, issue, message, c.Sha1); err != nil {
  191. return err
  192. }
  193. }
  194. refMarked = make(map[int64]bool)
  195. // FIXME: can merge this one and next one to a common function.
  196. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  197. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  198. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  199. if len(ref) == 0 {
  200. continue
  201. }
  202. // Add repo name if missing
  203. if ref[0] == '#' {
  204. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  205. } else if !strings.Contains(ref, "/") {
  206. // We don't support User#ID syntax yet
  207. // return ErrNotImplemented
  208. continue
  209. }
  210. issue, err := GetIssueByRef(ref)
  211. if err != nil {
  212. if IsErrIssueNotExist(err) {
  213. continue
  214. }
  215. return err
  216. }
  217. if refMarked[issue.ID] {
  218. continue
  219. }
  220. refMarked[issue.ID] = true
  221. if issue.RepoID != repo.ID || issue.IsClosed {
  222. continue
  223. }
  224. if err = issue.ChangeStatus(u, true); err != nil {
  225. return err
  226. }
  227. }
  228. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  229. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  230. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  231. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  232. if len(ref) == 0 {
  233. continue
  234. }
  235. // Add repo name if missing
  236. if ref[0] == '#' {
  237. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  238. } else if !strings.Contains(ref, "/") {
  239. // We don't support User#ID syntax yet
  240. // return ErrNotImplemented
  241. continue
  242. }
  243. issue, err := GetIssueByRef(ref)
  244. if err != nil {
  245. if IsErrIssueNotExist(err) {
  246. continue
  247. }
  248. return err
  249. }
  250. if refMarked[issue.ID] {
  251. continue
  252. }
  253. refMarked[issue.ID] = true
  254. if issue.RepoID != repo.ID || !issue.IsClosed {
  255. continue
  256. }
  257. if err = issue.ChangeStatus(u, false); err != nil {
  258. return err
  259. }
  260. }
  261. }
  262. return nil
  263. }
  264. // CommitRepoAction adds new action for committing repository.
  265. func CommitRepoAction(
  266. userID, repoUserID int64,
  267. userName, actEmail string,
  268. repoID int64,
  269. repoUserName, repoName string,
  270. refFullName string,
  271. commit *base.PushCommits,
  272. oldCommitID string, newCommitID string) error {
  273. u, err := GetUserByID(userID)
  274. if err != nil {
  275. return fmt.Errorf("GetUserByID: %v", err)
  276. }
  277. repo, err := GetRepositoryByName(repoUserID, repoName)
  278. if err != nil {
  279. return fmt.Errorf("GetRepositoryByName: %v", err)
  280. } else if err = repo.GetOwner(); err != nil {
  281. return fmt.Errorf("GetOwner: %v", err)
  282. }
  283. isNewBranch := false
  284. opType := COMMIT_REPO
  285. // Check it's tag push or branch.
  286. if strings.HasPrefix(refFullName, "refs/tags/") {
  287. opType = PUSH_TAG
  288. commit = &base.PushCommits{}
  289. } else {
  290. // if not the first commit, set the compareUrl
  291. if !strings.HasPrefix(oldCommitID, "0000000") {
  292. commit.CompareUrl = fmt.Sprintf("%s/%s/compare/%s...%s", repoUserName, repoName, oldCommitID, newCommitID)
  293. } else {
  294. isNewBranch = true
  295. }
  296. // Change repository bare status and update last updated time.
  297. repo.IsBare = false
  298. if err = UpdateRepository(repo, false); err != nil {
  299. return fmt.Errorf("UpdateRepository: %v", err)
  300. }
  301. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  302. log.Error(4, "updateIssuesCommit: %v", err)
  303. }
  304. }
  305. if len(commit.Commits) > setting.FeedMaxCommitNum {
  306. commit.Commits = commit.Commits[:setting.FeedMaxCommitNum]
  307. }
  308. bs, err := json.Marshal(commit)
  309. if err != nil {
  310. return fmt.Errorf("Marshal: %v", err)
  311. }
  312. refName := git.RefEndName(refFullName)
  313. if err = NotifyWatchers(&Action{
  314. ActUserID: u.Id,
  315. ActUserName: userName,
  316. ActEmail: actEmail,
  317. OpType: opType,
  318. Content: string(bs),
  319. RepoID: repo.ID,
  320. RepoUserName: repoUserName,
  321. RepoName: repoName,
  322. RefName: refName,
  323. IsPrivate: repo.IsPrivate,
  324. }); err != nil {
  325. return fmt.Errorf("NotifyWatchers: %v", err)
  326. }
  327. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  328. payloadRepo := &api.PayloadRepo{
  329. ID: repo.ID,
  330. Name: repo.LowerName,
  331. URL: repoLink,
  332. Description: repo.Description,
  333. Website: repo.Website,
  334. Watchers: repo.NumWatches,
  335. Owner: &api.PayloadAuthor{
  336. Name: repo.Owner.DisplayName(),
  337. Email: repo.Owner.Email,
  338. UserName: repo.Owner.Name,
  339. },
  340. Private: repo.IsPrivate,
  341. }
  342. pusher_email, pusher_name := "", ""
  343. pusher, err := GetUserByName(userName)
  344. if err == nil {
  345. pusher_email = pusher.Email
  346. pusher_name = pusher.DisplayName()
  347. }
  348. payloadSender := &api.PayloadUser{
  349. UserName: pusher.Name,
  350. ID: pusher.Id,
  351. AvatarUrl: setting.AppUrl + pusher.RelAvatarLink(),
  352. }
  353. switch opType {
  354. case COMMIT_REPO: // Push
  355. commits := make([]*api.PayloadCommit, len(commit.Commits))
  356. for i, cmt := range commit.Commits {
  357. author_username := ""
  358. author, err := GetUserByEmail(cmt.AuthorEmail)
  359. if err == nil {
  360. author_username = author.Name
  361. }
  362. commits[i] = &api.PayloadCommit{
  363. ID: cmt.Sha1,
  364. Message: cmt.Message,
  365. URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  366. Author: &api.PayloadAuthor{
  367. Name: cmt.AuthorName,
  368. Email: cmt.AuthorEmail,
  369. UserName: author_username,
  370. },
  371. }
  372. }
  373. p := &api.PushPayload{
  374. Ref: refFullName,
  375. Before: oldCommitID,
  376. After: newCommitID,
  377. CompareUrl: setting.AppUrl + commit.CompareUrl,
  378. Commits: commits,
  379. Repo: payloadRepo,
  380. Pusher: &api.PayloadAuthor{
  381. Name: pusher_name,
  382. Email: pusher_email,
  383. UserName: userName,
  384. },
  385. Sender: payloadSender,
  386. }
  387. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil {
  388. return fmt.Errorf("PrepareWebhooks: %v", err)
  389. }
  390. if isNewBranch {
  391. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  392. Ref: refName,
  393. RefType: "branch",
  394. Repo: payloadRepo,
  395. Sender: payloadSender,
  396. })
  397. }
  398. case PUSH_TAG: // Create
  399. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  400. Ref: refName,
  401. RefType: "tag",
  402. Repo: payloadRepo,
  403. Sender: payloadSender,
  404. })
  405. }
  406. return nil
  407. }
  408. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  409. if err = notifyWatchers(e, &Action{
  410. ActUserID: actUser.Id,
  411. ActUserName: actUser.Name,
  412. ActEmail: actUser.Email,
  413. OpType: TRANSFER_REPO,
  414. RepoID: repo.ID,
  415. RepoUserName: newOwner.Name,
  416. RepoName: repo.Name,
  417. IsPrivate: repo.IsPrivate,
  418. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  419. }); err != nil {
  420. return fmt.Errorf("notify watchers '%d/%s': %v", actUser.Id, repo.ID, err)
  421. }
  422. // Remove watch for organization.
  423. if repo.Owner.IsOrganization() {
  424. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  425. return fmt.Errorf("watch repository: %v", err)
  426. }
  427. }
  428. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  429. return nil
  430. }
  431. // TransferRepoAction adds new action for transferring repository.
  432. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  433. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  434. }
  435. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  436. return notifyWatchers(e, &Action{
  437. ActUserID: actUser.Id,
  438. ActUserName: actUser.Name,
  439. ActEmail: actUser.Email,
  440. OpType: MERGE_PULL_REQUEST,
  441. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  442. RepoID: repo.ID,
  443. RepoUserName: repo.Owner.Name,
  444. RepoName: repo.Name,
  445. IsPrivate: repo.IsPrivate,
  446. })
  447. }
  448. // MergePullRequestAction adds new action for merging pull request.
  449. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  450. return mergePullRequestAction(x, actUser, repo, pull)
  451. }
  452. // GetFeeds returns action list of given user in given context.
  453. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  454. actions := make([]*Action, 0, 20)
  455. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  456. if isProfile {
  457. sess.And("is_private=?", false).And("act_user_id=?", uid)
  458. }
  459. err := sess.Find(&actions)
  460. return actions, err
  461. }