action.go 21 KB

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