You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

action.go 13 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 = UpdateIssue(issue); err != nil {
  152. return err
  153. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  154. return err
  155. }
  156. if err = ChangeMilestoneIssueStats(issue); err != nil {
  157. return err
  158. }
  159. // If commit happened in the referenced repository, it means the issue can be closed.
  160. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, COMMENT_TYPE_CLOSE, "", nil); err != nil {
  161. return err
  162. }
  163. }
  164. }
  165. for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) {
  166. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  167. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  168. return !unicode.IsDigit(c)
  169. })
  170. if len(ref) == 0 {
  171. continue
  172. }
  173. // Add repo name if missing
  174. if ref[0] == '#' {
  175. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  176. } else if strings.Contains(ref, "/") == false {
  177. // We don't support User#ID syntax yet
  178. // return ErrNotImplemented
  179. continue
  180. }
  181. issue, err := GetIssueByRef(ref)
  182. if err != nil {
  183. return err
  184. }
  185. if issue.RepoId == repoId {
  186. if !issue.IsClosed {
  187. continue
  188. }
  189. issue.IsClosed = false
  190. if err = UpdateIssue(issue); err != nil {
  191. return err
  192. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  193. return err
  194. }
  195. if err = ChangeMilestoneIssueStats(issue); err != nil {
  196. return err
  197. }
  198. // If commit happened in the referenced repository, it means the issue can be closed.
  199. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, COMMENT_TYPE_REOPEN, "", nil); err != nil {
  200. return err
  201. }
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. // CommitRepoAction adds new action for committing repository.
  208. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  209. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitId string, newCommitId string) error {
  210. opType := COMMIT_REPO
  211. // Check it's tag push or branch.
  212. if strings.HasPrefix(refFullName, "refs/tags/") {
  213. opType = PUSH_TAG
  214. commit = &base.PushCommits{}
  215. }
  216. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  217. // if not the first commit, set the compareUrl
  218. if !strings.HasPrefix(oldCommitId, "0000000") {
  219. commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
  220. }
  221. bs, err := json.Marshal(commit)
  222. if err != nil {
  223. return errors.New("action.CommitRepoAction(json): " + err.Error())
  224. }
  225. refName := git.RefEndName(refFullName)
  226. // Change repository bare status and update last updated time.
  227. repo, err := GetRepositoryByName(repoUserId, repoName)
  228. if err != nil {
  229. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  230. }
  231. repo.IsBare = false
  232. if err = UpdateRepository(repo); err != nil {
  233. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  234. }
  235. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  236. if err != nil {
  237. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  238. }
  239. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  240. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  241. RepoName: repoName, RefName: refName,
  242. IsPrivate: repo.IsPrivate}); err != nil {
  243. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  244. }
  245. // New push event hook.
  246. if err := repo.GetOwner(); err != nil {
  247. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  248. }
  249. ws, err := GetActiveWebhooksByRepoId(repoId)
  250. if err != nil {
  251. return errors.New("action.CommitRepoAction(GetActiveWebhooksByRepoId): " + err.Error())
  252. }
  253. // check if repo belongs to org and append additional webhooks
  254. if repo.Owner.IsOrganization() {
  255. // get hooks for org
  256. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId)
  257. if err != nil {
  258. return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error())
  259. }
  260. ws = append(ws, orgws...)
  261. }
  262. if len(ws) == 0 {
  263. return nil
  264. }
  265. pusher_email, pusher_name := "", ""
  266. pusher, err := GetUserByName(userName)
  267. if err == nil {
  268. pusher_email = pusher.Email
  269. pusher_name = pusher.GetFullNameFallback()
  270. }
  271. commits := make([]*PayloadCommit, len(commit.Commits))
  272. for i, cmt := range commit.Commits {
  273. author_username := ""
  274. author, err := GetUserByEmail(cmt.AuthorEmail)
  275. if err == nil {
  276. author_username = author.Name
  277. }
  278. commits[i] = &PayloadCommit{
  279. Id: cmt.Sha1,
  280. Message: cmt.Message,
  281. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  282. Author: &PayloadAuthor{
  283. Name: cmt.AuthorName,
  284. Email: cmt.AuthorEmail,
  285. UserName: author_username,
  286. },
  287. }
  288. }
  289. p := &Payload{
  290. Ref: refFullName,
  291. Commits: commits,
  292. Repo: &PayloadRepo{
  293. Id: repo.Id,
  294. Name: repo.LowerName,
  295. Url: repoLink,
  296. Description: repo.Description,
  297. Website: repo.Website,
  298. Watchers: repo.NumWatches,
  299. Owner: &PayloadAuthor{
  300. Name: repo.Owner.GetFullNameFallback(),
  301. Email: repo.Owner.Email,
  302. UserName: repo.Owner.Name,
  303. },
  304. Private: repo.IsPrivate,
  305. },
  306. Pusher: &PayloadAuthor{
  307. Name: pusher_name,
  308. Email: pusher_email,
  309. UserName: userName,
  310. },
  311. Before: oldCommitId,
  312. After: newCommitId,
  313. CompareUrl: commit.CompareUrl,
  314. }
  315. for _, w := range ws {
  316. w.GetEvent()
  317. if !w.HasPushEvent() {
  318. continue
  319. }
  320. switch w.HookTaskType {
  321. case SLACK:
  322. {
  323. s, err := GetSlackPayload(p, w.Meta)
  324. if err != nil {
  325. return errors.New("action.GetSlackPayload: " + err.Error())
  326. }
  327. CreateHookTask(&HookTask{
  328. Type: w.HookTaskType,
  329. Url: w.Url,
  330. BasePayload: s,
  331. ContentType: w.ContentType,
  332. IsSsl: w.IsSsl,
  333. })
  334. }
  335. default:
  336. {
  337. p.Secret = w.Secret
  338. CreateHookTask(&HookTask{
  339. Type: w.HookTaskType,
  340. Url: w.Url,
  341. BasePayload: p,
  342. ContentType: w.ContentType,
  343. IsSsl: w.IsSsl,
  344. })
  345. }
  346. }
  347. }
  348. return nil
  349. }
  350. // NewRepoAction adds new action for creating repository.
  351. func NewRepoAction(u *User, repo *Repository) (err error) {
  352. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  353. OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  354. IsPrivate: repo.IsPrivate}); err != nil {
  355. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  356. return err
  357. }
  358. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  359. return err
  360. }
  361. // TransferRepoAction adds new action for transferring repository.
  362. func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
  363. action := &Action{
  364. ActUserId: u.Id,
  365. ActUserName: u.Name,
  366. ActEmail: u.Email,
  367. OpType: TRANSFER_REPO,
  368. RepoId: repo.Id,
  369. RepoUserName: newUser.Name,
  370. RepoName: repo.Name,
  371. IsPrivate: repo.IsPrivate,
  372. Content: path.Join(repo.Owner.LowerName, repo.LowerName),
  373. }
  374. if err = NotifyWatchers(action); err != nil {
  375. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  376. return err
  377. }
  378. // Remove watch for organization.
  379. if repo.Owner.IsOrganization() {
  380. if err = WatchRepo(repo.Owner.Id, repo.Id, false); err != nil {
  381. log.Error(4, "WatchRepo", err)
  382. }
  383. }
  384. log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name)
  385. return err
  386. }
  387. // GetFeeds returns action list of given user in given context.
  388. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  389. actions := make([]*Action, 0, 20)
  390. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  391. if isProfile {
  392. sess.And("is_private=?", false).And("act_user_id=?", uid)
  393. }
  394. err := sess.Find(&actions)
  395. return actions, err
  396. }