You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

599 lines
16 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. api "github.com/gogits/go-gogs-client"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/git"
  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. // AvatarLink tries to match user in database with e-mail
  194. // in order to show custom avatar, and falls back to general avatar link.
  195. func (push *PushCommits) AvatarLink(email string) string {
  196. _, ok := push.avatars[email]
  197. if !ok {
  198. u, err := GetUserByEmail(email)
  199. if err != nil {
  200. push.avatars[email] = base.AvatarLink(email)
  201. if !IsErrUserNotExist(err) {
  202. log.Error(4, "GetUserByEmail: %v", err)
  203. }
  204. } else {
  205. push.avatars[email] = u.AvatarLink()
  206. }
  207. }
  208. return push.avatars[email]
  209. }
  210. // updateIssuesCommit checks if issues are manipulated by commit message.
  211. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*PushCommit) error {
  212. // Commits are appended in the reverse order.
  213. for i := len(commits) - 1; i >= 0; i-- {
  214. c := commits[i]
  215. refMarked := make(map[int64]bool)
  216. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  217. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  218. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  219. if len(ref) == 0 {
  220. continue
  221. }
  222. // Add repo name if missing
  223. if ref[0] == '#' {
  224. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  225. } else if !strings.Contains(ref, "/") {
  226. // FIXME: We don't support User#ID syntax yet
  227. // return ErrNotImplemented
  228. continue
  229. }
  230. issue, err := GetIssueByRef(ref)
  231. if err != nil {
  232. if IsErrIssueNotExist(err) {
  233. continue
  234. }
  235. return err
  236. }
  237. if refMarked[issue.ID] {
  238. continue
  239. }
  240. refMarked[issue.ID] = true
  241. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  242. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  243. if err = CreateRefComment(u, repo, issue, message, c.Sha1); err != nil {
  244. return err
  245. }
  246. }
  247. refMarked = make(map[int64]bool)
  248. // FIXME: can merge this one and next one to a common function.
  249. for _, ref := range IssueCloseKeywordsPat.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. // 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. if issue.RepoID != repo.ID || issue.IsClosed {
  275. continue
  276. }
  277. if err = issue.ChangeStatus(u, true); err != nil {
  278. return err
  279. }
  280. }
  281. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  282. for _, ref := range IssueReopenKeywordsPat.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, false); err != nil {
  311. return err
  312. }
  313. }
  314. }
  315. return nil
  316. }
  317. // CommitRepoAction adds new action for committing repository.
  318. func CommitRepoAction(
  319. userID, repoUserID int64,
  320. userName, actEmail string,
  321. repoID int64,
  322. repoUserName, repoName string,
  323. refFullName string,
  324. commit *PushCommits,
  325. oldCommitID string, newCommitID string) error {
  326. u, err := GetUserByID(userID)
  327. if err != nil {
  328. return fmt.Errorf("GetUserByID: %v", err)
  329. }
  330. repo, err := GetRepositoryByName(repoUserID, repoName)
  331. if err != nil {
  332. return fmt.Errorf("GetRepositoryByName: %v", err)
  333. } else if err = repo.GetOwner(); err != nil {
  334. return fmt.Errorf("GetOwner: %v", err)
  335. }
  336. // Change repository bare status and update last updated time.
  337. repo.IsBare = false
  338. if err = UpdateRepository(repo, false); err != nil {
  339. return fmt.Errorf("UpdateRepository: %v", err)
  340. }
  341. isNewBranch := false
  342. opType := COMMIT_REPO
  343. // Check it's tag push or branch.
  344. if strings.HasPrefix(refFullName, "refs/tags/") {
  345. opType = PUSH_TAG
  346. commit = &PushCommits{}
  347. } else {
  348. // if not the first commit, set the compareUrl
  349. if !strings.HasPrefix(oldCommitID, "0000000") {
  350. commit.CompareUrl = fmt.Sprintf("%s/%s/compare/%s...%s", repoUserName, repoName, oldCommitID, newCommitID)
  351. } else {
  352. isNewBranch = true
  353. }
  354. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  355. log.Error(4, "updateIssuesCommit: %v", err)
  356. }
  357. }
  358. if len(commit.Commits) > setting.FeedMaxCommitNum {
  359. commit.Commits = commit.Commits[:setting.FeedMaxCommitNum]
  360. }
  361. bs, err := json.Marshal(commit)
  362. if err != nil {
  363. return fmt.Errorf("Marshal: %v", err)
  364. }
  365. refName := git.RefEndName(refFullName)
  366. if err = NotifyWatchers(&Action{
  367. ActUserID: u.Id,
  368. ActUserName: userName,
  369. ActEmail: actEmail,
  370. OpType: opType,
  371. Content: string(bs),
  372. RepoID: repo.ID,
  373. RepoUserName: repoUserName,
  374. RepoName: repoName,
  375. RefName: refName,
  376. IsPrivate: repo.IsPrivate,
  377. }); err != nil {
  378. return fmt.Errorf("NotifyWatchers: %v", err)
  379. }
  380. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  381. payloadRepo := &api.PayloadRepo{
  382. ID: repo.ID,
  383. Name: repo.LowerName,
  384. URL: repoLink,
  385. Description: repo.Description,
  386. Website: repo.Website,
  387. Watchers: repo.NumWatches,
  388. Owner: &api.PayloadAuthor{
  389. Name: repo.Owner.DisplayName(),
  390. Email: repo.Owner.Email,
  391. UserName: repo.Owner.Name,
  392. },
  393. Private: repo.IsPrivate,
  394. }
  395. pusher_email, pusher_name := "", ""
  396. pusher, err := GetUserByName(userName)
  397. if err == nil {
  398. pusher_email = pusher.Email
  399. pusher_name = pusher.DisplayName()
  400. }
  401. payloadSender := &api.PayloadUser{
  402. UserName: pusher.Name,
  403. ID: pusher.Id,
  404. AvatarUrl: setting.AppUrl + pusher.RelAvatarLink(),
  405. }
  406. switch opType {
  407. case COMMIT_REPO: // Push
  408. commits := make([]*api.PayloadCommit, len(commit.Commits))
  409. for i, cmt := range commit.Commits {
  410. author_username := ""
  411. author, err := GetUserByEmail(cmt.AuthorEmail)
  412. if err == nil {
  413. author_username = author.Name
  414. }
  415. commits[i] = &api.PayloadCommit{
  416. ID: cmt.Sha1,
  417. Message: cmt.Message,
  418. URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  419. Author: &api.PayloadAuthor{
  420. Name: cmt.AuthorName,
  421. Email: cmt.AuthorEmail,
  422. UserName: author_username,
  423. },
  424. }
  425. }
  426. p := &api.PushPayload{
  427. Ref: refFullName,
  428. Before: oldCommitID,
  429. After: newCommitID,
  430. CompareUrl: setting.AppUrl + commit.CompareUrl,
  431. Commits: commits,
  432. Repo: payloadRepo,
  433. Pusher: &api.PayloadAuthor{
  434. Name: pusher_name,
  435. Email: pusher_email,
  436. UserName: userName,
  437. },
  438. Sender: payloadSender,
  439. }
  440. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil {
  441. return fmt.Errorf("PrepareWebhooks: %v", err)
  442. }
  443. if isNewBranch {
  444. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  445. Ref: refName,
  446. RefType: "branch",
  447. Repo: payloadRepo,
  448. Sender: payloadSender,
  449. })
  450. }
  451. case PUSH_TAG: // Create
  452. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  453. Ref: refName,
  454. RefType: "tag",
  455. Repo: payloadRepo,
  456. Sender: payloadSender,
  457. })
  458. }
  459. return nil
  460. }
  461. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  462. if err = notifyWatchers(e, &Action{
  463. ActUserID: actUser.Id,
  464. ActUserName: actUser.Name,
  465. ActEmail: actUser.Email,
  466. OpType: TRANSFER_REPO,
  467. RepoID: repo.ID,
  468. RepoUserName: newOwner.Name,
  469. RepoName: repo.Name,
  470. IsPrivate: repo.IsPrivate,
  471. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  472. }); err != nil {
  473. return fmt.Errorf("notify watchers '%d/%d': %v", actUser.Id, repo.ID, err)
  474. }
  475. // Remove watch for organization.
  476. if repo.Owner.IsOrganization() {
  477. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  478. return fmt.Errorf("watch repository: %v", err)
  479. }
  480. }
  481. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  482. return nil
  483. }
  484. // TransferRepoAction adds new action for transferring repository.
  485. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  486. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  487. }
  488. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  489. return notifyWatchers(e, &Action{
  490. ActUserID: actUser.Id,
  491. ActUserName: actUser.Name,
  492. ActEmail: actUser.Email,
  493. OpType: MERGE_PULL_REQUEST,
  494. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  495. RepoID: repo.ID,
  496. RepoUserName: repo.Owner.Name,
  497. RepoName: repo.Name,
  498. IsPrivate: repo.IsPrivate,
  499. })
  500. }
  501. // MergePullRequestAction adds new action for merging pull request.
  502. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  503. return mergePullRequestAction(x, actUser, repo, pull)
  504. }
  505. // GetFeeds returns action list of given user in given context.
  506. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  507. actions := make([]*Action, 0, 20)
  508. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  509. if isProfile {
  510. sess.And("is_private=?", false).And("act_user_id=?", uid)
  511. }
  512. err := sess.Find(&actions)
  513. return actions, err
  514. }