action.go 12 KB

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