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 22KB

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