action.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. IssueCloseKeywordsPat *regexp.Regexp
  39. IssueReferenceKeywordsPat *regexp.Regexp
  40. )
  41. func init() {
  42. IssueCloseKeywordsPat = regexp.MustCompile(fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(IssueCloseKeywords, "|")))
  43. IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
  44. }
  45. // Action represents user operation type and other information to repository.,
  46. // it implemented interface base.Actioner so that can be used in template render.
  47. type Action struct {
  48. Id int64
  49. UserId int64 // Receiver user id.
  50. OpType ActionType
  51. ActUserId int64 // Action user id.
  52. ActUserName string // Action user name.
  53. ActEmail string
  54. ActAvatar string `xorm:"-"`
  55. RepoId int64
  56. RepoUserName string
  57. RepoName string
  58. RefName string
  59. IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
  60. Content string `xorm:"TEXT"`
  61. Created time.Time `xorm:"created"`
  62. }
  63. func (a Action) GetOpType() int {
  64. return int(a.OpType)
  65. }
  66. func (a Action) GetActUserName() string {
  67. return a.ActUserName
  68. }
  69. func (a Action) GetActEmail() string {
  70. return a.ActEmail
  71. }
  72. func (a Action) GetRepoUserName() string {
  73. return a.RepoUserName
  74. }
  75. func (a Action) GetRepoName() string {
  76. return a.RepoName
  77. }
  78. func (a Action) GetRepoLink() string {
  79. return path.Join(a.RepoUserName, a.RepoName)
  80. }
  81. func (a Action) GetBranch() string {
  82. return a.RefName
  83. }
  84. func (a Action) GetContent() string {
  85. return a.Content
  86. }
  87. func (a Action) GetCreate() time.Time {
  88. return a.Created
  89. }
  90. func (a Action) GetIssueInfos() []string {
  91. return strings.SplitN(a.Content, "|", 2)
  92. }
  93. func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, commits []*base.PushCommit) error {
  94. for _, c := range commits {
  95. references := IssueReferenceKeywordsPat.FindAllString(c.Message, -1)
  96. // FIXME: should not be a reference when it comes with action.
  97. // e.g. fixes #1 will not have duplicated reference message.
  98. for _, ref := range references {
  99. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  100. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  101. return !unicode.IsDigit(c)
  102. })
  103. if len(ref) == 0 {
  104. continue
  105. }
  106. // Add repo name if missing
  107. if ref[0] == '#' {
  108. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  109. } else if strings.Contains(ref, "/") == false {
  110. // FIXME: We don't support User#ID syntax yet
  111. // return ErrNotImplemented
  112. continue
  113. }
  114. issue, err := GetIssueByRef(ref)
  115. if err != nil {
  116. return err
  117. }
  118. url := fmt.Sprintf("%s/%s/%s/commit/%s", setting.AppSubUrl, repoUserName, repoName, c.Sha1)
  119. message := fmt.Sprintf(`<a href="%s">%s</a>`, url, c.Message)
  120. if _, err = CreateComment(userId, issue.RepoId, issue.Id, 0, 0, COMMIT, message, nil); err != nil {
  121. return err
  122. }
  123. }
  124. closes := IssueCloseKeywordsPat.FindAllString(c.Message, -1)
  125. for _, ref := range closes {
  126. ref := ref[strings.IndexByte(ref, byte(' '))+1:]
  127. ref = strings.TrimRightFunc(ref, func(c rune) bool {
  128. return !unicode.IsDigit(c)
  129. })
  130. if len(ref) == 0 {
  131. continue
  132. }
  133. // Add repo name if missing
  134. if ref[0] == '#' {
  135. ref = fmt.Sprintf("%s/%s%s", repoUserName, repoName, ref)
  136. } else if strings.Contains(ref, "/") == false {
  137. // We don't support User#ID syntax yet
  138. // return ErrNotImplemented
  139. continue
  140. }
  141. issue, err := GetIssueByRef(ref)
  142. if err != nil {
  143. return err
  144. }
  145. if issue.RepoId == repoId {
  146. if issue.IsClosed {
  147. continue
  148. }
  149. issue.IsClosed = true
  150. if err = UpdateIssue(issue); err != nil {
  151. return err
  152. } else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  153. return err
  154. }
  155. if err = ChangeMilestoneIssueStats(issue); err != nil {
  156. return err
  157. }
  158. // If commit happened in the referenced repository, it means the issue can be closed.
  159. if _, err = CreateComment(userId, repoId, issue.Id, 0, 0, CLOSE, "", nil); err != nil {
  160. return err
  161. }
  162. }
  163. }
  164. }
  165. return nil
  166. }
  167. // CommitRepoAction adds new action for committing repository.
  168. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
  169. repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitId string, newCommitId string) error {
  170. opType := COMMIT_REPO
  171. // Check it's tag push or branch.
  172. if strings.HasPrefix(refFullName, "refs/tags/") {
  173. opType = PUSH_TAG
  174. commit = &base.PushCommits{}
  175. }
  176. repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
  177. // if not the first commit, set the compareUrl
  178. if !strings.HasPrefix(oldCommitId, "0000000") {
  179. commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
  180. }
  181. bs, err := json.Marshal(commit)
  182. if err != nil {
  183. return errors.New("action.CommitRepoAction(json): " + err.Error())
  184. }
  185. refName := git.RefEndName(refFullName)
  186. // Change repository bare status and update last updated time.
  187. repo, err := GetRepositoryByName(repoUserId, repoName)
  188. if err != nil {
  189. return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
  190. }
  191. repo.IsBare = false
  192. if err = UpdateRepository(repo); err != nil {
  193. return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
  194. }
  195. err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits)
  196. if err != nil {
  197. log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err)
  198. }
  199. if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
  200. OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
  201. RepoName: repoName, RefName: refName,
  202. IsPrivate: repo.IsPrivate}); err != nil {
  203. return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
  204. }
  205. // New push event hook.
  206. if err := repo.GetOwner(); err != nil {
  207. return errors.New("action.CommitRepoAction(GetOwner): " + err.Error())
  208. }
  209. ws, err := GetActiveWebhooksByRepoId(repoId)
  210. if err != nil {
  211. return errors.New("action.CommitRepoAction(GetActiveWebhooksByRepoId): " + err.Error())
  212. }
  213. // check if repo belongs to org and append additional webhooks
  214. if repo.Owner.IsOrganization() {
  215. // get hooks for org
  216. orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId)
  217. if err != nil {
  218. return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error())
  219. }
  220. ws = append(ws, orgws...)
  221. }
  222. if len(ws) == 0 {
  223. return nil
  224. }
  225. pusher_email, pusher_name := "", ""
  226. pusher, err := GetUserByName(userName)
  227. if err == nil {
  228. pusher_email = pusher.Email
  229. pusher_name = pusher.GetFullNameFallback()
  230. }
  231. commits := make([]*PayloadCommit, len(commit.Commits))
  232. for i, cmt := range commit.Commits {
  233. author_username := ""
  234. author, err := GetUserByEmail(cmt.AuthorEmail)
  235. if err == nil {
  236. author_username = author.Name
  237. }
  238. commits[i] = &PayloadCommit{
  239. Id: cmt.Sha1,
  240. Message: cmt.Message,
  241. Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1),
  242. Author: &PayloadAuthor{
  243. Name: cmt.AuthorName,
  244. Email: cmt.AuthorEmail,
  245. UserName: author_username,
  246. },
  247. }
  248. }
  249. p := &Payload{
  250. Ref: refFullName,
  251. Commits: commits,
  252. Repo: &PayloadRepo{
  253. Id: repo.Id,
  254. Name: repo.LowerName,
  255. Url: repoLink,
  256. Description: repo.Description,
  257. Website: repo.Website,
  258. Watchers: repo.NumWatches,
  259. Owner: &PayloadAuthor{
  260. Name: repo.Owner.GetFullNameFallback(),
  261. Email: repo.Owner.Email,
  262. UserName: repo.Owner.Name,
  263. },
  264. Private: repo.IsPrivate,
  265. },
  266. Pusher: &PayloadAuthor{
  267. Name: pusher_name,
  268. Email: pusher_email,
  269. UserName: userName,
  270. },
  271. Before: oldCommitId,
  272. After: newCommitId,
  273. CompareUrl: commit.CompareUrl,
  274. }
  275. for _, w := range ws {
  276. w.GetEvent()
  277. if !w.HasPushEvent() {
  278. continue
  279. }
  280. switch w.HookTaskType {
  281. case SLACK:
  282. {
  283. s, err := GetSlackPayload(p, w.Meta)
  284. if err != nil {
  285. return errors.New("action.GetSlackPayload: " + err.Error())
  286. }
  287. CreateHookTask(&HookTask{
  288. Type: w.HookTaskType,
  289. Url: w.Url,
  290. BasePayload: s,
  291. ContentType: w.ContentType,
  292. IsSsl: w.IsSsl,
  293. })
  294. }
  295. default:
  296. {
  297. p.Secret = w.Secret
  298. CreateHookTask(&HookTask{
  299. Type: w.HookTaskType,
  300. Url: w.Url,
  301. BasePayload: p,
  302. ContentType: w.ContentType,
  303. IsSsl: w.IsSsl,
  304. })
  305. }
  306. }
  307. }
  308. return nil
  309. }
  310. // NewRepoAction adds new action for creating repository.
  311. func NewRepoAction(u *User, repo *Repository) (err error) {
  312. if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email,
  313. OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name,
  314. IsPrivate: repo.IsPrivate}); err != nil {
  315. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  316. return err
  317. }
  318. log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name)
  319. return err
  320. }
  321. // TransferRepoAction adds new action for transferring repository.
  322. func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
  323. action := &Action{
  324. ActUserId: u.Id,
  325. ActUserName: u.Name,
  326. ActEmail: u.Email,
  327. OpType: TRANSFER_REPO,
  328. RepoId: repo.Id,
  329. RepoUserName: newUser.Name,
  330. RepoName: repo.Name,
  331. IsPrivate: repo.IsPrivate,
  332. Content: path.Join(repo.Owner.LowerName, repo.LowerName),
  333. }
  334. if err = NotifyWatchers(action); err != nil {
  335. log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name)
  336. return err
  337. }
  338. // Remove watch for organization.
  339. if repo.Owner.IsOrganization() {
  340. if err = WatchRepo(repo.Owner.Id, repo.Id, false); err != nil {
  341. log.Error(4, "WatchRepo", err)
  342. }
  343. }
  344. log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name)
  345. return err
  346. }
  347. // GetFeeds returns action list of given user in given context.
  348. func GetFeeds(uid, offset int64, isProfile bool) ([]*Action, error) {
  349. actions := make([]*Action, 0, 20)
  350. sess := x.Limit(20, int(offset)).Desc("id").Where("user_id=?", uid)
  351. if isProfile {
  352. sess.And("is_private=?", false).And("act_user_id=?", uid)
  353. }
  354. err := sess.Find(&actions)
  355. return actions, err
  356. }