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.

514 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
  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/%s/compare/%s...%s", repoUserName, repoName, oldCommitId, newCommitId)
  244. }
  245. bs, err := json.Marshal(commit)
  246. if err != nil {
  247. return errors.New("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("GetRepositoryByName: " + err.Error())
  254. }
  255. repo.IsBare = false
  256. if err = UpdateRepository(repo, false); err != nil {
  257. return errors.New("UpdateRepository: " + err.Error())
  258. }
  259. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  260. if err != nil {
  261. log.Debug("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("NotifyWatchers: " + err.Error())
  276. }
  277. // New push event hook.
  278. if err := repo.GetOwner(); err != nil {
  279. return errors.New("GetOwner: " + err.Error())
  280. }
  281. ws, err := GetActiveWebhooksByRepoId(repoId)
  282. if err != nil {
  283. return errors.New("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("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: setting.AppUrl + 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. RepoID: repo.Id,
  366. HookID: w.Id,
  367. Type: w.HookTaskType,
  368. Url: w.Url,
  369. BasePayload: payload,
  370. ContentType: w.ContentType,
  371. EventType: HOOK_EVENT_PUSH,
  372. IsSsl: w.IsSsl,
  373. }); err != nil {
  374. return fmt.Errorf("CreateHookTask: %v", err)
  375. }
  376. }
  377. return nil
  378. }
  379. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  380. if err = notifyWatchers(e, &Action{
  381. ActUserID: u.Id,
  382. ActUserName: u.Name,
  383. ActEmail: u.Email,
  384. OpType: CREATE_REPO,
  385. RepoID: repo.Id,
  386. RepoUserName: repo.Owner.Name,
  387. RepoName: repo.Name,
  388. IsPrivate: repo.IsPrivate,
  389. }); err != nil {
  390. return fmt.Errorf("notify watchers '%d/%s'", u.Id, repo.Id)
  391. }
  392. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  393. return err
  394. }
  395. // NewRepoAction adds new action for creating repository.
  396. func NewRepoAction(u *User, repo *Repository) (err error) {
  397. return newRepoAction(x, u, repo)
  398. }
  399. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  400. action := &Action{
  401. ActUserID: actUser.Id,
  402. ActUserName: actUser.Name,
  403. ActEmail: actUser.Email,
  404. OpType: TRANSFER_REPO,
  405. RepoID: repo.Id,
  406. RepoUserName: newOwner.Name,
  407. RepoName: repo.Name,
  408. IsPrivate: repo.IsPrivate,
  409. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  410. }
  411. if err = notifyWatchers(e, action); err != nil {
  412. return fmt.Errorf("notify watchers '%d/%s'", actUser.Id, repo.Id)
  413. }
  414. // Remove watch for organization.
  415. if repo.Owner.IsOrganization() {
  416. if err = watchRepo(e, repo.Owner.Id, repo.Id, false); err != nil {
  417. return fmt.Errorf("watch repository: %v", err)
  418. }
  419. }
  420. log.Trace("action.TransferRepoAction: %s/%s", actUser.Name, repo.Name)
  421. return nil
  422. }
  423. // TransferRepoAction adds new action for transferring repository.
  424. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  425. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  426. }
  427. // GetFeeds returns action list of given user in given context.
  428. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  429. actions := make([]*Action, 0, 20)
  430. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  431. if isProfile {
  432. sess.And("is_private=?", false).And("act_user_id=?", uid)
  433. }
  434. err := sess.Find(&actions)
  435. return actions, err
  436. }