action.go 21 KB

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