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 14KB

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