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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "path"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "xorm.io/builder"
  18. )
  19. // ActionType represents the type of an action.
  20. type ActionType int
  21. // Possible action types.
  22. const (
  23. ActionCreateRepo ActionType = iota + 1 // 1
  24. ActionRenameRepo // 2
  25. ActionStarRepo // 3
  26. ActionWatchRepo // 4
  27. ActionCommitRepo // 5
  28. ActionCreateIssue // 6
  29. ActionCreatePullRequest // 7
  30. ActionTransferRepo // 8
  31. ActionPushTag // 9
  32. ActionCommentIssue // 10
  33. ActionMergePullRequest // 11
  34. ActionCloseIssue // 12
  35. ActionReopenIssue // 13
  36. ActionClosePullRequest // 14
  37. ActionReopenPullRequest // 15
  38. ActionDeleteTag // 16
  39. ActionDeleteBranch // 17
  40. ActionMirrorSyncPush // 18
  41. ActionMirrorSyncCreate // 19
  42. ActionMirrorSyncDelete // 20
  43. ActionApprovePullRequest // 21
  44. ActionRejectPullRequest // 22
  45. ActionCommentPull // 23
  46. ActionPublishRelease // 24
  47. ActionPullReviewDismissed // 25
  48. ActionPullRequestReadyForReview // 26
  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. // LoadActUser loads a.ActUser
  74. func (a *Action) LoadActUser() {
  75. if a.ActUser != nil {
  76. return
  77. }
  78. var err error
  79. a.ActUser, err = GetUserByID(a.ActUserID)
  80. if err == nil {
  81. return
  82. } else if IsErrUserNotExist(err) {
  83. a.ActUser = NewGhostUser()
  84. } else {
  85. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  86. }
  87. }
  88. func (a *Action) loadRepo() {
  89. if a.Repo != nil {
  90. return
  91. }
  92. var err error
  93. a.Repo, err = GetRepositoryByID(a.RepoID)
  94. if err != nil {
  95. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  96. }
  97. }
  98. // GetActFullName gets the action's user full name.
  99. func (a *Action) GetActFullName() string {
  100. a.LoadActUser()
  101. return a.ActUser.FullName
  102. }
  103. // GetActUserName gets the action's user name.
  104. func (a *Action) GetActUserName() string {
  105. a.LoadActUser()
  106. return a.ActUser.Name
  107. }
  108. // ShortActUserName gets the action's user name trimmed to max 20
  109. // chars.
  110. func (a *Action) ShortActUserName() string {
  111. return base.EllipsisString(a.GetActUserName(), 20)
  112. }
  113. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME, or falls back to the username if it is blank.
  114. func (a *Action) GetDisplayName() string {
  115. if setting.UI.DefaultShowFullName {
  116. trimmedFullName := strings.TrimSpace(a.GetActFullName())
  117. if len(trimmedFullName) > 0 {
  118. return trimmedFullName
  119. }
  120. }
  121. return a.ShortActUserName()
  122. }
  123. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  124. func (a *Action) GetDisplayNameTitle() string {
  125. if setting.UI.DefaultShowFullName {
  126. return a.ShortActUserName()
  127. }
  128. return a.GetActFullName()
  129. }
  130. // GetRepoUserName returns the name of the action repository owner.
  131. func (a *Action) GetRepoUserName() string {
  132. a.loadRepo()
  133. return a.Repo.OwnerName
  134. }
  135. // ShortRepoUserName returns the name of the action repository owner
  136. // trimmed to max 20 chars.
  137. func (a *Action) ShortRepoUserName() string {
  138. return base.EllipsisString(a.GetRepoUserName(), 20)
  139. }
  140. // GetRepoName returns the name of the action repository.
  141. func (a *Action) GetRepoName() string {
  142. a.loadRepo()
  143. return a.Repo.Name
  144. }
  145. // ShortRepoName returns the name of the action repository
  146. // trimmed to max 33 chars.
  147. func (a *Action) ShortRepoName() string {
  148. return base.EllipsisString(a.GetRepoName(), 33)
  149. }
  150. // GetRepoPath returns the virtual path to the action repository.
  151. func (a *Action) GetRepoPath() string {
  152. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  153. }
  154. // ShortRepoPath returns the virtual path to the action repository
  155. // trimmed to max 20 + 1 + 33 chars.
  156. func (a *Action) ShortRepoPath() string {
  157. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  158. }
  159. // GetRepoLink returns relative link to action repository.
  160. func (a *Action) GetRepoLink() string {
  161. if len(setting.AppSubURL) > 0 {
  162. return path.Join(setting.AppSubURL, a.GetRepoPath())
  163. }
  164. return "/" + a.GetRepoPath()
  165. }
  166. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  167. func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
  168. var err error
  169. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  170. if err != nil {
  171. if IsErrRepoNotExist(err) {
  172. log.Warn("Repository referenced in commit but does not exist: %v", err)
  173. return nil, err
  174. }
  175. log.Error("GetRepositoryByOwnerAndName: %v", err)
  176. return nil, err
  177. }
  178. return refRepo, nil
  179. }
  180. // GetCommentLink returns link to action comment.
  181. func (a *Action) GetCommentLink() string {
  182. return a.getCommentLink(x)
  183. }
  184. func (a *Action) getCommentLink(e Engine) string {
  185. if a == nil {
  186. return "#"
  187. }
  188. if a.Comment == nil && a.CommentID != 0 {
  189. a.Comment, _ = getCommentByID(e, a.CommentID)
  190. }
  191. if a.Comment != nil {
  192. return a.Comment.HTMLURL()
  193. }
  194. if len(a.GetIssueInfos()) == 0 {
  195. return "#"
  196. }
  197. // Return link to issue
  198. issueIDString := a.GetIssueInfos()[0]
  199. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  200. if err != nil {
  201. return "#"
  202. }
  203. issue, err := getIssueByID(e, issueID)
  204. if err != nil {
  205. return "#"
  206. }
  207. if err = issue.loadRepo(e); err != nil {
  208. return "#"
  209. }
  210. return issue.HTMLURL()
  211. }
  212. // GetBranch returns the action's repository branch.
  213. func (a *Action) GetBranch() string {
  214. return strings.TrimPrefix(a.RefName, git.BranchPrefix)
  215. }
  216. // GetTag returns the action's repository tag.
  217. func (a *Action) GetTag() string {
  218. return strings.TrimPrefix(a.RefName, git.TagPrefix)
  219. }
  220. // GetContent returns the action's content.
  221. func (a *Action) GetContent() string {
  222. return a.Content
  223. }
  224. // GetCreate returns the action creation time.
  225. func (a *Action) GetCreate() time.Time {
  226. return a.CreatedUnix.AsTime()
  227. }
  228. // GetIssueInfos returns a list of issues associated with
  229. // the action.
  230. func (a *Action) GetIssueInfos() []string {
  231. return strings.SplitN(a.Content, "|", 3)
  232. }
  233. // GetIssueTitle returns the title of first issue associated
  234. // with the action.
  235. func (a *Action) GetIssueTitle() string {
  236. index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
  237. issue, err := GetIssueByIndex(a.RepoID, index)
  238. if err != nil {
  239. log.Error("GetIssueByIndex: %v", err)
  240. return "500 when get issue"
  241. }
  242. return issue.Title
  243. }
  244. // GetIssueContent returns the content of first issue associated with
  245. // this action.
  246. func (a *Action) GetIssueContent() string {
  247. index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
  248. issue, err := GetIssueByIndex(a.RepoID, index)
  249. if err != nil {
  250. log.Error("GetIssueByIndex: %v", err)
  251. return "500 when get issue"
  252. }
  253. return issue.Content
  254. }
  255. // GetFeedsOptions options for retrieving feeds
  256. type GetFeedsOptions struct {
  257. RequestedUser *User // the user we want activity for
  258. RequestedTeam *Team // the team we want activity for
  259. Actor *User // the user viewing the activity
  260. IncludePrivate bool // include private actions
  261. OnlyPerformedBy bool // only actions performed by requested user
  262. IncludeDeleted bool // include deleted actions
  263. Date string // the day we want activity for: YYYY-MM-DD
  264. }
  265. // GetFeeds returns actions according to the provided options
  266. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  267. if !activityReadable(opts.RequestedUser, opts.Actor) {
  268. return make([]*Action, 0), nil
  269. }
  270. cond, err := activityQueryCondition(opts)
  271. if err != nil {
  272. return nil, err
  273. }
  274. actions := make([]*Action, 0, setting.UI.FeedPagingNum)
  275. if err := x.Limit(setting.UI.FeedPagingNum).Desc("id").Where(cond).Find(&actions); err != nil {
  276. return nil, fmt.Errorf("Find: %v", err)
  277. }
  278. if err := ActionList(actions).LoadAttributes(); err != nil {
  279. return nil, fmt.Errorf("LoadAttributes: %v", err)
  280. }
  281. return actions, nil
  282. }
  283. func activityReadable(user, doer *User) bool {
  284. var doerID int64
  285. if doer != nil {
  286. doerID = doer.ID
  287. }
  288. if doer == nil || !doer.IsAdmin {
  289. if user.KeepActivityPrivate && doerID != user.ID {
  290. return false
  291. }
  292. }
  293. return true
  294. }
  295. func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) {
  296. cond := builder.NewCond()
  297. var repoIDs []int64
  298. var actorID int64
  299. if opts.Actor != nil {
  300. actorID = opts.Actor.ID
  301. }
  302. // check readable repositories by doer/actor
  303. if opts.Actor == nil || !opts.Actor.IsAdmin {
  304. if opts.RequestedUser.IsOrganization() {
  305. env, err := opts.RequestedUser.AccessibleReposEnv(actorID)
  306. if err != nil {
  307. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  308. }
  309. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  310. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  311. }
  312. cond = cond.And(builder.In("repo_id", repoIDs))
  313. } else {
  314. cond = cond.And(builder.In("repo_id", AccessibleRepoIDsQuery(opts.Actor)))
  315. }
  316. }
  317. if opts.RequestedTeam != nil {
  318. env := opts.RequestedUser.AccessibleTeamReposEnv(opts.RequestedTeam)
  319. teamRepoIDs, err := env.RepoIDs(1, opts.RequestedUser.NumRepos)
  320. if err != nil {
  321. return nil, fmt.Errorf("GetTeamRepositories: %v", err)
  322. }
  323. cond = cond.And(builder.In("repo_id", teamRepoIDs))
  324. }
  325. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  326. if opts.OnlyPerformedBy {
  327. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  328. }
  329. if !opts.IncludePrivate {
  330. cond = cond.And(builder.Eq{"is_private": false})
  331. }
  332. if !opts.IncludeDeleted {
  333. cond = cond.And(builder.Eq{"is_deleted": false})
  334. }
  335. if opts.Date != "" {
  336. dateLow, err := time.ParseInLocation("2006-01-02", opts.Date, setting.DefaultUILocation)
  337. if err != nil {
  338. log.Warn("Unable to parse %s, filter not applied: %v", opts.Date, err)
  339. } else {
  340. dateHigh := dateLow.Add(86399000000000) // 23h59m59s
  341. cond = cond.And(builder.Gte{"created_unix": dateLow.Unix()})
  342. cond = cond.And(builder.Lte{"created_unix": dateHigh.Unix()})
  343. }
  344. }
  345. return cond, nil
  346. }
  347. // DeleteOldActions deletes all old actions from database.
  348. func DeleteOldActions(olderThan time.Duration) (err error) {
  349. if olderThan <= 0 {
  350. return nil
  351. }
  352. _, err = x.Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
  353. return
  354. }