action.go 10.0 KB

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