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