action.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. ACTION_CLOSE_PULL_REQUEST // 14
  38. ACTION_REOPEN_PULL_REQUEST // 15
  39. )
  40. var (
  41. ErrNotImplemented = errors.New("Not implemented yet")
  42. )
  43. var (
  44. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  45. IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  46. IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  47. IssueCloseKeywordsPat, IssueReopenKeywordsPat *regexp.Regexp
  48. IssueReferenceKeywordsPat *regexp.Regexp
  49. )
  50. func assembleKeywordsPattern(words []string) string {
  51. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  52. }
  53. func init() {
  54. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  55. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  56. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  57. }
  58. // Action represents user operation type and other information to repository.,
  59. // it implemented interface base.Actioner so that can be used in template render.
  60. type Action struct {
  61. ID int64 `xorm:"pk autoincr"`
  62. UserID int64 // Receiver user id.
  63. OpType ActionType
  64. ActUserID int64 // Action user id.
  65. ActUserName string // Action user name.
  66. ActEmail string
  67. ActAvatar string `xorm:"-"`
  68. RepoID int64
  69. RepoUserName string
  70. RepoName string
  71. RefName string
  72. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  73. Content string `xorm:"TEXT"`
  74. Created time.Time `xorm:"created"`
  75. }
  76. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  77. switch colName {
  78. case "created":
  79. a.Created = regulateTimeZone(a.Created)
  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.Name
  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. }
  198. type PushCommits struct {
  199. Len int
  200. Commits []*PushCommit
  201. CompareUrl string
  202. avatars map[string]string
  203. }
  204. func NewPushCommits() *PushCommits {
  205. return &PushCommits{
  206. avatars: make(map[string]string),
  207. }
  208. }
  209. func (pc *PushCommits) ToApiPayloadCommits(repoLink string) []*api.PayloadCommit {
  210. commits := make([]*api.PayloadCommit, len(pc.Commits))
  211. for i, cmt := range pc.Commits {
  212. author_username := ""
  213. author, err := GetUserByEmail(cmt.AuthorEmail)
  214. if err == nil {
  215. author_username = author.Name
  216. }
  217. commits[i] = &api.PayloadCommit{
  218. ID: cmt.Sha1,
  219. Message: cmt.Message,
  220. URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  221. Author: &api.PayloadAuthor{
  222. Name: cmt.AuthorName,
  223. Email: cmt.AuthorEmail,
  224. UserName: author_username,
  225. },
  226. }
  227. }
  228. return commits
  229. }
  230. // AvatarLink tries to match user in database with e-mail
  231. // in order to show custom avatar, and falls back to general avatar link.
  232. func (push *PushCommits) AvatarLink(email string) string {
  233. _, ok := push.avatars[email]
  234. if !ok {
  235. u, err := GetUserByEmail(email)
  236. if err != nil {
  237. push.avatars[email] = base.AvatarLink(email)
  238. if !IsErrUserNotExist(err) {
  239. log.Error(4, "GetUserByEmail: %v", err)
  240. }
  241. } else {
  242. push.avatars[email] = u.AvatarLink()
  243. }
  244. }
  245. return push.avatars[email]
  246. }
  247. // updateIssuesCommit checks if issues are manipulated by commit message.
  248. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*PushCommit) error {
  249. // Commits are appended in the reverse order.
  250. for i := len(commits) - 1; i >= 0; i-- {
  251. c := commits[i]
  252. refMarked := make(map[int64]bool)
  253. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  254. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  255. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  256. if len(ref) == 0 {
  257. continue
  258. }
  259. // Add repo name if missing
  260. if ref[0] == '#' {
  261. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  262. } else if !strings.Contains(ref, "/") {
  263. // FIXME: We don't support User#ID syntax yet
  264. // return ErrNotImplemented
  265. continue
  266. }
  267. issue, err := GetIssueByRef(ref)
  268. if err != nil {
  269. if IsErrIssueNotExist(err) {
  270. continue
  271. }
  272. return err
  273. }
  274. if refMarked[issue.ID] {
  275. continue
  276. }
  277. refMarked[issue.ID] = true
  278. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  279. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  280. if err = CreateRefComment(u, repo, issue, message, c.Sha1); err != nil {
  281. return err
  282. }
  283. }
  284. refMarked = make(map[int64]bool)
  285. // FIXME: can merge this one and next one to a common function.
  286. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  287. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  288. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  289. if len(ref) == 0 {
  290. continue
  291. }
  292. // Add repo name if missing
  293. if ref[0] == '#' {
  294. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  295. } else if !strings.Contains(ref, "/") {
  296. // We don't support User#ID syntax yet
  297. // return ErrNotImplemented
  298. continue
  299. }
  300. issue, err := GetIssueByRef(ref)
  301. if err != nil {
  302. if IsErrIssueNotExist(err) {
  303. continue
  304. }
  305. return err
  306. }
  307. if refMarked[issue.ID] {
  308. continue
  309. }
  310. refMarked[issue.ID] = true
  311. if issue.RepoID != repo.ID || issue.IsClosed {
  312. continue
  313. }
  314. if err = issue.ChangeStatus(u, repo, true); err != nil {
  315. return err
  316. }
  317. }
  318. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  319. for _, ref := range IssueReopenKeywordsPat.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%s", repoUserName, repoName, ref)
  328. } else if !strings.Contains(ref, "/") {
  329. // 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 IsErrIssueNotExist(err) {
  336. continue
  337. }
  338. return err
  339. }
  340. if refMarked[issue.ID] {
  341. continue
  342. }
  343. refMarked[issue.ID] = true
  344. if issue.RepoID != repo.ID || !issue.IsClosed {
  345. continue
  346. }
  347. if err = issue.ChangeStatus(u, repo, false); err != nil {
  348. return err
  349. }
  350. }
  351. }
  352. return nil
  353. }
  354. // CommitRepoAction adds new action for committing repository.
  355. func CommitRepoAction(
  356. userID, repoUserID int64,
  357. userName, actEmail string,
  358. repoID int64,
  359. repoUserName, repoName string,
  360. refFullName string,
  361. commit *PushCommits,
  362. oldCommitID string, newCommitID string) error {
  363. u, err := GetUserByID(userID)
  364. if err != nil {
  365. return fmt.Errorf("GetUserByID: %v", err)
  366. }
  367. repo, err := GetRepositoryByName(repoUserID, repoName)
  368. if err != nil {
  369. return fmt.Errorf("GetRepositoryByName: %v", err)
  370. } else if err = repo.GetOwner(); err != nil {
  371. return fmt.Errorf("GetOwner: %v", err)
  372. }
  373. // Change repository bare status and update last updated time.
  374. repo.IsBare = false
  375. if err = UpdateRepository(repo, false); err != nil {
  376. return fmt.Errorf("UpdateRepository: %v", err)
  377. }
  378. isNewBranch := false
  379. opType := ACTION_COMMIT_REPO
  380. // Check it's tag push or branch.
  381. if strings.HasPrefix(refFullName, "refs/tags/") {
  382. opType = ACTION_PUSH_TAG
  383. commit = &PushCommits{}
  384. } else {
  385. // if not the first commit, set the compareUrl
  386. if !strings.HasPrefix(oldCommitID, "0000000") {
  387. commit.CompareUrl = repo.ComposeCompareURL(oldCommitID, newCommitID)
  388. } else {
  389. isNewBranch = true
  390. }
  391. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  392. log.Error(4, "updateIssuesCommit: %v", err)
  393. }
  394. }
  395. if len(commit.Commits) > setting.FeedMaxCommitNum {
  396. commit.Commits = commit.Commits[:setting.FeedMaxCommitNum]
  397. }
  398. bs, err := json.Marshal(commit)
  399. if err != nil {
  400. return fmt.Errorf("Marshal: %v", err)
  401. }
  402. refName := git.RefEndName(refFullName)
  403. if err = NotifyWatchers(&Action{
  404. ActUserID: u.Id,
  405. ActUserName: userName,
  406. ActEmail: actEmail,
  407. OpType: opType,
  408. Content: string(bs),
  409. RepoID: repo.ID,
  410. RepoUserName: repoUserName,
  411. RepoName: repoName,
  412. RefName: refName,
  413. IsPrivate: repo.IsPrivate,
  414. }); err != nil {
  415. return fmt.Errorf("NotifyWatchers: %v", err)
  416. }
  417. payloadRepo := repo.ComposePayload()
  418. pusher_email, pusher_name := "", ""
  419. pusher, err := GetUserByName(userName)
  420. if err == nil {
  421. pusher_email = pusher.Email
  422. pusher_name = pusher.DisplayName()
  423. }
  424. payloadSender := &api.PayloadUser{
  425. UserName: pusher.Name,
  426. ID: pusher.Id,
  427. AvatarUrl: pusher.AvatarLink(),
  428. }
  429. switch opType {
  430. case ACTION_COMMIT_REPO: // Push
  431. p := &api.PushPayload{
  432. Ref: refFullName,
  433. Before: oldCommitID,
  434. After: newCommitID,
  435. CompareUrl: setting.AppUrl + commit.CompareUrl,
  436. Commits: commit.ToApiPayloadCommits(repo.FullRepoLink()),
  437. Repo: payloadRepo,
  438. Pusher: &api.PayloadAuthor{
  439. Name: pusher_name,
  440. Email: pusher_email,
  441. UserName: userName,
  442. },
  443. Sender: payloadSender,
  444. }
  445. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil {
  446. return fmt.Errorf("PrepareWebhooks: %v", err)
  447. }
  448. if isNewBranch {
  449. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  450. Ref: refName,
  451. RefType: "branch",
  452. Repo: payloadRepo,
  453. Sender: payloadSender,
  454. })
  455. }
  456. case ACTION_PUSH_TAG: // Create
  457. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  458. Ref: refName,
  459. RefType: "tag",
  460. Repo: payloadRepo,
  461. Sender: payloadSender,
  462. })
  463. }
  464. return nil
  465. }
  466. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  467. if err = notifyWatchers(e, &Action{
  468. ActUserID: actUser.Id,
  469. ActUserName: actUser.Name,
  470. ActEmail: actUser.Email,
  471. OpType: ACTION_TRANSFER_REPO,
  472. RepoID: repo.ID,
  473. RepoUserName: newOwner.Name,
  474. RepoName: repo.Name,
  475. IsPrivate: repo.IsPrivate,
  476. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  477. }); err != nil {
  478. return fmt.Errorf("notify watchers '%d/%d': %v", actUser.Id, repo.ID, err)
  479. }
  480. // Remove watch for organization.
  481. if repo.Owner.IsOrganization() {
  482. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  483. return fmt.Errorf("watch repository: %v", err)
  484. }
  485. }
  486. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  487. return nil
  488. }
  489. // TransferRepoAction adds new action for transferring repository.
  490. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  491. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  492. }
  493. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  494. return notifyWatchers(e, &Action{
  495. ActUserID: actUser.Id,
  496. ActUserName: actUser.Name,
  497. ActEmail: actUser.Email,
  498. OpType: ACTION_MERGE_PULL_REQUEST,
  499. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  500. RepoID: repo.ID,
  501. RepoUserName: repo.Owner.Name,
  502. RepoName: repo.Name,
  503. IsPrivate: repo.IsPrivate,
  504. })
  505. }
  506. // MergePullRequestAction adds new action for merging pull request.
  507. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  508. return mergePullRequestAction(x, actUser, repo, pull)
  509. }
  510. // GetFeeds returns action list of given user in given context.
  511. // userID is the user who's requesting, ctxUserID is the user/org that is requested.
  512. // userID can be -1, if isProfile is true or in order to skip the permission check.
  513. func GetFeeds(ctxUserID, userID, offset int64, isProfile bool) ([]*Action, error) {
  514. actions := make([]*Action, 0, 20)
  515. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", ctxUserID)
  516. if isProfile {
  517. sess.And("is_private=?", false).And("act_user_id=?", ctxUserID)
  518. } else if ctxUserID != -1 {
  519. ctxUser := &User{Id: ctxUserID}
  520. if err := ctxUser.GetUserRepositories(userID); err != nil {
  521. return nil, err
  522. }
  523. var repoIDs []int64
  524. for _, repo := range ctxUser.Repos {
  525. repoIDs = append(repoIDs, repo.ID)
  526. }
  527. if len(repoIDs) > 0 {
  528. sess.In("repo_id", repoIDs)
  529. }
  530. }
  531. err := sess.Find(&actions)
  532. return actions, err
  533. }