action.go 11 KB

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