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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "context"
  8. "fmt"
  9. "net/url"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models/db"
  15. repo_model "code.gitea.io/gitea/models/repo"
  16. "code.gitea.io/gitea/models/unit"
  17. user_model "code.gitea.io/gitea/models/user"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/git"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/structs"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "code.gitea.io/gitea/modules/util"
  25. "xorm.io/builder"
  26. )
  27. // ActionType represents the type of an action.
  28. type ActionType int
  29. // Possible action types.
  30. const (
  31. ActionCreateRepo ActionType = iota + 1 // 1
  32. ActionRenameRepo // 2
  33. ActionStarRepo // 3
  34. ActionWatchRepo // 4
  35. ActionCommitRepo // 5
  36. ActionCreateIssue // 6
  37. ActionCreatePullRequest // 7
  38. ActionTransferRepo // 8
  39. ActionPushTag // 9
  40. ActionCommentIssue // 10
  41. ActionMergePullRequest // 11
  42. ActionCloseIssue // 12
  43. ActionReopenIssue // 13
  44. ActionClosePullRequest // 14
  45. ActionReopenPullRequest // 15
  46. ActionDeleteTag // 16
  47. ActionDeleteBranch // 17
  48. ActionMirrorSyncPush // 18
  49. ActionMirrorSyncCreate // 19
  50. ActionMirrorSyncDelete // 20
  51. ActionApprovePullRequest // 21
  52. ActionRejectPullRequest // 22
  53. ActionCommentPull // 23
  54. ActionPublishRelease // 24
  55. ActionPullReviewDismissed // 25
  56. ActionPullRequestReadyForReview // 26
  57. )
  58. // Action represents user operation type and other information to
  59. // repository. It implemented interface base.Actioner so that can be
  60. // used in template render.
  61. type Action struct {
  62. ID int64 `xorm:"pk autoincr"`
  63. UserID int64 `xorm:"INDEX"` // Receiver user id.
  64. OpType ActionType
  65. ActUserID int64 `xorm:"INDEX"` // Action user id.
  66. ActUser *user_model.User `xorm:"-"`
  67. RepoID int64 `xorm:"INDEX"`
  68. Repo *repo_model.Repository `xorm:"-"`
  69. CommentID int64 `xorm:"INDEX"`
  70. Comment *Comment `xorm:"-"`
  71. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  72. RefName string
  73. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  74. Content string `xorm:"TEXT"`
  75. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  76. }
  77. func init() {
  78. db.RegisterModel(new(Action))
  79. }
  80. // GetOpType gets the ActionType of this action.
  81. func (a *Action) GetOpType() ActionType {
  82. return a.OpType
  83. }
  84. // LoadActUser loads a.ActUser
  85. func (a *Action) LoadActUser() {
  86. if a.ActUser != nil {
  87. return
  88. }
  89. var err error
  90. a.ActUser, err = user_model.GetUserByID(a.ActUserID)
  91. if err == nil {
  92. return
  93. } else if user_model.IsErrUserNotExist(err) {
  94. a.ActUser = user_model.NewGhostUser()
  95. } else {
  96. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  97. }
  98. }
  99. func (a *Action) loadRepo() {
  100. if a.Repo != nil {
  101. return
  102. }
  103. var err error
  104. a.Repo, err = repo_model.GetRepositoryByID(a.RepoID)
  105. if err != nil {
  106. log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err)
  107. }
  108. }
  109. // GetActFullName gets the action's user full name.
  110. func (a *Action) GetActFullName() string {
  111. a.LoadActUser()
  112. return a.ActUser.FullName
  113. }
  114. // GetActUserName gets the action's user name.
  115. func (a *Action) GetActUserName() string {
  116. a.LoadActUser()
  117. return a.ActUser.Name
  118. }
  119. // ShortActUserName gets the action's user name trimmed to max 20
  120. // chars.
  121. func (a *Action) ShortActUserName() string {
  122. return base.EllipsisString(a.GetActUserName(), 20)
  123. }
  124. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME, or falls back to the username if it is blank.
  125. func (a *Action) GetDisplayName() string {
  126. if setting.UI.DefaultShowFullName {
  127. trimmedFullName := strings.TrimSpace(a.GetActFullName())
  128. if len(trimmedFullName) > 0 {
  129. return trimmedFullName
  130. }
  131. }
  132. return a.ShortActUserName()
  133. }
  134. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  135. func (a *Action) GetDisplayNameTitle() string {
  136. if setting.UI.DefaultShowFullName {
  137. return a.ShortActUserName()
  138. }
  139. return a.GetActFullName()
  140. }
  141. // GetRepoUserName returns the name of the action repository owner.
  142. func (a *Action) GetRepoUserName() string {
  143. a.loadRepo()
  144. return a.Repo.OwnerName
  145. }
  146. // ShortRepoUserName returns the name of the action repository owner
  147. // trimmed to max 20 chars.
  148. func (a *Action) ShortRepoUserName() string {
  149. return base.EllipsisString(a.GetRepoUserName(), 20)
  150. }
  151. // GetRepoName returns the name of the action repository.
  152. func (a *Action) GetRepoName() string {
  153. a.loadRepo()
  154. return a.Repo.Name
  155. }
  156. // ShortRepoName returns the name of the action repository
  157. // trimmed to max 33 chars.
  158. func (a *Action) ShortRepoName() string {
  159. return base.EllipsisString(a.GetRepoName(), 33)
  160. }
  161. // GetRepoPath returns the virtual path to the action repository.
  162. func (a *Action) GetRepoPath() string {
  163. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  164. }
  165. // ShortRepoPath returns the virtual path to the action repository
  166. // trimmed to max 20 + 1 + 33 chars.
  167. func (a *Action) ShortRepoPath() string {
  168. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  169. }
  170. // GetRepoLink returns relative link to action repository.
  171. func (a *Action) GetRepoLink() string {
  172. // path.Join will skip empty strings
  173. return path.Join(setting.AppSubURL, "/", url.PathEscape(a.GetRepoUserName()), url.PathEscape(a.GetRepoName()))
  174. }
  175. // GetRepositoryFromMatch returns a *repo_model.Repository from a username and repo strings
  176. func GetRepositoryFromMatch(ownerName, repoName string) (*repo_model.Repository, error) {
  177. var err error
  178. refRepo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName)
  179. if err != nil {
  180. if repo_model.IsErrRepoNotExist(err) {
  181. log.Warn("Repository referenced in commit but does not exist: %v", err)
  182. return nil, err
  183. }
  184. log.Error("repo_model.GetRepositoryByOwnerAndName: %v", err)
  185. return nil, err
  186. }
  187. return refRepo, nil
  188. }
  189. // GetCommentLink returns link to action comment.
  190. func (a *Action) GetCommentLink() string {
  191. return a.getCommentLink(db.DefaultContext)
  192. }
  193. func (a *Action) getCommentLink(ctx context.Context) string {
  194. if a == nil {
  195. return "#"
  196. }
  197. e := db.GetEngine(ctx)
  198. if a.Comment == nil && a.CommentID != 0 {
  199. a.Comment, _ = getCommentByID(e, a.CommentID)
  200. }
  201. if a.Comment != nil {
  202. return a.Comment.HTMLURL()
  203. }
  204. if len(a.GetIssueInfos()) == 0 {
  205. return "#"
  206. }
  207. // Return link to issue
  208. issueIDString := a.GetIssueInfos()[0]
  209. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  210. if err != nil {
  211. return "#"
  212. }
  213. issue, err := getIssueByID(e, issueID)
  214. if err != nil {
  215. return "#"
  216. }
  217. if err = issue.loadRepo(ctx); err != nil {
  218. return "#"
  219. }
  220. return issue.HTMLURL()
  221. }
  222. // GetBranch returns the action's repository branch.
  223. func (a *Action) GetBranch() string {
  224. return strings.TrimPrefix(a.RefName, git.BranchPrefix)
  225. }
  226. // GetRefLink returns the action's ref link.
  227. func (a *Action) GetRefLink() string {
  228. switch {
  229. case strings.HasPrefix(a.RefName, git.BranchPrefix):
  230. return a.GetRepoLink() + "/src/branch/" + util.PathEscapeSegments(strings.TrimPrefix(a.RefName, git.BranchPrefix))
  231. case strings.HasPrefix(a.RefName, git.TagPrefix):
  232. return a.GetRepoLink() + "/src/tag/" + util.PathEscapeSegments(strings.TrimPrefix(a.RefName, git.TagPrefix))
  233. case len(a.RefName) == 40 && git.SHAPattern.MatchString(a.RefName):
  234. return a.GetRepoLink() + "/src/commit/" + a.RefName
  235. default:
  236. // FIXME: we will just assume it's a branch - this was the old way - at some point we may want to enforce that there is always a ref here.
  237. return a.GetRepoLink() + "/src/branch/" + util.PathEscapeSegments(strings.TrimPrefix(a.RefName, git.BranchPrefix))
  238. }
  239. }
  240. // GetTag returns the action's repository tag.
  241. func (a *Action) GetTag() string {
  242. return strings.TrimPrefix(a.RefName, git.TagPrefix)
  243. }
  244. // GetContent returns the action's content.
  245. func (a *Action) GetContent() string {
  246. return a.Content
  247. }
  248. // GetCreate returns the action creation time.
  249. func (a *Action) GetCreate() time.Time {
  250. return a.CreatedUnix.AsTime()
  251. }
  252. // GetIssueInfos returns a list of issues associated with
  253. // the action.
  254. func (a *Action) GetIssueInfos() []string {
  255. return strings.SplitN(a.Content, "|", 3)
  256. }
  257. // GetIssueTitle returns the title of first issue associated
  258. // with the action.
  259. func (a *Action) GetIssueTitle() string {
  260. index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
  261. issue, err := GetIssueByIndex(a.RepoID, index)
  262. if err != nil {
  263. log.Error("GetIssueByIndex: %v", err)
  264. return "500 when get issue"
  265. }
  266. return issue.Title
  267. }
  268. // GetIssueContent returns the content of first issue associated with
  269. // this action.
  270. func (a *Action) GetIssueContent() string {
  271. index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
  272. issue, err := GetIssueByIndex(a.RepoID, index)
  273. if err != nil {
  274. log.Error("GetIssueByIndex: %v", err)
  275. return "500 when get issue"
  276. }
  277. return issue.Content
  278. }
  279. // GetFeedsOptions options for retrieving feeds
  280. type GetFeedsOptions struct {
  281. db.ListOptions
  282. RequestedUser *user_model.User // the user we want activity for
  283. RequestedTeam *Team // the team we want activity for
  284. RequestedRepo *repo_model.Repository // the repo we want activity for
  285. Actor *user_model.User // the user viewing the activity
  286. IncludePrivate bool // include private actions
  287. OnlyPerformedBy bool // only actions performed by requested user
  288. IncludeDeleted bool // include deleted actions
  289. Date string // the day we want activity for: YYYY-MM-DD
  290. }
  291. // GetFeeds returns actions according to the provided options
  292. func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, error) {
  293. if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
  294. return nil, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
  295. }
  296. cond, err := activityQueryCondition(opts)
  297. if err != nil {
  298. return nil, err
  299. }
  300. e := db.GetEngine(ctx)
  301. sess := e.Where(cond)
  302. opts.SetDefaultValues()
  303. sess = db.SetSessionPagination(sess, &opts)
  304. actions := make([]*Action, 0, opts.PageSize)
  305. if err := sess.Desc("created_unix").Find(&actions); err != nil {
  306. return nil, fmt.Errorf("Find: %v", err)
  307. }
  308. if err := ActionList(actions).loadAttributes(e); err != nil {
  309. return nil, fmt.Errorf("LoadAttributes: %v", err)
  310. }
  311. return actions, nil
  312. }
  313. func activityReadable(user, doer *user_model.User) bool {
  314. return !user.KeepActivityPrivate ||
  315. doer != nil && (doer.IsAdmin || user.ID == doer.ID)
  316. }
  317. func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) {
  318. cond := builder.NewCond()
  319. if opts.RequestedTeam != nil && opts.RequestedUser == nil {
  320. org, err := user_model.GetUserByID(opts.RequestedTeam.OrgID)
  321. if err != nil {
  322. return nil, err
  323. }
  324. opts.RequestedUser = org
  325. }
  326. // check activity visibility for actor ( similar to activityReadable() )
  327. if opts.Actor == nil {
  328. cond = cond.And(builder.In("act_user_id",
  329. builder.Select("`user`.id").Where(
  330. builder.Eq{"keep_activity_private": false, "visibility": structs.VisibleTypePublic},
  331. ).From("`user`"),
  332. ))
  333. } else if !opts.Actor.IsAdmin {
  334. cond = cond.And(builder.In("act_user_id",
  335. builder.Select("`user`.id").Where(
  336. builder.Eq{"keep_activity_private": false}.
  337. And(builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))).
  338. Or(builder.Eq{"id": opts.Actor.ID}).From("`user`"),
  339. ))
  340. }
  341. // check readable repositories by doer/actor
  342. if opts.Actor == nil || !opts.Actor.IsAdmin {
  343. cond = cond.And(builder.In("repo_id", AccessibleRepoIDsQuery(opts.Actor)))
  344. }
  345. if opts.RequestedRepo != nil {
  346. cond = cond.And(builder.Eq{"repo_id": opts.RequestedRepo.ID})
  347. }
  348. if opts.RequestedTeam != nil {
  349. env := OrgFromUser(opts.RequestedUser).AccessibleTeamReposEnv(opts.RequestedTeam)
  350. teamRepoIDs, err := env.RepoIDs(1, opts.RequestedUser.NumRepos)
  351. if err != nil {
  352. return nil, fmt.Errorf("GetTeamRepositories: %v", err)
  353. }
  354. cond = cond.And(builder.In("repo_id", teamRepoIDs))
  355. }
  356. if opts.RequestedUser != nil {
  357. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  358. if opts.OnlyPerformedBy {
  359. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  360. }
  361. }
  362. if !opts.IncludePrivate {
  363. cond = cond.And(builder.Eq{"is_private": false})
  364. }
  365. if !opts.IncludeDeleted {
  366. cond = cond.And(builder.Eq{"is_deleted": false})
  367. }
  368. if opts.Date != "" {
  369. dateLow, err := time.ParseInLocation("2006-01-02", opts.Date, setting.DefaultUILocation)
  370. if err != nil {
  371. log.Warn("Unable to parse %s, filter not applied: %v", opts.Date, err)
  372. } else {
  373. dateHigh := dateLow.Add(86399000000000) // 23h59m59s
  374. cond = cond.And(builder.Gte{"created_unix": dateLow.Unix()})
  375. cond = cond.And(builder.Lte{"created_unix": dateHigh.Unix()})
  376. }
  377. }
  378. return cond, nil
  379. }
  380. // DeleteOldActions deletes all old actions from database.
  381. func DeleteOldActions(olderThan time.Duration) (err error) {
  382. if olderThan <= 0 {
  383. return nil
  384. }
  385. _, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
  386. return
  387. }
  388. func notifyWatchers(ctx context.Context, actions ...*Action) error {
  389. var watchers []*repo_model.Watch
  390. var repo *repo_model.Repository
  391. var err error
  392. var permCode []bool
  393. var permIssue []bool
  394. var permPR []bool
  395. e := db.GetEngine(ctx)
  396. for _, act := range actions {
  397. repoChanged := repo == nil || repo.ID != act.RepoID
  398. if repoChanged {
  399. // Add feeds for user self and all watchers.
  400. watchers, err = repo_model.GetWatchers(ctx, act.RepoID)
  401. if err != nil {
  402. return fmt.Errorf("get watchers: %v", err)
  403. }
  404. }
  405. // Add feed for actioner.
  406. act.UserID = act.ActUserID
  407. if _, err = e.Insert(act); err != nil {
  408. return fmt.Errorf("insert new actioner: %v", err)
  409. }
  410. if repoChanged {
  411. act.loadRepo()
  412. repo = act.Repo
  413. // check repo owner exist.
  414. if err := act.Repo.GetOwner(ctx); err != nil {
  415. return fmt.Errorf("can't get repo owner: %v", err)
  416. }
  417. } else if act.Repo == nil {
  418. act.Repo = repo
  419. }
  420. // Add feed for organization
  421. if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
  422. act.ID = 0
  423. act.UserID = act.Repo.Owner.ID
  424. if _, err = e.InsertOne(act); err != nil {
  425. return fmt.Errorf("insert new actioner: %v", err)
  426. }
  427. }
  428. if repoChanged {
  429. permCode = make([]bool, len(watchers))
  430. permIssue = make([]bool, len(watchers))
  431. permPR = make([]bool, len(watchers))
  432. for i, watcher := range watchers {
  433. user, err := user_model.GetUserByIDEngine(e, watcher.UserID)
  434. if err != nil {
  435. permCode[i] = false
  436. permIssue[i] = false
  437. permPR[i] = false
  438. continue
  439. }
  440. perm, err := getUserRepoPermission(ctx, repo, user)
  441. if err != nil {
  442. permCode[i] = false
  443. permIssue[i] = false
  444. permPR[i] = false
  445. continue
  446. }
  447. permCode[i] = perm.CanRead(unit.TypeCode)
  448. permIssue[i] = perm.CanRead(unit.TypeIssues)
  449. permPR[i] = perm.CanRead(unit.TypePullRequests)
  450. }
  451. }
  452. for i, watcher := range watchers {
  453. if act.ActUserID == watcher.UserID {
  454. continue
  455. }
  456. act.ID = 0
  457. act.UserID = watcher.UserID
  458. act.Repo.Units = nil
  459. switch act.OpType {
  460. case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionPublishRelease, ActionDeleteBranch:
  461. if !permCode[i] {
  462. continue
  463. }
  464. case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
  465. if !permIssue[i] {
  466. continue
  467. }
  468. case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
  469. if !permPR[i] {
  470. continue
  471. }
  472. }
  473. if _, err = e.InsertOne(act); err != nil {
  474. return fmt.Errorf("insert new action: %v", err)
  475. }
  476. }
  477. }
  478. return nil
  479. }
  480. // NotifyWatchers creates batch of actions for every watcher.
  481. func NotifyWatchers(actions ...*Action) error {
  482. return notifyWatchers(db.DefaultContext, actions...)
  483. }
  484. // NotifyWatchersActions creates batch of actions for every watcher.
  485. func NotifyWatchersActions(acts []*Action) error {
  486. ctx, committer, err := db.TxContext()
  487. if err != nil {
  488. return err
  489. }
  490. defer committer.Close()
  491. for _, act := range acts {
  492. if err := notifyWatchers(ctx, act); err != nil {
  493. return err
  494. }
  495. }
  496. return committer.Commit()
  497. }