You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

action.go 17 kB

11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. "github.com/gogits/git-module"
  16. api "github.com/gogits/go-gogs-client"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. type ActionType int
  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. )
  39. var (
  40. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  41. IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  42. IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  43. IssueCloseKeywordsPat, IssueReopenKeywordsPat *regexp.Regexp
  44. IssueReferenceKeywordsPat *regexp.Regexp
  45. )
  46. func assembleKeywordsPattern(words []string) string {
  47. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  48. }
  49. func init() {
  50. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  51. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  52. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  53. }
  54. // Action represents user operation type and other information to repository.,
  55. // it implemented interface base.Actioner so that can be used in template render.
  56. type Action struct {
  57. ID int64 `xorm:"pk autoincr"`
  58. UserID int64 // Receiver user id.
  59. OpType ActionType
  60. ActUserID int64 // Action user id.
  61. ActUserName string // Action user name.
  62. ActEmail string
  63. ActAvatar string `xorm:"-"`
  64. RepoID int64
  65. RepoUserName string
  66. RepoName string
  67. RefName string
  68. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  69. Content string `xorm:"TEXT"`
  70. Created time.Time `xorm:"-"`
  71. CreatedUnix int64
  72. }
  73. func (a *Action) BeforeInsert() {
  74. a.CreatedUnix = time.Now().Unix()
  75. }
  76. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  77. switch colName {
  78. case "created_unix":
  79. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  80. }
  81. }
  82. func (a *Action) GetOpType() int {
  83. return int(a.OpType)
  84. }
  85. func (a *Action) GetActUserName() string {
  86. return a.ActUserName
  87. }
  88. func (a *Action) ShortActUserName() string {
  89. return base.EllipsisString(a.ActUserName, 20)
  90. }
  91. func (a *Action) GetActEmail() string {
  92. return a.ActEmail
  93. }
  94. func (a *Action) GetRepoUserName() string {
  95. return a.RepoUserName
  96. }
  97. func (a *Action) ShortRepoUserName() string {
  98. return base.EllipsisString(a.RepoUserName, 20)
  99. }
  100. func (a *Action) GetRepoName() string {
  101. return a.RepoName
  102. }
  103. func (a *Action) ShortRepoName() string {
  104. return base.EllipsisString(a.RepoName, 33)
  105. }
  106. func (a *Action) GetRepoPath() string {
  107. return path.Join(a.RepoUserName, a.RepoName)
  108. }
  109. func (a *Action) ShortRepoPath() string {
  110. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  111. }
  112. func (a *Action) GetRepoLink() string {
  113. if len(setting.AppSubUrl) > 0 {
  114. return path.Join(setting.AppSubUrl, a.GetRepoPath())
  115. }
  116. return "/" + a.GetRepoPath()
  117. }
  118. func (a *Action) GetBranch() string {
  119. return a.RefName
  120. }
  121. func (a *Action) GetContent() string {
  122. return a.Content
  123. }
  124. func (a *Action) GetCreate() time.Time {
  125. return a.Created
  126. }
  127. func (a *Action) GetIssueInfos() []string {
  128. return strings.SplitN(a.Content, "|", 2)
  129. }
  130. func (a *Action) GetIssueTitle() string {
  131. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  132. issue, err := GetIssueByIndex(a.RepoID, index)
  133. if err != nil {
  134. log.Error(4, "GetIssueByIndex: %v", err)
  135. return "500 when get issue"
  136. }
  137. return issue.Title
  138. }
  139. func (a *Action) GetIssueContent() string {
  140. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  141. issue, err := GetIssueByIndex(a.RepoID, index)
  142. if err != nil {
  143. log.Error(4, "GetIssueByIndex: %v", err)
  144. return "500 when get issue"
  145. }
  146. return issue.Content
  147. }
  148. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  149. if err = notifyWatchers(e, &Action{
  150. ActUserID: u.ID,
  151. ActUserName: u.Name,
  152. ActEmail: u.Email,
  153. OpType: ACTION_CREATE_REPO,
  154. RepoID: repo.ID,
  155. RepoUserName: repo.Owner.Name,
  156. RepoName: repo.Name,
  157. IsPrivate: repo.IsPrivate,
  158. }); err != nil {
  159. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  160. }
  161. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  162. return err
  163. }
  164. // NewRepoAction adds new action for creating repository.
  165. func NewRepoAction(u *User, repo *Repository) (err error) {
  166. return newRepoAction(x, u, repo)
  167. }
  168. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  169. if err = notifyWatchers(e, &Action{
  170. ActUserID: actUser.ID,
  171. ActUserName: actUser.Name,
  172. ActEmail: actUser.Email,
  173. OpType: ACTION_RENAME_REPO,
  174. RepoID: repo.ID,
  175. RepoUserName: repo.Owner.Name,
  176. RepoName: repo.Name,
  177. IsPrivate: repo.IsPrivate,
  178. Content: oldRepoName,
  179. }); err != nil {
  180. return fmt.Errorf("notify watchers: %v", err)
  181. }
  182. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  183. return nil
  184. }
  185. // RenameRepoAction adds new action for renaming a repository.
  186. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  187. return renameRepoAction(x, actUser, oldRepoName, repo)
  188. }
  189. func issueIndexTrimRight(c rune) bool {
  190. return !unicode.IsDigit(c)
  191. }
  192. type PushCommit struct {
  193. Sha1 string
  194. Message string
  195. AuthorEmail string
  196. AuthorName string
  197. CommitterEmail string
  198. CommitterName string
  199. Timestamp time.Time
  200. }
  201. type PushCommits struct {
  202. Len int
  203. Commits []*PushCommit
  204. CompareURL string
  205. avatars map[string]string
  206. }
  207. func NewPushCommits() *PushCommits {
  208. return &PushCommits{
  209. avatars: make(map[string]string),
  210. }
  211. }
  212. func (pc *PushCommits) ToApiPayloadCommits(repoLink string) []*api.PayloadCommit {
  213. commits := make([]*api.PayloadCommit, len(pc.Commits))
  214. for i, commit := range pc.Commits {
  215. authorUsername := ""
  216. author, err := GetUserByEmail(commit.AuthorEmail)
  217. if err == nil {
  218. authorUsername = author.Name
  219. }
  220. committerUsername := ""
  221. committer, err := GetUserByEmail(commit.CommitterEmail)
  222. if err == nil {
  223. // TODO: check errors other than email not found.
  224. committerUsername = committer.Name
  225. }
  226. commits[i] = &api.PayloadCommit{
  227. ID: commit.Sha1,
  228. Message: commit.Message,
  229. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  230. Author: &api.PayloadUser{
  231. Name: commit.AuthorName,
  232. Email: commit.AuthorEmail,
  233. UserName: authorUsername,
  234. },
  235. Committer: &api.PayloadUser{
  236. Name: commit.CommitterName,
  237. Email: commit.CommitterEmail,
  238. UserName: committerUsername,
  239. },
  240. Timestamp: commit.Timestamp,
  241. }
  242. }
  243. return commits
  244. }
  245. // AvatarLink tries to match user in database with e-mail
  246. // in order to show custom avatar, and falls back to general avatar link.
  247. func (push *PushCommits) AvatarLink(email string) string {
  248. _, ok := push.avatars[email]
  249. if !ok {
  250. u, err := GetUserByEmail(email)
  251. if err != nil {
  252. push.avatars[email] = base.AvatarLink(email)
  253. if !IsErrUserNotExist(err) {
  254. log.Error(4, "GetUserByEmail: %v", err)
  255. }
  256. } else {
  257. push.avatars[email] = u.RelAvatarLink()
  258. }
  259. }
  260. return push.avatars[email]
  261. }
  262. // updateIssuesCommit checks if issues are manipulated by commit message.
  263. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*PushCommit) error {
  264. // Commits are appended in the reverse order.
  265. for i := len(commits) - 1; i >= 0; i-- {
  266. c := commits[i]
  267. refMarked := make(map[int64]bool)
  268. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  269. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  270. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  271. if len(ref) == 0 {
  272. continue
  273. }
  274. // Add repo name if missing
  275. if ref[0] == '#' {
  276. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  277. } else if !strings.Contains(ref, "/") {
  278. // FIXME: We don't support User#ID syntax yet
  279. // return ErrNotImplemented
  280. continue
  281. }
  282. issue, err := GetIssueByRef(ref)
  283. if err != nil {
  284. if IsErrIssueNotExist(err) {
  285. continue
  286. }
  287. return err
  288. }
  289. if refMarked[issue.ID] {
  290. continue
  291. }
  292. refMarked[issue.ID] = true
  293. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  294. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  295. if err = CreateRefComment(u, repo, issue, message, c.Sha1); err != nil {
  296. return err
  297. }
  298. }
  299. refMarked = make(map[int64]bool)
  300. // FIXME: can merge this one and next one to a common function.
  301. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  302. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  303. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  304. if len(ref) == 0 {
  305. continue
  306. }
  307. // Add repo name if missing
  308. if ref[0] == '#' {
  309. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  310. } else if !strings.Contains(ref, "/") {
  311. // We don't support User#ID syntax yet
  312. // return ErrNotImplemented
  313. continue
  314. }
  315. issue, err := GetIssueByRef(ref)
  316. if err != nil {
  317. if IsErrIssueNotExist(err) {
  318. continue
  319. }
  320. return err
  321. }
  322. if refMarked[issue.ID] {
  323. continue
  324. }
  325. refMarked[issue.ID] = true
  326. if issue.RepoID != repo.ID || issue.IsClosed {
  327. continue
  328. }
  329. if err = issue.ChangeStatus(u, repo, true); err != nil {
  330. return err
  331. }
  332. }
  333. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  334. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  335. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  336. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  337. if len(ref) == 0 {
  338. continue
  339. }
  340. // Add repo name if missing
  341. if ref[0] == '#' {
  342. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  343. } else if !strings.Contains(ref, "/") {
  344. // We don't support User#ID syntax yet
  345. // return ErrNotImplemented
  346. continue
  347. }
  348. issue, err := GetIssueByRef(ref)
  349. if err != nil {
  350. if IsErrIssueNotExist(err) {
  351. continue
  352. }
  353. return err
  354. }
  355. if refMarked[issue.ID] {
  356. continue
  357. }
  358. refMarked[issue.ID] = true
  359. if issue.RepoID != repo.ID || !issue.IsClosed {
  360. continue
  361. }
  362. if err = issue.ChangeStatus(u, repo, false); err != nil {
  363. return err
  364. }
  365. }
  366. }
  367. return nil
  368. }
  369. // CommitRepoAction adds new action for committing repository.
  370. func CommitRepoAction(
  371. userID, repoUserID int64,
  372. userName, actEmail string,
  373. repoID int64,
  374. repoUserName, repoName string,
  375. refFullName string,
  376. commit *PushCommits,
  377. oldCommitID string, newCommitID string) error {
  378. u, err := GetUserByID(userID)
  379. if err != nil {
  380. return fmt.Errorf("GetUserByID: %v", err)
  381. }
  382. repo, err := GetRepositoryByName(repoUserID, repoName)
  383. if err != nil {
  384. return fmt.Errorf("GetRepositoryByName: %v", err)
  385. } else if err = repo.GetOwner(); err != nil {
  386. return fmt.Errorf("GetOwner: %v", err)
  387. }
  388. // Change repository bare status and update last updated time.
  389. repo.IsBare = false
  390. if err = UpdateRepository(repo, false); err != nil {
  391. return fmt.Errorf("UpdateRepository: %v", err)
  392. }
  393. isNewBranch := false
  394. opType := ACTION_COMMIT_REPO
  395. // Check it's tag push or branch.
  396. if strings.HasPrefix(refFullName, "refs/tags/") {
  397. opType = ACTION_PUSH_TAG
  398. commit = &PushCommits{}
  399. } else {
  400. // if not the first commit, set the compareUrl
  401. if !strings.HasPrefix(oldCommitID, "0000000") {
  402. commit.CompareURL = repo.ComposeCompareURL(oldCommitID, newCommitID)
  403. } else {
  404. isNewBranch = true
  405. }
  406. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  407. log.Error(4, "updateIssuesCommit: %v", err)
  408. }
  409. }
  410. if len(commit.Commits) > setting.UI.FeedMaxCommitNum {
  411. commit.Commits = commit.Commits[:setting.UI.FeedMaxCommitNum]
  412. }
  413. bs, err := json.Marshal(commit)
  414. if err != nil {
  415. return fmt.Errorf("Marshal: %v", err)
  416. }
  417. refName := git.RefEndName(refFullName)
  418. if err = NotifyWatchers(&Action{
  419. ActUserID: u.ID,
  420. ActUserName: userName,
  421. ActEmail: actEmail,
  422. OpType: opType,
  423. Content: string(bs),
  424. RepoID: repo.ID,
  425. RepoUserName: repoUserName,
  426. RepoName: repo.Name,
  427. RefName: refName,
  428. IsPrivate: repo.IsPrivate,
  429. }); err != nil {
  430. return fmt.Errorf("NotifyWatchers: %v", err)
  431. }
  432. pusher, err := GetUserByName(userName)
  433. if err != nil {
  434. return fmt.Errorf("GetUserByName: %v", err)
  435. }
  436. apiPusher := pusher.APIFormat()
  437. apiRepo := repo.APIFormat(nil)
  438. switch opType {
  439. case ACTION_COMMIT_REPO: // Push
  440. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{
  441. Ref: refFullName,
  442. Before: oldCommitID,
  443. After: newCommitID,
  444. CompareURL: setting.AppUrl + commit.CompareURL,
  445. Commits: commit.ToApiPayloadCommits(repo.FullLink()),
  446. Repo: apiRepo,
  447. Pusher: apiPusher,
  448. Sender: apiPusher,
  449. }); err != nil {
  450. return fmt.Errorf("PrepareWebhooks: %v", err)
  451. }
  452. if isNewBranch {
  453. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  454. Ref: refName,
  455. RefType: "branch",
  456. Repo: apiRepo,
  457. Sender: apiPusher,
  458. })
  459. }
  460. case ACTION_PUSH_TAG: // Create
  461. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  462. Ref: refName,
  463. RefType: "tag",
  464. Repo: apiRepo,
  465. Sender: apiPusher,
  466. })
  467. }
  468. return nil
  469. }
  470. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  471. if err = notifyWatchers(e, &Action{
  472. ActUserID: actUser.ID,
  473. ActUserName: actUser.Name,
  474. ActEmail: actUser.Email,
  475. OpType: ACTION_TRANSFER_REPO,
  476. RepoID: repo.ID,
  477. RepoUserName: newOwner.Name,
  478. RepoName: repo.Name,
  479. IsPrivate: repo.IsPrivate,
  480. Content: path.Join(oldOwner.Name, repo.Name),
  481. }); err != nil {
  482. return fmt.Errorf("notify watchers '%d/%d': %v", actUser.ID, repo.ID, err)
  483. }
  484. // Remove watch for organization.
  485. if repo.Owner.IsOrganization() {
  486. if err = watchRepo(e, repo.Owner.ID, repo.ID, false); err != nil {
  487. return fmt.Errorf("watch repository: %v", err)
  488. }
  489. }
  490. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  491. return nil
  492. }
  493. // TransferRepoAction adds new action for transferring repository.
  494. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  495. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  496. }
  497. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  498. return notifyWatchers(e, &Action{
  499. ActUserID: actUser.ID,
  500. ActUserName: actUser.Name,
  501. ActEmail: actUser.Email,
  502. OpType: ACTION_MERGE_PULL_REQUEST,
  503. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  504. RepoID: repo.ID,
  505. RepoUserName: repo.Owner.Name,
  506. RepoName: repo.Name,
  507. IsPrivate: repo.IsPrivate,
  508. })
  509. }
  510. // MergePullRequestAction adds new action for merging pull request.
  511. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  512. return mergePullRequestAction(x, actUser, repo, pull)
  513. }
  514. // GetFeeds returns action list of given user in given context.
  515. // actorID is the user who's requesting, ctxUserID is the user/org that is requested.
  516. // actorID can be -1 when isProfile is true or to skip the permission check.
  517. func GetFeeds(ctxUser *User, actorID, offset int64, isProfile bool) ([]*Action, error) {
  518. actions := make([]*Action, 0, 20)
  519. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id = ?", ctxUser.ID)
  520. if isProfile {
  521. sess.And("is_private = ?", false).And("act_user_id = ?", ctxUser.ID)
  522. } else if actorID != -1 && ctxUser.IsOrganization() {
  523. // FIXME: only need to get IDs here, not all fields of repository.
  524. repos, _, err := ctxUser.GetUserRepositories(actorID, 1, ctxUser.NumRepos)
  525. if err != nil {
  526. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  527. }
  528. var repoIDs []int64
  529. for _, repo := range repos {
  530. repoIDs = append(repoIDs, repo.ID)
  531. }
  532. if len(repoIDs) > 0 {
  533. sess.In("repo_id", repoIDs)
  534. }
  535. }
  536. err := sess.Find(&actions)
  537. return actions, err
  538. }