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.

action.go 19KB

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