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