action.go 13 KB

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