action.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package models
  7. import (
  8. "fmt"
  9. "gitote/gitote/models/errors"
  10. "gitote/gitote/pkg/setting"
  11. "gitote/gitote/pkg/tool"
  12. "path"
  13. "regexp"
  14. "strings"
  15. "time"
  16. "unicode"
  17. raven "github.com/getsentry/raven-go"
  18. "github.com/go-xorm/xorm"
  19. "github.com/json-iterator/go"
  20. "gitlab.com/gitote/com"
  21. "gitlab.com/gitote/git-module"
  22. api "gitlab.com/gitote/go-gitote-client"
  23. log "gopkg.in/clog.v1"
  24. )
  25. type ActionType int
  26. // Note: To maintain backward compatibility only append to the end of list
  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. ActionCreateBranch // 16
  44. ActionDeleteBranch // 17
  45. ActionDeleteTag // 18
  46. ActionForkRepo // 19
  47. ActionMirrorSyncPush // 20
  48. ActionMirrorSyncCreate // 21
  49. ActionMirrorSyncDelete // 22
  50. )
  51. var (
  52. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  53. IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  54. IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  55. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  56. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  57. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  58. )
  59. func assembleKeywordsPattern(words []string) string {
  60. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  61. }
  62. // Action represents user operation type and other information to repository,
  63. // it implemented interface base.Actioner so that can be used in template render.
  64. type Action struct {
  65. ID int64
  66. UserID int64 // Receiver user ID
  67. OpType ActionType
  68. ActUserID int64 // Doer user ID
  69. ActUserName string // Doer user name
  70. ActAvatar string `xorm:"-" json:"-"`
  71. RepoID int64 `xorm:"INDEX"`
  72. RepoUserName string
  73. RepoName string
  74. RefName string
  75. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  76. Content string `xorm:"TEXT"`
  77. Created time.Time `xorm:"-" json:"-"`
  78. CreatedUnix int64
  79. }
  80. func (a *Action) BeforeInsert() {
  81. a.CreatedUnix = time.Now().Unix()
  82. }
  83. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  84. switch colName {
  85. case "created_unix":
  86. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  87. }
  88. }
  89. func (a *Action) GetOpType() int {
  90. return int(a.OpType)
  91. }
  92. func (a *Action) GetActUserName() string {
  93. return a.ActUserName
  94. }
  95. func (a *Action) ShortActUserName() string {
  96. return tool.EllipsisString(a.ActUserName, 20)
  97. }
  98. func (a *Action) GetRepoUserName() string {
  99. return a.RepoUserName
  100. }
  101. func (a *Action) ShortRepoUserName() string {
  102. return tool.EllipsisString(a.RepoUserName, 20)
  103. }
  104. func (a *Action) GetRepoName() string {
  105. return a.RepoName
  106. }
  107. func (a *Action) ShortRepoName() string {
  108. return tool.EllipsisString(a.RepoName, 33)
  109. }
  110. func (a *Action) GetRepoPath() string {
  111. return path.Join(a.RepoUserName, a.RepoName)
  112. }
  113. func (a *Action) ShortRepoPath() string {
  114. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  115. }
  116. func (a *Action) GetRepoLink() string {
  117. if len(setting.AppSubURL) > 0 {
  118. return path.Join(setting.AppSubURL, a.GetRepoPath())
  119. }
  120. return "/" + a.GetRepoPath()
  121. }
  122. func (a *Action) GetBranch() string {
  123. return a.RefName
  124. }
  125. func (a *Action) GetContent() string {
  126. return a.Content
  127. }
  128. func (a *Action) GetCreate() time.Time {
  129. return a.Created
  130. }
  131. func (a *Action) GetIssueInfos() []string {
  132. return strings.SplitN(a.Content, "|", 2)
  133. }
  134. func (a *Action) GetIssueTitle() string {
  135. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  136. issue, err := GetIssueByIndex(a.RepoID, index)
  137. if err != nil {
  138. raven.CaptureErrorAndWait(err, nil)
  139. log.Error(4, "GetIssueByIndex: %v", err)
  140. return "500 when get issue"
  141. }
  142. return issue.Title
  143. }
  144. func (a *Action) GetIssueContent() string {
  145. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  146. issue, err := GetIssueByIndex(a.RepoID, index)
  147. if err != nil {
  148. raven.CaptureErrorAndWait(err, nil)
  149. log.Error(4, "GetIssueByIndex: %v", err)
  150. return "500 when get issue"
  151. }
  152. return issue.Content
  153. }
  154. func newRepoAction(e Engine, doer, owner *User, repo *Repository) (err error) {
  155. opType := ActionCreateRepo
  156. if repo.IsFork {
  157. opType = ActionForkRepo
  158. }
  159. return notifyWatchers(e, &Action{
  160. ActUserID: doer.ID,
  161. ActUserName: doer.Name,
  162. OpType: opType,
  163. RepoID: repo.ID,
  164. RepoUserName: repo.Owner.Name,
  165. RepoName: repo.Name,
  166. IsPrivate: repo.IsPrivate,
  167. })
  168. }
  169. // NewRepoAction adds new action for creating repository.
  170. func NewRepoAction(doer, owner *User, repo *Repository) (err error) {
  171. return newRepoAction(x, doer, owner, repo)
  172. }
  173. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  174. if err = notifyWatchers(e, &Action{
  175. ActUserID: actUser.ID,
  176. ActUserName: actUser.Name,
  177. OpType: ActionRenameRepo,
  178. RepoID: repo.ID,
  179. RepoUserName: repo.Owner.Name,
  180. RepoName: repo.Name,
  181. IsPrivate: repo.IsPrivate,
  182. Content: oldRepoName,
  183. }); err != nil {
  184. return fmt.Errorf("notify watchers: %v", err)
  185. }
  186. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  187. return nil
  188. }
  189. // RenameRepoAction adds new action for renaming a repository.
  190. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  191. return renameRepoAction(x, actUser, oldRepoName, repo)
  192. }
  193. func issueIndexTrimRight(c rune) bool {
  194. return !unicode.IsDigit(c)
  195. }
  196. type PushCommit struct {
  197. Sha1 string
  198. Message string
  199. AuthorEmail string
  200. AuthorName string
  201. CommitterEmail string
  202. CommitterName string
  203. Timestamp time.Time
  204. }
  205. type PushCommits struct {
  206. Len int
  207. Commits []*PushCommit
  208. CompareURL string
  209. avatars map[string]string
  210. }
  211. // NewPushCommits returns new push commits
  212. func NewPushCommits() *PushCommits {
  213. return &PushCommits{
  214. avatars: make(map[string]string),
  215. }
  216. }
  217. func (pc *PushCommits) ToApiPayloadCommits(repoPath, repoURL string) ([]*api.PayloadCommit, error) {
  218. commits := make([]*api.PayloadCommit, len(pc.Commits))
  219. for i, commit := range pc.Commits {
  220. authorUsername := ""
  221. author, err := GetUserByEmail(commit.AuthorEmail)
  222. if err == nil {
  223. authorUsername = author.Name
  224. } else if !errors.IsUserNotExist(err) {
  225. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  226. }
  227. committerUsername := ""
  228. committer, err := GetUserByEmail(commit.CommitterEmail)
  229. if err == nil {
  230. committerUsername = committer.Name
  231. } else if !errors.IsUserNotExist(err) {
  232. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  233. }
  234. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  235. if err != nil {
  236. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  237. }
  238. commits[i] = &api.PayloadCommit{
  239. ID: commit.Sha1,
  240. Message: commit.Message,
  241. URL: fmt.Sprintf("%s/commit/%s", repoURL, commit.Sha1),
  242. Author: &api.PayloadUser{
  243. Name: commit.AuthorName,
  244. Email: commit.AuthorEmail,
  245. UserName: authorUsername,
  246. },
  247. Committer: &api.PayloadUser{
  248. Name: commit.CommitterName,
  249. Email: commit.CommitterEmail,
  250. UserName: committerUsername,
  251. },
  252. Added: fileStatus.Added,
  253. Removed: fileStatus.Removed,
  254. Modified: fileStatus.Modified,
  255. Timestamp: commit.Timestamp,
  256. }
  257. }
  258. return commits, nil
  259. }
  260. // AvatarLink tries to match user in database with e-mail
  261. // in order to show custom avatar, and falls back to general avatar link.
  262. func (push *PushCommits) AvatarLink(email string) string {
  263. _, ok := push.avatars[email]
  264. if !ok {
  265. u, err := GetUserByEmail(email)
  266. if err != nil {
  267. push.avatars[email] = tool.AvatarLink(email)
  268. if !errors.IsUserNotExist(err) {
  269. raven.CaptureErrorAndWait(err, nil)
  270. log.Error(4, "GetUserByEmail: %v", err)
  271. }
  272. } else {
  273. push.avatars[email] = u.RelAvatarLink()
  274. }
  275. }
  276. return push.avatars[email]
  277. }
  278. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  279. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) error {
  280. // Commits are appended in the reverse order.
  281. for i := len(commits) - 1; i >= 0; i-- {
  282. c := commits[i]
  283. refMarked := make(map[int64]bool)
  284. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  285. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  286. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  287. if len(ref) == 0 {
  288. continue
  289. }
  290. // Add repo name if missing
  291. if ref[0] == '#' {
  292. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  293. } else if !strings.Contains(ref, "/") {
  294. // FIXME: We don't support User#ID syntax yet
  295. // return ErrNotImplemented
  296. continue
  297. }
  298. issue, err := GetIssueByRef(ref)
  299. if err != nil {
  300. if errors.IsIssueNotExist(err) {
  301. continue
  302. }
  303. return err
  304. }
  305. if refMarked[issue.ID] {
  306. continue
  307. }
  308. refMarked[issue.ID] = true
  309. msgLines := strings.Split(c.Message, "\n")
  310. shortMsg := msgLines[0]
  311. if len(msgLines) > 2 {
  312. shortMsg += "..."
  313. }
  314. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, shortMsg)
  315. if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil {
  316. return err
  317. }
  318. }
  319. refMarked = make(map[int64]bool)
  320. // FIXME: can merge this one and next one to a common function.
  321. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  322. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  323. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  324. if len(ref) == 0 {
  325. continue
  326. }
  327. // Add repo name if missing
  328. if ref[0] == '#' {
  329. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  330. } else if !strings.Contains(ref, "/") {
  331. // FIXME: We don't support User#ID syntax yet
  332. continue
  333. }
  334. issue, err := GetIssueByRef(ref)
  335. if err != nil {
  336. if errors.IsIssueNotExist(err) {
  337. continue
  338. }
  339. return err
  340. }
  341. if refMarked[issue.ID] {
  342. continue
  343. }
  344. refMarked[issue.ID] = true
  345. if issue.RepoID != repo.ID || issue.IsClosed {
  346. continue
  347. }
  348. if err = issue.ChangeStatus(doer, repo, true); err != nil {
  349. return err
  350. }
  351. }
  352. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  353. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  354. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  355. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  356. if len(ref) == 0 {
  357. continue
  358. }
  359. // Add repo name if missing
  360. if ref[0] == '#' {
  361. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  362. } else if !strings.Contains(ref, "/") {
  363. // We don't support User#ID syntax yet
  364. // return ErrNotImplemented
  365. continue
  366. }
  367. issue, err := GetIssueByRef(ref)
  368. if err != nil {
  369. if errors.IsIssueNotExist(err) {
  370. continue
  371. }
  372. return err
  373. }
  374. if refMarked[issue.ID] {
  375. continue
  376. }
  377. refMarked[issue.ID] = true
  378. if issue.RepoID != repo.ID || !issue.IsClosed {
  379. continue
  380. }
  381. if err = issue.ChangeStatus(doer, repo, false); err != nil {
  382. return err
  383. }
  384. }
  385. }
  386. return nil
  387. }
  388. type CommitRepoActionOptions struct {
  389. PusherName string
  390. RepoOwnerID int64
  391. RepoName string
  392. RefFullName string
  393. OldCommitID string
  394. NewCommitID string
  395. Commits *PushCommits
  396. }
  397. // CommitRepoAction adds new commit actio to the repository, and prepare corresponding webhooks.
  398. func CommitRepoAction(opts CommitRepoActionOptions) error {
  399. pusher, err := GetUserByName(opts.PusherName)
  400. if err != nil {
  401. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  402. }
  403. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  404. if err != nil {
  405. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  406. }
  407. // Change repository bare status and update last updated time.
  408. repo.IsBare = false
  409. if err = UpdateRepository(repo, false); err != nil {
  410. return fmt.Errorf("UpdateRepository: %v", err)
  411. }
  412. isNewRef := opts.OldCommitID == git.EMPTY_SHA
  413. isDelRef := opts.NewCommitID == git.EMPTY_SHA
  414. opType := ActionCommitRepo
  415. // Check if it's tag push or branch.
  416. if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
  417. opType = ActionPushTag
  418. } else {
  419. // if not the first commit, set the compare URL.
  420. if !isNewRef && !isDelRef {
  421. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  422. }
  423. // Only update issues via commits when internal issue tracker is enabled
  424. if repo.EnableIssues && !repo.EnableExternalTracker {
  425. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits); err != nil {
  426. raven.CaptureErrorAndWait(err, nil)
  427. log.Error(2, "UpdateIssuesCommit: %v", err)
  428. }
  429. }
  430. }
  431. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  432. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  433. }
  434. data, err := jsoniter.Marshal(opts.Commits)
  435. if err != nil {
  436. return fmt.Errorf("Marshal: %v", err)
  437. }
  438. refName := git.RefEndName(opts.RefFullName)
  439. action := &Action{
  440. ActUserID: pusher.ID,
  441. ActUserName: pusher.Name,
  442. Content: string(data),
  443. RepoID: repo.ID,
  444. RepoUserName: repo.MustOwner().Name,
  445. RepoName: repo.Name,
  446. RefName: refName,
  447. IsPrivate: repo.IsPrivate,
  448. }
  449. apiRepo := repo.APIFormat(nil)
  450. apiPusher := pusher.APIFormat()
  451. switch opType {
  452. case ActionCommitRepo: // Push
  453. if isDelRef {
  454. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  455. Ref: refName,
  456. RefType: "branch",
  457. PusherType: api.PUSHER_TYPE_USER,
  458. Repo: apiRepo,
  459. Sender: apiPusher,
  460. }); err != nil {
  461. return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
  462. }
  463. action.OpType = ActionDeleteBranch
  464. if err = NotifyWatchers(action); err != nil {
  465. return fmt.Errorf("NotifyWatchers.(delete branch): %v", err)
  466. }
  467. // Delete branch doesn't have anything to push or compare
  468. return nil
  469. }
  470. compareURL := setting.AppURL + opts.Commits.CompareURL
  471. if isNewRef {
  472. compareURL = ""
  473. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  474. Ref: refName,
  475. RefType: "branch",
  476. DefaultBranch: repo.DefaultBranch,
  477. Repo: apiRepo,
  478. Sender: apiPusher,
  479. }); err != nil {
  480. return fmt.Errorf("PrepareWebhooks.(new branch): %v", err)
  481. }
  482. action.OpType = ActionCreateBranch
  483. if err = NotifyWatchers(action); err != nil {
  484. return fmt.Errorf("NotifyWatchers.(new branch): %v", err)
  485. }
  486. }
  487. commits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
  488. if err != nil {
  489. return fmt.Errorf("ToApiPayloadCommits: %v", err)
  490. }
  491. if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  492. Ref: opts.RefFullName,
  493. Before: opts.OldCommitID,
  494. After: opts.NewCommitID,
  495. CompareURL: compareURL,
  496. Commits: commits,
  497. Repo: apiRepo,
  498. Pusher: apiPusher,
  499. Sender: apiPusher,
  500. }); err != nil {
  501. return fmt.Errorf("PrepareWebhooks.(new commit): %v", err)
  502. }
  503. action.OpType = ActionCommitRepo
  504. if err = NotifyWatchers(action); err != nil {
  505. return fmt.Errorf("NotifyWatchers.(new commit): %v", err)
  506. }
  507. case ActionPushTag: // Tag
  508. if isDelRef {
  509. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  510. Ref: refName,
  511. RefType: "tag",
  512. PusherType: api.PUSHER_TYPE_USER,
  513. Repo: apiRepo,
  514. Sender: apiPusher,
  515. }); err != nil {
  516. return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
  517. }
  518. action.OpType = ActionDeleteTag
  519. if err = NotifyWatchers(action); err != nil {
  520. return fmt.Errorf("NotifyWatchers.(delete tag): %v", err)
  521. }
  522. return nil
  523. }
  524. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  525. Ref: refName,
  526. RefType: "tag",
  527. DefaultBranch: repo.DefaultBranch,
  528. Repo: apiRepo,
  529. Sender: apiPusher,
  530. }); err != nil {
  531. return fmt.Errorf("PrepareWebhooks.(new tag): %v", err)
  532. }
  533. action.OpType = ActionPushTag
  534. if err = NotifyWatchers(action); err != nil {
  535. return fmt.Errorf("NotifyWatchers.(new tag): %v", err)
  536. }
  537. }
  538. return nil
  539. }
  540. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  541. if err = notifyWatchers(e, &Action{
  542. ActUserID: doer.ID,
  543. ActUserName: doer.Name,
  544. OpType: ActionTransferRepo,
  545. RepoID: repo.ID,
  546. RepoUserName: repo.Owner.Name,
  547. RepoName: repo.Name,
  548. IsPrivate: repo.IsPrivate,
  549. Content: path.Join(oldOwner.Name, repo.Name),
  550. }); err != nil {
  551. return fmt.Errorf("notifyWatchers: %v", err)
  552. }
  553. // Remove watch for organization.
  554. if oldOwner.IsOrganization() {
  555. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  556. return fmt.Errorf("watchRepo [false]: %v", err)
  557. }
  558. }
  559. return nil
  560. }
  561. // TransferRepoAction adds new action for transferring repository,
  562. // the Owner field of repository is assumed to be new owner.
  563. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  564. return transferRepoAction(x, doer, oldOwner, repo)
  565. }
  566. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  567. return notifyWatchers(e, &Action{
  568. ActUserID: doer.ID,
  569. ActUserName: doer.Name,
  570. OpType: ActionMergePullRequest,
  571. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  572. RepoID: repo.ID,
  573. RepoUserName: repo.Owner.Name,
  574. RepoName: repo.Name,
  575. IsPrivate: repo.IsPrivate,
  576. })
  577. }
  578. // MergePullRequestAction adds new action for merging pull request.
  579. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  580. return mergePullRequestAction(x, actUser, repo, pull)
  581. }
  582. func mirrorSyncAction(opType ActionType, repo *Repository, refName string, data []byte) error {
  583. return NotifyWatchers(&Action{
  584. ActUserID: repo.OwnerID,
  585. ActUserName: repo.MustOwner().Name,
  586. OpType: opType,
  587. Content: string(data),
  588. RepoID: repo.ID,
  589. RepoUserName: repo.MustOwner().Name,
  590. RepoName: repo.Name,
  591. RefName: refName,
  592. IsPrivate: repo.IsPrivate,
  593. })
  594. }
  595. type MirrorSyncPushActionOptions struct {
  596. RefName string
  597. OldCommitID string
  598. NewCommitID string
  599. Commits *PushCommits
  600. }
  601. // MirrorSyncPushAction adds new action for mirror synchronization of pushed commits.
  602. func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) error {
  603. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  604. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  605. }
  606. apiCommits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
  607. if err != nil {
  608. return fmt.Errorf("ToApiPayloadCommits: %v", err)
  609. }
  610. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  611. apiPusher := repo.MustOwner().APIFormat()
  612. if err := PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  613. Ref: opts.RefName,
  614. Before: opts.OldCommitID,
  615. After: opts.NewCommitID,
  616. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  617. Commits: apiCommits,
  618. Repo: repo.APIFormat(nil),
  619. Pusher: apiPusher,
  620. Sender: apiPusher,
  621. }); err != nil {
  622. return fmt.Errorf("PrepareWebhooks: %v", err)
  623. }
  624. data, err := jsoniter.Marshal(opts.Commits)
  625. if err != nil {
  626. return err
  627. }
  628. return mirrorSyncAction(ActionMirrorSyncPush, repo, opts.RefName, data)
  629. }
  630. // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
  631. func MirrorSyncCreateAction(repo *Repository, refName string) error {
  632. return mirrorSyncAction(ActionMirrorSyncCreate, repo, refName, nil)
  633. }
  634. // MirrorSyncDeleteAction deletes action for mirror synchronization of delete reference.
  635. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  636. return mirrorSyncAction(ActionMirrorSyncDelete, repo, refName, nil)
  637. }
  638. // GetFeeds returns action list of given user in given context.
  639. // actorID is the user who's requesting, ctxUserID is the user/org that is requested.
  640. // actorID can be -1 when isProfile is true or to skip the permission check.
  641. func GetFeeds(ctxUser *User, actorID, afterID int64, isProfile bool) ([]*Action, error) {
  642. actions := make([]*Action, 0, setting.UI.User.NewsFeedPagingNum)
  643. sess := x.Limit(setting.UI.User.NewsFeedPagingNum).Where("user_id = ?", ctxUser.ID).Desc("id")
  644. if afterID > 0 {
  645. sess.And("id < ?", afterID)
  646. }
  647. if isProfile {
  648. sess.And("is_private = ?", false).And("act_user_id = ?", ctxUser.ID)
  649. } else if actorID != -1 && ctxUser.IsOrganization() {
  650. // FIXME: only need to get IDs here, not all fields of repository.
  651. repos, _, err := ctxUser.GetUserRepositories(actorID, 1, ctxUser.NumRepos)
  652. if err != nil {
  653. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  654. }
  655. var repoIDs []int64
  656. for _, repo := range repos {
  657. repoIDs = append(repoIDs, repo.ID)
  658. }
  659. if len(repoIDs) > 0 {
  660. sess.In("repo_id", repoIDs)
  661. }
  662. }
  663. err := sess.Find(&actions)
  664. return actions, err
  665. }