action.go 23 KB

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