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.

issue_search.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package issues
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models/db"
  9. "code.gitea.io/gitea/models/organization"
  10. repo_model "code.gitea.io/gitea/models/repo"
  11. "code.gitea.io/gitea/models/unit"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/util"
  14. "xorm.io/builder"
  15. "xorm.io/xorm"
  16. )
  17. // IssuesOptions represents options of an issue.
  18. type IssuesOptions struct { //nolint
  19. db.ListOptions
  20. RepoIDs []int64 // overwrites RepoCond if the length is not 0
  21. RepoCond builder.Cond
  22. AssigneeID int64
  23. PosterID int64
  24. MentionedID int64
  25. ReviewRequestedID int64
  26. ReviewedID int64
  27. SubscriberID int64
  28. MilestoneIDs []int64
  29. ProjectID int64
  30. ProjectBoardID int64
  31. IsClosed util.OptionalBool
  32. IsPull util.OptionalBool
  33. LabelIDs []int64
  34. IncludedLabelNames []string
  35. ExcludedLabelNames []string
  36. IncludeMilestones []string
  37. SortType string
  38. IssueIDs []int64
  39. UpdatedAfterUnix int64
  40. UpdatedBeforeUnix int64
  41. // prioritize issues from this repo
  42. PriorityRepoID int64
  43. IsArchived util.OptionalBool
  44. Org *organization.Organization // issues permission scope
  45. Team *organization.Team // issues permission scope
  46. User *user_model.User // issues permission scope
  47. }
  48. // applySorts sort an issues-related session based on the provided
  49. // sortType string
  50. func applySorts(sess *xorm.Session, sortType string, priorityRepoID int64) {
  51. switch sortType {
  52. case "oldest":
  53. sess.Asc("issue.created_unix").Asc("issue.id")
  54. case "recentupdate":
  55. sess.Desc("issue.updated_unix").Desc("issue.created_unix").Desc("issue.id")
  56. case "leastupdate":
  57. sess.Asc("issue.updated_unix").Asc("issue.created_unix").Asc("issue.id")
  58. case "mostcomment":
  59. sess.Desc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  60. case "leastcomment":
  61. sess.Asc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  62. case "priority":
  63. sess.Desc("issue.priority").Desc("issue.created_unix").Desc("issue.id")
  64. case "nearduedate":
  65. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  66. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  67. OrderBy("CASE " +
  68. "WHEN issue.deadline_unix = 0 AND (milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL) THEN 253370764800 " +
  69. "WHEN milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  70. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  71. "ELSE issue.deadline_unix END ASC").
  72. Desc("issue.created_unix").
  73. Desc("issue.id")
  74. case "farduedate":
  75. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  76. OrderBy("CASE " +
  77. "WHEN milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  78. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  79. "ELSE issue.deadline_unix END DESC").
  80. Desc("issue.created_unix").
  81. Desc("issue.id")
  82. case "priorityrepo":
  83. sess.OrderBy("CASE "+
  84. "WHEN issue.repo_id = ? THEN 1 "+
  85. "ELSE 2 END ASC", priorityRepoID).
  86. Desc("issue.created_unix").
  87. Desc("issue.id")
  88. case "project-column-sorting":
  89. sess.Asc("project_issue.sorting").Desc("issue.created_unix").Desc("issue.id")
  90. default:
  91. sess.Desc("issue.created_unix").Desc("issue.id")
  92. }
  93. }
  94. func applyLimit(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  95. if opts.Page >= 0 && opts.PageSize > 0 {
  96. var start int
  97. if opts.Page == 0 {
  98. start = 0
  99. } else {
  100. start = (opts.Page - 1) * opts.PageSize
  101. }
  102. sess.Limit(opts.PageSize, start)
  103. }
  104. return sess
  105. }
  106. func applyLabelsCondition(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  107. if len(opts.LabelIDs) > 0 {
  108. if opts.LabelIDs[0] == 0 {
  109. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label)")
  110. } else {
  111. for i, labelID := range opts.LabelIDs {
  112. if labelID > 0 {
  113. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  114. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  115. } else if labelID < 0 { // 0 is not supported here, so just ignore it
  116. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  117. }
  118. }
  119. }
  120. }
  121. if len(opts.IncludedLabelNames) > 0 {
  122. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  123. }
  124. if len(opts.ExcludedLabelNames) > 0 {
  125. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  126. }
  127. return sess
  128. }
  129. func applyMilestoneCondition(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  130. if len(opts.MilestoneIDs) == 1 && opts.MilestoneIDs[0] == db.NoConditionID {
  131. sess.And("issue.milestone_id = 0")
  132. } else if len(opts.MilestoneIDs) > 0 {
  133. sess.In("issue.milestone_id", opts.MilestoneIDs)
  134. }
  135. if len(opts.IncludeMilestones) > 0 {
  136. sess.In("issue.milestone_id",
  137. builder.Select("id").
  138. From("milestone").
  139. Where(builder.In("name", opts.IncludeMilestones)))
  140. }
  141. return sess
  142. }
  143. func applyProjectCondition(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  144. if opts.ProjectID > 0 { // specific project
  145. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  146. And("project_issue.project_id=?", opts.ProjectID)
  147. } else if opts.ProjectID == db.NoConditionID { // show those that are in no project
  148. sess.And(builder.NotIn("issue.id", builder.Select("issue_id").From("project_issue").And(builder.Neq{"project_id": 0})))
  149. }
  150. // opts.ProjectID == 0 means all projects,
  151. // do not need to apply any condition
  152. return sess
  153. }
  154. func applyRepoConditions(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  155. if len(opts.RepoIDs) == 1 {
  156. opts.RepoCond = builder.Eq{"issue.repo_id": opts.RepoIDs[0]}
  157. } else if len(opts.RepoIDs) > 1 {
  158. opts.RepoCond = builder.In("issue.repo_id", opts.RepoIDs)
  159. }
  160. if opts.RepoCond != nil {
  161. sess.And(opts.RepoCond)
  162. }
  163. return sess
  164. }
  165. func applyConditions(sess *xorm.Session, opts *IssuesOptions) *xorm.Session {
  166. if len(opts.IssueIDs) > 0 {
  167. sess.In("issue.id", opts.IssueIDs)
  168. }
  169. applyRepoConditions(sess, opts)
  170. if !opts.IsClosed.IsNone() {
  171. sess.And("issue.is_closed=?", opts.IsClosed.IsTrue())
  172. }
  173. if opts.AssigneeID > 0 {
  174. applyAssigneeCondition(sess, opts.AssigneeID)
  175. } else if opts.AssigneeID == db.NoConditionID {
  176. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_assignees)")
  177. }
  178. if opts.PosterID > 0 {
  179. applyPosterCondition(sess, opts.PosterID)
  180. }
  181. if opts.MentionedID > 0 {
  182. applyMentionedCondition(sess, opts.MentionedID)
  183. }
  184. if opts.ReviewRequestedID > 0 {
  185. applyReviewRequestedCondition(sess, opts.ReviewRequestedID)
  186. }
  187. if opts.ReviewedID > 0 {
  188. applyReviewedCondition(sess, opts.ReviewedID)
  189. }
  190. if opts.SubscriberID > 0 {
  191. applySubscribedCondition(sess, opts.SubscriberID)
  192. }
  193. applyMilestoneCondition(sess, opts)
  194. if opts.UpdatedAfterUnix != 0 {
  195. sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix})
  196. }
  197. if opts.UpdatedBeforeUnix != 0 {
  198. sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix})
  199. }
  200. applyProjectCondition(sess, opts)
  201. if opts.ProjectBoardID != 0 {
  202. if opts.ProjectBoardID > 0 {
  203. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID}))
  204. } else {
  205. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  206. }
  207. }
  208. switch opts.IsPull {
  209. case util.OptionalBoolTrue:
  210. sess.And("issue.is_pull=?", true)
  211. case util.OptionalBoolFalse:
  212. sess.And("issue.is_pull=?", false)
  213. }
  214. if opts.IsArchived != util.OptionalBoolNone {
  215. sess.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()})
  216. }
  217. applyLabelsCondition(sess, opts)
  218. if opts.User != nil {
  219. sess.And(issuePullAccessibleRepoCond("issue.repo_id", opts.User.ID, opts.Org, opts.Team, opts.IsPull.IsTrue()))
  220. }
  221. return sess
  222. }
  223. // teamUnitsRepoCond returns query condition for those repo id in the special org team with special units access
  224. func teamUnitsRepoCond(id string, userID, orgID, teamID int64, units ...unit.Type) builder.Cond {
  225. return builder.In(id,
  226. builder.Select("repo_id").From("team_repo").Where(
  227. builder.Eq{
  228. "team_id": teamID,
  229. }.And(
  230. builder.Or(
  231. // Check if the user is member of the team.
  232. builder.In(
  233. "team_id", builder.Select("team_id").From("team_user").Where(
  234. builder.Eq{
  235. "uid": userID,
  236. },
  237. ),
  238. ),
  239. // Check if the user is in the owner team of the organisation.
  240. builder.Exists(builder.Select("team_id").From("team_user").
  241. Where(builder.Eq{
  242. "org_id": orgID,
  243. "team_id": builder.Select("id").From("team").Where(
  244. builder.Eq{
  245. "org_id": orgID,
  246. "lower_name": strings.ToLower(organization.OwnerTeamName),
  247. }),
  248. "uid": userID,
  249. }),
  250. ),
  251. )).And(
  252. builder.In(
  253. "team_id", builder.Select("team_id").From("team_unit").Where(
  254. builder.Eq{
  255. "`team_unit`.org_id": orgID,
  256. }.And(
  257. builder.In("`team_unit`.type", units),
  258. ),
  259. ),
  260. ),
  261. ),
  262. ))
  263. }
  264. // issuePullAccessibleRepoCond userID must not be zero, this condition require join repository table
  265. func issuePullAccessibleRepoCond(repoIDstr string, userID int64, org *organization.Organization, team *organization.Team, isPull bool) builder.Cond {
  266. cond := builder.NewCond()
  267. unitType := unit.TypeIssues
  268. if isPull {
  269. unitType = unit.TypePullRequests
  270. }
  271. if org != nil {
  272. if team != nil {
  273. cond = cond.And(teamUnitsRepoCond(repoIDstr, userID, org.ID, team.ID, unitType)) // special team member repos
  274. } else {
  275. cond = cond.And(
  276. builder.Or(
  277. repo_model.UserOrgUnitRepoCond(repoIDstr, userID, org.ID, unitType), // team member repos
  278. repo_model.UserOrgPublicUnitRepoCond(userID, org.ID), // user org public non-member repos, TODO: check repo has issues
  279. ),
  280. )
  281. }
  282. } else {
  283. cond = cond.And(
  284. builder.Or(
  285. repo_model.UserOwnedRepoCond(userID), // owned repos
  286. repo_model.UserAccessRepoCond(repoIDstr, userID), // user can access repo in a unit independent way
  287. repo_model.UserAssignedRepoCond(repoIDstr, userID), // user has been assigned accessible public repos
  288. repo_model.UserMentionedRepoCond(repoIDstr, userID), // user has been mentioned accessible public repos
  289. repo_model.UserCreateIssueRepoCond(repoIDstr, userID, isPull), // user has created issue/pr accessible public repos
  290. ),
  291. )
  292. }
  293. return cond
  294. }
  295. func applyAssigneeCondition(sess *xorm.Session, assigneeID int64) *xorm.Session {
  296. return sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  297. And("issue_assignees.assignee_id = ?", assigneeID)
  298. }
  299. func applyPosterCondition(sess *xorm.Session, posterID int64) *xorm.Session {
  300. return sess.And("issue.poster_id=?", posterID)
  301. }
  302. func applyMentionedCondition(sess *xorm.Session, mentionedID int64) *xorm.Session {
  303. return sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  304. And("issue_user.is_mentioned = ?", true).
  305. And("issue_user.uid = ?", mentionedID)
  306. }
  307. func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64) *xorm.Session {
  308. return sess.Join("INNER", []string{"review", "r"}, "issue.id = r.issue_id").
  309. And("issue.poster_id <> ?", reviewRequestedID).
  310. And("r.type = ?", ReviewTypeRequest).
  311. And("r.reviewer_id = ? and r.id in (select max(id) from review where issue_id = r.issue_id and reviewer_id = r.reviewer_id and type in (?, ?, ?))"+
  312. " or r.reviewer_team_id in (select team_id from team_user where uid = ?)",
  313. reviewRequestedID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest, reviewRequestedID)
  314. }
  315. func applyReviewedCondition(sess *xorm.Session, reviewedID int64) *xorm.Session {
  316. // Query for pull requests where you are a reviewer or commenter, excluding
  317. // any pull requests already returned by the the review requested filter.
  318. notPoster := builder.Neq{"issue.poster_id": reviewedID}
  319. reviewed := builder.In("issue.id", builder.
  320. Select("issue_id").
  321. From("review").
  322. Where(builder.And(
  323. builder.Neq{"type": ReviewTypeRequest},
  324. builder.Or(
  325. builder.Eq{"reviewer_id": reviewedID},
  326. builder.In("reviewer_team_id", builder.
  327. Select("team_id").
  328. From("team_user").
  329. Where(builder.Eq{"uid": reviewedID}),
  330. ),
  331. ),
  332. )),
  333. )
  334. commented := builder.In("issue.id", builder.
  335. Select("issue_id").
  336. From("comment").
  337. Where(builder.And(
  338. builder.Eq{"poster_id": reviewedID},
  339. builder.In("type", CommentTypeComment, CommentTypeCode, CommentTypeReview),
  340. )),
  341. )
  342. return sess.And(notPoster, builder.Or(reviewed, commented))
  343. }
  344. func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Session {
  345. return sess.And(
  346. builder.
  347. NotIn("issue.id",
  348. builder.Select("issue_id").
  349. From("issue_watch").
  350. Where(builder.Eq{"is_watching": false, "user_id": subscriberID}),
  351. ),
  352. ).And(
  353. builder.Or(
  354. builder.In("issue.id", builder.
  355. Select("issue_id").
  356. From("issue_watch").
  357. Where(builder.Eq{"is_watching": true, "user_id": subscriberID}),
  358. ),
  359. builder.In("issue.id", builder.
  360. Select("issue_id").
  361. From("comment").
  362. Where(builder.Eq{"poster_id": subscriberID}),
  363. ),
  364. builder.Eq{"issue.poster_id": subscriberID},
  365. builder.In("issue.repo_id", builder.
  366. Select("id").
  367. From("watch").
  368. Where(builder.And(builder.Eq{"user_id": subscriberID},
  369. builder.In("mode", repo_model.WatchModeNormal, repo_model.WatchModeAuto))),
  370. ),
  371. ),
  372. )
  373. }
  374. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  375. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]int64, error) {
  376. repoIDs := make([]int64, 0, 5)
  377. e := db.GetEngine(db.DefaultContext)
  378. sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  379. applyConditions(sess, opts)
  380. accessCond := repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)
  381. if err := sess.Where(accessCond).
  382. Distinct("issue.repo_id").
  383. Table("issue").
  384. Find(&repoIDs); err != nil {
  385. return nil, fmt.Errorf("unable to GetRepoIDsForIssuesOptions: %w", err)
  386. }
  387. return repoIDs, nil
  388. }
  389. // Issues returns a list of issues by given conditions.
  390. func Issues(ctx context.Context, opts *IssuesOptions) ([]*Issue, error) {
  391. sess := db.GetEngine(ctx).
  392. Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  393. applyLimit(sess, opts)
  394. applyConditions(sess, opts)
  395. applySorts(sess, opts.SortType, opts.PriorityRepoID)
  396. issues := make(IssueList, 0, opts.ListOptions.PageSize)
  397. if err := sess.Find(&issues); err != nil {
  398. return nil, fmt.Errorf("unable to query Issues: %w", err)
  399. }
  400. if err := issues.LoadAttributes(); err != nil {
  401. return nil, fmt.Errorf("unable to LoadAttributes for Issues: %w", err)
  402. }
  403. return issues, nil
  404. }
  405. // SearchIssueIDsByKeyword search issues on database
  406. func SearchIssueIDsByKeyword(ctx context.Context, kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  407. repoCond := builder.In("repo_id", repoIDs)
  408. subQuery := builder.Select("id").From("issue").Where(repoCond)
  409. cond := builder.And(
  410. repoCond,
  411. builder.Or(
  412. db.BuildCaseInsensitiveLike("name", kw),
  413. db.BuildCaseInsensitiveLike("content", kw),
  414. builder.In("id", builder.Select("issue_id").
  415. From("comment").
  416. Where(builder.And(
  417. builder.Eq{"type": CommentTypeComment},
  418. builder.In("issue_id", subQuery),
  419. db.BuildCaseInsensitiveLike("content", kw),
  420. )),
  421. ),
  422. ),
  423. )
  424. ids := make([]int64, 0, limit)
  425. res := make([]struct {
  426. ID int64
  427. UpdatedUnix int64
  428. }, 0, limit)
  429. err := db.GetEngine(ctx).Distinct("id", "updated_unix").Table("issue").Where(cond).
  430. OrderBy("`updated_unix` DESC").Limit(limit, start).
  431. Find(&res)
  432. if err != nil {
  433. return 0, nil, err
  434. }
  435. for _, r := range res {
  436. ids = append(ids, r.ID)
  437. }
  438. total, err := db.GetEngine(ctx).Distinct("id").Table("issue").Where(cond).Count()
  439. if err != nil {
  440. return 0, nil, err
  441. }
  442. return total, ids, nil
  443. }