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