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

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