action.go 21 KB

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