action.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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. "github.com/Unknwon/com"
  18. raven "github.com/getsentry/raven-go"
  19. "github.com/go-xorm/xorm"
  20. "github.com/json-iterator/go"
  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. ACTION_CREATE_REPO ActionType = iota + 1 // 1
  29. ACTION_RENAME_REPO // 2
  30. ACTION_STAR_REPO // 3
  31. ACTION_WATCH_REPO // 4
  32. ACTION_COMMIT_REPO // 5
  33. ACTION_CREATE_ISSUE // 6
  34. ACTION_CREATE_PULL_REQUEST // 7
  35. ACTION_TRANSFER_REPO // 8
  36. ACTION_PUSH_TAG // 9
  37. ACTION_COMMENT_ISSUE // 10
  38. ACTION_MERGE_PULL_REQUEST // 11
  39. ACTION_CLOSE_ISSUE // 12
  40. ACTION_REOPEN_ISSUE // 13
  41. ACTION_CLOSE_PULL_REQUEST // 14
  42. ACTION_REOPEN_PULL_REQUEST // 15
  43. ACTION_CREATE_BRANCH // 16
  44. ACTION_DELETE_BRANCH // 17
  45. ACTION_DELETE_TAG // 18
  46. ACTION_FORK_REPO // 19
  47. ACTION_MIRROR_SYNC_PUSH // 20
  48. ACTION_MIRROR_SYNC_CREATE // 21
  49. ACTION_MIRROR_SYNC_DELETE // 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, IssueReopenKeywordsPat *regexp.Regexp
  56. IssueReferenceKeywordsPat *regexp.Regexp
  57. )
  58. func assembleKeywordsPattern(words []string) string {
  59. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  60. }
  61. func init() {
  62. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  63. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  64. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  65. }
  66. // Action represents user operation type and other information to repository,
  67. // it implemented interface base.Actioner so that can be used in template render.
  68. type Action struct {
  69. ID int64
  70. UserID int64 // Receiver user ID
  71. OpType ActionType
  72. ActUserID int64 // Doer user ID
  73. ActUserName string // Doer user name
  74. ActAvatar string `xorm:"-" json:"-"`
  75. RepoID int64 `xorm:"INDEX"`
  76. RepoUserName string
  77. RepoName string
  78. RefName string
  79. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  80. Content string `xorm:"TEXT"`
  81. Created time.Time `xorm:"-" json:"-"`
  82. CreatedUnix int64
  83. }
  84. func (a *Action) BeforeInsert() {
  85. a.CreatedUnix = time.Now().Unix()
  86. }
  87. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  88. switch colName {
  89. case "created_unix":
  90. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  91. }
  92. }
  93. func (a *Action) GetOpType() int {
  94. return int(a.OpType)
  95. }
  96. func (a *Action) GetActUserName() string {
  97. return a.ActUserName
  98. }
  99. func (a *Action) ShortActUserName() string {
  100. return tool.EllipsisString(a.ActUserName, 20)
  101. }
  102. func (a *Action) GetRepoUserName() string {
  103. return a.RepoUserName
  104. }
  105. func (a *Action) ShortRepoUserName() string {
  106. return tool.EllipsisString(a.RepoUserName, 20)
  107. }
  108. func (a *Action) GetRepoName() string {
  109. return a.RepoName
  110. }
  111. func (a *Action) ShortRepoName() string {
  112. return tool.EllipsisString(a.RepoName, 33)
  113. }
  114. func (a *Action) GetRepoPath() string {
  115. return path.Join(a.RepoUserName, a.RepoName)
  116. }
  117. func (a *Action) ShortRepoPath() string {
  118. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  119. }
  120. func (a *Action) GetRepoLink() string {
  121. if len(setting.AppSubURL) > 0 {
  122. return path.Join(setting.AppSubURL, a.GetRepoPath())
  123. }
  124. return "/" + a.GetRepoPath()
  125. }
  126. func (a *Action) GetBranch() string {
  127. return a.RefName
  128. }
  129. func (a *Action) GetContent() string {
  130. return a.Content
  131. }
  132. func (a *Action) GetCreate() time.Time {
  133. return a.Created
  134. }
  135. func (a *Action) GetIssueInfos() []string {
  136. return strings.SplitN(a.Content, "|", 2)
  137. }
  138. func (a *Action) GetIssueTitle() string {
  139. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  140. issue, err := GetIssueByIndex(a.RepoID, index)
  141. if err != nil {
  142. raven.CaptureErrorAndWait(err, nil)
  143. log.Error(4, "GetIssueByIndex: %v", err)
  144. return "500 when get issue"
  145. }
  146. return issue.Title
  147. }
  148. func (a *Action) GetIssueContent() string {
  149. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  150. issue, err := GetIssueByIndex(a.RepoID, index)
  151. if err != nil {
  152. raven.CaptureErrorAndWait(err, nil)
  153. log.Error(4, "GetIssueByIndex: %v", err)
  154. return "500 when get issue"
  155. }
  156. return issue.Content
  157. }
  158. func newRepoAction(e Engine, doer, owner *User, repo *Repository) (err error) {
  159. opType := ACTION_CREATE_REPO
  160. if repo.IsFork {
  161. opType = ACTION_FORK_REPO
  162. }
  163. return notifyWatchers(e, &Action{
  164. ActUserID: doer.ID,
  165. ActUserName: doer.Name,
  166. OpType: opType,
  167. RepoID: repo.ID,
  168. RepoUserName: repo.Owner.Name,
  169. RepoName: repo.Name,
  170. IsPrivate: repo.IsPrivate,
  171. })
  172. }
  173. // NewRepoAction adds new action for creating repository.
  174. func NewRepoAction(doer, owner *User, repo *Repository) (err error) {
  175. return newRepoAction(x, doer, owner, repo)
  176. }
  177. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  178. if err = notifyWatchers(e, &Action{
  179. ActUserID: actUser.ID,
  180. ActUserName: actUser.Name,
  181. OpType: ACTION_RENAME_REPO,
  182. RepoID: repo.ID,
  183. RepoUserName: repo.Owner.Name,
  184. RepoName: repo.Name,
  185. IsPrivate: repo.IsPrivate,
  186. Content: oldRepoName,
  187. }); err != nil {
  188. return fmt.Errorf("notify watchers: %v", err)
  189. }
  190. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  191. return nil
  192. }
  193. // RenameRepoAction adds new action for renaming a repository.
  194. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  195. return renameRepoAction(x, actUser, oldRepoName, repo)
  196. }
  197. func issueIndexTrimRight(c rune) bool {
  198. return !unicode.IsDigit(c)
  199. }
  200. type PushCommit struct {
  201. Sha1 string
  202. Message string
  203. AuthorEmail string
  204. AuthorName string
  205. CommitterEmail string
  206. CommitterName string
  207. Timestamp time.Time
  208. }
  209. type PushCommits struct {
  210. Len int
  211. Commits []*PushCommit
  212. CompareURL string
  213. avatars map[string]string
  214. }
  215. func NewPushCommits() *PushCommits {
  216. return &PushCommits{
  217. avatars: make(map[string]string),
  218. }
  219. }
  220. func (pc *PushCommits) ToApiPayloadCommits(repoPath, repoURL string) ([]*api.PayloadCommit, error) {
  221. commits := make([]*api.PayloadCommit, len(pc.Commits))
  222. for i, commit := range pc.Commits {
  223. authorUsername := ""
  224. author, err := GetUserByEmail(commit.AuthorEmail)
  225. if err == nil {
  226. authorUsername = author.Name
  227. } else if !errors.IsUserNotExist(err) {
  228. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  229. }
  230. committerUsername := ""
  231. committer, err := GetUserByEmail(commit.CommitterEmail)
  232. if err == nil {
  233. committerUsername = committer.Name
  234. } else if !errors.IsUserNotExist(err) {
  235. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  236. }
  237. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  238. if err != nil {
  239. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  240. }
  241. commits[i] = &api.PayloadCommit{
  242. ID: commit.Sha1,
  243. Message: commit.Message,
  244. URL: fmt.Sprintf("%s/commit/%s", repoURL, commit.Sha1),
  245. Author: &api.PayloadUser{
  246. Name: commit.AuthorName,
  247. Email: commit.AuthorEmail,
  248. UserName: authorUsername,
  249. },
  250. Committer: &api.PayloadUser{
  251. Name: commit.CommitterName,
  252. Email: commit.CommitterEmail,
  253. UserName: committerUsername,
  254. },
  255. Added: fileStatus.Added,
  256. Removed: fileStatus.Removed,
  257. Modified: fileStatus.Modified,
  258. Timestamp: commit.Timestamp,
  259. }
  260. }
  261. return commits, nil
  262. }
  263. // AvatarLink tries to match user in database with e-mail
  264. // in order to show custom avatar, and falls back to general avatar link.
  265. func (push *PushCommits) AvatarLink(email string) string {
  266. _, ok := push.avatars[email]
  267. if !ok {
  268. u, err := GetUserByEmail(email)
  269. if err != nil {
  270. push.avatars[email] = tool.AvatarLink(email)
  271. if !errors.IsUserNotExist(err) {
  272. raven.CaptureErrorAndWait(err, nil)
  273. log.Error(4, "GetUserByEmail: %v", err)
  274. }
  275. } else {
  276. push.avatars[email] = u.RelAvatarLink()
  277. }
  278. }
  279. return push.avatars[email]
  280. }
  281. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  282. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) error {
  283. // Commits are appended in the reverse order.
  284. for i := len(commits) - 1; i >= 0; i-- {
  285. c := commits[i]
  286. refMarked := make(map[int64]bool)
  287. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  288. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  289. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  290. if len(ref) == 0 {
  291. continue
  292. }
  293. // Add repo name if missing
  294. if ref[0] == '#' {
  295. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  296. } else if !strings.Contains(ref, "/") {
  297. // FIXME: We don't support User#ID syntax yet
  298. // return ErrNotImplemented
  299. continue
  300. }
  301. issue, err := GetIssueByRef(ref)
  302. if err != nil {
  303. if errors.IsIssueNotExist(err) {
  304. continue
  305. }
  306. return err
  307. }
  308. if refMarked[issue.ID] {
  309. continue
  310. }
  311. refMarked[issue.ID] = true
  312. msgLines := strings.Split(c.Message, "\n")
  313. shortMsg := msgLines[0]
  314. if len(msgLines) > 2 {
  315. shortMsg += "..."
  316. }
  317. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, shortMsg)
  318. if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil {
  319. return err
  320. }
  321. }
  322. refMarked = make(map[int64]bool)
  323. // FIXME: can merge this one and next one to a common function.
  324. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  325. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  326. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  327. if len(ref) == 0 {
  328. continue
  329. }
  330. // Add repo name if missing
  331. if ref[0] == '#' {
  332. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  333. } else if !strings.Contains(ref, "/") {
  334. // FIXME: We don't support User#ID syntax yet
  335. continue
  336. }
  337. issue, err := GetIssueByRef(ref)
  338. if err != nil {
  339. if errors.IsIssueNotExist(err) {
  340. continue
  341. }
  342. return err
  343. }
  344. if refMarked[issue.ID] {
  345. continue
  346. }
  347. refMarked[issue.ID] = true
  348. if issue.RepoID != repo.ID || issue.IsClosed {
  349. continue
  350. }
  351. if err = issue.ChangeStatus(doer, repo, true); err != nil {
  352. return err
  353. }
  354. }
  355. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  356. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  357. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  358. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  359. if len(ref) == 0 {
  360. continue
  361. }
  362. // Add repo name if missing
  363. if ref[0] == '#' {
  364. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  365. } else if !strings.Contains(ref, "/") {
  366. // We don't support User#ID syntax yet
  367. // return ErrNotImplemented
  368. continue
  369. }
  370. issue, err := GetIssueByRef(ref)
  371. if err != nil {
  372. if errors.IsIssueNotExist(err) {
  373. continue
  374. }
  375. return err
  376. }
  377. if refMarked[issue.ID] {
  378. continue
  379. }
  380. refMarked[issue.ID] = true
  381. if issue.RepoID != repo.ID || !issue.IsClosed {
  382. continue
  383. }
  384. if err = issue.ChangeStatus(doer, repo, false); err != nil {
  385. return err
  386. }
  387. }
  388. }
  389. return nil
  390. }
  391. type CommitRepoActionOptions struct {
  392. PusherName string
  393. RepoOwnerID int64
  394. RepoName string
  395. RefFullName string
  396. OldCommitID string
  397. NewCommitID string
  398. Commits *PushCommits
  399. }
  400. // CommitRepoAction adds new commit actio to the repository, and prepare corresponding webhooks.
  401. func CommitRepoAction(opts CommitRepoActionOptions) error {
  402. pusher, err := GetUserByName(opts.PusherName)
  403. if err != nil {
  404. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  405. }
  406. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  407. if err != nil {
  408. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  409. }
  410. // Change repository bare status and update last updated time.
  411. repo.IsBare = false
  412. if err = UpdateRepository(repo, false); err != nil {
  413. return fmt.Errorf("UpdateRepository: %v", err)
  414. }
  415. isNewRef := opts.OldCommitID == git.EMPTY_SHA
  416. isDelRef := opts.NewCommitID == git.EMPTY_SHA
  417. opType := ACTION_COMMIT_REPO
  418. // Check if it's tag push or branch.
  419. if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
  420. opType = ACTION_PUSH_TAG
  421. } else {
  422. // if not the first commit, set the compare URL.
  423. if !isNewRef && !isDelRef {
  424. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  425. }
  426. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits); err != nil {
  427. raven.CaptureErrorAndWait(err, nil)
  428. log.Error(2, "UpdateIssuesCommit: %v", err)
  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 ACTION_COMMIT_REPO: // Push
  453. if isDelRef {
  454. if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &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 = ACTION_DELETE_BRANCH
  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, HOOK_EVENT_CREATE, &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 = ACTION_CREATE_BRANCH
  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, HOOK_EVENT_PUSH, &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 = ACTION_COMMIT_REPO
  504. if err = NotifyWatchers(action); err != nil {
  505. return fmt.Errorf("NotifyWatchers.(new commit): %v", err)
  506. }
  507. case ACTION_PUSH_TAG: // Tag
  508. if isDelRef {
  509. if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &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 = ACTION_DELETE_TAG
  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, HOOK_EVENT_CREATE, &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 = ACTION_PUSH_TAG
  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: ACTION_TRANSFER_REPO,
  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: ACTION_MERGE_PULL_REQUEST,
  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, HOOK_EVENT_PUSH, &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(ACTION_MIRROR_SYNC_PUSH, 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(ACTION_MIRROR_SYNC_CREATE, repo, refName, nil)
  633. }
  634. // MirrorSyncCreateAction adds new action for mirror synchronization of delete reference.
  635. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  636. return mirrorSyncAction(ACTION_MIRROR_SYNC_DELETE, 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. }