Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

action.go 20KB

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