action.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 = 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 := ACTION_CREATE_REPO
  156. if repo.IsFork {
  157. opType = ACTION_FORK_REPO
  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: ACTION_RENAME_REPO,
  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. func NewPushCommits() *PushCommits {
  212. return &PushCommits{
  213. avatars: make(map[string]string),
  214. }
  215. }
  216. func (pc *PushCommits) ToApiPayloadCommits(repoPath, repoURL string) ([]*api.PayloadCommit, error) {
  217. commits := make([]*api.PayloadCommit, len(pc.Commits))
  218. for i, commit := range pc.Commits {
  219. authorUsername := ""
  220. author, err := GetUserByEmail(commit.AuthorEmail)
  221. if err == nil {
  222. authorUsername = author.Name
  223. } else if !errors.IsUserNotExist(err) {
  224. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  225. }
  226. committerUsername := ""
  227. committer, err := GetUserByEmail(commit.CommitterEmail)
  228. if err == nil {
  229. committerUsername = committer.Name
  230. } else if !errors.IsUserNotExist(err) {
  231. return nil, fmt.Errorf("GetUserByEmail: %v", err)
  232. }
  233. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  234. if err != nil {
  235. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  236. }
  237. commits[i] = &api.PayloadCommit{
  238. ID: commit.Sha1,
  239. Message: commit.Message,
  240. URL: fmt.Sprintf("%s/commit/%s", repoURL, commit.Sha1),
  241. Author: &api.PayloadUser{
  242. Name: commit.AuthorName,
  243. Email: commit.AuthorEmail,
  244. UserName: authorUsername,
  245. },
  246. Committer: &api.PayloadUser{
  247. Name: commit.CommitterName,
  248. Email: commit.CommitterEmail,
  249. UserName: committerUsername,
  250. },
  251. Added: fileStatus.Added,
  252. Removed: fileStatus.Removed,
  253. Modified: fileStatus.Modified,
  254. Timestamp: commit.Timestamp,
  255. }
  256. }
  257. return commits, nil
  258. }
  259. // AvatarLink tries to match user in database with e-mail
  260. // in order to show custom avatar, and falls back to general avatar link.
  261. func (push *PushCommits) AvatarLink(email string) string {
  262. _, ok := push.avatars[email]
  263. if !ok {
  264. u, err := GetUserByEmail(email)
  265. if err != nil {
  266. push.avatars[email] = tool.AvatarLink(email)
  267. if !errors.IsUserNotExist(err) {
  268. raven.CaptureErrorAndWait(err, nil)
  269. log.Error(4, "GetUserByEmail: %v", err)
  270. }
  271. } else {
  272. push.avatars[email] = u.RelAvatarLink()
  273. }
  274. }
  275. return push.avatars[email]
  276. }
  277. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  278. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) error {
  279. // Commits are appended in the reverse order.
  280. for i := len(commits) - 1; i >= 0; i-- {
  281. c := commits[i]
  282. refMarked := make(map[int64]bool)
  283. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  284. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  285. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  286. if len(ref) == 0 {
  287. continue
  288. }
  289. // Add repo name if missing
  290. if ref[0] == '#' {
  291. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  292. } else if !strings.Contains(ref, "/") {
  293. // FIXME: We don't support User#ID syntax yet
  294. // return ErrNotImplemented
  295. continue
  296. }
  297. issue, err := GetIssueByRef(ref)
  298. if err != nil {
  299. if errors.IsIssueNotExist(err) {
  300. continue
  301. }
  302. return err
  303. }
  304. if refMarked[issue.ID] {
  305. continue
  306. }
  307. refMarked[issue.ID] = true
  308. msgLines := strings.Split(c.Message, "\n")
  309. shortMsg := msgLines[0]
  310. if len(msgLines) > 2 {
  311. shortMsg += "..."
  312. }
  313. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, shortMsg)
  314. if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil {
  315. return err
  316. }
  317. }
  318. refMarked = make(map[int64]bool)
  319. // FIXME: can merge this one and next one to a common function.
  320. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  321. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  322. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  323. if len(ref) == 0 {
  324. continue
  325. }
  326. // Add repo name if missing
  327. if ref[0] == '#' {
  328. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  329. } else if !strings.Contains(ref, "/") {
  330. // FIXME: We don't support User#ID syntax yet
  331. continue
  332. }
  333. issue, err := GetIssueByRef(ref)
  334. if err != nil {
  335. if errors.IsIssueNotExist(err) {
  336. continue
  337. }
  338. return err
  339. }
  340. if refMarked[issue.ID] {
  341. continue
  342. }
  343. refMarked[issue.ID] = true
  344. if issue.RepoID != repo.ID || issue.IsClosed {
  345. continue
  346. }
  347. if err = issue.ChangeStatus(doer, repo, true); err != nil {
  348. return err
  349. }
  350. }
  351. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  352. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  353. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  354. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  355. if len(ref) == 0 {
  356. continue
  357. }
  358. // Add repo name if missing
  359. if ref[0] == '#' {
  360. ref = fmt.Sprintf("%s%s", repo.FullName(), ref)
  361. } else if !strings.Contains(ref, "/") {
  362. // We don't support User#ID syntax yet
  363. // return ErrNotImplemented
  364. continue
  365. }
  366. issue, err := GetIssueByRef(ref)
  367. if err != nil {
  368. if errors.IsIssueNotExist(err) {
  369. continue
  370. }
  371. return err
  372. }
  373. if refMarked[issue.ID] {
  374. continue
  375. }
  376. refMarked[issue.ID] = true
  377. if issue.RepoID != repo.ID || !issue.IsClosed {
  378. continue
  379. }
  380. if err = issue.ChangeStatus(doer, repo, false); err != nil {
  381. return err
  382. }
  383. }
  384. }
  385. return nil
  386. }
  387. type CommitRepoActionOptions struct {
  388. PusherName string
  389. RepoOwnerID int64
  390. RepoName string
  391. RefFullName string
  392. OldCommitID string
  393. NewCommitID string
  394. Commits *PushCommits
  395. }
  396. // CommitRepoAction adds new commit actio to the repository, and prepare corresponding webhooks.
  397. func CommitRepoAction(opts CommitRepoActionOptions) error {
  398. pusher, err := GetUserByName(opts.PusherName)
  399. if err != nil {
  400. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  401. }
  402. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  403. if err != nil {
  404. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  405. }
  406. // Change repository bare status and update last updated time.
  407. repo.IsBare = false
  408. if err = UpdateRepository(repo, false); err != nil {
  409. return fmt.Errorf("UpdateRepository: %v", err)
  410. }
  411. isNewRef := opts.OldCommitID == git.EMPTY_SHA
  412. isDelRef := opts.NewCommitID == git.EMPTY_SHA
  413. opType := ACTION_COMMIT_REPO
  414. // Check if it's tag push or branch.
  415. if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
  416. opType = ACTION_PUSH_TAG
  417. } else {
  418. // if not the first commit, set the compare URL.
  419. if !isNewRef && !isDelRef {
  420. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  421. }
  422. // Only update issues via commits when internal issue tracker is enabled
  423. if repo.EnableIssues && !repo.EnableExternalTracker {
  424. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits); err != nil {
  425. raven.CaptureErrorAndWait(err, nil)
  426. log.Error(2, "UpdateIssuesCommit: %v", err)
  427. }
  428. }
  429. }
  430. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  431. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  432. }
  433. data, err := jsoniter.Marshal(opts.Commits)
  434. if err != nil {
  435. return fmt.Errorf("Marshal: %v", err)
  436. }
  437. refName := git.RefEndName(opts.RefFullName)
  438. action := &Action{
  439. ActUserID: pusher.ID,
  440. ActUserName: pusher.Name,
  441. Content: string(data),
  442. RepoID: repo.ID,
  443. RepoUserName: repo.MustOwner().Name,
  444. RepoName: repo.Name,
  445. RefName: refName,
  446. IsPrivate: repo.IsPrivate,
  447. }
  448. apiRepo := repo.APIFormat(nil)
  449. apiPusher := pusher.APIFormat()
  450. switch opType {
  451. case ACTION_COMMIT_REPO: // Push
  452. if isDelRef {
  453. if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &api.DeletePayload{
  454. Ref: refName,
  455. RefType: "branch",
  456. PusherType: api.PUSHER_TYPE_USER,
  457. Repo: apiRepo,
  458. Sender: apiPusher,
  459. }); err != nil {
  460. return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
  461. }
  462. action.OpType = ACTION_DELETE_BRANCH
  463. if err = NotifyWatchers(action); err != nil {
  464. return fmt.Errorf("NotifyWatchers.(delete branch): %v", err)
  465. }
  466. // Delete branch doesn't have anything to push or compare
  467. return nil
  468. }
  469. compareURL := setting.AppURL + opts.Commits.CompareURL
  470. if isNewRef {
  471. compareURL = ""
  472. if err = PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  473. Ref: refName,
  474. RefType: "branch",
  475. DefaultBranch: repo.DefaultBranch,
  476. Repo: apiRepo,
  477. Sender: apiPusher,
  478. }); err != nil {
  479. return fmt.Errorf("PrepareWebhooks.(new branch): %v", err)
  480. }
  481. action.OpType = ACTION_CREATE_BRANCH
  482. if err = NotifyWatchers(action); err != nil {
  483. return fmt.Errorf("NotifyWatchers.(new branch): %v", err)
  484. }
  485. }
  486. commits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
  487. if err != nil {
  488. return fmt.Errorf("ToApiPayloadCommits: %v", err)
  489. }
  490. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{
  491. Ref: opts.RefFullName,
  492. Before: opts.OldCommitID,
  493. After: opts.NewCommitID,
  494. CompareURL: compareURL,
  495. Commits: commits,
  496. Repo: apiRepo,
  497. Pusher: apiPusher,
  498. Sender: apiPusher,
  499. }); err != nil {
  500. return fmt.Errorf("PrepareWebhooks.(new commit): %v", err)
  501. }
  502. action.OpType = ACTION_COMMIT_REPO
  503. if err = NotifyWatchers(action); err != nil {
  504. return fmt.Errorf("NotifyWatchers.(new commit): %v", err)
  505. }
  506. case ACTION_PUSH_TAG: // Tag
  507. if isDelRef {
  508. if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &api.DeletePayload{
  509. Ref: refName,
  510. RefType: "tag",
  511. PusherType: api.PUSHER_TYPE_USER,
  512. Repo: apiRepo,
  513. Sender: apiPusher,
  514. }); err != nil {
  515. return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
  516. }
  517. action.OpType = ACTION_DELETE_TAG
  518. if err = NotifyWatchers(action); err != nil {
  519. return fmt.Errorf("NotifyWatchers.(delete tag): %v", err)
  520. }
  521. return nil
  522. }
  523. if err = PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  524. Ref: refName,
  525. RefType: "tag",
  526. DefaultBranch: repo.DefaultBranch,
  527. Repo: apiRepo,
  528. Sender: apiPusher,
  529. }); err != nil {
  530. return fmt.Errorf("PrepareWebhooks.(new tag): %v", err)
  531. }
  532. action.OpType = ACTION_PUSH_TAG
  533. if err = NotifyWatchers(action); err != nil {
  534. return fmt.Errorf("NotifyWatchers.(new tag): %v", err)
  535. }
  536. }
  537. return nil
  538. }
  539. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  540. if err = notifyWatchers(e, &Action{
  541. ActUserID: doer.ID,
  542. ActUserName: doer.Name,
  543. OpType: ACTION_TRANSFER_REPO,
  544. RepoID: repo.ID,
  545. RepoUserName: repo.Owner.Name,
  546. RepoName: repo.Name,
  547. IsPrivate: repo.IsPrivate,
  548. Content: path.Join(oldOwner.Name, repo.Name),
  549. }); err != nil {
  550. return fmt.Errorf("notifyWatchers: %v", err)
  551. }
  552. // Remove watch for organization.
  553. if oldOwner.IsOrganization() {
  554. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  555. return fmt.Errorf("watchRepo [false]: %v", err)
  556. }
  557. }
  558. return nil
  559. }
  560. // TransferRepoAction adds new action for transferring repository,
  561. // the Owner field of repository is assumed to be new owner.
  562. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  563. return transferRepoAction(x, doer, oldOwner, repo)
  564. }
  565. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  566. return notifyWatchers(e, &Action{
  567. ActUserID: doer.ID,
  568. ActUserName: doer.Name,
  569. OpType: ACTION_MERGE_PULL_REQUEST,
  570. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  571. RepoID: repo.ID,
  572. RepoUserName: repo.Owner.Name,
  573. RepoName: repo.Name,
  574. IsPrivate: repo.IsPrivate,
  575. })
  576. }
  577. // MergePullRequestAction adds new action for merging pull request.
  578. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  579. return mergePullRequestAction(x, actUser, repo, pull)
  580. }
  581. func mirrorSyncAction(opType ActionType, repo *Repository, refName string, data []byte) error {
  582. return NotifyWatchers(&Action{
  583. ActUserID: repo.OwnerID,
  584. ActUserName: repo.MustOwner().Name,
  585. OpType: opType,
  586. Content: string(data),
  587. RepoID: repo.ID,
  588. RepoUserName: repo.MustOwner().Name,
  589. RepoName: repo.Name,
  590. RefName: refName,
  591. IsPrivate: repo.IsPrivate,
  592. })
  593. }
  594. type MirrorSyncPushActionOptions struct {
  595. RefName string
  596. OldCommitID string
  597. NewCommitID string
  598. Commits *PushCommits
  599. }
  600. // MirrorSyncPushAction adds new action for mirror synchronization of pushed commits.
  601. func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) error {
  602. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  603. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  604. }
  605. apiCommits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
  606. if err != nil {
  607. return fmt.Errorf("ToApiPayloadCommits: %v", err)
  608. }
  609. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  610. apiPusher := repo.MustOwner().APIFormat()
  611. if err := PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{
  612. Ref: opts.RefName,
  613. Before: opts.OldCommitID,
  614. After: opts.NewCommitID,
  615. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  616. Commits: apiCommits,
  617. Repo: repo.APIFormat(nil),
  618. Pusher: apiPusher,
  619. Sender: apiPusher,
  620. }); err != nil {
  621. return fmt.Errorf("PrepareWebhooks: %v", err)
  622. }
  623. data, err := jsoniter.Marshal(opts.Commits)
  624. if err != nil {
  625. return err
  626. }
  627. return mirrorSyncAction(ACTION_MIRROR_SYNC_PUSH, repo, opts.RefName, data)
  628. }
  629. // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
  630. func MirrorSyncCreateAction(repo *Repository, refName string) error {
  631. return mirrorSyncAction(ACTION_MIRROR_SYNC_CREATE, repo, refName, nil)
  632. }
  633. // MirrorSyncCreateAction adds new action for mirror synchronization of delete reference.
  634. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  635. return mirrorSyncAction(ACTION_MIRROR_SYNC_DELETE, repo, refName, nil)
  636. }
  637. // GetFeeds returns action list of given user in given context.
  638. // actorID is the user who's requesting, ctxUserID is the user/org that is requested.
  639. // actorID can be -1 when isProfile is true or to skip the permission check.
  640. func GetFeeds(ctxUser *User, actorID, afterID int64, isProfile bool) ([]*Action, error) {
  641. actions := make([]*Action, 0, setting.UI.User.NewsFeedPagingNum)
  642. sess := x.Limit(setting.UI.User.NewsFeedPagingNum).Where("user_id = ?", ctxUser.ID).Desc("id")
  643. if afterID > 0 {
  644. sess.And("id < ?", afterID)
  645. }
  646. if isProfile {
  647. sess.And("is_private = ?", false).And("act_user_id = ?", ctxUser.ID)
  648. } else if actorID != -1 && ctxUser.IsOrganization() {
  649. // FIXME: only need to get IDs here, not all fields of repository.
  650. repos, _, err := ctxUser.GetUserRepositories(actorID, 1, ctxUser.NumRepos)
  651. if err != nil {
  652. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  653. }
  654. var repoIDs []int64
  655. for _, repo := range repos {
  656. repoIDs = append(repoIDs, repo.ID)
  657. }
  658. if len(repoIDs) > 0 {
  659. sess.In("repo_id", repoIDs)
  660. }
  661. }
  662. err := sess.Find(&actions)
  663. return actions, err
  664. }