Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

action.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "html"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/references"
  18. "code.gitea.io/gitea/modules/setting"
  19. api "code.gitea.io/gitea/modules/structs"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. "github.com/unknwon/com"
  22. "xorm.io/builder"
  23. )
  24. // ActionType represents the type of an action.
  25. type ActionType int
  26. // Possible action types.
  27. const (
  28. ActionCreateRepo ActionType = iota + 1 // 1
  29. ActionRenameRepo // 2
  30. ActionStarRepo // 3
  31. ActionWatchRepo // 4
  32. ActionCommitRepo // 5
  33. ActionCreateIssue // 6
  34. ActionCreatePullRequest // 7
  35. ActionTransferRepo // 8
  36. ActionPushTag // 9
  37. ActionCommentIssue // 10
  38. ActionMergePullRequest // 11
  39. ActionCloseIssue // 12
  40. ActionReopenIssue // 13
  41. ActionClosePullRequest // 14
  42. ActionReopenPullRequest // 15
  43. ActionDeleteTag // 16
  44. ActionDeleteBranch // 17
  45. ActionMirrorSyncPush // 18
  46. ActionMirrorSyncCreate // 19
  47. ActionMirrorSyncDelete // 20
  48. )
  49. // Action represents user operation type and other information to
  50. // repository. It implemented interface base.Actioner so that can be
  51. // used in template render.
  52. type Action struct {
  53. ID int64 `xorm:"pk autoincr"`
  54. UserID int64 `xorm:"INDEX"` // Receiver user id.
  55. OpType ActionType
  56. ActUserID int64 `xorm:"INDEX"` // Action user id.
  57. ActUser *User `xorm:"-"`
  58. RepoID int64 `xorm:"INDEX"`
  59. Repo *Repository `xorm:"-"`
  60. CommentID int64 `xorm:"INDEX"`
  61. Comment *Comment `xorm:"-"`
  62. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  63. RefName string
  64. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  65. Content string `xorm:"TEXT"`
  66. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  67. }
  68. // GetOpType gets the ActionType of this action.
  69. func (a *Action) GetOpType() ActionType {
  70. return a.OpType
  71. }
  72. func (a *Action) loadActUser() {
  73. if a.ActUser != nil {
  74. return
  75. }
  76. var err error
  77. a.ActUser, err = GetUserByID(a.ActUserID)
  78. if err == nil {
  79. return
  80. } else if IsErrUserNotExist(err) {
  81. a.ActUser = NewGhostUser()
  82. } else {
  83. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  84. }
  85. }
  86. func (a *Action) loadRepo() {
  87. if a.Repo != nil {
  88. return
  89. }
  90. var err error
  91. a.Repo, err = GetRepositoryByID(a.RepoID)
  92. if err != nil {
  93. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  94. }
  95. }
  96. // GetActFullName gets the action's user full name.
  97. func (a *Action) GetActFullName() string {
  98. a.loadActUser()
  99. return a.ActUser.FullName
  100. }
  101. // GetActUserName gets the action's user name.
  102. func (a *Action) GetActUserName() string {
  103. a.loadActUser()
  104. return a.ActUser.Name
  105. }
  106. // ShortActUserName gets the action's user name trimmed to max 20
  107. // chars.
  108. func (a *Action) ShortActUserName() string {
  109. return base.EllipsisString(a.GetActUserName(), 20)
  110. }
  111. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME
  112. func (a *Action) GetDisplayName() string {
  113. if setting.UI.DefaultShowFullName {
  114. return a.GetActFullName()
  115. }
  116. return a.ShortActUserName()
  117. }
  118. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  119. func (a *Action) GetDisplayNameTitle() string {
  120. if setting.UI.DefaultShowFullName {
  121. return a.ShortActUserName()
  122. }
  123. return a.GetActFullName()
  124. }
  125. // GetActAvatar the action's user's avatar link
  126. func (a *Action) GetActAvatar() string {
  127. a.loadActUser()
  128. return a.ActUser.RelAvatarLink()
  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. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  167. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  168. var err error
  169. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  170. if err != nil {
  171. if IsErrRepoNotExist(err) {
  172. log.Warn("Repository referenced in commit but does not exist: %v", err)
  173. return nil, err
  174. }
  175. log.Error("GetRepositoryByOwnerAndName: %v", err)
  176. return nil, err
  177. }
  178. return refRepo, nil
  179. }
  180. // GetCommentLink returns link to action comment.
  181. func (a *Action) GetCommentLink() string {
  182. return a.getCommentLink(x)
  183. }
  184. func (a *Action) getCommentLink(e Engine) string {
  185. if a == nil {
  186. return "#"
  187. }
  188. if a.Comment == nil && a.CommentID != 0 {
  189. a.Comment, _ = GetCommentByID(a.CommentID)
  190. }
  191. if a.Comment != nil {
  192. return a.Comment.HTMLURL()
  193. }
  194. if len(a.GetIssueInfos()) == 0 {
  195. return "#"
  196. }
  197. //Return link to issue
  198. issueIDString := a.GetIssueInfos()[0]
  199. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  200. if err != nil {
  201. return "#"
  202. }
  203. issue, err := getIssueByID(e, issueID)
  204. if err != nil {
  205. return "#"
  206. }
  207. if err = issue.loadRepo(e); err != nil {
  208. return "#"
  209. }
  210. return issue.HTMLURL()
  211. }
  212. // GetBranch returns the action's repository branch.
  213. func (a *Action) GetBranch() string {
  214. return a.RefName
  215. }
  216. // GetContent returns the action's content.
  217. func (a *Action) GetContent() string {
  218. return a.Content
  219. }
  220. // GetCreate returns the action creation time.
  221. func (a *Action) GetCreate() time.Time {
  222. return a.CreatedUnix.AsTime()
  223. }
  224. // GetIssueInfos returns a list of issues associated with
  225. // the action.
  226. func (a *Action) GetIssueInfos() []string {
  227. return strings.SplitN(a.Content, "|", 2)
  228. }
  229. // GetIssueTitle returns the title of first issue associated
  230. // with the action.
  231. func (a *Action) GetIssueTitle() string {
  232. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  233. issue, err := GetIssueByIndex(a.RepoID, index)
  234. if err != nil {
  235. log.Error("GetIssueByIndex: %v", err)
  236. return "500 when get issue"
  237. }
  238. return issue.Title
  239. }
  240. // GetIssueContent returns the content of first issue associated with
  241. // this action.
  242. func (a *Action) GetIssueContent() string {
  243. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  244. issue, err := GetIssueByIndex(a.RepoID, index)
  245. if err != nil {
  246. log.Error("GetIssueByIndex: %v", err)
  247. return "500 when get issue"
  248. }
  249. return issue.Content
  250. }
  251. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  252. if err = notifyWatchers(e, &Action{
  253. ActUserID: u.ID,
  254. ActUser: u,
  255. OpType: ActionCreateRepo,
  256. RepoID: repo.ID,
  257. Repo: repo,
  258. IsPrivate: repo.IsPrivate,
  259. }); err != nil {
  260. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  261. }
  262. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  263. return err
  264. }
  265. // NewRepoAction adds new action for creating repository.
  266. func NewRepoAction(u *User, repo *Repository) (err error) {
  267. return newRepoAction(x, u, repo)
  268. }
  269. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  270. if err = notifyWatchers(e, &Action{
  271. ActUserID: actUser.ID,
  272. ActUser: actUser,
  273. OpType: ActionRenameRepo,
  274. RepoID: repo.ID,
  275. Repo: repo,
  276. IsPrivate: repo.IsPrivate,
  277. Content: oldRepoName,
  278. }); err != nil {
  279. return fmt.Errorf("notify watchers: %v", err)
  280. }
  281. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  282. return nil
  283. }
  284. // RenameRepoAction adds new action for renaming a repository.
  285. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  286. return renameRepoAction(x, actUser, oldRepoName, repo)
  287. }
  288. // PushCommit represents a commit in a push operation.
  289. type PushCommit struct {
  290. Sha1 string
  291. Message string
  292. AuthorEmail string
  293. AuthorName string
  294. CommitterEmail string
  295. CommitterName string
  296. Timestamp time.Time
  297. }
  298. // PushCommits represents list of commits in a push operation.
  299. type PushCommits struct {
  300. Len int
  301. Commits []*PushCommit
  302. CompareURL string
  303. avatars map[string]string
  304. emailUsers map[string]*User
  305. }
  306. // NewPushCommits creates a new PushCommits object.
  307. func NewPushCommits() *PushCommits {
  308. return &PushCommits{
  309. avatars: make(map[string]string),
  310. emailUsers: make(map[string]*User),
  311. }
  312. }
  313. // ToAPIPayloadCommits converts a PushCommits object to
  314. // api.PayloadCommit format.
  315. func (pc *PushCommits) ToAPIPayloadCommits(repoPath, repoLink string) ([]*api.PayloadCommit, error) {
  316. commits := make([]*api.PayloadCommit, len(pc.Commits))
  317. if pc.emailUsers == nil {
  318. pc.emailUsers = make(map[string]*User)
  319. }
  320. var err error
  321. for i, commit := range pc.Commits {
  322. authorUsername := ""
  323. author, ok := pc.emailUsers[commit.AuthorEmail]
  324. if !ok {
  325. author, err = GetUserByEmail(commit.AuthorEmail)
  326. if err == nil {
  327. authorUsername = author.Name
  328. pc.emailUsers[commit.AuthorEmail] = author
  329. }
  330. } else {
  331. authorUsername = author.Name
  332. }
  333. committerUsername := ""
  334. committer, ok := pc.emailUsers[commit.CommitterEmail]
  335. if !ok {
  336. committer, err = GetUserByEmail(commit.CommitterEmail)
  337. if err == nil {
  338. // TODO: check errors other than email not found.
  339. committerUsername = committer.Name
  340. pc.emailUsers[commit.CommitterEmail] = committer
  341. }
  342. } else {
  343. committerUsername = committer.Name
  344. }
  345. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  346. if err != nil {
  347. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  348. }
  349. commits[i] = &api.PayloadCommit{
  350. ID: commit.Sha1,
  351. Message: commit.Message,
  352. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  353. Author: &api.PayloadUser{
  354. Name: commit.AuthorName,
  355. Email: commit.AuthorEmail,
  356. UserName: authorUsername,
  357. },
  358. Committer: &api.PayloadUser{
  359. Name: commit.CommitterName,
  360. Email: commit.CommitterEmail,
  361. UserName: committerUsername,
  362. },
  363. Added: fileStatus.Added,
  364. Removed: fileStatus.Removed,
  365. Modified: fileStatus.Modified,
  366. Timestamp: commit.Timestamp,
  367. }
  368. }
  369. return commits, nil
  370. }
  371. // AvatarLink tries to match user in database with e-mail
  372. // in order to show custom avatar, and falls back to general avatar link.
  373. func (pc *PushCommits) AvatarLink(email string) string {
  374. if pc.avatars == nil {
  375. pc.avatars = make(map[string]string)
  376. }
  377. avatar, ok := pc.avatars[email]
  378. if ok {
  379. return avatar
  380. }
  381. u, ok := pc.emailUsers[email]
  382. if !ok {
  383. var err error
  384. u, err = GetUserByEmail(email)
  385. if err != nil {
  386. pc.avatars[email] = base.AvatarLink(email)
  387. if !IsErrUserNotExist(err) {
  388. log.Error("GetUserByEmail: %v", err)
  389. return ""
  390. }
  391. } else {
  392. pc.emailUsers[email] = u
  393. }
  394. }
  395. if u != nil {
  396. pc.avatars[email] = u.RelAvatarLink()
  397. }
  398. return pc.avatars[email]
  399. }
  400. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  401. // if the provided ref references a non-existent issue.
  402. func getIssueFromRef(repo *Repository, index int64) (*Issue, error) {
  403. issue, err := GetIssueByIndex(repo.ID, index)
  404. if err != nil {
  405. if IsErrIssueNotExist(err) {
  406. return nil, nil
  407. }
  408. return nil, err
  409. }
  410. return issue, nil
  411. }
  412. func changeIssueStatus(repo *Repository, issue *Issue, doer *User, status bool) error {
  413. stopTimerIfAvailable := func(doer *User, issue *Issue) error {
  414. if StopwatchExists(doer.ID, issue.ID) {
  415. if err := CreateOrStopIssueStopwatch(doer, issue); err != nil {
  416. return err
  417. }
  418. }
  419. return nil
  420. }
  421. issue.Repo = repo
  422. if err := issue.ChangeStatus(doer, status); err != nil {
  423. // Don't return an error when dependencies are open as this would let the push fail
  424. if IsErrDependenciesLeft(err) {
  425. return stopTimerIfAvailable(doer, issue)
  426. }
  427. return err
  428. }
  429. return stopTimerIfAvailable(doer, issue)
  430. }
  431. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  432. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit, branchName string) error {
  433. // Commits are appended in the reverse order.
  434. for i := len(commits) - 1; i >= 0; i-- {
  435. c := commits[i]
  436. type markKey struct {
  437. ID int64
  438. Action references.XRefAction
  439. }
  440. refMarked := make(map[markKey]bool)
  441. var refRepo *Repository
  442. var refIssue *Issue
  443. var err error
  444. for _, ref := range references.FindAllIssueReferences(c.Message) {
  445. // issue is from another repo
  446. if len(ref.Owner) > 0 && len(ref.Name) > 0 {
  447. refRepo, err = GetRepositoryFromMatch(ref.Owner, ref.Name)
  448. if err != nil {
  449. continue
  450. }
  451. } else {
  452. refRepo = repo
  453. }
  454. if refIssue, err = getIssueFromRef(refRepo, ref.Index); err != nil {
  455. return err
  456. }
  457. if refIssue == nil {
  458. continue
  459. }
  460. perm, err := GetUserRepoPermission(refRepo, doer)
  461. if err != nil {
  462. return err
  463. }
  464. key := markKey{ID: refIssue.ID, Action: ref.Action}
  465. if refMarked[key] {
  466. continue
  467. }
  468. refMarked[key] = true
  469. // FIXME: this kind of condition is all over the code, it should be consolidated in a single place
  470. canclose := perm.IsAdmin() || perm.IsOwner() || perm.CanWrite(UnitTypeIssues) || refIssue.PosterID == doer.ID
  471. cancomment := canclose || perm.CanRead(UnitTypeIssues)
  472. // Don't proceed if the user can't comment
  473. if !cancomment {
  474. continue
  475. }
  476. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, html.EscapeString(c.Message))
  477. if err = CreateRefComment(doer, refRepo, refIssue, message, c.Sha1); err != nil {
  478. return err
  479. }
  480. // Only issues can be closed/reopened this way, and user needs the correct permissions
  481. if refIssue.IsPull || !canclose {
  482. continue
  483. }
  484. // Only process closing/reopening keywords
  485. if ref.Action != references.XRefActionCloses && ref.Action != references.XRefActionReopens {
  486. continue
  487. }
  488. if !repo.CloseIssuesViaCommitInAnyBranch {
  489. // If the issue was specified to be in a particular branch, don't allow commits in other branches to close it
  490. if refIssue.Ref != "" {
  491. if branchName != refIssue.Ref {
  492. continue
  493. }
  494. // Otherwise, only process commits to the default branch
  495. } else if branchName != repo.DefaultBranch {
  496. continue
  497. }
  498. }
  499. if err := changeIssueStatus(refRepo, refIssue, doer, ref.Action == references.XRefActionCloses); err != nil {
  500. return err
  501. }
  502. }
  503. }
  504. return nil
  505. }
  506. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  507. if err = notifyWatchers(e, &Action{
  508. ActUserID: doer.ID,
  509. ActUser: doer,
  510. OpType: ActionTransferRepo,
  511. RepoID: repo.ID,
  512. Repo: repo,
  513. IsPrivate: repo.IsPrivate,
  514. Content: path.Join(oldOwner.Name, repo.Name),
  515. }); err != nil {
  516. return fmt.Errorf("notifyWatchers: %v", err)
  517. }
  518. // Remove watch for organization.
  519. if oldOwner.IsOrganization() {
  520. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  521. return fmt.Errorf("watchRepo [false]: %v", err)
  522. }
  523. }
  524. return nil
  525. }
  526. // TransferRepoAction adds new action for transferring repository,
  527. // the Owner field of repository is assumed to be new owner.
  528. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  529. return transferRepoAction(x, doer, oldOwner, repo)
  530. }
  531. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  532. return notifyWatchers(e, &Action{
  533. ActUserID: doer.ID,
  534. ActUser: doer,
  535. OpType: ActionMergePullRequest,
  536. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  537. RepoID: repo.ID,
  538. Repo: repo,
  539. IsPrivate: repo.IsPrivate,
  540. })
  541. }
  542. // MergePullRequestAction adds new action for merging pull request.
  543. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  544. return mergePullRequestAction(x, actUser, repo, pull)
  545. }
  546. func mirrorSyncAction(e Engine, opType ActionType, repo *Repository, refName string, data []byte) error {
  547. if err := notifyWatchers(e, &Action{
  548. ActUserID: repo.OwnerID,
  549. ActUser: repo.MustOwner(),
  550. OpType: opType,
  551. RepoID: repo.ID,
  552. Repo: repo,
  553. IsPrivate: repo.IsPrivate,
  554. RefName: refName,
  555. Content: string(data),
  556. }); err != nil {
  557. return fmt.Errorf("notifyWatchers: %v", err)
  558. }
  559. defer func() {
  560. go HookQueue.Add(repo.ID)
  561. }()
  562. return nil
  563. }
  564. // MirrorSyncPushActionOptions mirror synchronization action options.
  565. type MirrorSyncPushActionOptions struct {
  566. RefName string
  567. OldCommitID string
  568. NewCommitID string
  569. Commits *PushCommits
  570. }
  571. // MirrorSyncPushAction adds new action for mirror synchronization of pushed commits.
  572. func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) error {
  573. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  574. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  575. }
  576. apiCommits, err := opts.Commits.ToAPIPayloadCommits(repo.RepoPath(), repo.HTMLURL())
  577. if err != nil {
  578. return err
  579. }
  580. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  581. apiPusher := repo.MustOwner().APIFormat()
  582. if err := PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  583. Ref: opts.RefName,
  584. Before: opts.OldCommitID,
  585. After: opts.NewCommitID,
  586. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  587. Commits: apiCommits,
  588. Repo: repo.APIFormat(AccessModeOwner),
  589. Pusher: apiPusher,
  590. Sender: apiPusher,
  591. }); err != nil {
  592. return fmt.Errorf("PrepareWebhooks: %v", err)
  593. }
  594. data, err := json.Marshal(opts.Commits)
  595. if err != nil {
  596. return err
  597. }
  598. return mirrorSyncAction(x, ActionMirrorSyncPush, repo, opts.RefName, data)
  599. }
  600. // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
  601. func MirrorSyncCreateAction(repo *Repository, refName string) error {
  602. return mirrorSyncAction(x, ActionMirrorSyncCreate, repo, refName, nil)
  603. }
  604. // MirrorSyncDeleteAction adds new action for mirror synchronization of delete reference.
  605. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  606. return mirrorSyncAction(x, ActionMirrorSyncDelete, repo, refName, nil)
  607. }
  608. // GetFeedsOptions options for retrieving feeds
  609. type GetFeedsOptions struct {
  610. RequestedUser *User
  611. RequestingUserID int64
  612. IncludePrivate bool // include private actions
  613. OnlyPerformedBy bool // only actions performed by requested user
  614. IncludeDeleted bool // include deleted actions
  615. }
  616. // GetFeeds returns actions according to the provided options
  617. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  618. cond := builder.NewCond()
  619. var repoIDs []int64
  620. if opts.RequestedUser.IsOrganization() {
  621. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  622. if err != nil {
  623. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  624. }
  625. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  626. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  627. }
  628. cond = cond.And(builder.In("repo_id", repoIDs))
  629. }
  630. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  631. if opts.OnlyPerformedBy {
  632. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  633. }
  634. if !opts.IncludePrivate {
  635. cond = cond.And(builder.Eq{"is_private": false})
  636. }
  637. if !opts.IncludeDeleted {
  638. cond = cond.And(builder.Eq{"is_deleted": false})
  639. }
  640. actions := make([]*Action, 0, 20)
  641. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  642. return nil, fmt.Errorf("Find: %v", err)
  643. }
  644. if err := ActionList(actions).LoadAttributes(); err != nil {
  645. return nil, fmt.Errorf("LoadAttributes: %v", err)
  646. }
  647. return actions, nil
  648. }