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

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