A fork of Gitea (see branch `mj`) adding Majority Judgment Polls 𐄷 over Issues and Merge Requests. https://git.mieuxvoter.fr
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.

755 lines
20 KiB

9 years ago
9 years ago
9 years ago
6 years ago
6 years ago
9 years ago
9 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
9 years ago
6 years ago
9 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
7 years ago
7 years ago
9 years ago
9 years ago
9 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. "fmt"
  8. "path"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "unicode"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/util"
  19. api "code.gitea.io/sdk/gitea"
  20. "github.com/Unknwon/com"
  21. "github.com/go-xorm/builder"
  22. )
  23. // ActionType represents the type of an action.
  24. type ActionType int
  25. // Possible action types.
  26. const (
  27. ActionCreateRepo ActionType = iota + 1 // 1
  28. ActionRenameRepo // 2
  29. ActionStarRepo // 3
  30. ActionWatchRepo // 4
  31. ActionCommitRepo // 5
  32. ActionCreateIssue // 6
  33. ActionCreatePullRequest // 7
  34. ActionTransferRepo // 8
  35. ActionPushTag // 9
  36. ActionCommentIssue // 10
  37. ActionMergePullRequest // 11
  38. ActionCloseIssue // 12
  39. ActionReopenIssue // 13
  40. ActionClosePullRequest // 14
  41. ActionReopenPullRequest // 15
  42. ActionDeleteTag // 16
  43. ActionDeleteBranch // 17
  44. )
  45. var (
  46. // Same as Github. See
  47. // https://help.github.com/articles/closing-issues-via-commit-messages
  48. issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  49. issueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  50. issueCloseKeywordsPat, issueReopenKeywordsPat *regexp.Regexp
  51. issueReferenceKeywordsPat *regexp.Regexp
  52. )
  53. const issueRefRegexpStr = `(?:\S+/\S=)?#\d+`
  54. func assembleKeywordsPattern(words []string) string {
  55. return fmt.Sprintf(`(?i)(?:%s) %s`, strings.Join(words, "|"), issueRefRegexpStr)
  56. }
  57. func init() {
  58. issueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueCloseKeywords))
  59. issueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueReopenKeywords))
  60. issueReferenceKeywordsPat = regexp.MustCompile(issueRefRegexpStr)
  61. }
  62. // Action represents user operation type and other information to
  63. // repository. It implemented interface base.Actioner so that can be
  64. // used in template render.
  65. type Action struct {
  66. ID int64 `xorm:"pk autoincr"`
  67. UserID int64 `xorm:"INDEX"` // Receiver user id.
  68. OpType ActionType
  69. ActUserID int64 `xorm:"INDEX"` // Action user id.
  70. ActUser *User `xorm:"-"`
  71. RepoID int64 `xorm:"INDEX"`
  72. Repo *Repository `xorm:"-"`
  73. CommentID int64 `xorm:"INDEX"`
  74. Comment *Comment `xorm:"-"`
  75. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  76. RefName string
  77. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  78. Content string `xorm:"TEXT"`
  79. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  80. }
  81. // GetOpType gets the ActionType of this action.
  82. func (a *Action) GetOpType() ActionType {
  83. return a.OpType
  84. }
  85. func (a *Action) loadActUser() {
  86. if a.ActUser != nil {
  87. return
  88. }
  89. var err error
  90. a.ActUser, err = GetUserByID(a.ActUserID)
  91. if err == nil {
  92. return
  93. } else if IsErrUserNotExist(err) {
  94. a.ActUser = NewGhostUser()
  95. } else {
  96. log.Error(4, "GetUserByID(%d): %v", a.ActUserID, err)
  97. }
  98. }
  99. func (a *Action) loadRepo() {
  100. if a.Repo != nil {
  101. return
  102. }
  103. var err error
  104. a.Repo, err = GetRepositoryByID(a.RepoID)
  105. if err != nil {
  106. log.Error(4, "GetRepositoryByID(%d): %v", a.RepoID, err)
  107. }
  108. }
  109. // GetActUserName gets the action's user name.
  110. func (a *Action) GetActUserName() string {
  111. a.loadActUser()
  112. return a.ActUser.Name
  113. }
  114. // ShortActUserName gets the action's user name trimmed to max 20
  115. // chars.
  116. func (a *Action) ShortActUserName() string {
  117. return base.EllipsisString(a.GetActUserName(), 20)
  118. }
  119. // GetActAvatar the action's user's avatar link
  120. func (a *Action) GetActAvatar() string {
  121. a.loadActUser()
  122. return a.ActUser.RelAvatarLink()
  123. }
  124. // GetRepoUserName returns the name of the action repository owner.
  125. func (a *Action) GetRepoUserName() string {
  126. a.loadRepo()
  127. return a.Repo.MustOwner().Name
  128. }
  129. // ShortRepoUserName returns the name of the action repository owner
  130. // trimmed to max 20 chars.
  131. func (a *Action) ShortRepoUserName() string {
  132. return base.EllipsisString(a.GetRepoUserName(), 20)
  133. }
  134. // GetRepoName returns the name of the action repository.
  135. func (a *Action) GetRepoName() string {
  136. a.loadRepo()
  137. return a.Repo.Name
  138. }
  139. // ShortRepoName returns the name of the action repository
  140. // trimmed to max 33 chars.
  141. func (a *Action) ShortRepoName() string {
  142. return base.EllipsisString(a.GetRepoName(), 33)
  143. }
  144. // GetRepoPath returns the virtual path to the action repository.
  145. func (a *Action) GetRepoPath() string {
  146. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  147. }
  148. // ShortRepoPath returns the virtual path to the action repository
  149. // trimmed to max 20 + 1 + 33 chars.
  150. func (a *Action) ShortRepoPath() string {
  151. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  152. }
  153. // GetRepoLink returns relative link to action repository.
  154. func (a *Action) GetRepoLink() string {
  155. if len(setting.AppSubURL) > 0 {
  156. return path.Join(setting.AppSubURL, a.GetRepoPath())
  157. }
  158. return "/" + a.GetRepoPath()
  159. }
  160. // GetCommentLink returns link to action comment.
  161. func (a *Action) GetCommentLink() string {
  162. if a == nil {
  163. return "#"
  164. }
  165. if a.Comment == nil && a.CommentID != 0 {
  166. a.Comment, _ = GetCommentByID(a.CommentID)
  167. }
  168. if a.Comment != nil {
  169. return a.Comment.HTMLURL()
  170. }
  171. if len(a.GetIssueInfos()) == 0 {
  172. return "#"
  173. }
  174. //Return link to issue
  175. issueIDString := a.GetIssueInfos()[0]
  176. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  177. if err != nil {
  178. return "#"
  179. }
  180. issue, err := GetIssueByID(issueID)
  181. if err != nil {
  182. return "#"
  183. }
  184. return issue.HTMLURL()
  185. }
  186. // GetBranch returns the action's repository branch.
  187. func (a *Action) GetBranch() string {
  188. return a.RefName
  189. }
  190. // GetContent returns the action's content.
  191. func (a *Action) GetContent() string {
  192. return a.Content
  193. }
  194. // GetCreate returns the action creation time.
  195. func (a *Action) GetCreate() time.Time {
  196. return a.CreatedUnix.AsTime()
  197. }
  198. // GetIssueInfos returns a list of issues associated with
  199. // the action.
  200. func (a *Action) GetIssueInfos() []string {
  201. return strings.SplitN(a.Content, "|", 2)
  202. }
  203. // GetIssueTitle returns the title of first issue associated
  204. // with the action.
  205. func (a *Action) GetIssueTitle() string {
  206. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  207. issue, err := GetIssueByIndex(a.RepoID, index)
  208. if err != nil {
  209. log.Error(4, "GetIssueByIndex: %v", err)
  210. return "500 when get issue"
  211. }
  212. return issue.Title
  213. }
  214. // GetIssueContent returns the content of first issue associated with
  215. // this action.
  216. func (a *Action) GetIssueContent() string {
  217. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  218. issue, err := GetIssueByIndex(a.RepoID, index)
  219. if err != nil {
  220. log.Error(4, "GetIssueByIndex: %v", err)
  221. return "500 when get issue"
  222. }
  223. return issue.Content
  224. }
  225. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  226. if err = notifyWatchers(e, &Action{
  227. ActUserID: u.ID,
  228. ActUser: u,
  229. OpType: ActionCreateRepo,
  230. RepoID: repo.ID,
  231. Repo: repo,
  232. IsPrivate: repo.IsPrivate,
  233. }); err != nil {
  234. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  235. }
  236. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  237. return err
  238. }
  239. // NewRepoAction adds new action for creating repository.
  240. func NewRepoAction(u *User, repo *Repository) (err error) {
  241. return newRepoAction(x, u, repo)
  242. }
  243. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  244. if err = notifyWatchers(e, &Action{
  245. ActUserID: actUser.ID,
  246. ActUser: actUser,
  247. OpType: ActionRenameRepo,
  248. RepoID: repo.ID,
  249. Repo: repo,
  250. IsPrivate: repo.IsPrivate,
  251. Content: oldRepoName,
  252. }); err != nil {
  253. return fmt.Errorf("notify watchers: %v", err)
  254. }
  255. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  256. return nil
  257. }
  258. // RenameRepoAction adds new action for renaming a repository.
  259. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  260. return renameRepoAction(x, actUser, oldRepoName, repo)
  261. }
  262. func issueIndexTrimRight(c rune) bool {
  263. return !unicode.IsDigit(c)
  264. }
  265. // PushCommit represents a commit in a push operation.
  266. type PushCommit struct {
  267. Sha1 string
  268. Message string
  269. AuthorEmail string
  270. AuthorName string
  271. CommitterEmail string
  272. CommitterName string
  273. Timestamp time.Time
  274. }
  275. // PushCommits represents list of commits in a push operation.
  276. type PushCommits struct {
  277. Len int
  278. Commits []*PushCommit
  279. CompareURL string
  280. avatars map[string]string
  281. }
  282. // NewPushCommits creates a new PushCommits object.
  283. func NewPushCommits() *PushCommits {
  284. return &PushCommits{
  285. avatars: make(map[string]string),
  286. }
  287. }
  288. // ToAPIPayloadCommits converts a PushCommits object to
  289. // api.PayloadCommit format.
  290. func (pc *PushCommits) ToAPIPayloadCommits(repoLink string) []*api.PayloadCommit {
  291. commits := make([]*api.PayloadCommit, len(pc.Commits))
  292. for i, commit := range pc.Commits {
  293. authorUsername := ""
  294. author, err := GetUserByEmail(commit.AuthorEmail)
  295. if err == nil {
  296. authorUsername = author.Name
  297. }
  298. committerUsername := ""
  299. committer, err := GetUserByEmail(commit.CommitterEmail)
  300. if err == nil {
  301. // TODO: check errors other than email not found.
  302. committerUsername = committer.Name
  303. }
  304. commits[i] = &api.PayloadCommit{
  305. ID: commit.Sha1,
  306. Message: commit.Message,
  307. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  308. Author: &api.PayloadUser{
  309. Name: commit.AuthorName,
  310. Email: commit.AuthorEmail,
  311. UserName: authorUsername,
  312. },
  313. Committer: &api.PayloadUser{
  314. Name: commit.CommitterName,
  315. Email: commit.CommitterEmail,
  316. UserName: committerUsername,
  317. },
  318. Timestamp: commit.Timestamp,
  319. }
  320. }
  321. return commits
  322. }
  323. // AvatarLink tries to match user in database with e-mail
  324. // in order to show custom avatar, and falls back to general avatar link.
  325. func (pc *PushCommits) AvatarLink(email string) string {
  326. _, ok := pc.avatars[email]
  327. if !ok {
  328. u, err := GetUserByEmail(email)
  329. if err != nil {
  330. pc.avatars[email] = base.AvatarLink(email)
  331. if !IsErrUserNotExist(err) {
  332. log.Error(4, "GetUserByEmail: %v", err)
  333. }
  334. } else {
  335. pc.avatars[email] = u.RelAvatarLink()
  336. }
  337. }
  338. return pc.avatars[email]
  339. }
  340. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  341. // if the provided ref is misformatted or references a non-existent issue.
  342. func getIssueFromRef(repo *Repository, ref string) (*Issue, error) {
  343. ref = ref[strings.IndexByte(ref, ' ')+1:]
  344. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  345. var refRepo *Repository
  346. poundIndex := strings.IndexByte(ref, '#')
  347. if poundIndex < 0 {
  348. return nil, nil
  349. } else if poundIndex == 0 {
  350. refRepo = repo
  351. } else {
  352. slashIndex := strings.IndexByte(ref, '/')
  353. if slashIndex < 0 || slashIndex >= poundIndex {
  354. return nil, nil
  355. }
  356. ownerName := ref[:slashIndex]
  357. repoName := ref[slashIndex+1 : poundIndex]
  358. var err error
  359. refRepo, err = GetRepositoryByOwnerAndName(ownerName, repoName)
  360. if err != nil {
  361. if IsErrRepoNotExist(err) {
  362. return nil, nil
  363. }
  364. return nil, err
  365. }
  366. }
  367. issueIndex, err := strconv.ParseInt(ref[poundIndex+1:], 10, 64)
  368. if err != nil {
  369. return nil, nil
  370. }
  371. issue, err := GetIssueByIndex(refRepo.ID, int64(issueIndex))
  372. if err != nil {
  373. if IsErrIssueNotExist(err) {
  374. return nil, nil
  375. }
  376. return nil, err
  377. }
  378. return issue, nil
  379. }
  380. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  381. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) error {
  382. // Commits are appended in the reverse order.
  383. for i := len(commits) - 1; i >= 0; i-- {
  384. c := commits[i]
  385. refMarked := make(map[int64]bool)
  386. for _, ref := range issueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  387. issue, err := getIssueFromRef(repo, ref)
  388. if err != nil {
  389. return err
  390. }
  391. if issue == nil || refMarked[issue.ID] {
  392. continue
  393. }
  394. refMarked[issue.ID] = true
  395. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, c.Message)
  396. if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil {
  397. return err
  398. }
  399. }
  400. refMarked = make(map[int64]bool)
  401. // FIXME: can merge this one and next one to a common function.
  402. for _, ref := range issueCloseKeywordsPat.FindAllString(c.Message, -1) {
  403. issue, err := getIssueFromRef(repo, ref)
  404. if err != nil {
  405. return err
  406. }
  407. if issue == nil || refMarked[issue.ID] {
  408. continue
  409. }
  410. refMarked[issue.ID] = true
  411. if issue.RepoID != repo.ID || issue.IsClosed {
  412. continue
  413. }
  414. if err = issue.ChangeStatus(doer, repo, true); err != nil {
  415. return err
  416. }
  417. }
  418. // It is conflict to have close and reopen at same time, so refsMarked doesn't need to reinit here.
  419. for _, ref := range issueReopenKeywordsPat.FindAllString(c.Message, -1) {
  420. issue, err := getIssueFromRef(repo, ref)
  421. if err != nil {
  422. return err
  423. }
  424. if issue == nil || refMarked[issue.ID] {
  425. continue
  426. }
  427. refMarked[issue.ID] = true
  428. if issue.RepoID != repo.ID || !issue.IsClosed {
  429. continue
  430. }
  431. if err = issue.ChangeStatus(doer, repo, false); err != nil {
  432. return err
  433. }
  434. }
  435. }
  436. return nil
  437. }
  438. // CommitRepoActionOptions represent options of a new commit action.
  439. type CommitRepoActionOptions struct {
  440. PusherName string
  441. RepoOwnerID int64
  442. RepoName string
  443. RefFullName string
  444. OldCommitID string
  445. NewCommitID string
  446. Commits *PushCommits
  447. }
  448. // CommitRepoAction adds new commit action to the repository, and prepare
  449. // corresponding webhooks.
  450. func CommitRepoAction(opts CommitRepoActionOptions) error {
  451. pusher, err := GetUserByName(opts.PusherName)
  452. if err != nil {
  453. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  454. }
  455. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  456. if err != nil {
  457. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  458. }
  459. // Change repository bare status and update last updated time.
  460. repo.IsBare = repo.IsBare && opts.Commits.Len <= 0
  461. if err = UpdateRepository(repo, false); err != nil {
  462. return fmt.Errorf("UpdateRepository: %v", err)
  463. }
  464. isNewBranch := false
  465. opType := ActionCommitRepo
  466. // Check it's tag push or branch.
  467. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  468. opType = ActionPushTag
  469. if opts.NewCommitID == git.EmptySHA {
  470. opType = ActionDeleteTag
  471. }
  472. opts.Commits = &PushCommits{}
  473. } else if opts.NewCommitID == git.EmptySHA {
  474. opType = ActionDeleteBranch
  475. opts.Commits = &PushCommits{}
  476. } else {
  477. // if not the first commit, set the compare URL.
  478. if opts.OldCommitID == git.EmptySHA {
  479. isNewBranch = true
  480. } else {
  481. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  482. }
  483. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits); err != nil {
  484. log.Error(4, "updateIssuesCommit: %v", err)
  485. }
  486. }
  487. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  488. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  489. }
  490. data, err := json.Marshal(opts.Commits)
  491. if err != nil {
  492. return fmt.Errorf("Marshal: %v", err)
  493. }
  494. refName := git.RefEndName(opts.RefFullName)
  495. if err = NotifyWatchers(&Action{
  496. ActUserID: pusher.ID,
  497. ActUser: pusher,
  498. OpType: opType,
  499. Content: string(data),
  500. RepoID: repo.ID,
  501. Repo: repo,
  502. RefName: refName,
  503. IsPrivate: repo.IsPrivate,
  504. }); err != nil {
  505. return fmt.Errorf("NotifyWatchers: %v", err)
  506. }
  507. defer func() {
  508. go HookQueue.Add(repo.ID)
  509. }()
  510. apiPusher := pusher.APIFormat()
  511. apiRepo := repo.APIFormat(AccessModeNone)
  512. var shaSum string
  513. var isHookEventPush = false
  514. switch opType {
  515. case ActionCommitRepo: // Push
  516. isHookEventPush = true
  517. if isNewBranch {
  518. gitRepo, err := git.OpenRepository(repo.RepoPath())
  519. if err != nil {
  520. log.Error(4, "OpenRepository[%s]: %v", repo.RepoPath(), err)
  521. }
  522. shaSum, err = gitRepo.GetBranchCommitID(refName)
  523. if err != nil {
  524. log.Error(4, "GetBranchCommitID[%s]: %v", opts.RefFullName, err)
  525. }
  526. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  527. Ref: refName,
  528. Sha: shaSum,
  529. RefType: "branch",
  530. Repo: apiRepo,
  531. Sender: apiPusher,
  532. }); err != nil {
  533. return fmt.Errorf("PrepareWebhooks: %v", err)
  534. }
  535. }
  536. case ActionDeleteBranch: // Delete Branch
  537. isHookEventPush = true
  538. case ActionPushTag: // Create
  539. isHookEventPush = true
  540. gitRepo, err := git.OpenRepository(repo.RepoPath())
  541. if err != nil {
  542. log.Error(4, "OpenRepository[%s]: %v", repo.RepoPath(), err)
  543. }
  544. shaSum, err = gitRepo.GetTagCommitID(refName)
  545. if err != nil {
  546. log.Error(4, "GetTagCommitID[%s]: %v", opts.RefFullName, err)
  547. }
  548. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  549. Ref: refName,
  550. Sha: shaSum,
  551. RefType: "tag",
  552. Repo: apiRepo,
  553. Sender: apiPusher,
  554. }); err != nil {
  555. return fmt.Errorf("PrepareWebhooks: %v", err)
  556. }
  557. case ActionDeleteTag: // Delete Tag
  558. isHookEventPush = true
  559. }
  560. if isHookEventPush {
  561. if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  562. Ref: opts.RefFullName,
  563. Before: opts.OldCommitID,
  564. After: opts.NewCommitID,
  565. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  566. Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()),
  567. Repo: apiRepo,
  568. Pusher: apiPusher,
  569. Sender: apiPusher,
  570. }); err != nil {
  571. return fmt.Errorf("PrepareWebhooks: %v", err)
  572. }
  573. }
  574. return nil
  575. }
  576. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  577. if err = notifyWatchers(e, &Action{
  578. ActUserID: doer.ID,
  579. ActUser: doer,
  580. OpType: ActionTransferRepo,
  581. RepoID: repo.ID,
  582. Repo: repo,
  583. IsPrivate: repo.IsPrivate,
  584. Content: path.Join(oldOwner.Name, repo.Name),
  585. }); err != nil {
  586. return fmt.Errorf("notifyWatchers: %v", err)
  587. }
  588. // Remove watch for organization.
  589. if oldOwner.IsOrganization() {
  590. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  591. return fmt.Errorf("watchRepo [false]: %v", err)
  592. }
  593. }
  594. return nil
  595. }
  596. // TransferRepoAction adds new action for transferring repository,
  597. // the Owner field of repository is assumed to be new owner.
  598. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  599. return transferRepoAction(x, doer, oldOwner, repo)
  600. }
  601. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  602. return notifyWatchers(e, &Action{
  603. ActUserID: doer.ID,
  604. ActUser: doer,
  605. OpType: ActionMergePullRequest,
  606. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  607. RepoID: repo.ID,
  608. Repo: repo,
  609. IsPrivate: repo.IsPrivate,
  610. })
  611. }
  612. // MergePullRequestAction adds new action for merging pull request.
  613. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  614. return mergePullRequestAction(x, actUser, repo, pull)
  615. }
  616. // GetFeedsOptions options for retrieving feeds
  617. type GetFeedsOptions struct {
  618. RequestedUser *User
  619. RequestingUserID int64
  620. IncludePrivate bool // include private actions
  621. OnlyPerformedBy bool // only actions performed by requested user
  622. IncludeDeleted bool // include deleted actions
  623. }
  624. // GetFeeds returns actions according to the provided options
  625. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  626. cond := builder.NewCond()
  627. var repoIDs []int64
  628. if opts.RequestedUser.IsOrganization() {
  629. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  630. if err != nil {
  631. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  632. }
  633. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  634. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  635. }
  636. cond = cond.And(builder.In("repo_id", repoIDs))
  637. }
  638. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  639. if opts.OnlyPerformedBy {
  640. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  641. }
  642. if !opts.IncludePrivate {
  643. cond = cond.And(builder.Eq{"is_private": false})
  644. }
  645. if !opts.IncludeDeleted {
  646. cond = cond.And(builder.Eq{"is_deleted": false})
  647. }
  648. actions := make([]*Action, 0, 20)
  649. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  650. return nil, fmt.Errorf("Find: %v", err)
  651. }
  652. if err := ActionList(actions).LoadAttributes(); err != nil {
  653. return nil, fmt.Errorf("LoadAttributes: %v", err)
  654. }
  655. return actions, nil
  656. }