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 24 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 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
4 years ago
4 years ago
4 years ago
4 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
11 years ago
4 years ago
11 years ago
11 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 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
11 years ago
3 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
4 years ago
4 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. "net/http"
  9. "strconv"
  10. "strings"
  11. "code.gitea.io/gitea/services/repository"
  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. tplHomeTerm base.TplName = "terms"
  38. )
  39. // Home render home page
  40. func Home(ctx *context.Context) {
  41. ctx.Data["PageIsHome"] = true
  42. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  43. setRecommendURL(ctx)
  44. ctx.HTML(200, tplHome)
  45. }
  46. func setRecommendURLOnly(ctx *context.Context) {
  47. addr := setting.RecommentRepoAddr[10:]
  48. start := strings.Index(addr, "/")
  49. end := strings.Index(addr, "raw")
  50. if start != -1 && end != -1 {
  51. ctx.Data["RecommendURL"] = addr[start:end]
  52. } else {
  53. ctx.Data["RecommendURL"] = setting.RecommentRepoAddr
  54. }
  55. }
  56. func setRecommendURL(ctx *context.Context) {
  57. setRecommendURLOnly(ctx)
  58. ctx.Data["page_title"] = ctx.Tr("home.page_title")
  59. ctx.Data["page_small_title"] = ctx.Tr("home.page_small_title")
  60. ctx.Data["page_description"] = ctx.Tr("home.page_description")
  61. ctx.Data["page_use"] = ctx.Tr("home.page_use")
  62. ctx.Data["page_only_dynamic"] = ctx.Tr("home.page_only_dynamic")
  63. ctx.Data["page_recommend_org"] = ctx.Tr("home.page_recommend_org")
  64. ctx.Data["page_recommend_org_desc"] = ctx.Tr("home.page_recommend_org_desc")
  65. ctx.Data["page_recommend_org_commit"] = ctx.Tr("home.page_recommend_org_commit")
  66. ctx.Data["page_recommend_org_more"] = ctx.Tr("home.page_recommend_org_more")
  67. ctx.Data["page_recommend_repo"] = ctx.Tr("home.page_recommend_repo")
  68. ctx.Data["page_recommend_repo_desc"] = ctx.Tr("home.page_recommend_repo_desc")
  69. ctx.Data["page_recommend_repo_commit"] = ctx.Tr("home.page_recommend_repo_commit")
  70. ctx.Data["page_recommend_repo_go"] = ctx.Tr("home.page_recommend_repo_go")
  71. ctx.Data["page_recommend_repo_more"] = ctx.Tr("home.page_recommend_repo_more")
  72. ctx.Data["page_dev_env"] = ctx.Tr("home.page_dev_env")
  73. ctx.Data["page_dev_env_desc"] = ctx.Tr("home.page_dev_env_desc")
  74. ctx.Data["page_dev_env_desc_title"] = ctx.Tr("home.page_dev_env_desc_title")
  75. ctx.Data["page_dev_env_desc_desc"] = ctx.Tr("home.page_dev_env_desc_desc")
  76. ctx.Data["page_dev_env_desc1_title"] = ctx.Tr("home.page_dev_env_desc1_title")
  77. ctx.Data["page_dev_env_desc1_desc"] = ctx.Tr("home.page_dev_env_desc1_desc")
  78. ctx.Data["page_dev_env_desc2_title"] = ctx.Tr("home.page_dev_env_desc2_title")
  79. ctx.Data["page_dev_env_desc2_desc"] = ctx.Tr("home.page_dev_env_desc2_desc")
  80. ctx.Data["page_dev_env_desc3_title"] = ctx.Tr("home.page_dev_env_desc3_title")
  81. ctx.Data["page_dev_env_desc3_desc"] = ctx.Tr("home.page_dev_env_desc3_desc")
  82. ctx.Data["page_dev_yunlao"] = ctx.Tr("home.page_dev_yunlao")
  83. ctx.Data["page_dev_yunlao_desc1"] = ctx.Tr("home.page_dev_yunlao_desc1")
  84. ctx.Data["page_dev_yunlao_desc2"] = ctx.Tr("home.page_dev_yunlao_desc2")
  85. ctx.Data["page_dev_yunlao_desc3"] = ctx.Tr("home.page_dev_yunlao_desc3")
  86. ctx.Data["page_dev_yunlao_desc4"] = ctx.Tr("home.page_dev_yunlao_desc4")
  87. ctx.Data["page_dev_yunlao_apply"] = ctx.Tr("home.page_dev_yunlao_apply")
  88. ctx.Data["page_recommend_activity"] = ctx.Tr("home.page_recommend_activity")
  89. ctx.Data["page_recommend_activity_desc"] = ctx.Tr("home.page_recommend_activity_desc")
  90. }
  91. func Dashboard(ctx *context.Context) {
  92. if ctx.IsSigned {
  93. pictureInfo, err := getImageInfo("dashboard-picture")
  94. if err == nil && len(pictureInfo) > 0 {
  95. log.Info("set image info=" + pictureInfo[0]["url"])
  96. ctx.Data["image_url"] = pictureInfo[0]["url"]
  97. ctx.Data["image_link"] = pictureInfo[0]["image_link"]
  98. }
  99. if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  100. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  101. ctx.HTML(200, user.TplActivate)
  102. } else if !ctx.User.IsActive || ctx.User.ProhibitLogin {
  103. log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
  104. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  105. ctx.HTML(200, "user/auth/prohibit_login")
  106. } else if ctx.User.MustChangePassword {
  107. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  108. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  109. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  110. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  111. } else {
  112. user.Dashboard(ctx)
  113. }
  114. return
  115. // Check non-logged users landing page.
  116. } else if setting.LandingPageURL != setting.LandingPageHome {
  117. ctx.Redirect(setting.AppSubURL + string(setting.LandingPageURL))
  118. return
  119. }
  120. // Check auto-login.
  121. uname := ctx.GetCookie(setting.CookieUserName)
  122. if len(uname) != 0 {
  123. ctx.Redirect(setting.AppSubURL + "/user/login")
  124. return
  125. }
  126. setRecommendURL(ctx)
  127. ctx.Data["PageIsHome"] = true
  128. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  129. ctx.HTML(200, tplHome)
  130. }
  131. // RepoSearchOptions when calling search repositories
  132. type RepoSearchOptions struct {
  133. OwnerID int64
  134. Private bool
  135. Restricted bool
  136. PageSize int
  137. TplName base.TplName
  138. Course util.OptionalBool
  139. }
  140. var (
  141. nullByte = []byte{0x00}
  142. )
  143. func isKeywordValid(keyword string) bool {
  144. return !bytes.Contains([]byte(keyword), nullByte)
  145. }
  146. // RenderRepoSearch render repositories search page
  147. func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
  148. page := ctx.QueryInt("page")
  149. if page <= 0 {
  150. page = 1
  151. }
  152. var (
  153. repos []*models.Repository
  154. count int64
  155. err error
  156. orderBy models.SearchOrderBy
  157. )
  158. ctx.Data["SortType"] = ctx.Query("sort")
  159. switch ctx.Query("sort") {
  160. case "newest":
  161. orderBy = models.SearchOrderByNewest
  162. case "oldest":
  163. orderBy = models.SearchOrderByOldest
  164. case "recentupdate":
  165. orderBy = models.SearchOrderByRecentUpdated
  166. case "leastupdate":
  167. orderBy = models.SearchOrderByLeastUpdated
  168. case "reversealphabetically":
  169. orderBy = models.SearchOrderByAlphabeticallyReverse
  170. case "alphabetically":
  171. orderBy = models.SearchOrderByAlphabetically
  172. case "reversesize":
  173. orderBy = models.SearchOrderBySizeReverse
  174. case "size":
  175. orderBy = models.SearchOrderBySize
  176. case "moststars":
  177. orderBy = models.SearchOrderByStarsReverse
  178. case "feweststars":
  179. orderBy = models.SearchOrderByStars
  180. case "mostforks":
  181. orderBy = models.SearchOrderByForksReverse
  182. case "fewestforks":
  183. orderBy = models.SearchOrderByForks
  184. case "hot":
  185. orderBy = models.SearchOrderByHot
  186. case "active":
  187. orderBy = models.SearchOrderByActive
  188. default:
  189. ctx.Data["SortType"] = "hot"
  190. orderBy = models.SearchOrderByHot
  191. }
  192. orderBy = orderBy + ",id"
  193. //todo:support other topics
  194. keyword := strings.Trim(ctx.Query("q"), " ")
  195. topic := strings.Trim(ctx.Query("topic"), " ")
  196. repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
  197. ListOptions: models.ListOptions{
  198. Page: page,
  199. PageSize: opts.PageSize,
  200. },
  201. Actor: ctx.User,
  202. OrderBy: orderBy,
  203. Private: opts.Private,
  204. Keyword: keyword,
  205. OwnerID: opts.OwnerID,
  206. AllPublic: true,
  207. AllLimited: true,
  208. TopicName: topic,
  209. IncludeDescription: setting.UI.SearchRepoDescription,
  210. Course: opts.Course,
  211. })
  212. if err != nil {
  213. ctx.ServerError("SearchRepository", err)
  214. return
  215. }
  216. for _, repo := range repos {
  217. repo.Hot = int64(repo.NumWatches) + int64(repo.NumStars) + int64(repo.NumForks) + int64(repo.CloneCnt)
  218. repo.Active = int64(repo.NumIssues) + int64(repo.NumPulls) + int64(repo.NumCommit)
  219. }
  220. ctx.Data["Keyword"] = keyword
  221. ctx.Data["Topic"] = topic
  222. ctx.Data["Total"] = count
  223. ctx.Data["Repos"] = repos
  224. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  225. pager := context.NewPagination(int(count), opts.PageSize, page, 5)
  226. pager.SetDefaultParams(ctx)
  227. pager.AddParam(ctx, "topic", "TopicOnly")
  228. ctx.Data["Page"] = pager
  229. recommendOrgs, err := models.GetRecommendOrgInfos()
  230. if err != nil {
  231. log.Error("GetRecommendOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  232. ctx.ServerError("GetRecommendOrgInfos", err)
  233. return
  234. }
  235. ctx.Data["RecommendOrgs"] = recommendOrgs
  236. ctx.HTML(http.StatusOK, opts.TplName)
  237. }
  238. // ExploreRepos render explore repositories page
  239. func ExploreRepos(ctx *context.Context) {
  240. ctx.Data["Title"] = ctx.Tr("explore")
  241. ctx.Data["PageIsExplore"] = true
  242. ctx.Data["PageIsExploreRepositories"] = true
  243. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  244. pictureInfo, err := getImageInfo("explore-user-picture")
  245. if err == nil && len(pictureInfo) > 0 {
  246. ctx.Data["image_url"] = pictureInfo[0]["url"]
  247. ctx.Data["image_link"] = pictureInfo[0]["image_link"]
  248. }
  249. var ownerID int64
  250. if ctx.User != nil && !ctx.User.IsAdmin {
  251. ownerID = ctx.User.ID
  252. }
  253. RenderRepoSearch(ctx, &RepoSearchOptions{
  254. PageSize: setting.UI.ExplorePagingNum,
  255. OwnerID: ownerID,
  256. Private: ctx.User != nil,
  257. TplName: tplExploreRepos,
  258. })
  259. }
  260. func ExploreDatasets(ctx *context.Context) {
  261. ctx.Data["Title"] = ctx.Tr("explore")
  262. ctx.Data["PageIsExplore"] = true
  263. ctx.Data["PageIsExploreDatasets"] = true
  264. // ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  265. var (
  266. datasets []*models.Dataset
  267. datasetsWithStar []*models.DatasetWithStar
  268. count int64
  269. err error
  270. orderBy models.SearchOrderBy
  271. )
  272. page := ctx.QueryInt("page")
  273. if page <= 0 {
  274. page = 1
  275. }
  276. ctx.Data["SortType"] = ctx.Query("sort")
  277. switch ctx.Query("sort") {
  278. case "newest":
  279. orderBy = models.SearchOrderByNewest
  280. case "oldest":
  281. orderBy = models.SearchOrderByOldest
  282. case "recentupdate":
  283. orderBy = models.SearchOrderByRecentUpdated
  284. case "leastupdate":
  285. orderBy = models.SearchOrderByLeastUpdated
  286. case "reversealphabetically":
  287. orderBy = models.SearchOrderByAlphabeticallyReverse
  288. case "alphabetically":
  289. orderBy = models.SearchOrderByAlphabetically
  290. case "reversesize":
  291. orderBy = models.SearchOrderBySizeReverse
  292. case "downloadtimes":
  293. orderBy = models.SearchOrderByDownloadTimes
  294. case "moststars":
  295. orderBy = models.SearchOrderByStarsReverse
  296. case "feweststars":
  297. orderBy = models.SearchOrderByStars
  298. case "default":
  299. orderBy = models.SearchOrderByDefault
  300. default:
  301. ctx.Data["SortType"] = "default"
  302. orderBy = models.SearchOrderByDefault
  303. }
  304. keyword := strings.Trim(ctx.Query("q"), " ")
  305. category := ctx.Query("category")
  306. task := ctx.Query("task")
  307. license := ctx.Query("license")
  308. var ownerID int64
  309. if ctx.User != nil && !ctx.User.IsAdmin {
  310. ownerID = ctx.User.ID
  311. }
  312. opts := &models.SearchDatasetOptions{
  313. Keyword: keyword,
  314. IncludePublic: true,
  315. SearchOrderBy: orderBy,
  316. Category: category,
  317. Task: task,
  318. License: license,
  319. OwnerID: ownerID,
  320. RecommendOnly: ctx.QueryBool("recommend"),
  321. ListOptions: models.ListOptions{
  322. Page: page,
  323. PageSize: 30,
  324. },
  325. }
  326. datasets, count, err = models.SearchDataset(opts)
  327. if err != nil {
  328. ctx.ServerError("SearchDatasets", err)
  329. return
  330. }
  331. for _, dataset := range datasets {
  332. if !ctx.IsSigned {
  333. datasetsWithStar = append(datasetsWithStar, &models.DatasetWithStar{Dataset: *dataset, IsStaring: false})
  334. } else {
  335. datasetsWithStar = append(datasetsWithStar, &models.DatasetWithStar{Dataset: *dataset, IsStaring: models.IsDatasetStaring(ctx.User.ID, dataset.ID)})
  336. }
  337. }
  338. pager := context.NewPagination(int(count), opts.PageSize, page, 5)
  339. ctx.Data["Keyword"] = opts.Keyword
  340. ctx.Data["Category"] = category
  341. ctx.Data["Task"] = task
  342. ctx.Data["License"] = license
  343. ctx.Data["Recommend"] = ctx.QueryBool("recommend")
  344. pager.SetDefaultParams(ctx)
  345. ctx.Data["Page"] = pager
  346. ctx.Data["Datasets"] = datasetsWithStar
  347. ctx.Data["Total"] = count
  348. ctx.Data["PageIsDatasets"] = true
  349. ctx.HTML(200, tplExploreDataset)
  350. }
  351. // RenderUserSearch render user search page
  352. func RenderUserSearch(ctx *context.Context, opts *models.SearchUserOptions, tplName base.TplName) {
  353. opts.Page = ctx.QueryInt("page")
  354. if opts.Page <= 1 {
  355. opts.Page = 1
  356. }
  357. var (
  358. users []*models.User
  359. count int64
  360. err error
  361. orderBy models.SearchOrderBy
  362. )
  363. ctx.Data["SortType"] = ctx.Query("sort")
  364. switch ctx.Query("sort") {
  365. case "newest":
  366. orderBy = models.SearchOrderByIDReverse
  367. case "oldest":
  368. orderBy = models.SearchOrderByID
  369. case "recentupdate":
  370. orderBy = models.SearchOrderByRecentUpdated
  371. case "leastupdate":
  372. orderBy = models.SearchOrderByLeastUpdated
  373. case "reversealphabetically":
  374. orderBy = models.SearchOrderByAlphabeticallyReverse
  375. case "alphabetically":
  376. orderBy = models.SearchOrderByAlphabetically
  377. default:
  378. ctx.Data["SortType"] = "alphabetically"
  379. orderBy = models.SearchOrderByAlphabetically
  380. }
  381. opts.Keyword = strings.Trim(ctx.Query("q"), " ")
  382. opts.OrderBy = orderBy
  383. if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) {
  384. users, count, err = models.SearchUsers(opts)
  385. if err != nil {
  386. ctx.ServerError("SearchUsers", err)
  387. return
  388. }
  389. }
  390. ctx.Data["Keyword"] = opts.Keyword
  391. ctx.Data["Total"] = count
  392. ctx.Data["Users"] = users
  393. ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail
  394. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  395. pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
  396. pager.SetDefaultParams(ctx)
  397. ctx.Data["Page"] = pager
  398. ctx.HTML(200, tplName)
  399. }
  400. // ExploreUsers render explore users page
  401. func ExploreUsers(ctx *context.Context) {
  402. ctx.Data["Title"] = ctx.Tr("explore")
  403. ctx.Data["PageIsExplore"] = true
  404. ctx.Data["PageIsExploreUsers"] = true
  405. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  406. pictureInfo, err := getImageInfo("explore-user-picture")
  407. if err == nil && len(pictureInfo) > 0 {
  408. ctx.Data["image_url"] = pictureInfo[0]["url"]
  409. ctx.Data["image_link"] = pictureInfo[0]["image_link"]
  410. }
  411. RenderUserSearch(ctx, &models.SearchUserOptions{
  412. Actor: ctx.User,
  413. Type: models.UserTypeIndividual,
  414. ListOptions: models.ListOptions{PageSize: setting.UI.ExplorePagingNum},
  415. IsActive: util.OptionalBoolTrue,
  416. Visible: []structs.VisibleType{structs.VisibleTypePublic, structs.VisibleTypeLimited, structs.VisibleTypePrivate},
  417. }, tplExploreUsers)
  418. }
  419. // ExploreOrganizations render explore organizations page
  420. func ExploreOrganizations(ctx *context.Context) {
  421. ctx.Data["Title"] = ctx.Tr("explore")
  422. ctx.Data["PageIsExplore"] = true
  423. ctx.Data["PageIsExploreOrganizations"] = true
  424. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  425. N := 10
  426. starInfo, err := models.FindTopNStarsOrgs(N)
  427. if err != nil {
  428. log.Error("GetStarOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  429. ctx.ServerError("GetStarOrgInfos", err)
  430. return
  431. }
  432. memberInfo, err := models.FindTopNMembersOrgs(N)
  433. if err != nil {
  434. log.Error("GetMemberOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  435. ctx.ServerError("GetMemberOrgInfos", err)
  436. return
  437. }
  438. openIInfo, err := models.FindTopNOpenIOrgs(N)
  439. if err != nil {
  440. log.Error("GetOpenIOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  441. ctx.ServerError("GetOpenIOrgInfos", err)
  442. return
  443. }
  444. recommendOrgs, err := getRecommendOrg()
  445. if err != nil {
  446. log.Error("GetRecommendOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  447. ctx.ServerError("GetRecommendOrgInfos", err)
  448. return
  449. }
  450. setRecommendURLOnly(ctx)
  451. ctx.Data["RecommendOrgs"] = recommendOrgs
  452. ctx.Data["StarOrgs"] = starInfo
  453. ctx.Data["MemberOrgs"] = memberInfo
  454. ctx.Data["ActiveOrgs"] = openIInfo
  455. ctx.HTML(http.StatusOK, tplExploreOrganizations)
  456. }
  457. // ExploreCode render explore code page
  458. func ExploreCode(ctx *context.Context) {
  459. if !setting.Indexer.RepoIndexerEnabled {
  460. ctx.Redirect(setting.AppSubURL+"/explore", 302)
  461. return
  462. }
  463. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  464. ctx.Data["Title"] = ctx.Tr("explore")
  465. ctx.Data["PageIsExplore"] = true
  466. ctx.Data["PageIsExploreCode"] = true
  467. language := strings.TrimSpace(ctx.Query("l"))
  468. keyword := strings.TrimSpace(ctx.Query("q"))
  469. page := ctx.QueryInt("page")
  470. if page <= 0 {
  471. page = 1
  472. }
  473. var (
  474. repoIDs []int64
  475. err error
  476. isAdmin bool
  477. userID int64
  478. )
  479. if ctx.User != nil {
  480. userID = ctx.User.ID
  481. isAdmin = ctx.User.IsAdmin
  482. }
  483. // guest user or non-admin user
  484. if ctx.User == nil || !isAdmin {
  485. repoIDs, err = models.FindUserAccessibleRepoIDs(ctx.User)
  486. if err != nil {
  487. ctx.ServerError("SearchResults", err)
  488. return
  489. }
  490. }
  491. var (
  492. total int
  493. searchResults []*code_indexer.Result
  494. searchResultLanguages []*code_indexer.SearchResultLanguages
  495. )
  496. // if non-admin login user, we need check UnitTypeCode at first
  497. if ctx.User != nil && len(repoIDs) > 0 {
  498. repoMaps, err := models.GetRepositoriesMapByIDs(repoIDs)
  499. if err != nil {
  500. ctx.ServerError("SearchResults", err)
  501. return
  502. }
  503. var rightRepoMap = make(map[int64]*models.Repository, len(repoMaps))
  504. repoIDs = make([]int64, 0, len(repoMaps))
  505. for id, repo := range repoMaps {
  506. if repo.CheckUnitUser(userID, isAdmin, models.UnitTypeCode) {
  507. rightRepoMap[id] = repo
  508. repoIDs = append(repoIDs, id)
  509. }
  510. }
  511. ctx.Data["RepoMaps"] = rightRepoMap
  512. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  513. if err != nil {
  514. ctx.ServerError("SearchResults", err)
  515. return
  516. }
  517. // if non-login user or isAdmin, no need to check UnitTypeCode
  518. } else if (ctx.User == nil && len(repoIDs) > 0) || isAdmin {
  519. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  520. if err != nil {
  521. ctx.ServerError("SearchResults", err)
  522. return
  523. }
  524. var loadRepoIDs = make([]int64, 0, len(searchResults))
  525. for _, result := range searchResults {
  526. var find bool
  527. for _, id := range loadRepoIDs {
  528. if id == result.RepoID {
  529. find = true
  530. break
  531. }
  532. }
  533. if !find {
  534. loadRepoIDs = append(loadRepoIDs, result.RepoID)
  535. }
  536. }
  537. repoMaps, err := models.GetRepositoriesMapByIDs(loadRepoIDs)
  538. if err != nil {
  539. ctx.ServerError("SearchResults", err)
  540. return
  541. }
  542. ctx.Data["RepoMaps"] = repoMaps
  543. }
  544. ctx.Data["Keyword"] = keyword
  545. ctx.Data["Language"] = language
  546. ctx.Data["SearchResults"] = searchResults
  547. ctx.Data["SearchResultLanguages"] = searchResultLanguages
  548. ctx.Data["RequireHighlightJS"] = true
  549. ctx.Data["PageIsViewCode"] = true
  550. pager := context.NewPagination(total, setting.UI.RepoSearchPagingNum, page, 5)
  551. pager.SetDefaultParams(ctx)
  552. pager.AddParam(ctx, "l", "Language")
  553. ctx.Data["Page"] = pager
  554. ctx.HTML(200, tplExploreCode)
  555. }
  556. func ExploreImages(ctx *context.Context) {
  557. ctx.HTML(200, tplExploreImages)
  558. }
  559. func ExploreDataAnalysisUserTrend(ctx *context.Context) {
  560. ctx.Data["url_params"] = "UserTrend"
  561. ctx.HTML(200, tplExploreExploreDataAnalysis)
  562. }
  563. func ExploreDataAnalysisUserAnalysis(ctx *context.Context) {
  564. ctx.Data["url_params"] = "UserAnalysis"
  565. ctx.HTML(200, tplExploreExploreDataAnalysis)
  566. }
  567. func ExploreDataAnalysisProTrend(ctx *context.Context) {
  568. ctx.Data["url_params"] = "ProTrend"
  569. ctx.HTML(200, tplExploreExploreDataAnalysis)
  570. }
  571. func ExploreDataAnalysisProAnalysis(ctx *context.Context) {
  572. ctx.Data["url_params"] = "ProAnalysis"
  573. ctx.HTML(200, tplExploreExploreDataAnalysis)
  574. }
  575. func ExploreDataAnalysisOverview(ctx *context.Context) {
  576. ctx.Data["url_params"] = "Overview"
  577. ctx.HTML(200, tplExploreExploreDataAnalysis)
  578. }
  579. func ExploreDataAnalysisBrainAnalysis(ctx *context.Context) {
  580. ctx.Data["url_params"] = "BrainAnalysis"
  581. ctx.HTML(200, tplExploreExploreDataAnalysis)
  582. }
  583. func ExploreDataAnalysis(ctx *context.Context) {
  584. ctx.Data["url_params"] = ""
  585. ctx.HTML(200, tplExploreExploreDataAnalysis)
  586. }
  587. // NotFound render 404 page
  588. func NotFound(ctx *context.Context) {
  589. ctx.Data["Title"] = "Page Not Found"
  590. ctx.NotFound("home.NotFound", nil)
  591. }
  592. func getRecommendOrg() ([]map[string]interface{}, error) {
  593. url := setting.RecommentRepoAddr + "organizations"
  594. result, err := repository.RecommendFromPromote(url)
  595. if err != nil {
  596. return nil, err
  597. }
  598. resultOrg := make([]map[string]interface{}, 0)
  599. for _, userName := range result {
  600. user, err := models.GetUserByName(userName)
  601. if err == nil {
  602. userMap := make(map[string]interface{})
  603. userMap["Name"] = user.Name
  604. userMap["Description"] = user.Description
  605. userMap["FullName"] = user.FullName
  606. userMap["HomeLink"] = user.HomeLink()
  607. userMap["ID"] = user.ID
  608. userMap["Avatar"] = user.RelAvatarLink()
  609. userMap["NumRepos"] = user.NumRepos
  610. userMap["NumTeams"] = user.NumTeams
  611. userMap["NumMembers"] = user.NumMembers
  612. resultOrg = append(resultOrg, userMap)
  613. } else {
  614. log.Info("query user error," + err.Error())
  615. }
  616. }
  617. return resultOrg, nil
  618. }
  619. func getImageInfo(filename string) ([]map[string]string, error) {
  620. url := setting.RecommentRepoAddr + filename
  621. result, err := repository.RecommendFromPromote(url)
  622. if err != nil {
  623. return nil, err
  624. }
  625. imageInfo := make([]map[string]string, 0)
  626. for i := 0; i < (len(result) - 1); i++ {
  627. line := result[i]
  628. imageMap := make(map[string]string)
  629. if line[0:4] == "url=" {
  630. url := line[4:]
  631. imageMap["url"] = url
  632. if result[i+1][0:11] == "image_link=" {
  633. image_link := result[i+1][11:]
  634. imageMap["image_link"] = image_link
  635. }
  636. }
  637. imageInfo = append(imageInfo, imageMap)
  638. i = i + 1
  639. }
  640. return imageInfo, nil
  641. }
  642. func GetRankUser(index string) ([]map[string]interface{}, error) {
  643. url := setting.RecommentRepoAddr + "user_rank_" + index
  644. result, err := repository.RecommendFromPromote(url)
  645. if err != nil {
  646. return nil, err
  647. }
  648. resultOrg := make([]map[string]interface{}, 0)
  649. for _, userRank := range result {
  650. tmpIndex := strings.Index(userRank, " ")
  651. userName := userRank
  652. score := 0
  653. if tmpIndex != -1 {
  654. userName = userRank[0:tmpIndex]
  655. tmpScore, err := strconv.Atoi(userRank[tmpIndex+1:])
  656. if err != nil {
  657. log.Info("convert to int error.")
  658. }
  659. score = tmpScore
  660. }
  661. user, err := models.GetUserByName(userName)
  662. if err == nil {
  663. userMap := make(map[string]interface{})
  664. userMap["Name"] = user.Name
  665. userMap["Description"] = user.Description
  666. userMap["FullName"] = user.FullName
  667. userMap["HomeLink"] = user.HomeLink()
  668. userMap["ID"] = user.ID
  669. userMap["Avatar"] = user.RelAvatarLink()
  670. userMap["Score"] = score
  671. resultOrg = append(resultOrg, userMap)
  672. } else {
  673. log.Info("query user error," + err.Error())
  674. }
  675. }
  676. return resultOrg, nil
  677. }
  678. func GetUserRankFromPromote(ctx *context.Context) {
  679. index := ctx.Params("index")
  680. resultUserRank, err := GetRankUser(index)
  681. if err != nil {
  682. ctx.ServerError("500", err)
  683. return
  684. }
  685. ctx.JSON(200, resultUserRank)
  686. }
  687. func RecommendHomeInfo(ctx *context.Context) {
  688. resultOrg, err := getRecommendOrg()
  689. if err != nil {
  690. log.Info("error." + err.Error())
  691. }
  692. resultRepo, err := repository.GetRecommendRepoFromPromote("projects")
  693. if err != nil {
  694. log.Info("error." + err.Error())
  695. }
  696. resultImage, err := getImageInfo("picture_info")
  697. if err != nil {
  698. log.Info("error." + err.Error())
  699. }
  700. mapInterface := make(map[string]interface{})
  701. mapInterface["org"] = resultOrg
  702. mapInterface["repo"] = resultRepo
  703. mapInterface["image"] = resultImage
  704. ctx.JSON(http.StatusOK, mapInterface)
  705. }
  706. func RecommendRepoFromPromote(ctx *context.Context) {
  707. result, err := repository.GetRecommendRepoFromPromote("projects")
  708. if err != nil {
  709. ctx.ServerError("500", err)
  710. } else {
  711. ctx.JSON(200, result)
  712. }
  713. }
  714. func HomeTerm(ctx *context.Context) {
  715. ctx.HTML(200, tplHomeTerm)
  716. }