action.go 21 KB

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