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

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