action.go 13 KB

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