action.go 15 KB

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