本站源代码
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.

360 lines
11KB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/modules/structs"
  9. "code.gitea.io/gitea/modules/util"
  10. "xorm.io/builder"
  11. )
  12. // RepositoryListDefaultPageSize is the default number of repositories
  13. // to load in memory when running administrative tasks on all (or almost
  14. // all) of them.
  15. // The number should be low enough to avoid filling up all RAM with
  16. // repository data...
  17. const RepositoryListDefaultPageSize = 64
  18. // RepositoryList contains a list of repositories
  19. type RepositoryList []*Repository
  20. func (repos RepositoryList) Len() int {
  21. return len(repos)
  22. }
  23. func (repos RepositoryList) Less(i, j int) bool {
  24. return repos[i].FullName() < repos[j].FullName()
  25. }
  26. func (repos RepositoryList) Swap(i, j int) {
  27. repos[i], repos[j] = repos[j], repos[i]
  28. }
  29. // RepositoryListOfMap make list from values of map
  30. func RepositoryListOfMap(repoMap map[int64]*Repository) RepositoryList {
  31. return RepositoryList(valuesRepository(repoMap))
  32. }
  33. func (repos RepositoryList) loadAttributes(e Engine) error {
  34. if len(repos) == 0 {
  35. return nil
  36. }
  37. // Load owners.
  38. set := make(map[int64]struct{})
  39. for i := range repos {
  40. set[repos[i].OwnerID] = struct{}{}
  41. }
  42. users := make(map[int64]*User, len(set))
  43. if err := e.
  44. Where("id > 0").
  45. In("id", keysInt64(set)).
  46. Find(&users); err != nil {
  47. return fmt.Errorf("find users: %v", err)
  48. }
  49. for i := range repos {
  50. repos[i].Owner = users[repos[i].OwnerID]
  51. }
  52. return nil
  53. }
  54. // LoadAttributes loads the attributes for the given RepositoryList
  55. func (repos RepositoryList) LoadAttributes() error {
  56. return repos.loadAttributes(x)
  57. }
  58. // MirrorRepositoryList contains the mirror repositories
  59. type MirrorRepositoryList []*Repository
  60. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  61. if len(repos) == 0 {
  62. return nil
  63. }
  64. // Load mirrors.
  65. repoIDs := make([]int64, 0, len(repos))
  66. for i := range repos {
  67. if !repos[i].IsMirror {
  68. continue
  69. }
  70. repoIDs = append(repoIDs, repos[i].ID)
  71. }
  72. mirrors := make([]*Mirror, 0, len(repoIDs))
  73. if err := e.
  74. Where("id > 0").
  75. In("repo_id", repoIDs).
  76. Find(&mirrors); err != nil {
  77. return fmt.Errorf("find mirrors: %v", err)
  78. }
  79. set := make(map[int64]*Mirror)
  80. for i := range mirrors {
  81. set[mirrors[i].RepoID] = mirrors[i]
  82. }
  83. for i := range repos {
  84. repos[i].Mirror = set[repos[i].ID]
  85. }
  86. return nil
  87. }
  88. // LoadAttributes loads the attributes for the given MirrorRepositoryList
  89. func (repos MirrorRepositoryList) LoadAttributes() error {
  90. return repos.loadAttributes(x)
  91. }
  92. // SearchRepoOptions holds the search options
  93. type SearchRepoOptions struct {
  94. UserID int64
  95. UserIsAdmin bool
  96. Keyword string
  97. OwnerID int64
  98. OrderBy SearchOrderBy
  99. Private bool // Include private repositories in results
  100. StarredByID int64
  101. Page int
  102. IsProfile bool
  103. AllPublic bool // Include also all public repositories
  104. AllPrivate bool //开放所有所有私有库
  105. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  106. // None -> include collaborative AND non-collaborative
  107. // True -> include just collaborative
  108. // False -> incude just non-collaborative
  109. Collaborate util.OptionalBool
  110. // None -> include forks AND non-forks
  111. // True -> include just forks
  112. // False -> include just non-forks
  113. Fork util.OptionalBool
  114. // None -> include mirrors AND non-mirrors
  115. // True -> include just mirrors
  116. // False -> include just non-mirrors
  117. Mirror util.OptionalBool
  118. // only search topic name
  119. TopicOnly bool
  120. // include description in keyword search
  121. IncludeDescription bool
  122. }
  123. //SearchOrderBy is used to sort the result
  124. type SearchOrderBy string
  125. func (s SearchOrderBy) String() string {
  126. return string(s)
  127. }
  128. // Strings for sorting result
  129. const (
  130. SearchOrderByAlphabetically SearchOrderBy = "name ASC"
  131. SearchOrderByAlphabeticallyReverse SearchOrderBy = "name DESC"
  132. SearchOrderByLeastUpdated SearchOrderBy = "updated_unix ASC"
  133. SearchOrderByRecentUpdated SearchOrderBy = "updated_unix DESC"
  134. SearchOrderByOldest SearchOrderBy = "created_unix ASC"
  135. SearchOrderByNewest SearchOrderBy = "created_unix DESC"
  136. SearchOrderBySize SearchOrderBy = "size ASC"
  137. SearchOrderBySizeReverse SearchOrderBy = "size DESC"
  138. SearchOrderByID SearchOrderBy = "id ASC"
  139. SearchOrderByIDReverse SearchOrderBy = "id DESC"
  140. SearchOrderByStars SearchOrderBy = "num_stars ASC"
  141. SearchOrderByStarsReverse SearchOrderBy = "num_stars DESC"
  142. SearchOrderByForks SearchOrderBy = "num_forks ASC"
  143. SearchOrderByForksReverse SearchOrderBy = "num_forks DESC"
  144. SearchOrderByPoint SearchOrderBy = "Point DESC"
  145. )
  146. // SearchRepository returns repositories based on search options,
  147. // it returns results in given range and number of total results.
  148. func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  149. if opts.Page <= 0 {
  150. opts.Page = 1
  151. }
  152. var cond = builder.NewCond()
  153. if opts.Private {
  154. if !opts.UserIsAdmin && opts.UserID != 0 && opts.UserID != opts.OwnerID {
  155. // OK we're in the context of a User
  156. cond = cond.And(accessibleRepositoryCondition(opts.UserID))
  157. }
  158. } else {
  159. // Not looking at private organisations
  160. // We should be able to see all non-private repositories that either:
  161. cond = cond.And(builder.Eq{"is_private": false})
  162. accessCond := builder.Or(
  163. // A. Aren't in organisations __OR__
  164. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})),
  165. // B. Isn't a private or limited organisation.
  166. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Or(builder.Eq{"visibility": structs.VisibleTypeLimited}, builder.Eq{"visibility": structs.VisibleTypePrivate}))))
  167. cond = cond.And(accessCond)
  168. }
  169. // Restrict to starred repositories
  170. if opts.StarredByID > 0 {
  171. cond = cond.And(builder.In("id", builder.Select("repo_id").From("star").Where(builder.Eq{"uid": opts.StarredByID})))
  172. }
  173. // Restrict repositories to those the OwnerID owns or contributes to as per opts.Collaborate
  174. if opts.OwnerID > 0 {
  175. var accessCond = builder.NewCond()
  176. if opts.Collaborate != util.OptionalBoolTrue {
  177. accessCond = builder.Eq{"owner_id": opts.OwnerID}
  178. }
  179. if opts.Collaborate != util.OptionalBoolFalse {
  180. collaborateCond := builder.And(
  181. builder.Or(
  182. builder.Expr("repository.id IN (SELECT repo_id FROM `access` WHERE access.user_id = ?)", opts.OwnerID),
  183. builder.In("id", builder.Select("`team_repo`.repo_id").
  184. From("team_repo").
  185. Where(builder.Eq{"`team_user`.uid": opts.OwnerID}).
  186. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id"))),
  187. builder.Neq{"owner_id": opts.OwnerID})
  188. if !opts.Private {
  189. collaborateCond = collaborateCond.And(builder.Expr("owner_id NOT IN (SELECT org_id FROM org_user WHERE org_user.uid = ? AND org_user.is_public = ?)", opts.OwnerID, false))
  190. }
  191. accessCond = accessCond.Or(collaborateCond)
  192. }
  193. if opts.AllPublic {
  194. accessCond = accessCond.Or(builder.Eq{"is_private": false})
  195. }
  196. //开放私有库
  197. if opts.AllPrivate {
  198. accessCond = accessCond.Or(builder.Eq{"is_private": true})
  199. }
  200. cond = cond.And(accessCond)
  201. }
  202. if opts.Keyword != "" {
  203. // separate keyword
  204. var subQueryCond = builder.NewCond()
  205. for _, v := range strings.Split(opts.Keyword, ",") {
  206. if opts.TopicOnly {
  207. subQueryCond = subQueryCond.Or(builder.Eq{"topic.name": strings.ToLower(v)})
  208. } else {
  209. subQueryCond = subQueryCond.Or(builder.Like{"topic.name", strings.ToLower(v)})
  210. }
  211. }
  212. subQuery := builder.Select("repo_topic.repo_id").From("repo_topic").
  213. Join("INNER", "topic", "topic.id = repo_topic.topic_id").
  214. Where(subQueryCond).
  215. GroupBy("repo_topic.repo_id")
  216. var keywordCond = builder.In("id", subQuery)
  217. if !opts.TopicOnly {
  218. var likes = builder.NewCond()
  219. for _, v := range strings.Split(opts.Keyword, ",") {
  220. likes = likes.Or(builder.Like{"lower_name", strings.ToLower(v)})
  221. if opts.IncludeDescription {
  222. likes = likes.Or(builder.Like{"LOWER(description)", strings.ToLower(v)})
  223. }
  224. }
  225. keywordCond = keywordCond.Or(likes)
  226. }
  227. cond = cond.And(keywordCond)
  228. }
  229. if opts.Fork != util.OptionalBoolNone {
  230. cond = cond.And(builder.Eq{"is_fork": opts.Fork == util.OptionalBoolTrue})
  231. }
  232. if opts.Mirror != util.OptionalBoolNone {
  233. cond = cond.And(builder.Eq{"is_mirror": opts.Mirror == util.OptionalBoolTrue})
  234. }
  235. if len(opts.OrderBy) == 0 {
  236. opts.OrderBy = SearchOrderByAlphabetically
  237. }
  238. sess := x.NewSession()
  239. defer sess.Close()
  240. count, err := sess.
  241. Where(cond).
  242. Count(new(Repository))
  243. if err != nil {
  244. return nil, 0, fmt.Errorf("Count: %v", err)
  245. }
  246. repos := make(RepositoryList, 0, opts.PageSize)
  247. if err = sess.
  248. Where(cond).
  249. OrderBy(opts.OrderBy.String()).
  250. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  251. Find(&repos); err != nil {
  252. return nil, 0, fmt.Errorf("Repo: %v", err)
  253. }
  254. if !opts.IsProfile {
  255. if err = repos.loadAttributes(sess); err != nil {
  256. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  257. }
  258. }
  259. return repos, count, nil
  260. }
  261. // accessibleRepositoryCondition takes a user a returns a condition for checking if a repository is accessible
  262. func accessibleRepositoryCondition(userID int64) builder.Cond {
  263. return builder.Or(
  264. // 1. Be able to see all non-private repositories that either:
  265. builder.And(
  266. builder.Eq{"`repository`.is_private": false},
  267. builder.Or(
  268. // A. Aren't in organisations __OR__
  269. builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})),
  270. // B. Isn't a private organisation. (Limited is OK because we're logged in)
  271. builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"visibility": structs.VisibleTypePrivate}))),
  272. ),
  273. // 2. Be able to see all repositories that we have access to
  274. builder.In("`repository`.id", builder.Select("repo_id").
  275. From("`access`").
  276. Where(builder.And(
  277. builder.Eq{"user_id": userID},
  278. builder.Gt{"mode": int(AccessModeNone)}))),
  279. // 3. Be able to see all repositories that we are in a team
  280. builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").
  281. From("team_repo").
  282. Where(builder.Eq{"`team_user`.uid": userID}).
  283. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id")))
  284. }
  285. // SearchRepositoryByName takes keyword and part of repository name to search,
  286. // it returns results in given range and number of total results.
  287. func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  288. opts.IncludeDescription = false
  289. return SearchRepository(opts)
  290. }
  291. // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id
  292. func FindUserAccessibleRepoIDs(userID int64) ([]int64, error) {
  293. var accessCond builder.Cond = builder.Eq{"is_private": false}
  294. if userID > 0 {
  295. accessCond = accessCond.Or(
  296. builder.Eq{"owner_id": userID},
  297. builder.And(
  298. builder.Expr("id IN (SELECT repo_id FROM `access` WHERE access.user_id = ?)", userID),
  299. builder.Neq{"owner_id": userID},
  300. ),
  301. )
  302. }
  303. repoIDs := make([]int64, 0, 10)
  304. if err := x.
  305. Table("repository").
  306. Cols("id").
  307. Where(accessCond).
  308. Find(&repoIDs); err != nil {
  309. return nil, fmt.Errorf("FindUserAccesibleRepoIDs: %v", err)
  310. }
  311. return repoIDs, nil
  312. }
上海开阖软件有限公司 沪ICP备12045867号-1