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