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.

500 lines
13 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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
  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) GetRepoLink() string {
  84. return path.Join(setting.AppSubUrl, a.RepoUserName, a.RepoName)
  85. }
  86. func (a Action) GetBranch() string {
  87. return a.RefName
  88. }
  89. func (a Action) GetContent() string {
  90. return a.Content
  91. }
  92. func (a Action) GetCreate() time.Time {
  93. return a.Created
  94. }
  95. func (a Action) GetIssueInfos() []string {
  96. return strings.SplitN(a.Content, "|", 2)
  97. }
  98. func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, commits []*base.PushCommit) error {
  99. for _, c := range commits {
  100. for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  101. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  102. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  103. return !unicode.IsDigit(c)
  104. })
  105. if len(ref) == 0 {
  106. continue
  107. }
  108. // Add repo name if missing
  109. if ref[0] == '#' {
  110. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  111. } else if strings.Contains(ref, "/") == false {
  112. // FIXME: We don't support User#ID syntax yet
  113. // return ErrNotImplemented
  114. continue
  115. }
  116. issue, err := GetIssueByRef(ref)
  117. if err != nil {
  118. return err
  119. }
  120. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  121. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  122. if _, err = CreateComment(userId, issue.RepoId, issue.Id, 0, 0, COMMENT_TYPE_COMMIT, message, nil); err != nil {
  123. return err
  124. }
  125. }
  126. for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) {
  127. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  128. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  129. return !unicode.IsDigit(c)
  130. })
  131. if len(ref) == 0 {
  132. continue
  133. }
  134. // Add repo name if missing
  135. if ref[0] == '#' {
  136. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  137. } else if strings.Contains(ref, "/") == false {
  138. // We don't support User#ID syntax yet
  139. // return ErrNotImplemented
  140. continue
  141. }
  142. issue, err := GetIssueByRef(ref)
  143. if err != nil {
  144. return err
  145. }
  146. if issue.RepoId == repoId {
  147. if issue.IsClosed {
  148. continue
  149. }
  150. issue.IsClosed = true
  151. if err = issue.GetLabels(); err != nil {
  152. return err
  153. }
  154. for _, label := range issue.Labels {
  155. label.NumClosedIssues++
  156. if err = UpdateLabel(label); err != nil {
  157. return err
  158. }
  159. }
  160. if err = UpdateIssue(issue); err != nil {
  161. return err
  162. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  163. return err
  164. }
  165. if err = ChangeMilestoneIssueStats(issue); err != nil {
  166. return err
  167. }
  168. // If commit happened in the referenced repository, it means the issue can be closed.
  169. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, COMMENT_TYPE_CLOSE, "", nil); err != nil {
  170. return err
  171. }
  172. }
  173. }
  174. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  175. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  176. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  177. return !unicode.IsDigit(c)
  178. })
  179. if len(ref) == 0 {
  180. continue
  181. }
  182. // Add repo name if missing
  183. if ref[0] == '#' {
  184. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  185. } else if strings.Contains(ref, "/") == false {
  186. // We don't support User#ID syntax yet
  187. // return ErrNotImplemented
  188. continue
  189. }
  190. issue, err := GetIssueByRef(ref)
  191. if err != nil {
  192. return err
  193. }
  194. if issue.RepoId == repoId {
  195. if !issue.IsClosed {
  196. continue
  197. }
  198. issue.IsClosed = false
  199. if err = issue.GetLabels(); err != nil {
  200. return err
  201. }
  202. for _, label := range issue.Labels {
  203. label.NumClosedIssues--
  204. if err = UpdateLabel(label); err != nil {
  205. return err
  206. }
  207. }
  208. if err = UpdateIssue(issue); err != nil {
  209. return err
  210. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  211. return err
  212. }
  213. if err = ChangeMilestoneIssueStats(issue); err != nil {
  214. return err
  215. }
  216. // If commit happened in the referenced repository, it means the issue can be closed.
  217. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, COMMENT_TYPE_REOPEN, "", nil); err != nil {
  218. return err
  219. }
  220. }
  221. }
  222. }
  223. return nil
  224. }
  225. // CommitRepoAction adds new action for committing repository.
  226. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  227. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitId string, newCommitId string) error {
  228. opType := COMMIT_REPO
  229. // Check it's tag push or branch.
  230. if strings.HasPrefix(refFullName, "refs/tags/") {
  231. opType = PUSH_TAG
  232. commit = &base.PushCommits{}
  233. }
  234. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  235. // if not the first commit, set the compareUrl
  236. if !strings.HasPrefix(oldCommitId, "0000000") {
  237. commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
  238. }
  239. bs, err := json.Marshal(commit)
  240. if err != nil {
  241. return errors.New("action.CommitRepoAction(json): " + err.Error())
  242. }
  243. refName := git.RefEndName(refFullName)
  244. // Change repository bare status and update last updated time.
  245. repo, err := GetRepositoryByName(repoUserId, repoName)
  246. if err != nil {
  247. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  248. }
  249. repo.IsBare = false
  250. if err = UpdateRepository(repo); err != nil {
  251. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  252. }
  253. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  254. if err != nil {
  255. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  256. }
  257. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  258. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  259. RepoName: repoName, RefName: refName,
  260. IsPrivate: repo.IsPrivate}); err != nil {
  261. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  262. }
  263. // New push event hook.
  264. if err := repo.GetOwner(); err != nil {
  265. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  266. }
  267. ws, err := GetActiveWebhooksByRepoId(repoId)
  268. if err != nil {
  269. return errors.New("action.CommitRepoAction(GetActiveWebhooksByRepoId): " + err.Error())
  270. }
  271. // check if repo belongs to org and append additional webhooks
  272. if repo.Owner.IsOrganization() {
  273. // get hooks for org
  274. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId)
  275. if err != nil {
  276. return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error())
  277. }
  278. ws = append(ws, orgws...)
  279. }
  280. if len(ws) == 0 {
  281. return nil
  282. }
  283. pusher_email, pusher_name := "", ""
  284. pusher, err := GetUserByName(userName)
  285. if err == nil {
  286. pusher_email = pusher.Email
  287. pusher_name = pusher.GetFullNameFallback()
  288. }
  289. commits := make([]*PayloadCommit, len(commit.Commits))
  290. for i, cmt := range commit.Commits {
  291. author_username := ""
  292. author, err := GetUserByEmail(cmt.AuthorEmail)
  293. if err == nil {
  294. author_username = author.Name
  295. }
  296. commits[i] = &PayloadCommit{
  297. Id: cmt.Sha1,
  298. Message: cmt.Message,
  299. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  300. Author: &PayloadAuthor{
  301. Name: cmt.AuthorName,
  302. Email: cmt.AuthorEmail,
  303. UserName: author_username,
  304. },
  305. }
  306. }
  307. p := &Payload{
  308. Ref: refFullName,
  309. Commits: commits,
  310. Repo: &PayloadRepo{
  311. Id: repo.Id,
  312. Name: repo.LowerName,
  313. Url: repoLink,
  314. Description: repo.Description,
  315. Website: repo.Website,
  316. Watchers: repo.NumWatches,
  317. Owner: &PayloadAuthor{
  318. Name: repo.Owner.GetFullNameFallback(),
  319. Email: repo.Owner.Email,
  320. UserName: repo.Owner.Name,
  321. },
  322. Private: repo.IsPrivate,
  323. },
  324. Pusher: &PayloadAuthor{
  325. Name: pusher_name,
  326. Email: pusher_email,
  327. UserName: userName,
  328. },
  329. Before: oldCommitId,
  330. After: newCommitId,
  331. CompareUrl: commit.CompareUrl,
  332. }
  333. for _, w := range ws {
  334. w.GetEvent()
  335. if !w.HasPushEvent() {
  336. continue
  337. }
  338. switch w.HookTaskType {
  339. case SLACK:
  340. {
  341. s, err := GetSlackPayload(p, w.Meta)
  342. if err != nil {
  343. return errors.New("action.GetSlackPayload: " + err.Error())
  344. }
  345. CreateHookTask(&HookTask{
  346. Type: w.HookTaskType,
  347. Url: w.Url,
  348. BasePayload: s,
  349. ContentType: w.ContentType,
  350. IsSsl: w.IsSsl,
  351. })
  352. }
  353. default:
  354. {
  355. p.Secret = w.Secret
  356. CreateHookTask(&HookTask{
  357. Type: w.HookTaskType,
  358. Url: w.Url,
  359. BasePayload: p,
  360. ContentType: w.ContentType,
  361. IsSsl: w.IsSsl,
  362. })
  363. }
  364. }
  365. }
  366. return nil
  367. }
  368. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  369. if err = notifyWatchers(e, &Action{
  370. ActUserId: u.Id,
  371. ActUserName: u.Name,
  372. ActEmail: u.Email,
  373. OpType: CREATE_REPO,
  374. RepoId: repo.Id,
  375. RepoUserName: repo.Owner.Name,
  376. RepoName: repo.Name,
  377. IsPrivate: repo.IsPrivate}); err != nil {
  378. return fmt.Errorf("notify watchers '%d/%s'", u.Id, repo.Id)
  379. }
  380. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  381. return err
  382. }
  383. // NewRepoAction adds new action for creating repository.
  384. func NewRepoAction(u *User, repo *Repository) (err error) {
  385. return newRepoAction(x, u, repo)
  386. }
  387. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  388. action := &Action{
  389. ActUserId: actUser.Id,
  390. ActUserName: actUser.Name,
  391. ActEmail: actUser.Email,
  392. OpType: TRANSFER_REPO,
  393. RepoId: repo.Id,
  394. RepoUserName: newOwner.Name,
  395. RepoName: repo.Name,
  396. IsPrivate: repo.IsPrivate,
  397. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  398. }
  399. if err = notifyWatchers(e, action); err != nil {
  400. return fmt.Errorf("notify watchers '%d/%s'", actUser.Id, repo.Id)
  401. }
  402. // Remove watch for organization.
  403. if repo.Owner.IsOrganization() {
  404. if err = watchRepo(e, repo.Owner.Id, repo.Id, false); err != nil {
  405. return fmt.Errorf("watch repository: %v", err)
  406. }
  407. }
  408. log.Trace("action.TransferRepoAction: %s/%s", actUser.Name, repo.Name)
  409. return nil
  410. }
  411. // TransferRepoAction adds new action for transferring repository.
  412. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  413. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  414. }
  415. // GetFeeds returns action list of given user in given context.
  416. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  417. actions := make([]*Action, 0, 20)
  418. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  419. if isProfile {
  420. sess.And("is_private=?", false).And("act_user_id=?", uid)
  421. }
  422. err := sess.Find(&actions)
  423. return actions, err
  424. }