You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

action.go 10 kB

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