You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

home.go 16 kB

11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
3 years ago
4 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
10 years ago
3 years ago
10 years ago
10 years ago
3 years ago
3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
10 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 routers
  6. import (
  7. "bytes"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. code_indexer "code.gitea.io/gitea/modules/indexer/code"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/structs"
  19. "code.gitea.io/gitea/modules/util"
  20. "code.gitea.io/gitea/routers/user"
  21. )
  22. const (
  23. // tplHome home page template
  24. tplHome base.TplName = "home"
  25. // tplExploreRepos explore repositories page template
  26. tplExploreRepos base.TplName = "explore/repos"
  27. // tplExploreDataset explore datasets page template
  28. tplExploreDataset base.TplName = "explore/datasets"
  29. // tplExploreUsers explore users page template
  30. tplExploreUsers base.TplName = "explore/users"
  31. // tplExploreOrganizations explore organizations page template
  32. tplExploreOrganizations base.TplName = "explore/organizations"
  33. // tplExploreCode explore code page template
  34. tplExploreCode base.TplName = "explore/code"
  35. tplExploreImages base.TplName = "explore/images"
  36. tplExploreExploreDataAnalysis base.TplName = "explore/data_analysis"
  37. )
  38. // Home render home page
  39. func Home(ctx *context.Context) {
  40. ctx.Data["PageIsHome"] = true
  41. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  42. ctx.HTML(200, tplHome)
  43. }
  44. func Dashboard(ctx *context.Context) {
  45. if ctx.IsSigned {
  46. if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  47. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  48. ctx.HTML(200, user.TplActivate)
  49. } else if !ctx.User.IsActive || ctx.User.ProhibitLogin {
  50. log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
  51. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  52. ctx.HTML(200, "user/auth/prohibit_login")
  53. } else if ctx.User.MustChangePassword {
  54. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  55. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  56. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  57. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  58. } else {
  59. user.Dashboard(ctx)
  60. }
  61. return
  62. // Check non-logged users landing page.
  63. } else if setting.LandingPageURL != setting.LandingPageHome {
  64. ctx.Redirect(setting.AppSubURL + string(setting.LandingPageURL))
  65. return
  66. }
  67. // Check auto-login.
  68. uname := ctx.GetCookie(setting.CookieUserName)
  69. if len(uname) != 0 {
  70. ctx.Redirect(setting.AppSubURL + "/user/login")
  71. return
  72. }
  73. ctx.Data["PageIsHome"] = true
  74. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  75. ctx.HTML(200, tplHome)
  76. }
  77. // RepoSearchOptions when calling search repositories
  78. type RepoSearchOptions struct {
  79. OwnerID int64
  80. Private bool
  81. Restricted bool
  82. PageSize int
  83. TplName base.TplName
  84. }
  85. var (
  86. nullByte = []byte{0x00}
  87. )
  88. func isKeywordValid(keyword string) bool {
  89. return !bytes.Contains([]byte(keyword), nullByte)
  90. }
  91. // RenderRepoSearch render repositories search page
  92. func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
  93. page := ctx.QueryInt("page")
  94. if page <= 0 {
  95. page = 1
  96. }
  97. var (
  98. repos []*models.Repository
  99. count int64
  100. err error
  101. orderBy models.SearchOrderBy
  102. )
  103. ctx.Data["SortType"] = ctx.Query("sort")
  104. switch ctx.Query("sort") {
  105. case "newest":
  106. orderBy = models.SearchOrderByNewest
  107. case "oldest":
  108. orderBy = models.SearchOrderByOldest
  109. case "recentupdate":
  110. orderBy = models.SearchOrderByRecentUpdated
  111. case "leastupdate":
  112. orderBy = models.SearchOrderByLeastUpdated
  113. case "reversealphabetically":
  114. orderBy = models.SearchOrderByAlphabeticallyReverse
  115. case "alphabetically":
  116. orderBy = models.SearchOrderByAlphabetically
  117. case "reversesize":
  118. orderBy = models.SearchOrderBySizeReverse
  119. case "size":
  120. orderBy = models.SearchOrderBySize
  121. case "moststars":
  122. orderBy = models.SearchOrderByStarsReverse
  123. case "feweststars":
  124. orderBy = models.SearchOrderByStars
  125. case "mostforks":
  126. orderBy = models.SearchOrderByForksReverse
  127. case "fewestforks":
  128. orderBy = models.SearchOrderByForks
  129. case "hot":
  130. orderBy = models.SearchOrderByHot
  131. case "active":
  132. orderBy = models.SearchOrderByActive
  133. default:
  134. ctx.Data["SortType"] = "hot"
  135. orderBy = models.SearchOrderByHot
  136. }
  137. orderBy = orderBy + ",id"
  138. //todo:support other topics
  139. keyword := strings.Trim(ctx.Query("q"), " ")
  140. topic := strings.Trim(ctx.Query("topic"), " ")
  141. repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
  142. ListOptions: models.ListOptions{
  143. Page: page,
  144. PageSize: opts.PageSize,
  145. },
  146. Actor: ctx.User,
  147. OrderBy: orderBy,
  148. Private: opts.Private,
  149. Keyword: keyword,
  150. OwnerID: opts.OwnerID,
  151. AllPublic: true,
  152. AllLimited: true,
  153. TopicName: topic,
  154. IncludeDescription: setting.UI.SearchRepoDescription,
  155. })
  156. if err != nil {
  157. ctx.ServerError("SearchRepository", err)
  158. return
  159. }
  160. for _, repo := range repos {
  161. repo.Hot = int64(repo.NumWatches) + int64(repo.NumStars) + int64(repo.NumForks) + int64(repo.CloneCnt)
  162. repo.Active = int64(repo.NumIssues) + int64(repo.NumPulls) + int64(repo.NumCommit)
  163. }
  164. ctx.Data["Keyword"] = keyword
  165. ctx.Data["Topic"] = topic
  166. ctx.Data["Total"] = count
  167. ctx.Data["Repos"] = repos
  168. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  169. pager := context.NewPagination(int(count), opts.PageSize, page, 5)
  170. pager.SetDefaultParams(ctx)
  171. pager.AddParam(ctx, "topic", "TopicOnly")
  172. ctx.Data["Page"] = pager
  173. recommendOrgs, err := models.GetRecommendOrgInfos()
  174. if err != nil {
  175. log.Error("GetRecommendOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  176. ctx.ServerError("GetRecommendOrgInfos", err)
  177. return
  178. }
  179. ctx.Data["RecommendOrgs"] = recommendOrgs
  180. ctx.HTML(http.StatusOK, opts.TplName)
  181. }
  182. // ExploreRepos render explore repositories page
  183. func ExploreRepos(ctx *context.Context) {
  184. ctx.Data["Title"] = ctx.Tr("explore")
  185. ctx.Data["PageIsExplore"] = true
  186. ctx.Data["PageIsExploreRepositories"] = true
  187. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  188. var ownerID int64
  189. if ctx.User != nil && !ctx.User.IsAdmin {
  190. ownerID = ctx.User.ID
  191. }
  192. RenderRepoSearch(ctx, &RepoSearchOptions{
  193. PageSize: setting.UI.ExplorePagingNum,
  194. OwnerID: ownerID,
  195. Private: ctx.User != nil,
  196. TplName: tplExploreRepos,
  197. })
  198. }
  199. func ExploreDatasets(ctx *context.Context) {
  200. ctx.Data["Title"] = ctx.Tr("explore")
  201. ctx.Data["PageIsExplore"] = true
  202. ctx.Data["PageIsExploreDatasets"] = true
  203. // ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  204. var (
  205. datasets []*models.Dataset
  206. count int64
  207. err error
  208. orderBy models.SearchOrderBy
  209. )
  210. page := ctx.QueryInt("page")
  211. if page <= 0 {
  212. page = 1
  213. }
  214. ctx.Data["SortType"] = ctx.Query("sort")
  215. switch ctx.Query("sort") {
  216. case "newest":
  217. orderBy = models.SearchOrderByNewest
  218. case "oldest":
  219. orderBy = models.SearchOrderByOldest
  220. case "recentupdate":
  221. orderBy = models.SearchOrderByRecentUpdated
  222. case "leastupdate":
  223. orderBy = models.SearchOrderByLeastUpdated
  224. case "reversealphabetically":
  225. orderBy = models.SearchOrderByAlphabeticallyReverse
  226. case "alphabetically":
  227. orderBy = models.SearchOrderByAlphabetically
  228. case "reversesize":
  229. orderBy = models.SearchOrderBySizeReverse
  230. case "downloadtimes":
  231. orderBy = models.SearchOrderByDownloadTimes
  232. default:
  233. ctx.Data["SortType"] = "recentupdate"
  234. orderBy = models.SearchOrderByRecentUpdated
  235. }
  236. keyword := strings.Trim(ctx.Query("q"), " ")
  237. var ownerID int64
  238. if ctx.User != nil && !ctx.User.IsAdmin {
  239. ownerID = ctx.User.ID
  240. }
  241. opts := &models.SearchDatasetOptions{
  242. Keyword: keyword,
  243. IncludePublic: true,
  244. SearchOrderBy: orderBy,
  245. OwnerID: ownerID,
  246. ListOptions: models.ListOptions{
  247. Page: page,
  248. PageSize: setting.UI.ExplorePagingNum,
  249. },
  250. }
  251. datasets, count, err = models.SearchDataset(opts)
  252. if err != nil {
  253. ctx.ServerError("SearchDatasets", err)
  254. return
  255. }
  256. pager := context.NewPagination(int(count), opts.PageSize, page, 5)
  257. ctx.Data["Keyword"] = opts.Keyword
  258. pager.SetDefaultParams(ctx)
  259. ctx.Data["Page"] = pager
  260. ctx.Data["Datasets"] = datasets
  261. ctx.Data["Total"] = count
  262. ctx.Data["PageIsDatasets"] = true
  263. ctx.HTML(200, tplExploreDataset)
  264. }
  265. // RenderUserSearch render user search page
  266. func RenderUserSearch(ctx *context.Context, opts *models.SearchUserOptions, tplName base.TplName) {
  267. opts.Page = ctx.QueryInt("page")
  268. if opts.Page <= 1 {
  269. opts.Page = 1
  270. }
  271. var (
  272. users []*models.User
  273. count int64
  274. err error
  275. orderBy models.SearchOrderBy
  276. )
  277. ctx.Data["SortType"] = ctx.Query("sort")
  278. switch ctx.Query("sort") {
  279. case "newest":
  280. orderBy = models.SearchOrderByIDReverse
  281. case "oldest":
  282. orderBy = models.SearchOrderByID
  283. case "recentupdate":
  284. orderBy = models.SearchOrderByRecentUpdated
  285. case "leastupdate":
  286. orderBy = models.SearchOrderByLeastUpdated
  287. case "reversealphabetically":
  288. orderBy = models.SearchOrderByAlphabeticallyReverse
  289. case "alphabetically":
  290. orderBy = models.SearchOrderByAlphabetically
  291. default:
  292. ctx.Data["SortType"] = "alphabetically"
  293. orderBy = models.SearchOrderByAlphabetically
  294. }
  295. opts.Keyword = strings.Trim(ctx.Query("q"), " ")
  296. opts.OrderBy = orderBy
  297. if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) {
  298. users, count, err = models.SearchUsers(opts)
  299. if err != nil {
  300. ctx.ServerError("SearchUsers", err)
  301. return
  302. }
  303. }
  304. ctx.Data["Keyword"] = opts.Keyword
  305. ctx.Data["Total"] = count
  306. ctx.Data["Users"] = users
  307. ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail
  308. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  309. pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
  310. pager.SetDefaultParams(ctx)
  311. ctx.Data["Page"] = pager
  312. ctx.HTML(200, tplName)
  313. }
  314. // ExploreUsers render explore users page
  315. func ExploreUsers(ctx *context.Context) {
  316. ctx.Data["Title"] = ctx.Tr("explore")
  317. ctx.Data["PageIsExplore"] = true
  318. ctx.Data["PageIsExploreUsers"] = true
  319. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  320. RenderUserSearch(ctx, &models.SearchUserOptions{
  321. Actor: ctx.User,
  322. Type: models.UserTypeIndividual,
  323. ListOptions: models.ListOptions{PageSize: setting.UI.ExplorePagingNum},
  324. IsActive: util.OptionalBoolTrue,
  325. Visible: []structs.VisibleType{structs.VisibleTypePublic, structs.VisibleTypeLimited, structs.VisibleTypePrivate},
  326. }, tplExploreUsers)
  327. }
  328. // ExploreOrganizations render explore organizations page
  329. func ExploreOrganizations(ctx *context.Context) {
  330. ctx.Data["Title"] = ctx.Tr("explore")
  331. ctx.Data["PageIsExplore"] = true
  332. ctx.Data["PageIsExploreOrganizations"] = true
  333. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  334. visibleTypes := []structs.VisibleType{structs.VisibleTypePublic}
  335. if ctx.User != nil {
  336. visibleTypes = append(visibleTypes, structs.VisibleTypeLimited, structs.VisibleTypePrivate)
  337. }
  338. RenderUserSearch(ctx, &models.SearchUserOptions{
  339. Actor: ctx.User,
  340. Type: models.UserTypeOrganization,
  341. ListOptions: models.ListOptions{PageSize: setting.UI.ExplorePagingNum},
  342. Visible: visibleTypes,
  343. }, tplExploreOrganizations)
  344. }
  345. // ExploreCode render explore code page
  346. func ExploreCode(ctx *context.Context) {
  347. if !setting.Indexer.RepoIndexerEnabled {
  348. ctx.Redirect(setting.AppSubURL+"/explore", 302)
  349. return
  350. }
  351. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  352. ctx.Data["Title"] = ctx.Tr("explore")
  353. ctx.Data["PageIsExplore"] = true
  354. ctx.Data["PageIsExploreCode"] = true
  355. language := strings.TrimSpace(ctx.Query("l"))
  356. keyword := strings.TrimSpace(ctx.Query("q"))
  357. page := ctx.QueryInt("page")
  358. if page <= 0 {
  359. page = 1
  360. }
  361. var (
  362. repoIDs []int64
  363. err error
  364. isAdmin bool
  365. userID int64
  366. )
  367. if ctx.User != nil {
  368. userID = ctx.User.ID
  369. isAdmin = ctx.User.IsAdmin
  370. }
  371. // guest user or non-admin user
  372. if ctx.User == nil || !isAdmin {
  373. repoIDs, err = models.FindUserAccessibleRepoIDs(ctx.User)
  374. if err != nil {
  375. ctx.ServerError("SearchResults", err)
  376. return
  377. }
  378. }
  379. var (
  380. total int
  381. searchResults []*code_indexer.Result
  382. searchResultLanguages []*code_indexer.SearchResultLanguages
  383. )
  384. // if non-admin login user, we need check UnitTypeCode at first
  385. if ctx.User != nil && len(repoIDs) > 0 {
  386. repoMaps, err := models.GetRepositoriesMapByIDs(repoIDs)
  387. if err != nil {
  388. ctx.ServerError("SearchResults", err)
  389. return
  390. }
  391. var rightRepoMap = make(map[int64]*models.Repository, len(repoMaps))
  392. repoIDs = make([]int64, 0, len(repoMaps))
  393. for id, repo := range repoMaps {
  394. if repo.CheckUnitUser(userID, isAdmin, models.UnitTypeCode) {
  395. rightRepoMap[id] = repo
  396. repoIDs = append(repoIDs, id)
  397. }
  398. }
  399. ctx.Data["RepoMaps"] = rightRepoMap
  400. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  401. if err != nil {
  402. ctx.ServerError("SearchResults", err)
  403. return
  404. }
  405. // if non-login user or isAdmin, no need to check UnitTypeCode
  406. } else if (ctx.User == nil && len(repoIDs) > 0) || isAdmin {
  407. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  408. if err != nil {
  409. ctx.ServerError("SearchResults", err)
  410. return
  411. }
  412. var loadRepoIDs = make([]int64, 0, len(searchResults))
  413. for _, result := range searchResults {
  414. var find bool
  415. for _, id := range loadRepoIDs {
  416. if id == result.RepoID {
  417. find = true
  418. break
  419. }
  420. }
  421. if !find {
  422. loadRepoIDs = append(loadRepoIDs, result.RepoID)
  423. }
  424. }
  425. repoMaps, err := models.GetRepositoriesMapByIDs(loadRepoIDs)
  426. if err != nil {
  427. ctx.ServerError("SearchResults", err)
  428. return
  429. }
  430. ctx.Data["RepoMaps"] = repoMaps
  431. }
  432. ctx.Data["Keyword"] = keyword
  433. ctx.Data["Language"] = language
  434. ctx.Data["SearchResults"] = searchResults
  435. ctx.Data["SearchResultLanguages"] = searchResultLanguages
  436. ctx.Data["RequireHighlightJS"] = true
  437. ctx.Data["PageIsViewCode"] = true
  438. pager := context.NewPagination(total, setting.UI.RepoSearchPagingNum, page, 5)
  439. pager.SetDefaultParams(ctx)
  440. pager.AddParam(ctx, "l", "Language")
  441. ctx.Data["Page"] = pager
  442. ctx.HTML(200, tplExploreCode)
  443. }
  444. func ExploreImages(ctx *context.Context) {
  445. ctx.HTML(200, tplExploreImages)
  446. }
  447. func ExploreDataAnalysis(ctx *context.Context) {
  448. ctx.HTML(200, tplExploreExploreDataAnalysis)
  449. }
  450. // NotFound render 404 page
  451. func NotFound(ctx *context.Context) {
  452. ctx.Data["Title"] = "Page Not Found"
  453. ctx.NotFound("home.NotFound", nil)
  454. }
  455. func RecommendOrgFromPromote(ctx *context.Context) {
  456. url := setting.RecommentRepoAddr + "organizations"
  457. recommendFromPromote(ctx, url)
  458. }
  459. func recommendFromPromote(ctx *context.Context, url string) {
  460. resp, err := http.Get(url)
  461. if err != nil {
  462. log.Info("Get organizations url error=" + err.Error())
  463. ctx.ServerError("QueryTrainJobList:", err)
  464. return
  465. }
  466. bytes, err := ioutil.ReadAll(resp.Body)
  467. resp.Body.Close()
  468. if err != nil {
  469. log.Info("Get organizations url error=" + err.Error())
  470. ctx.ServerError("QueryTrainJobList:", err)
  471. return
  472. }
  473. allLineStr := string(bytes)
  474. lines := strings.Split(allLineStr, "\n")
  475. result := make([]string, len(lines))
  476. for i, line := range lines {
  477. tmpIndex := strings.Index(line, ".")
  478. log.Info("i=" + fmt.Sprint(i) + " line=" + line + " tmpIndex=" + fmt.Sprint(tmpIndex))
  479. if tmpIndex == -1 {
  480. result[i] = strings.Trim(line, " ")
  481. } else {
  482. result[i] = strings.Trim(line[tmpIndex+1:], " ")
  483. }
  484. }
  485. ctx.JSON(http.StatusOK, result)
  486. }
  487. func RecommendRepoFromPromote(ctx *context.Context) {
  488. url := setting.RecommentRepoAddr + "projects"
  489. recommendFromPromote(ctx, url)
  490. }