action.go 14 KB

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