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

action.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "html"
  9. "path"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/references"
  17. "code.gitea.io/gitea/modules/setting"
  18. api "code.gitea.io/gitea/modules/structs"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "github.com/unknwon/com"
  21. "xorm.io/builder"
  22. )
  23. // ActionType represents the type of an action.
  24. type ActionType int
  25. // Possible action types.
  26. const (
  27. ActionCreateRepo ActionType = iota + 1 // 1
  28. ActionRenameRepo // 2
  29. ActionStarRepo // 3
  30. ActionWatchRepo // 4
  31. ActionCommitRepo // 5
  32. ActionCreateIssue // 6
  33. ActionCreatePullRequest // 7
  34. ActionTransferRepo // 8
  35. ActionPushTag // 9
  36. ActionCommentIssue // 10
  37. ActionMergePullRequest // 11
  38. ActionCloseIssue // 12
  39. ActionReopenIssue // 13
  40. ActionClosePullRequest // 14
  41. ActionReopenPullRequest // 15
  42. ActionDeleteTag // 16
  43. ActionDeleteBranch // 17
  44. ActionMirrorSyncPush // 18
  45. ActionMirrorSyncCreate // 19
  46. ActionMirrorSyncDelete // 20
  47. ActionApprovePullRequest // 21
  48. ActionRejectPullRequest // 22
  49. )
  50. // Action represents user operation type and other information to
  51. // repository. It implemented interface base.Actioner so that can be
  52. // used in template render.
  53. type Action struct {
  54. ID int64 `xorm:"pk autoincr"`
  55. UserID int64 `xorm:"INDEX"` // Receiver user id.
  56. OpType ActionType
  57. ActUserID int64 `xorm:"INDEX"` // Action user id.
  58. ActUser *User `xorm:"-"`
  59. RepoID int64 `xorm:"INDEX"`
  60. Repo *Repository `xorm:"-"`
  61. CommentID int64 `xorm:"INDEX"`
  62. Comment *Comment `xorm:"-"`
  63. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  64. RefName string
  65. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  66. Content string `xorm:"TEXT"`
  67. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  68. }
  69. // GetOpType gets the ActionType of this action.
  70. func (a *Action) GetOpType() ActionType {
  71. return a.OpType
  72. }
  73. func (a *Action) loadActUser() {
  74. if a.ActUser != nil {
  75. return
  76. }
  77. var err error
  78. a.ActUser, err = GetUserByID(a.ActUserID)
  79. if err == nil {
  80. return
  81. } else if IsErrUserNotExist(err) {
  82. a.ActUser = NewGhostUser()
  83. } else {
  84. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  85. }
  86. }
  87. func (a *Action) loadRepo() {
  88. if a.Repo != nil {
  89. return
  90. }
  91. var err error
  92. a.Repo, err = GetRepositoryByID(a.RepoID)
  93. if err != nil {
  94. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  95. }
  96. }
  97. // GetActFullName gets the action's user full name.
  98. func (a *Action) GetActFullName() string {
  99. a.loadActUser()
  100. return a.ActUser.FullName
  101. }
  102. // GetActUserName gets the action's user name.
  103. func (a *Action) GetActUserName() string {
  104. a.loadActUser()
  105. return a.ActUser.Name
  106. }
  107. // ShortActUserName gets the action's user name trimmed to max 20
  108. // chars.
  109. func (a *Action) ShortActUserName() string {
  110. return base.EllipsisString(a.GetActUserName(), 20)
  111. }
  112. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME
  113. func (a *Action) GetDisplayName() string {
  114. if setting.UI.DefaultShowFullName {
  115. return a.GetActFullName()
  116. }
  117. return a.ShortActUserName()
  118. }
  119. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  120. func (a *Action) GetDisplayNameTitle() string {
  121. if setting.UI.DefaultShowFullName {
  122. return a.ShortActUserName()
  123. }
  124. return a.GetActFullName()
  125. }
  126. // GetActAvatar the action's user's avatar link
  127. func (a *Action) GetActAvatar() string {
  128. a.loadActUser()
  129. return a.ActUser.RelAvatarLink()
  130. }
  131. // GetRepoUserName returns the name of the action repository owner.
  132. func (a *Action) GetRepoUserName() string {
  133. a.loadRepo()
  134. return a.Repo.MustOwner().Name
  135. }
  136. // ShortRepoUserName returns the name of the action repository owner
  137. // trimmed to max 20 chars.
  138. func (a *Action) ShortRepoUserName() string {
  139. return base.EllipsisString(a.GetRepoUserName(), 20)
  140. }
  141. // GetRepoName returns the name of the action repository.
  142. func (a *Action) GetRepoName() string {
  143. a.loadRepo()
  144. return a.Repo.Name
  145. }
  146. // ShortRepoName returns the name of the action repository
  147. // trimmed to max 33 chars.
  148. func (a *Action) ShortRepoName() string {
  149. return base.EllipsisString(a.GetRepoName(), 33)
  150. }
  151. // GetRepoPath returns the virtual path to the action repository.
  152. func (a *Action) GetRepoPath() string {
  153. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  154. }
  155. // ShortRepoPath returns the virtual path to the action repository
  156. // trimmed to max 20 + 1 + 33 chars.
  157. func (a *Action) ShortRepoPath() string {
  158. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  159. }
  160. // GetRepoLink returns relative link to action repository.
  161. func (a *Action) GetRepoLink() string {
  162. if len(setting.AppSubURL) > 0 {
  163. return path.Join(setting.AppSubURL, a.GetRepoPath())
  164. }
  165. return "/" + a.GetRepoPath()
  166. }
  167. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  168. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  169. var err error
  170. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  171. if err != nil {
  172. if IsErrRepoNotExist(err) {
  173. log.Warn("Repository referenced in commit but does not exist: %v", err)
  174. return nil, err
  175. }
  176. log.Error("GetRepositoryByOwnerAndName: %v", err)
  177. return nil, err
  178. }
  179. return refRepo, nil
  180. }
  181. // GetCommentLink returns link to action comment.
  182. func (a *Action) GetCommentLink() string {
  183. return a.getCommentLink(x)
  184. }
  185. func (a *Action) getCommentLink(e Engine) string {
  186. if a == nil {
  187. return "#"
  188. }
  189. if a.Comment == nil && a.CommentID != 0 {
  190. a.Comment, _ = GetCommentByID(a.CommentID)
  191. }
  192. if a.Comment != nil {
  193. return a.Comment.HTMLURL()
  194. }
  195. if len(a.GetIssueInfos()) == 0 {
  196. return "#"
  197. }
  198. //Return link to issue
  199. issueIDString := a.GetIssueInfos()[0]
  200. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  201. if err != nil {
  202. return "#"
  203. }
  204. issue, err := getIssueByID(e, issueID)
  205. if err != nil {
  206. return "#"
  207. }
  208. if err = issue.loadRepo(e); err != nil {
  209. return "#"
  210. }
  211. return issue.HTMLURL()
  212. }
  213. // GetBranch returns the action's repository branch.
  214. func (a *Action) GetBranch() string {
  215. return a.RefName
  216. }
  217. // GetContent returns the action's content.
  218. func (a *Action) GetContent() string {
  219. return a.Content
  220. }
  221. // GetCreate returns the action creation time.
  222. func (a *Action) GetCreate() time.Time {
  223. return a.CreatedUnix.AsTime()
  224. }
  225. // GetIssueInfos returns a list of issues associated with
  226. // the action.
  227. func (a *Action) GetIssueInfos() []string {
  228. return strings.SplitN(a.Content, "|", 2)
  229. }
  230. // GetIssueTitle returns the title of first issue associated
  231. // with the action.
  232. func (a *Action) GetIssueTitle() string {
  233. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  234. issue, err := GetIssueByIndex(a.RepoID, index)
  235. if err != nil {
  236. log.Error("GetIssueByIndex: %v", err)
  237. return "500 when get issue"
  238. }
  239. return issue.Title
  240. }
  241. // GetIssueContent returns the content of first issue associated with
  242. // this action.
  243. func (a *Action) GetIssueContent() string {
  244. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  245. issue, err := GetIssueByIndex(a.RepoID, index)
  246. if err != nil {
  247. log.Error("GetIssueByIndex: %v", err)
  248. return "500 when get issue"
  249. }
  250. return issue.Content
  251. }
  252. // PushCommit represents a commit in a push operation.
  253. type PushCommit struct {
  254. Sha1 string
  255. Message string
  256. AuthorEmail string
  257. AuthorName string
  258. CommitterEmail string
  259. CommitterName string
  260. Timestamp time.Time
  261. }
  262. // PushCommits represents list of commits in a push operation.
  263. type PushCommits struct {
  264. Len int
  265. Commits []*PushCommit
  266. CompareURL string
  267. avatars map[string]string
  268. emailUsers map[string]*User
  269. }
  270. // NewPushCommits creates a new PushCommits object.
  271. func NewPushCommits() *PushCommits {
  272. return &PushCommits{
  273. avatars: make(map[string]string),
  274. emailUsers: make(map[string]*User),
  275. }
  276. }
  277. // ToAPIPayloadCommits converts a PushCommits object to
  278. // api.PayloadCommit format.
  279. func (pc *PushCommits) ToAPIPayloadCommits(repoPath, repoLink string) ([]*api.PayloadCommit, error) {
  280. commits := make([]*api.PayloadCommit, len(pc.Commits))
  281. if pc.emailUsers == nil {
  282. pc.emailUsers = make(map[string]*User)
  283. }
  284. var err error
  285. for i, commit := range pc.Commits {
  286. authorUsername := ""
  287. author, ok := pc.emailUsers[commit.AuthorEmail]
  288. if !ok {
  289. author, err = GetUserByEmail(commit.AuthorEmail)
  290. if err == nil {
  291. authorUsername = author.Name
  292. pc.emailUsers[commit.AuthorEmail] = author
  293. }
  294. } else {
  295. authorUsername = author.Name
  296. }
  297. committerUsername := ""
  298. committer, ok := pc.emailUsers[commit.CommitterEmail]
  299. if !ok {
  300. committer, err = GetUserByEmail(commit.CommitterEmail)
  301. if err == nil {
  302. // TODO: check errors other than email not found.
  303. committerUsername = committer.Name
  304. pc.emailUsers[commit.CommitterEmail] = committer
  305. }
  306. } else {
  307. committerUsername = committer.Name
  308. }
  309. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  310. if err != nil {
  311. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  312. }
  313. commits[i] = &api.PayloadCommit{
  314. ID: commit.Sha1,
  315. Message: commit.Message,
  316. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  317. Author: &api.PayloadUser{
  318. Name: commit.AuthorName,
  319. Email: commit.AuthorEmail,
  320. UserName: authorUsername,
  321. },
  322. Committer: &api.PayloadUser{
  323. Name: commit.CommitterName,
  324. Email: commit.CommitterEmail,
  325. UserName: committerUsername,
  326. },
  327. Added: fileStatus.Added,
  328. Removed: fileStatus.Removed,
  329. Modified: fileStatus.Modified,
  330. Timestamp: commit.Timestamp,
  331. }
  332. }
  333. return commits, nil
  334. }
  335. // AvatarLink tries to match user in database with e-mail
  336. // in order to show custom avatar, and falls back to general avatar link.
  337. func (pc *PushCommits) AvatarLink(email string) string {
  338. if pc.avatars == nil {
  339. pc.avatars = make(map[string]string)
  340. }
  341. avatar, ok := pc.avatars[email]
  342. if ok {
  343. return avatar
  344. }
  345. u, ok := pc.emailUsers[email]
  346. if !ok {
  347. var err error
  348. u, err = GetUserByEmail(email)
  349. if err != nil {
  350. pc.avatars[email] = base.AvatarLink(email)
  351. if !IsErrUserNotExist(err) {
  352. log.Error("GetUserByEmail: %v", err)
  353. return ""
  354. }
  355. } else {
  356. pc.emailUsers[email] = u
  357. }
  358. }
  359. if u != nil {
  360. pc.avatars[email] = u.RelAvatarLink()
  361. }
  362. return pc.avatars[email]
  363. }
  364. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  365. // if the provided ref references a non-existent issue.
  366. func getIssueFromRef(repo *Repository, index int64) (*Issue, error) {
  367. issue, err := GetIssueByIndex(repo.ID, index)
  368. if err != nil {
  369. if IsErrIssueNotExist(err) {
  370. return nil, nil
  371. }
  372. return nil, err
  373. }
  374. return issue, nil
  375. }
  376. func changeIssueStatus(repo *Repository, issue *Issue, doer *User, status bool) error {
  377. stopTimerIfAvailable := func(doer *User, issue *Issue) error {
  378. if StopwatchExists(doer.ID, issue.ID) {
  379. if err := CreateOrStopIssueStopwatch(doer, issue); err != nil {
  380. return err
  381. }
  382. }
  383. return nil
  384. }
  385. issue.Repo = repo
  386. if err := issue.ChangeStatus(doer, status); err != nil {
  387. // Don't return an error when dependencies are open as this would let the push fail
  388. if IsErrDependenciesLeft(err) {
  389. return stopTimerIfAvailable(doer, issue)
  390. }
  391. return err
  392. }
  393. return stopTimerIfAvailable(doer, issue)
  394. }
  395. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  396. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit, branchName string) error {
  397. // Commits are appended in the reverse order.
  398. for i := len(commits) - 1; i >= 0; i-- {
  399. c := commits[i]
  400. type markKey struct {
  401. ID int64
  402. Action references.XRefAction
  403. }
  404. refMarked := make(map[markKey]bool)
  405. var refRepo *Repository
  406. var refIssue *Issue
  407. var err error
  408. for _, ref := range references.FindAllIssueReferences(c.Message) {
  409. // issue is from another repo
  410. if len(ref.Owner) > 0 && len(ref.Name) > 0 {
  411. refRepo, err = GetRepositoryFromMatch(ref.Owner, ref.Name)
  412. if err != nil {
  413. continue
  414. }
  415. } else {
  416. refRepo = repo
  417. }
  418. if refIssue, err = getIssueFromRef(refRepo, ref.Index); err != nil {
  419. return err
  420. }
  421. if refIssue == nil {
  422. continue
  423. }
  424. perm, err := GetUserRepoPermission(refRepo, doer)
  425. if err != nil {
  426. return err
  427. }
  428. key := markKey{ID: refIssue.ID, Action: ref.Action}
  429. if refMarked[key] {
  430. continue
  431. }
  432. refMarked[key] = true
  433. // only create comments for issues if user has permission for it
  434. if perm.IsAdmin() || perm.IsOwner() || perm.CanWrite(UnitTypeIssues) {
  435. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, html.EscapeString(c.Message))
  436. if err = CreateRefComment(doer, refRepo, refIssue, message, c.Sha1); err != nil {
  437. return err
  438. }
  439. }
  440. // Process closing/reopening keywords
  441. if ref.Action != references.XRefActionCloses && ref.Action != references.XRefActionReopens {
  442. continue
  443. }
  444. // Change issue status only if the commit has been pushed to the default branch.
  445. // and if the repo is configured to allow only that
  446. // FIXME: we should be using Issue.ref if set instead of repo.DefaultBranch
  447. if repo.DefaultBranch != branchName && !repo.CloseIssuesViaCommitInAnyBranch {
  448. continue
  449. }
  450. // only close issues in another repo if user has push access
  451. if perm.IsAdmin() || perm.IsOwner() || perm.CanWrite(UnitTypeCode) {
  452. if err := changeIssueStatus(refRepo, refIssue, doer, ref.Action == references.XRefActionCloses); err != nil {
  453. return err
  454. }
  455. }
  456. }
  457. }
  458. return nil
  459. }
  460. // GetFeedsOptions options for retrieving feeds
  461. type GetFeedsOptions struct {
  462. RequestedUser *User
  463. RequestingUserID int64
  464. IncludePrivate bool // include private actions
  465. OnlyPerformedBy bool // only actions performed by requested user
  466. IncludeDeleted bool // include deleted actions
  467. }
  468. // GetFeeds returns actions according to the provided options
  469. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  470. cond := builder.NewCond()
  471. var repoIDs []int64
  472. if opts.RequestedUser.IsOrganization() {
  473. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  474. if err != nil {
  475. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  476. }
  477. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  478. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  479. }
  480. cond = cond.And(builder.In("repo_id", repoIDs))
  481. }
  482. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  483. if opts.OnlyPerformedBy {
  484. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  485. }
  486. if !opts.IncludePrivate {
  487. cond = cond.And(builder.Eq{"is_private": false})
  488. }
  489. if !opts.IncludeDeleted {
  490. cond = cond.And(builder.Eq{"is_deleted": false})
  491. }
  492. actions := make([]*Action, 0, 20)
  493. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  494. return nil, fmt.Errorf("Find: %v", err)
  495. }
  496. if err := ActionList(actions).LoadAttributes(); err != nil {
  497. return nil, fmt.Errorf("LoadAttributes: %v", err)
  498. }
  499. return actions, nil
  500. }