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 25 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 "mostusecount":
  299. orderBy = models.SearchOrderByUseCountReverse
  300. case "fewestusecount":
  301. orderBy = models.SearchOrderByUseCount
  302. case "default":
  303. orderBy = models.SearchOrderByDefault
  304. default:
  305. ctx.Data["SortType"] = "default"
  306. orderBy = models.SearchOrderByDefault
  307. }
  308. keyword := strings.Trim(ctx.Query("q"), " ")
  309. category := ctx.Query("category")
  310. task := ctx.Query("task")
  311. license := ctx.Query("license")
  312. var ownerID int64
  313. if ctx.User != nil && !ctx.User.IsAdmin {
  314. ownerID = ctx.User.ID
  315. }
  316. opts := &models.SearchDatasetOptions{
  317. Keyword: keyword,
  318. IncludePublic: true,
  319. SearchOrderBy: orderBy,
  320. Category: category,
  321. Task: task,
  322. License: license,
  323. OwnerID: ownerID,
  324. RecommendOnly: ctx.QueryBool("recommend"),
  325. ListOptions: models.ListOptions{
  326. Page: page,
  327. PageSize: 30,
  328. },
  329. }
  330. datasets, count, err = models.SearchDataset(opts)
  331. if err != nil {
  332. ctx.ServerError("SearchDatasets", err)
  333. return
  334. }
  335. for _, dataset := range datasets {
  336. if !ctx.IsSigned {
  337. datasetsWithStar = append(datasetsWithStar, &models.DatasetWithStar{Dataset: *dataset, IsStaring: false})
  338. } else {
  339. datasetsWithStar = append(datasetsWithStar, &models.DatasetWithStar{Dataset: *dataset, IsStaring: models.IsDatasetStaring(ctx.User.ID, dataset.ID)})
  340. }
  341. }
  342. pager := context.NewPagination(int(count), opts.PageSize, page, 5)
  343. ctx.Data["Keyword"] = opts.Keyword
  344. ctx.Data["Category"] = category
  345. ctx.Data["Task"] = task
  346. ctx.Data["License"] = license
  347. ctx.Data["Recommend"] = ctx.QueryBool("recommend")
  348. pager.SetDefaultParams(ctx)
  349. ctx.Data["Page"] = pager
  350. ctx.Data["Datasets"] = datasetsWithStar
  351. ctx.Data["Total"] = count
  352. ctx.Data["PageIsDatasets"] = true
  353. ctx.HTML(200, tplExploreDataset)
  354. }
  355. // RenderUserSearch render user search page
  356. func RenderUserSearch(ctx *context.Context, opts *models.SearchUserOptions, tplName base.TplName) {
  357. opts.Page = ctx.QueryInt("page")
  358. if opts.Page <= 1 {
  359. opts.Page = 1
  360. }
  361. var (
  362. users []*models.User
  363. count int64
  364. err error
  365. orderBy models.SearchOrderBy
  366. )
  367. ctx.Data["SortType"] = ctx.Query("sort")
  368. switch ctx.Query("sort") {
  369. case "newest":
  370. orderBy = models.SearchOrderByIDReverse
  371. case "oldest":
  372. orderBy = models.SearchOrderByID
  373. case "recentupdate":
  374. orderBy = models.SearchOrderByRecentUpdated
  375. case "leastupdate":
  376. orderBy = models.SearchOrderByLeastUpdated
  377. case "reversealphabetically":
  378. orderBy = models.SearchOrderByAlphabeticallyReverse
  379. case "alphabetically":
  380. orderBy = models.SearchOrderByAlphabetically
  381. default:
  382. ctx.Data["SortType"] = "alphabetically"
  383. orderBy = models.SearchOrderByAlphabetically
  384. }
  385. opts.Keyword = strings.Trim(ctx.Query("q"), " ")
  386. opts.OrderBy = orderBy
  387. if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) {
  388. users, count, err = models.SearchUsers(opts)
  389. if err != nil {
  390. ctx.ServerError("SearchUsers", err)
  391. return
  392. }
  393. }
  394. ctx.Data["Keyword"] = opts.Keyword
  395. ctx.Data["Total"] = count
  396. ctx.Data["Users"] = users
  397. ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail
  398. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  399. pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
  400. pager.SetDefaultParams(ctx)
  401. ctx.Data["Page"] = pager
  402. ctx.HTML(200, tplName)
  403. }
  404. // ExploreUsers render explore users page
  405. func ExploreUsers(ctx *context.Context) {
  406. ctx.Data["Title"] = ctx.Tr("explore")
  407. ctx.Data["PageIsExplore"] = true
  408. ctx.Data["PageIsExploreUsers"] = true
  409. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  410. pictureInfo, err := getImageInfo("explore-user-picture")
  411. if err == nil && len(pictureInfo) > 0 {
  412. ctx.Data["image_url"] = pictureInfo[0]["url"]
  413. ctx.Data["image_link"] = pictureInfo[0]["image_link"]
  414. }
  415. RenderUserSearch(ctx, &models.SearchUserOptions{
  416. Actor: ctx.User,
  417. Type: models.UserTypeIndividual,
  418. ListOptions: models.ListOptions{PageSize: setting.UI.ExplorePagingNum},
  419. IsActive: util.OptionalBoolTrue,
  420. Visible: []structs.VisibleType{structs.VisibleTypePublic, structs.VisibleTypeLimited, structs.VisibleTypePrivate},
  421. }, tplExploreUsers)
  422. }
  423. // ExploreOrganizations render explore organizations page
  424. func ExploreOrganizations(ctx *context.Context) {
  425. ctx.Data["Title"] = ctx.Tr("explore")
  426. ctx.Data["PageIsExplore"] = true
  427. ctx.Data["PageIsExploreOrganizations"] = true
  428. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  429. N := 10
  430. starInfo, err := models.FindTopNStarsOrgs(N)
  431. if err != nil {
  432. log.Error("GetStarOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  433. ctx.ServerError("GetStarOrgInfos", err)
  434. return
  435. }
  436. memberInfo, err := models.FindTopNMembersOrgs(N)
  437. if err != nil {
  438. log.Error("GetMemberOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  439. ctx.ServerError("GetMemberOrgInfos", err)
  440. return
  441. }
  442. openIInfo, err := models.FindTopNOpenIOrgs(N)
  443. if err != nil {
  444. log.Error("GetOpenIOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  445. ctx.ServerError("GetOpenIOrgInfos", err)
  446. return
  447. }
  448. recommendOrgs, err := getRecommendOrg()
  449. if err != nil {
  450. log.Error("GetRecommendOrgInfos failed:%v", err.Error(), ctx.Data["MsgID"])
  451. ctx.ServerError("GetRecommendOrgInfos", err)
  452. return
  453. }
  454. setRecommendURLOnly(ctx)
  455. ctx.Data["RecommendOrgs"] = recommendOrgs
  456. ctx.Data["StarOrgs"] = starInfo
  457. ctx.Data["MemberOrgs"] = memberInfo
  458. ctx.Data["ActiveOrgs"] = openIInfo
  459. ctx.HTML(http.StatusOK, tplExploreOrganizations)
  460. }
  461. // ExploreCode render explore code page
  462. func ExploreCode(ctx *context.Context) {
  463. if !setting.Indexer.RepoIndexerEnabled {
  464. ctx.Redirect(setting.AppSubURL+"/explore", 302)
  465. return
  466. }
  467. ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
  468. ctx.Data["Title"] = ctx.Tr("explore")
  469. ctx.Data["PageIsExplore"] = true
  470. ctx.Data["PageIsExploreCode"] = true
  471. language := strings.TrimSpace(ctx.Query("l"))
  472. keyword := strings.TrimSpace(ctx.Query("q"))
  473. page := ctx.QueryInt("page")
  474. if page <= 0 {
  475. page = 1
  476. }
  477. var (
  478. repoIDs []int64
  479. err error
  480. isAdmin bool
  481. userID int64
  482. )
  483. if ctx.User != nil {
  484. userID = ctx.User.ID
  485. isAdmin = ctx.User.IsAdmin
  486. }
  487. // guest user or non-admin user
  488. if ctx.User == nil || !isAdmin {
  489. repoIDs, err = models.FindUserAccessibleRepoIDs(ctx.User)
  490. if err != nil {
  491. ctx.ServerError("SearchResults", err)
  492. return
  493. }
  494. }
  495. var (
  496. total int
  497. searchResults []*code_indexer.Result
  498. searchResultLanguages []*code_indexer.SearchResultLanguages
  499. )
  500. // if non-admin login user, we need check UnitTypeCode at first
  501. if ctx.User != nil && len(repoIDs) > 0 {
  502. repoMaps, err := models.GetRepositoriesMapByIDs(repoIDs)
  503. if err != nil {
  504. ctx.ServerError("SearchResults", err)
  505. return
  506. }
  507. var rightRepoMap = make(map[int64]*models.Repository, len(repoMaps))
  508. repoIDs = make([]int64, 0, len(repoMaps))
  509. for id, repo := range repoMaps {
  510. if repo.CheckUnitUser(userID, isAdmin, models.UnitTypeCode) {
  511. rightRepoMap[id] = repo
  512. repoIDs = append(repoIDs, id)
  513. }
  514. }
  515. ctx.Data["RepoMaps"] = rightRepoMap
  516. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  517. if err != nil {
  518. ctx.ServerError("SearchResults", err)
  519. return
  520. }
  521. // if non-login user or isAdmin, no need to check UnitTypeCode
  522. } else if (ctx.User == nil && len(repoIDs) > 0) || isAdmin {
  523. total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(repoIDs, language, keyword, page, setting.UI.RepoSearchPagingNum)
  524. if err != nil {
  525. ctx.ServerError("SearchResults", err)
  526. return
  527. }
  528. var loadRepoIDs = make([]int64, 0, len(searchResults))
  529. for _, result := range searchResults {
  530. var find bool
  531. for _, id := range loadRepoIDs {
  532. if id == result.RepoID {
  533. find = true
  534. break
  535. }
  536. }
  537. if !find {
  538. loadRepoIDs = append(loadRepoIDs, result.RepoID)
  539. }
  540. }
  541. repoMaps, err := models.GetRepositoriesMapByIDs(loadRepoIDs)
  542. if err != nil {
  543. ctx.ServerError("SearchResults", err)
  544. return
  545. }
  546. ctx.Data["RepoMaps"] = repoMaps
  547. }
  548. ctx.Data["Keyword"] = keyword
  549. ctx.Data["Language"] = language
  550. ctx.Data["SearchResults"] = searchResults
  551. ctx.Data["SearchResultLanguages"] = searchResultLanguages
  552. ctx.Data["RequireHighlightJS"] = true
  553. ctx.Data["PageIsViewCode"] = true
  554. pager := context.NewPagination(total, setting.UI.RepoSearchPagingNum, page, 5)
  555. pager.SetDefaultParams(ctx)
  556. pager.AddParam(ctx, "l", "Language")
  557. ctx.Data["Page"] = pager
  558. ctx.HTML(200, tplExploreCode)
  559. }
  560. func ExploreImages(ctx *context.Context) {
  561. ctx.HTML(200, tplExploreImages)
  562. }
  563. func ExploreDataAnalysisUserTrend(ctx *context.Context) {
  564. ctx.Data["url_params"] = "UserTrend"
  565. ctx.HTML(200, tplExploreExploreDataAnalysis)
  566. }
  567. func ExploreDataAnalysisUserAnalysis(ctx *context.Context) {
  568. ctx.Data["url_params"] = "UserAnalysis"
  569. ctx.HTML(200, tplExploreExploreDataAnalysis)
  570. }
  571. func ExploreDataAnalysisProTrend(ctx *context.Context) {
  572. ctx.Data["url_params"] = "ProTrend"
  573. ctx.HTML(200, tplExploreExploreDataAnalysis)
  574. }
  575. func ExploreDataAnalysisProAnalysis(ctx *context.Context) {
  576. ctx.Data["url_params"] = "ProAnalysis"
  577. ctx.HTML(200, tplExploreExploreDataAnalysis)
  578. }
  579. func ExploreDataAnalysisOverview(ctx *context.Context) {
  580. ctx.Data["url_params"] = "Overview"
  581. ctx.HTML(200, tplExploreExploreDataAnalysis)
  582. }
  583. func ExploreDataAnalysisBrainAnalysis(ctx *context.Context) {
  584. ctx.Data["url_params"] = "BrainAnalysis"
  585. ctx.HTML(200, tplExploreExploreDataAnalysis)
  586. }
  587. func ExploreDataAnalysis(ctx *context.Context) {
  588. ctx.Data["url_params"] = ""
  589. ctx.HTML(200, tplExploreExploreDataAnalysis)
  590. }
  591. // NotFound render 404 page
  592. func NotFound(ctx *context.Context) {
  593. ctx.Data["Title"] = "Page Not Found"
  594. ctx.NotFound("home.NotFound", nil)
  595. }
  596. func getRecommendOrg() ([]map[string]interface{}, error) {
  597. url := setting.RecommentRepoAddr + "organizations"
  598. result, err := repository.RecommendFromPromote(url)
  599. if err != nil {
  600. return nil, err
  601. }
  602. resultOrg := make([]map[string]interface{}, 0)
  603. for _, userName := range result {
  604. user, err := models.GetUserByName(userName)
  605. if err == nil {
  606. userMap := make(map[string]interface{})
  607. userMap["Name"] = user.Name
  608. userMap["Description"] = user.Description
  609. userMap["FullName"] = user.FullName
  610. userMap["HomeLink"] = user.HomeLink()
  611. userMap["ID"] = user.ID
  612. userMap["Avatar"] = user.RelAvatarLink()
  613. userMap["NumRepos"] = user.NumRepos
  614. userMap["NumTeams"] = user.NumTeams
  615. userMap["NumMembers"] = user.NumMembers
  616. resultOrg = append(resultOrg, userMap)
  617. } else {
  618. log.Info("query user error," + err.Error())
  619. }
  620. }
  621. return resultOrg, nil
  622. }
  623. func getImageInfo(filename string) ([]map[string]string, error) {
  624. url := setting.RecommentRepoAddr + filename
  625. result, err := repository.RecommendFromPromote(url)
  626. if err != nil {
  627. return nil, err
  628. }
  629. imageInfo := make([]map[string]string, 0)
  630. for i := 0; i < (len(result) - 1); i++ {
  631. line := result[i]
  632. imageMap := make(map[string]string)
  633. if line[0:4] == "url=" {
  634. url := line[4:]
  635. imageMap["url"] = url
  636. if result[i+1][0:11] == "image_link=" {
  637. image_link := result[i+1][11:]
  638. imageMap["image_link"] = image_link
  639. }
  640. }
  641. imageInfo = append(imageInfo, imageMap)
  642. i = i + 1
  643. }
  644. return imageInfo, nil
  645. }
  646. func GetRankUser(index string) ([]map[string]interface{}, error) {
  647. url := setting.RecommentRepoAddr + "user_rank_" + index
  648. result, err := repository.RecommendFromPromote(url)
  649. if err != nil {
  650. return nil, err
  651. }
  652. resultOrg := make([]map[string]interface{}, 0)
  653. for _, userRank := range result {
  654. tmpIndex := strings.Index(userRank, " ")
  655. userName := userRank
  656. score := 0
  657. if tmpIndex != -1 {
  658. userName = userRank[0:tmpIndex]
  659. tmpScore, err := strconv.Atoi(userRank[tmpIndex+1:])
  660. if err != nil {
  661. log.Info("convert to int error.")
  662. }
  663. score = tmpScore
  664. }
  665. user, err := models.GetUserByName(userName)
  666. if err == nil {
  667. userMap := make(map[string]interface{})
  668. userMap["Name"] = user.Name
  669. userMap["Description"] = user.Description
  670. userMap["FullName"] = user.FullName
  671. userMap["HomeLink"] = user.HomeLink()
  672. userMap["ID"] = user.ID
  673. userMap["Avatar"] = user.RelAvatarLink()
  674. userMap["Score"] = score
  675. resultOrg = append(resultOrg, userMap)
  676. } else {
  677. log.Info("query user error," + err.Error())
  678. }
  679. }
  680. return resultOrg, nil
  681. }
  682. func GetUserRankFromPromote(ctx *context.Context) {
  683. index := ctx.Params("index")
  684. resultUserRank, err := GetRankUser(index)
  685. if err != nil {
  686. ctx.ServerError("500", err)
  687. return
  688. }
  689. ctx.JSON(200, resultUserRank)
  690. }
  691. func RecommendHomeInfo(ctx *context.Context) {
  692. resultOrg, err := getRecommendOrg()
  693. if err != nil {
  694. log.Info("error." + err.Error())
  695. }
  696. resultRepo, err := repository.GetRecommendRepoFromPromote("projects")
  697. if err != nil {
  698. log.Info("error." + err.Error())
  699. }
  700. resultImage, err := getImageInfo("picture_info")
  701. if err != nil {
  702. log.Info("error." + err.Error())
  703. }
  704. mapInterface := make(map[string]interface{})
  705. mapInterface["org"] = resultOrg
  706. mapInterface["repo"] = resultRepo
  707. mapInterface["image"] = resultImage
  708. ctx.JSON(http.StatusOK, mapInterface)
  709. }
  710. func RecommendRepoFromPromote(ctx *context.Context) {
  711. result, err := repository.GetRecommendRepoFromPromote("projects")
  712. if err != nil {
  713. ctx.ServerError("500", err)
  714. } else {
  715. ctx.JSON(200, result)
  716. }
  717. }
  718. func HomeTerm(ctx *context.Context) {
  719. ctx.HTML(200, tplHomeTerm)
  720. }