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.

action.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. // updateIssuesCommit checks if issues are manipulated by commit message.
  155. func updateIssuesCommit(u *User, repo *Repository, repoUserName, repoName string, commits []*base.PushCommit) error {
  156. for _, c := range commits {
  157. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  158. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  159. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  160. return !unicode.IsDigit(c)
  161. })
  162. if len(ref) == 0 {
  163. continue
  164. }
  165. // Add repo name if missing
  166. if ref[0] == '#' {
  167. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  168. } else if strings.Contains(ref, "/") == false {
  169. // FIXME: We don't support User#ID syntax yet
  170. // return ErrNotImplemented
  171. continue
  172. }
  173. issue, err := GetIssueByRef(ref)
  174. if err != nil {
  175. return err
  176. }
  177. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  178. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  179. if _, err = CreateComment(u, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, message, nil); err != nil {
  180. return err
  181. }
  182. }
  183. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  184. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  185. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  186. return !unicode.IsDigit(c)
  187. })
  188. if len(ref) == 0 {
  189. continue
  190. }
  191. // Add repo name if missing
  192. if ref[0] == '#' {
  193. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  194. } else if strings.Contains(ref, "/") == false {
  195. // We don't support User#ID syntax yet
  196. // return ErrNotImplemented
  197. continue
  198. }
  199. issue, err := GetIssueByRef(ref)
  200. if err != nil {
  201. return err
  202. }
  203. if issue.RepoID == repo.ID {
  204. if issue.IsClosed {
  205. continue
  206. }
  207. issue.IsClosed = true
  208. if err = issue.GetLabels(); err != nil {
  209. return err
  210. }
  211. for _, label := range issue.Labels {
  212. label.NumClosedIssues++
  213. if err = UpdateLabel(label); err != nil {
  214. return err
  215. }
  216. }
  217. if err = UpdateIssue(issue); err != nil {
  218. return err
  219. } else if err = UpdateIssueUsersByStatus(issue.ID, issue.IsClosed); err != nil {
  220. return err
  221. }
  222. if err = ChangeMilestoneIssueStats(issue); err != nil {
  223. return err
  224. }
  225. // If commit happened in the referenced repository, it means the issue can be closed.
  226. if _, err = CreateComment(u, repo, issue, 0, 0, COMMENT_TYPE_CLOSE, "", nil); err != nil {
  227. return err
  228. }
  229. }
  230. }
  231. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  232. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  233. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  234. return !unicode.IsDigit(c)
  235. })
  236. if len(ref) == 0 {
  237. continue
  238. }
  239. // Add repo name if missing
  240. if ref[0] == '#' {
  241. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  242. } else if strings.Contains(ref, "/") == false {
  243. // We don't support User#ID syntax yet
  244. // return ErrNotImplemented
  245. continue
  246. }
  247. issue, err := GetIssueByRef(ref)
  248. if err != nil {
  249. return err
  250. }
  251. if issue.RepoID == repo.ID {
  252. if !issue.IsClosed {
  253. continue
  254. }
  255. issue.IsClosed = false
  256. if err = issue.GetLabels(); err != nil {
  257. return err
  258. }
  259. for _, label := range issue.Labels {
  260. label.NumClosedIssues--
  261. if err = UpdateLabel(label); err != nil {
  262. return err
  263. }
  264. }
  265. if err = UpdateIssue(issue); err != nil {
  266. return err
  267. } else if err = UpdateIssueUsersByStatus(issue.ID, issue.IsClosed); err != nil {
  268. return err
  269. }
  270. if err = ChangeMilestoneIssueStats(issue); err != nil {
  271. return err
  272. }
  273. // If commit happened in the referenced repository, it means the issue can be closed.
  274. if _, err = CreateComment(u, repo, issue, 0, 0, COMMENT_TYPE_REOPEN, "", nil); err != nil {
  275. return err
  276. }
  277. }
  278. }
  279. }
  280. return nil
  281. }
  282. // CommitRepoAction adds new action for committing repository.
  283. func CommitRepoAction(
  284. userID, repoUserID int64,
  285. userName, actEmail string,
  286. repoID int64,
  287. repoUserName, repoName string,
  288. refFullName string,
  289. commit *base.PushCommits,
  290. oldCommitID string, newCommitID string) error {
  291. u, err := GetUserByID(userID)
  292. if err != nil {
  293. return fmt.Errorf("GetUserByID: %v", err)
  294. }
  295. repo, err := GetRepositoryByName(repoUserID, repoName)
  296. if err != nil {
  297. return fmt.Errorf("GetRepositoryByName: %v", err)
  298. } else if err = repo.GetOwner(); err != nil {
  299. return fmt.Errorf("GetOwner: %v", err)
  300. }
  301. isNewBranch := false
  302. opType := COMMIT_REPO
  303. // Check it's tag push or branch.
  304. if strings.HasPrefix(refFullName, "refs/tags/") {
  305. opType = PUSH_TAG
  306. commit = &base.PushCommits{}
  307. } else {
  308. // if not the first commit, set the compareUrl
  309. if !strings.HasPrefix(oldCommitID, "0000000") {
  310. commit.CompareUrl = fmt.Sprintf("%s/%s/compare/%s...%s", repoUserName, repoName, oldCommitID, newCommitID)
  311. } else {
  312. isNewBranch = true
  313. }
  314. // Change repository bare status and update last updated time.
  315. repo.IsBare = false
  316. if err = UpdateRepository(repo, false); err != nil {
  317. return fmt.Errorf("UpdateRepository: %v", err)
  318. }
  319. if err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits); err != nil {
  320. log.Debug("updateIssuesCommit: %v", err)
  321. }
  322. }
  323. bs, err := json.Marshal(commit)
  324. if err != nil {
  325. return fmt.Errorf("Marshal: %v", err)
  326. }
  327. refName := git.RefEndName(refFullName)
  328. if err = NotifyWatchers(&Action{
  329. ActUserID: u.Id,
  330. ActUserName: userName,
  331. ActEmail: actEmail,
  332. OpType: opType,
  333. Content: string(bs),
  334. RepoID: repo.ID,
  335. RepoUserName: repoUserName,
  336. RepoName: repoName,
  337. RefName: refName,
  338. IsPrivate: repo.IsPrivate,
  339. }); err != nil {
  340. return fmt.Errorf("NotifyWatchers: %v", err)
  341. }
  342. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  343. payloadRepo := &api.PayloadRepo{
  344. ID: repo.ID,
  345. Name: repo.LowerName,
  346. URL: repoLink,
  347. Description: repo.Description,
  348. Website: repo.Website,
  349. Watchers: repo.NumWatches,
  350. Owner: &api.PayloadAuthor{
  351. Name: repo.Owner.DisplayName(),
  352. Email: repo.Owner.Email,
  353. UserName: repo.Owner.Name,
  354. },
  355. Private: repo.IsPrivate,
  356. }
  357. pusher_email, pusher_name := "", ""
  358. pusher, err := GetUserByName(userName)
  359. if err == nil {
  360. pusher_email = pusher.Email
  361. pusher_name = pusher.DisplayName()
  362. }
  363. payloadSender := &api.PayloadUser{
  364. UserName: pusher.Name,
  365. ID: pusher.Id,
  366. AvatarUrl: setting.AppUrl + pusher.RelAvatarLink(),
  367. }
  368. switch opType {
  369. case COMMIT_REPO: // Push
  370. commits := make([]*api.PayloadCommit, len(commit.Commits))
  371. for i, cmt := range commit.Commits {
  372. author_username := ""
  373. author, err := GetUserByEmail(cmt.AuthorEmail)
  374. if err == nil {
  375. author_username = author.Name
  376. }
  377. commits[i] = &api.PayloadCommit{
  378. ID: cmt.Sha1,
  379. Message: cmt.Message,
  380. URL: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  381. Author: &api.PayloadAuthor{
  382. Name: cmt.AuthorName,
  383. Email: cmt.AuthorEmail,
  384. UserName: author_username,
  385. },
  386. }
  387. }
  388. p := &api.PushPayload{
  389. Ref: refFullName,
  390. Before: oldCommitID,
  391. After: newCommitID,
  392. CompareUrl: setting.AppUrl + commit.CompareUrl,
  393. Commits: commits,
  394. Repo: payloadRepo,
  395. Pusher: &api.PayloadAuthor{
  396. Name: pusher_name,
  397. Email: pusher_email,
  398. UserName: userName,
  399. },
  400. Sender: payloadSender,
  401. }
  402. if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, p); err != nil {
  403. return fmt.Errorf("PrepareWebhooks: %v", err)
  404. }
  405. if isNewBranch {
  406. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  407. Ref: refName,
  408. RefType: "branch",
  409. Repo: payloadRepo,
  410. Sender: payloadSender,
  411. })
  412. }
  413. case PUSH_TAG: // Create
  414. return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
  415. Ref: refName,
  416. RefType: "tag",
  417. Repo: payloadRepo,
  418. Sender: payloadSender,
  419. })
  420. }
  421. return nil
  422. }
  423. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  424. if err = notifyWatchers(e, &Action{
  425. ActUserID: actUser.Id,
  426. ActUserName: actUser.Name,
  427. ActEmail: actUser.Email,
  428. OpType: TRANSFER_REPO,
  429. RepoID: repo.ID,
  430. RepoUserName: newOwner.Name,
  431. RepoName: repo.Name,
  432. IsPrivate: repo.IsPrivate,
  433. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  434. }); err != nil {
  435. return fmt.Errorf("notify watchers '%d/%s': %v", actUser.Id, repo.ID, err)
  436. }
  437. // Remove watch for organization.
  438. if repo.Owner.IsOrganization() {
  439. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  440. return fmt.Errorf("watch repository: %v", err)
  441. }
  442. }
  443. log.Trace("action.transferRepoAction: %s/%s", actUser.Name, repo.Name)
  444. return nil
  445. }
  446. // TransferRepoAction adds new action for transferring repository.
  447. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) error {
  448. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  449. }
  450. func mergePullRequestAction(e Engine, actUser *User, repo *Repository, pull *Issue) error {
  451. return notifyWatchers(e, &Action{
  452. ActUserID: actUser.Id,
  453. ActUserName: actUser.Name,
  454. ActEmail: actUser.Email,
  455. OpType: MERGE_PULL_REQUEST,
  456. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  457. RepoID: repo.ID,
  458. RepoUserName: repo.Owner.Name,
  459. RepoName: repo.Name,
  460. IsPrivate: repo.IsPrivate,
  461. })
  462. }
  463. // MergePullRequestAction adds new action for merging pull request.
  464. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  465. return mergePullRequestAction(x, actUser, repo, pull)
  466. }
  467. // GetFeeds returns action list of given user in given context.
  468. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  469. actions := make([]*Action, 0, 20)
  470. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  471. if isProfile {
  472. sess.And("is_private=?", false).And("act_user_id=?", uid)
  473. }
  474. err := sess.Find(&actions)
  475. return actions, err
  476. }