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.

522 lines
14 KiB

10 years ago
10 years ago
10 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
10 years ago
10 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/go-xorm/xorm"
  15. api "github.com/gogits/go-gogs-client"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/git"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. type ActionType int
  22. const (
  23. CREATE_REPO ActionType = iota + 1 // 1
  24. RENAME_REPO // 2
  25. STAR_REPO // 3
  26. FOLLOW_REPO // 4
  27. COMMIT_REPO // 5
  28. CREATE_ISSUE // 6
  29. CREATE_PULL_REQUEST // 7
  30. TRANSFER_REPO // 8
  31. PUSH_TAG // 9
  32. COMMENT_ISSUE // 10
  33. MERGE_PULL_REQUEST // 11
  34. )
  35. var (
  36. ErrNotImplemented = errors.New("Not implemented yet")
  37. )
  38. var (
  39. // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
  40. IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  41. IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  42. IssueCloseKeywordsPat, IssueReopenKeywordsPat *regexp.Regexp
  43. IssueReferenceKeywordsPat *regexp.Regexp
  44. )
  45. func assembleKeywordsPattern(words []string) string {
  46. return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|"))
  47. }
  48. func init() {
  49. IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
  50. IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
  51. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  52. }
  53. // Action represents user operation type and other information to repository.,
  54. // it implemented interface base.Actioner so that can be used in template render.
  55. type Action struct {
  56. ID int64 `xorm:"pk autoincr"`
  57. UserID int64 // Receiver user id.
  58. OpType ActionType
  59. ActUserID int64 // Action user id.
  60. ActUserName string // Action user name.
  61. ActEmail string
  62. ActAvatar string `xorm:"-"`
  63. RepoID int64
  64. RepoUserName string
  65. RepoName string
  66. RefName string
  67. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  68. Content string `xorm:"TEXT"`
  69. Created time.Time `xorm:"created"`
  70. }
  71. func (a *Action) AfterSet(colName string, _ xorm.Cell) {
  72. switch colName {
  73. case "created":
  74. a.Created = regulateTimeZone(a.Created)
  75. }
  76. }
  77. func (a Action) GetOpType() int {
  78. return int(a.OpType)
  79. }
  80. func (a Action) GetActUserName() string {
  81. return a.ActUserName
  82. }
  83. func (a Action) GetActEmail() string {
  84. return a.ActEmail
  85. }
  86. func (a Action) GetRepoUserName() string {
  87. return a.RepoUserName
  88. }
  89. func (a Action) GetRepoName() string {
  90. return a.RepoName
  91. }
  92. func (a Action) GetRepoPath() string {
  93. return path.Join(a.RepoUserName, a.RepoName)
  94. }
  95. func (a Action) GetRepoLink() string {
  96. if len(setting.AppSubUrl) > 0 {
  97. return path.Join(setting.AppSubUrl, a.GetRepoPath())
  98. }
  99. return "/" + a.GetRepoPath()
  100. }
  101. func (a Action) GetBranch() string {
  102. return a.RefName
  103. }
  104. func (a Action) GetContent() string {
  105. return a.Content
  106. }
  107. func (a Action) GetCreate() time.Time {
  108. return a.Created
  109. }
  110. func (a Action) GetIssueInfos() []string {
  111. return strings.SplitN(a.Content, "|", 2)
  112. }
  113. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  114. if err = notifyWatchers(e, &Action{
  115. ActUserID: u.Id,
  116. ActUserName: u.Name,
  117. ActEmail: u.Email,
  118. OpType: CREATE_REPO,
  119. RepoID: repo.ID,
  120. RepoUserName: repo.Owner.Name,
  121. RepoName: repo.Name,
  122. IsPrivate: repo.IsPrivate,
  123. }); err != nil {
  124. return fmt.Errorf("notify watchers '%d/%s': %v", u.Id, repo.ID, err)
  125. }
  126. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  127. return err
  128. }
  129. // NewRepoAction adds new action for creating repository.
  130. func NewRepoAction(u *User, repo *Repository) (err error) {
  131. return newRepoAction(x, u, repo)
  132. }
  133. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  134. if err = notifyWatchers(e, &Action{
  135. ActUserID: actUser.Id,
  136. ActUserName: actUser.Name,
  137. ActEmail: actUser.Email,
  138. OpType: RENAME_REPO,
  139. RepoID: repo.ID,
  140. RepoUserName: repo.Owner.Name,
  141. RepoName: repo.Name,
  142. IsPrivate: repo.IsPrivate,
  143. Content: oldRepoName,
  144. }); err != nil {
  145. return fmt.Errorf("notify watchers: %v", err)
  146. }
  147. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  148. return nil
  149. }
  150. // RenameRepoAction adds new action for renaming a repository.
  151. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  152. return renameRepoAction(x, actUser, oldRepoName, repo)
  153. }
  154. func issueIndexTrimRight(c rune) bool {
  155. return !unicode.IsDigit(c)
  156. }
  157. // updateIssuesCommit checks if issues are manipulated by commit message.
  158. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*base.PushCommit) error {
  159. for _, c := range commits {
  160. refMarked := make(map[int64]bool)
  161. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  162. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  163. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  164. if len(ref) == 0 {
  165. continue
  166. }
  167. // Add repo name if missing
  168. if ref[0] == '#' {
  169. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  170. } else if !strings.Contains(ref, "/") {
  171. // FIXME: We don't support User#ID syntax yet
  172. // return ErrNotImplemented
  173. continue
  174. }
  175. issue, err := GetIssueByRef(ref)
  176. if err != nil {
  177. return err
  178. }
  179. if refMarked[issue.ID] {
  180. continue
  181. }
  182. refMarked[issue.ID] = true
  183. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  184. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  185. if _, err = CreateComment(u, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, message, nil); err != nil {
  186. return err
  187. }
  188. }
  189. refMarked = make(map[int64]bool)
  190. // FIXME: can merge this one and next one to a common function.
  191. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  192. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  193. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  194. if len(ref) == 0 {
  195. continue
  196. }
  197. // Add repo name if missing
  198. if ref[0] == '#' {
  199. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  200. } else if !strings.Contains(ref, "/") {
  201. // We don't support User#ID syntax yet
  202. // return ErrNotImplemented
  203. continue
  204. }
  205. issue, err := GetIssueByRef(ref)
  206. if err != nil {
  207. return err
  208. }
  209. if refMarked[issue.ID] {
  210. continue
  211. }
  212. refMarked[issue.ID] = true
  213. if issue.RepoID != repo.ID || issue.IsClosed {
  214. continue
  215. }
  216. if err = issue.ChangeStatus(u, true); err != nil {
  217. return err
  218. }
  219. }
  220. // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here.
  221. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  222. ref = ref[strings.IndexByte(ref, byte(' '))+1:]
  223. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  224. if len(ref) == 0 {
  225. continue
  226. }
  227. // Add repo name if missing
  228. if ref[0] == '#' {
  229. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  230. } else if !strings.Contains(ref, "/") {
  231. // We don't support User#ID syntax yet
  232. // return ErrNotImplemented
  233. continue
  234. }
  235. issue, err := GetIssueByRef(ref)
  236. if err != nil {
  237. return err
  238. }
  239. if refMarked[issue.ID] {
  240. continue
  241. }
  242. refMarked[issue.ID] = true
  243. if issue.RepoID != repo.ID || !issue.IsClosed {
  244. continue
  245. }
  246. if err = issue.ChangeStatus(u, false); err != nil {
  247. return err
  248. }
  249. }
  250. }
  251. return nil
  252. }
  253. // CommitRepoAction adds new action for committing repository.
  254. func CommitRepoAction(
  255. userID, repoUserID int64,
  256. userName, actEmail string,
  257. repoID int64,
  258. repoUserName, repoName string,
  259. refFullName string,
  260. commit *base.PushCommits,
  261. oldCommitID string, newCommitID string) error {
  262. u, err := GetUserByID(userID)
  263. if err != nil {
  264. return fmt.Errorf("GetUserByID: %v", err)
  265. }
  266. repo, err := GetRepositoryByName(repoUserID, repoName)
  267. if err != nil {
  268. return fmt.Errorf("GetRepositoryByName: %v", err)
  269. } else if err = repo.GetOwner(); err != nil {
  270. return fmt.Errorf("GetOwner: %v", err)
  271. }
  272. isNewBranch := false
  273. opType := COMMIT_REPO
  274. // Check it's tag push or branch.
  275. if strings.HasPrefix(refFullName, "refs/tags/") {
  276. opType = PUSH_TAG
  277. commit = &base.PushCommits{}
  278. } else {
  279. // if not the first commit, set the compareUrl
  280. if !strings.HasPrefix(oldCommitID, "0000000") {
  281. commit.CompareUrl = fmt.Sprintf("%s/%s/compare/%s...%s", repoUserName, repoName, oldCommitID, newCommitID)
  282. } else {
  283. isNewBranch = true
  284. }
  285. // Change repository bare status and update last updated time.
  286. repo.IsBare = false
  287. if err = UpdateRepository(repo, false); err != nil {
  288. return fmt.Errorf("UpdateRepository: %v", err)
  289. }
  290. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  291. log.Debug("updateIssuesCommit: %v", err)
  292. }
  293. }
  294. bs, err := json.Marshal(commit)
  295. if err != nil {
  296. return fmt.Errorf("Marshal: %v", err)
  297. }
  298. refName := git.RefEndName(refFullName)
  299. if err = NotifyWatchers(&Action{
  300. ActUserID: u.Id,
  301. ActUserName: userName,
  302. ActEmail: actEmail,
  303. OpType: opType,
  304. Content: string(bs),
  305. RepoID: repo.ID,
  306. RepoUserName: repoUserName,
  307. RepoName: repoName,
  308. RefName: refName,
  309. IsPrivate: repo.IsPrivate,
  310. }); err != nil {
  311. return fmt.Errorf("NotifyWatchers: %v", err)
  312. }
  313. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  314. payloadRepo := &api.PayloadRepo{
  315. ID: repo.ID,
  316. Name: repo.LowerName,
  317. URL: repoLink,
  318. Description: repo.Description,
  319. Website: repo.Website,
  320. Watchers: repo.NumWatches,
  321. Owner: &api.PayloadAuthor{
  322. Name: repo.Owner.DisplayName(),
  323. Email: repo.Owner.Email,
  324. UserName: repo.Owner.Name,
  325. },
  326. Private: repo.IsPrivate,
  327. }
  328. pusher_email, pusher_name := "", ""
  329. pusher, err := GetUserByName(userName)
  330. if err == nil {
  331. pusher_email = pusher.Email
  332. pusher_name = pusher.DisplayName()
  333. }
  334. payloadSender := &api.PayloadUser{
  335. UserName: pusher.Name,
  336. ID: pusher.Id,
  337. AvatarUrl: setting.AppUrl + pusher.RelAvatarLink(),
  338. }
  339. switch opType {
  340. case COMMIT_REPO: // Push
  341. commits := make([]*api.PayloadCommit, len(commit.Commits))
  342. for i, cmt := range commit.Commits {
  343. author_username := ""
  344. author, err := GetUserByEmail(cmt.AuthorEmail)
  345. if err == nil {
  346. author_username = author.Name
  347. }
  348. commits[i] = &api.PayloadCommit{
  349. ID: cmt.Sha1,
  350. Message: cmt.Message,
  351. URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  352. Author: &api.PayloadAuthor{
  353. Name: cmt.AuthorName,
  354. Email: cmt.AuthorEmail,
  355. UserName: author_username,
  356. },
  357. }
  358. }
  359. p := &api.PushPayload{
  360. Ref: refFullName,
  361. Before: oldCommitID,
  362. After: newCommitID,
  363. CompareUrl: setting.AppUrl + commit.CompareUrl,
  364. Commits: commits,
  365. Repo: payloadRepo,
  366. Pusher: &api.PayloadAuthor{
  367. Name: pusher_name,
  368. Email: pusher_email,
  369. UserName: userName,
  370. },
  371. Sender: payloadSender,
  372. }
  373. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil {
  374. return fmt.Errorf("PrepareWebhooks: %v", err)
  375. }
  376. if isNewBranch {
  377. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  378. Ref: refName,
  379. RefType: "branch",
  380. Repo: payloadRepo,
  381. Sender: payloadSender,
  382. })
  383. }
  384. case PUSH_TAG: // Create
  385. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  386. Ref: refName,
  387. RefType: "tag",
  388. Repo: payloadRepo,
  389. Sender: payloadSender,
  390. })
  391. }
  392. return nil
  393. }
  394. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  395. if err = notifyWatchers(e, &Action{
  396. ActUserID: actUser.Id,
  397. ActUserName: actUser.Name,
  398. ActEmail: actUser.Email,
  399. OpType: TRANSFER_REPO,
  400. RepoID: repo.ID,
  401. RepoUserName: newOwner.Name,
  402. RepoName: repo.Name,
  403. IsPrivate: repo.IsPrivate,
  404. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  405. }); err != nil {
  406. return fmt.Errorf("notify watchers '%d/%s': %v", actUser.Id, repo.ID, err)
  407. }
  408. // Remove watch for organization.
  409. if repo.Owner.IsOrganization() {
  410. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  411. return fmt.Errorf("watch repository: %v", err)
  412. }
  413. }
  414. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  415. return nil
  416. }
  417. // TransferRepoAction adds new action for transferring repository.
  418. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  419. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  420. }
  421. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  422. return notifyWatchers(e, &Action{
  423. ActUserID: actUser.Id,
  424. ActUserName: actUser.Name,
  425. ActEmail: actUser.Email,
  426. OpType: MERGE_PULL_REQUEST,
  427. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  428. RepoID: repo.ID,
  429. RepoUserName: repo.Owner.Name,
  430. RepoName: repo.Name,
  431. IsPrivate: repo.IsPrivate,
  432. })
  433. }
  434. // MergePullRequestAction adds new action for merging pull request.
  435. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  436. return mergePullRequestAction(x, actUser, repo, pull)
  437. }
  438. // GetFeeds returns action list of given user in given context.
  439. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  440. actions := make([]*Action, 0, 20)
  441. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  442. if isProfile {
  443. sess.And("is_private=?", false).And("act_user_id=?", uid)
  444. }
  445. err := sess.Find(&actions)
  446. return actions, err
  447. }