action.go 14 KB

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