action.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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(u *User, repo *Repository, 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(u, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, 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 == repo.ID {
  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 = UpdateIssueUsersByStatus(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(u, repo, issue, 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 == repo.ID {
  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 = UpdateIssueUsersByStatus(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(u, repo, issue, 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 fmt.Errorf("Marshal: %v", err)
  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 fmt.Errorf("GetRepositoryByName: %v", err)
  254. }
  255. repo.IsBare = false
  256. if err = UpdateRepository(repo, false); err != nil {
  257. return fmt.Errorf("UpdateRepository: %v", err)
  258. }
  259. u, err := GetUserByID(userID)
  260. if err != nil {
  261. return fmt.Errorf("GetUserByID: %v", err)
  262. }
  263. err = updateIssuesCommit(u, repo, repoUserName, repoName, commit.Commits)
  264. if err != nil {
  265. log.Debug("updateIssuesCommit: ", err)
  266. }
  267. if err = NotifyWatchers(&Action{
  268. ActUserID: u.Id,
  269. ActUserName: userName,
  270. ActEmail: actEmail,
  271. OpType: opType,
  272. Content: string(bs),
  273. RepoID: repo.ID,
  274. RepoUserName: repoUserName,
  275. RepoName: repoName,
  276. RefName: refName,
  277. IsPrivate: repo.IsPrivate,
  278. }); err != nil {
  279. return errors.New("NotifyWatchers: " + err.Error())
  280. }
  281. // New push event hook.
  282. if err := repo.GetOwner(); err != nil {
  283. return errors.New("GetOwner: " + err.Error())
  284. }
  285. ws, err := GetActiveWebhooksByRepoId(repo.ID)
  286. if err != nil {
  287. return errors.New("GetActiveWebhooksByRepoId: " + err.Error())
  288. }
  289. // check if repo belongs to org and append additional webhooks
  290. if repo.Owner.IsOrganization() {
  291. // get hooks for org
  292. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerID)
  293. if err != nil {
  294. return errors.New("GetActiveWebhooksByOrgId: " + err.Error())
  295. }
  296. ws = append(ws, orgws...)
  297. }
  298. if len(ws) == 0 {
  299. return nil
  300. }
  301. pusher_email, pusher_name := "", ""
  302. pusher, err := GetUserByName(userName)
  303. if err == nil {
  304. pusher_email = pusher.Email
  305. pusher_name = pusher.GetFullNameFallback()
  306. }
  307. commits := make([]*PayloadCommit, len(commit.Commits))
  308. for i, cmt := range commit.Commits {
  309. author_username := ""
  310. author, err := GetUserByEmail(cmt.AuthorEmail)
  311. if err == nil {
  312. author_username = author.Name
  313. }
  314. commits[i] = &PayloadCommit{
  315. Id: cmt.Sha1,
  316. Message: cmt.Message,
  317. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  318. Author: &PayloadAuthor{
  319. Name: cmt.AuthorName,
  320. Email: cmt.AuthorEmail,
  321. UserName: author_username,
  322. },
  323. }
  324. }
  325. p := &Payload{
  326. Ref: refFullName,
  327. Commits: commits,
  328. Repo: &PayloadRepo{
  329. Id: repo.ID,
  330. Name: repo.LowerName,
  331. Url: repoLink,
  332. Description: repo.Description,
  333. Website: repo.Website,
  334. Watchers: repo.NumWatches,
  335. Owner: &PayloadAuthor{
  336. Name: repo.Owner.GetFullNameFallback(),
  337. Email: repo.Owner.Email,
  338. UserName: repo.Owner.Name,
  339. },
  340. Private: repo.IsPrivate,
  341. },
  342. Pusher: &PayloadAuthor{
  343. Name: pusher_name,
  344. Email: pusher_email,
  345. UserName: userName,
  346. },
  347. Before: oldCommitID,
  348. After: newCommitID,
  349. CompareUrl: setting.AppUrl + commit.CompareUrl,
  350. }
  351. for _, w := range ws {
  352. w.GetEvent()
  353. if !w.HasPushEvent() {
  354. continue
  355. }
  356. var payload BasePayload
  357. switch w.HookTaskType {
  358. case SLACK:
  359. s, err := GetSlackPayload(p, w.Meta)
  360. if err != nil {
  361. return errors.New("action.GetSlackPayload: " + err.Error())
  362. }
  363. payload = s
  364. default:
  365. payload = p
  366. p.Secret = w.Secret
  367. }
  368. if err = CreateHookTask(&HookTask{
  369. RepoID: repo.ID,
  370. HookID: w.Id,
  371. Type: w.HookTaskType,
  372. Url: w.Url,
  373. BasePayload: payload,
  374. ContentType: w.ContentType,
  375. EventType: HOOK_EVENT_PUSH,
  376. IsSsl: w.IsSsl,
  377. }); err != nil {
  378. return fmt.Errorf("CreateHookTask: %v", err)
  379. }
  380. }
  381. return nil
  382. }
  383. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  384. if err = notifyWatchers(e, &Action{
  385. ActUserID: u.Id,
  386. ActUserName: u.Name,
  387. ActEmail: u.Email,
  388. OpType: CREATE_REPO,
  389. RepoID: repo.ID,
  390. RepoUserName: repo.Owner.Name,
  391. RepoName: repo.Name,
  392. IsPrivate: repo.IsPrivate,
  393. }); err != nil {
  394. return fmt.Errorf("notify watchers '%d/%s'", u.Id, repo.ID)
  395. }
  396. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  397. return err
  398. }
  399. // NewRepoAction adds new action for creating repository.
  400. func NewRepoAction(u *User, repo *Repository) (err error) {
  401. return newRepoAction(x, u, repo)
  402. }
  403. func transferRepoAction(e Engine, actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  404. action := &Action{
  405. ActUserID: actUser.Id,
  406. ActUserName: actUser.Name,
  407. ActEmail: actUser.Email,
  408. OpType: TRANSFER_REPO,
  409. RepoID: repo.ID,
  410. RepoUserName: newOwner.Name,
  411. RepoName: repo.Name,
  412. IsPrivate: repo.IsPrivate,
  413. Content: path.Join(oldOwner.LowerName, repo.LowerName),
  414. }
  415. if err = notifyWatchers(e, action); err != nil {
  416. return fmt.Errorf("notify watchers '%d/%s'", actUser.Id, repo.ID)
  417. }
  418. // Remove watch for organization.
  419. if repo.Owner.IsOrganization() {
  420. if err = watchRepo(e, repo.Owner.Id, repo.ID, false); err != nil {
  421. return fmt.Errorf("watch repository: %v", err)
  422. }
  423. }
  424. log.Trace("action.TransferRepoAction: %s/%s", actUser.Name, repo.Name)
  425. return nil
  426. }
  427. // TransferRepoAction adds new action for transferring repository.
  428. func TransferRepoAction(actUser, oldOwner, newOwner *User, repo *Repository) (err error) {
  429. return transferRepoAction(x, actUser, oldOwner, newOwner, repo)
  430. }
  431. // GetFeeds returns action list of given user in given context.
  432. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  433. actions := make([]*Action, 0, 20)
  434. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  435. if isProfile {
  436. sess.And("is_private=?", false).And("act_user_id=?", uid)
  437. }
  438. err := sess.Find(&actions)
  439. return actions, err
  440. }