gitea源码

home.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package user
  5. import (
  6. "bytes"
  7. "fmt"
  8. "net/http"
  9. "regexp"
  10. "slices"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. activities_model "code.gitea.io/gitea/models/activities"
  15. asymkey_model "code.gitea.io/gitea/models/asymkey"
  16. "code.gitea.io/gitea/models/db"
  17. git_model "code.gitea.io/gitea/models/git"
  18. issues_model "code.gitea.io/gitea/models/issues"
  19. "code.gitea.io/gitea/models/organization"
  20. "code.gitea.io/gitea/models/renderhelper"
  21. repo_model "code.gitea.io/gitea/models/repo"
  22. "code.gitea.io/gitea/models/unit"
  23. user_model "code.gitea.io/gitea/models/user"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/container"
  26. "code.gitea.io/gitea/modules/indexer"
  27. issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/markup/markdown"
  30. "code.gitea.io/gitea/modules/optional"
  31. "code.gitea.io/gitea/modules/setting"
  32. "code.gitea.io/gitea/modules/templates"
  33. "code.gitea.io/gitea/modules/util"
  34. "code.gitea.io/gitea/routers/web/feed"
  35. "code.gitea.io/gitea/routers/web/shared/issue"
  36. "code.gitea.io/gitea/routers/web/shared/user"
  37. "code.gitea.io/gitea/services/context"
  38. feed_service "code.gitea.io/gitea/services/feed"
  39. issue_service "code.gitea.io/gitea/services/issue"
  40. pull_service "code.gitea.io/gitea/services/pull"
  41. "github.com/ProtonMail/go-crypto/openpgp"
  42. "github.com/ProtonMail/go-crypto/openpgp/armor"
  43. "xorm.io/builder"
  44. )
  45. const (
  46. tplDashboard templates.TplName = "user/dashboard/dashboard"
  47. tplIssues templates.TplName = "user/dashboard/issues"
  48. tplMilestones templates.TplName = "user/dashboard/milestones"
  49. tplProfile templates.TplName = "user/profile"
  50. )
  51. // getDashboardContextUser finds out which context user dashboard is being viewed as .
  52. func getDashboardContextUser(ctx *context.Context) *user_model.User {
  53. ctxUser := ctx.Doer
  54. orgName := ctx.PathParam("org")
  55. if len(orgName) > 0 {
  56. ctxUser = ctx.Org.Organization.AsUser()
  57. ctx.Data["Teams"] = ctx.Org.Teams
  58. }
  59. ctx.Data["ContextUser"] = ctxUser
  60. orgs, err := organization.GetUserOrgsList(ctx, ctx.Doer)
  61. if err != nil {
  62. ctx.ServerError("GetUserOrgsList", err)
  63. return nil
  64. }
  65. ctx.Data["Orgs"] = orgs
  66. return ctxUser
  67. }
  68. // Dashboard render the dashboard page
  69. func Dashboard(ctx *context.Context) {
  70. ctxUser := getDashboardContextUser(ctx)
  71. if ctx.Written() {
  72. return
  73. }
  74. var (
  75. date = ctx.FormString("date")
  76. page = ctx.FormInt("page")
  77. )
  78. // Make sure page number is at least 1. Will be posted to ctx.Data.
  79. if page <= 1 {
  80. page = 1
  81. }
  82. ctx.Data["Title"] = ctxUser.DisplayName() + " - " + ctx.Locale.TrString("dashboard")
  83. ctx.Data["PageIsDashboard"] = true
  84. ctx.Data["PageIsNews"] = true
  85. cnt, _ := organization.GetOrganizationCount(ctx, ctxUser)
  86. ctx.Data["UserOrgsCount"] = cnt
  87. ctx.Data["MirrorsEnabled"] = setting.Mirror.Enabled
  88. ctx.Data["Date"] = date
  89. var uid int64
  90. if ctxUser != nil {
  91. uid = ctxUser.ID
  92. }
  93. ctx.PageData["dashboardRepoList"] = map[string]any{
  94. "searchLimit": setting.UI.User.RepoPagingNum,
  95. "uid": uid,
  96. }
  97. if setting.Service.EnableUserHeatmap {
  98. data, err := activities_model.GetUserHeatmapDataByUserTeam(ctx, ctxUser, ctx.Org.Team, ctx.Doer)
  99. if err != nil {
  100. ctx.ServerError("GetUserHeatmapDataByUserTeam", err)
  101. return
  102. }
  103. ctx.Data["HeatmapData"] = data
  104. ctx.Data["HeatmapTotalContributions"] = activities_model.GetTotalContributionsInHeatmap(data)
  105. }
  106. feeds, count, err := feed_service.GetFeedsForDashboard(ctx, activities_model.GetFeedsOptions{
  107. RequestedUser: ctxUser,
  108. RequestedTeam: ctx.Org.Team,
  109. Actor: ctx.Doer,
  110. IncludePrivate: true,
  111. OnlyPerformedBy: false,
  112. IncludeDeleted: false,
  113. Date: ctx.FormString("date"),
  114. ListOptions: db.ListOptions{
  115. Page: page,
  116. PageSize: setting.UI.FeedPagingNum,
  117. },
  118. })
  119. if err != nil {
  120. ctx.ServerError("GetFeeds", err)
  121. return
  122. }
  123. pager := context.NewPagination(count, setting.UI.FeedPagingNum, page, 5).WithCurRows(len(feeds))
  124. pager.AddParamFromRequest(ctx.Req)
  125. ctx.Data["Page"] = pager
  126. ctx.Data["Feeds"] = feeds
  127. ctx.HTML(http.StatusOK, tplDashboard)
  128. }
  129. // Milestones render the user milestones page
  130. func Milestones(ctx *context.Context) {
  131. if unit.TypeIssues.UnitGlobalDisabled() && unit.TypePullRequests.UnitGlobalDisabled() {
  132. log.Debug("Milestones overview page not available as both issues and pull requests are globally disabled")
  133. ctx.Status(http.StatusNotFound)
  134. return
  135. }
  136. ctx.Data["Title"] = ctx.Tr("milestones")
  137. ctx.Data["PageIsMilestonesDashboard"] = true
  138. ctxUser := getDashboardContextUser(ctx)
  139. if ctx.Written() {
  140. return
  141. }
  142. repoOpts := repo_model.SearchRepoOptions{
  143. Actor: ctx.Doer,
  144. OwnerID: ctxUser.ID,
  145. Private: true,
  146. AllPublic: false, // Include also all public repositories of users and public organisations
  147. AllLimited: false, // Include also all public repositories of limited organisations
  148. Archived: optional.Some(false),
  149. HasMilestones: optional.Some(true), // Just needs display repos has milestones
  150. }
  151. if ctxUser.IsOrganization() && ctx.Org.Team != nil {
  152. repoOpts.TeamID = ctx.Org.Team.ID
  153. }
  154. var (
  155. userRepoCond = repo_model.SearchRepositoryCondition(repoOpts) // all repo condition user could visit
  156. repoCond = userRepoCond
  157. repoIDs []int64
  158. reposQuery = ctx.FormString("repos")
  159. isShowClosed = ctx.FormString("state") == "closed"
  160. sortType = ctx.FormString("sort")
  161. page = ctx.FormInt("page")
  162. keyword = ctx.FormTrim("q")
  163. )
  164. if page <= 1 {
  165. page = 1
  166. }
  167. if len(reposQuery) != 0 {
  168. if issueReposQueryPattern.MatchString(reposQuery) {
  169. // remove "[" and "]" from string
  170. reposQuery = reposQuery[1 : len(reposQuery)-1]
  171. // for each ID (delimiter ",") add to int to repoIDs
  172. for rID := range strings.SplitSeq(reposQuery, ",") {
  173. // Ensure nonempty string entries
  174. if rID != "" && rID != "0" {
  175. rIDint64, err := strconv.ParseInt(rID, 10, 64)
  176. // If the repo id specified by query is not parseable or not accessible by user, just ignore it.
  177. if err == nil {
  178. repoIDs = append(repoIDs, rIDint64)
  179. }
  180. }
  181. }
  182. if len(repoIDs) > 0 {
  183. // Don't just let repoCond = builder.In("id", repoIDs) because user may has no permission on repoIDs
  184. // But the original repoCond has a limitation
  185. repoCond = repoCond.And(builder.In("id", repoIDs))
  186. }
  187. } else {
  188. log.Warn("issueReposQueryPattern not match with query")
  189. }
  190. }
  191. counts, err := issues_model.CountMilestonesMap(ctx, issues_model.FindMilestoneOptions{
  192. RepoCond: userRepoCond,
  193. Name: keyword,
  194. IsClosed: optional.Some(isShowClosed),
  195. })
  196. if err != nil {
  197. ctx.ServerError("CountMilestonesByRepoIDs", err)
  198. return
  199. }
  200. milestones, err := db.Find[issues_model.Milestone](ctx, issues_model.FindMilestoneOptions{
  201. ListOptions: db.ListOptions{
  202. Page: page,
  203. PageSize: setting.UI.IssuePagingNum,
  204. },
  205. RepoCond: repoCond,
  206. IsClosed: optional.Some(isShowClosed),
  207. SortType: sortType,
  208. Name: keyword,
  209. })
  210. if err != nil {
  211. ctx.ServerError("SearchMilestones", err)
  212. return
  213. }
  214. showRepos, _, err := repo_model.SearchRepositoryByCondition(ctx, repoOpts, userRepoCond, false)
  215. if err != nil {
  216. ctx.ServerError("SearchRepositoryByCondition", err)
  217. return
  218. }
  219. sort.Sort(showRepos)
  220. for i := 0; i < len(milestones); {
  221. for _, repo := range showRepos {
  222. if milestones[i].RepoID == repo.ID {
  223. milestones[i].Repo = repo
  224. break
  225. }
  226. }
  227. if milestones[i].Repo == nil {
  228. log.Warn("Cannot find milestone %d 's repository %d", milestones[i].ID, milestones[i].RepoID)
  229. milestones = append(milestones[:i], milestones[i+1:]...)
  230. continue
  231. }
  232. rctx := renderhelper.NewRenderContextRepoComment(ctx, milestones[i].Repo)
  233. milestones[i].RenderedContent, err = markdown.RenderString(rctx, milestones[i].Content)
  234. if err != nil {
  235. ctx.ServerError("RenderString", err)
  236. return
  237. }
  238. if milestones[i].Repo.IsTimetrackerEnabled(ctx) {
  239. err := milestones[i].LoadTotalTrackedTime(ctx)
  240. if err != nil {
  241. ctx.ServerError("LoadTotalTrackedTime", err)
  242. return
  243. }
  244. }
  245. i++
  246. }
  247. milestoneStats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(ctx, repoCond, keyword)
  248. if err != nil {
  249. ctx.ServerError("GetMilestoneStats", err)
  250. return
  251. }
  252. var totalMilestoneStats *issues_model.MilestonesStats
  253. if len(repoIDs) == 0 {
  254. totalMilestoneStats = milestoneStats
  255. } else {
  256. totalMilestoneStats, err = issues_model.GetMilestonesStatsByRepoCondAndKw(ctx, userRepoCond, keyword)
  257. if err != nil {
  258. ctx.ServerError("GetMilestoneStats", err)
  259. return
  260. }
  261. }
  262. showRepoIDs := make(container.Set[int64], len(showRepos))
  263. for _, repo := range showRepos {
  264. if repo.ID > 0 {
  265. showRepoIDs.Add(repo.ID)
  266. }
  267. }
  268. if len(repoIDs) == 0 {
  269. repoIDs = showRepoIDs.Values()
  270. }
  271. repoIDs = slices.DeleteFunc(repoIDs, func(v int64) bool {
  272. return !showRepoIDs.Contains(v)
  273. })
  274. var pagerCount int
  275. if isShowClosed {
  276. ctx.Data["State"] = "closed"
  277. ctx.Data["Total"] = totalMilestoneStats.ClosedCount
  278. pagerCount = int(milestoneStats.ClosedCount)
  279. } else {
  280. ctx.Data["State"] = "open"
  281. ctx.Data["Total"] = totalMilestoneStats.OpenCount
  282. pagerCount = int(milestoneStats.OpenCount)
  283. }
  284. ctx.Data["Milestones"] = milestones
  285. ctx.Data["Repos"] = showRepos
  286. ctx.Data["Counts"] = counts
  287. ctx.Data["MilestoneStats"] = milestoneStats
  288. ctx.Data["SortType"] = sortType
  289. ctx.Data["Keyword"] = keyword
  290. ctx.Data["RepoIDs"] = repoIDs
  291. ctx.Data["IsShowClosed"] = isShowClosed
  292. pager := context.NewPagination(pagerCount, setting.UI.IssuePagingNum, page, 5)
  293. pager.AddParamFromRequest(ctx.Req)
  294. ctx.Data["Page"] = pager
  295. ctx.HTML(http.StatusOK, tplMilestones)
  296. }
  297. // Pulls renders the user's pull request overview page
  298. func Pulls(ctx *context.Context) {
  299. if unit.TypePullRequests.UnitGlobalDisabled() {
  300. log.Debug("Pull request overview page not available as it is globally disabled.")
  301. ctx.Status(http.StatusNotFound)
  302. return
  303. }
  304. ctx.Data["Title"] = ctx.Tr("pull_requests")
  305. ctx.Data["PageIsPulls"] = true
  306. buildIssueOverview(ctx, unit.TypePullRequests)
  307. }
  308. // Issues renders the user's issues overview page
  309. func Issues(ctx *context.Context) {
  310. if unit.TypeIssues.UnitGlobalDisabled() {
  311. log.Debug("Issues overview page not available as it is globally disabled.")
  312. ctx.Status(http.StatusNotFound)
  313. return
  314. }
  315. ctx.Data["Title"] = ctx.Tr("issues")
  316. ctx.Data["PageIsIssues"] = true
  317. buildIssueOverview(ctx, unit.TypeIssues)
  318. }
  319. // Regexp for repos query
  320. var issueReposQueryPattern = regexp.MustCompile(`^\[\d+(,\d+)*,?\]$`)
  321. func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
  322. // ----------------------------------------------------
  323. // Determine user; can be either user or organization.
  324. // Return with NotFound or ServerError if unsuccessful.
  325. // ----------------------------------------------------
  326. ctxUser := getDashboardContextUser(ctx)
  327. if ctx.Written() {
  328. return
  329. }
  330. // Default to recently updated, unlike repository issues list
  331. sortType := util.IfZero(ctx.FormString("sort"), "recentupdate")
  332. // --------------------------------------------------------------------------------
  333. // Distinguish User from Organization.
  334. // Org:
  335. // - Remember pre-determined viewType string for later. Will be posted to ctx.Data.
  336. // Organization does not have view type and filter mode.
  337. // User:
  338. // - Use ctx.FormString("type") to determine filterMode.
  339. // The type is set when clicking for example "assigned to me" on the overview page.
  340. // - Remember either this or a fallback. Will be posted to ctx.Data.
  341. // --------------------------------------------------------------------------------
  342. // TODO: distinguish during routing
  343. viewType := ctx.FormString("type")
  344. var filterMode int
  345. switch viewType {
  346. case "assigned":
  347. filterMode = issues_model.FilterModeAssign
  348. case "created_by":
  349. filterMode = issues_model.FilterModeCreate
  350. case "mentioned":
  351. filterMode = issues_model.FilterModeMention
  352. case "review_requested":
  353. filterMode = issues_model.FilterModeReviewRequested
  354. case "reviewed_by":
  355. filterMode = issues_model.FilterModeReviewed
  356. case "your_repositories":
  357. fallthrough
  358. default:
  359. filterMode = issues_model.FilterModeYourRepositories
  360. viewType = "your_repositories"
  361. }
  362. isPullList := unitType == unit.TypePullRequests
  363. opts := &issues_model.IssuesOptions{
  364. IsPull: optional.Some(isPullList),
  365. SortType: sortType,
  366. IsArchived: optional.Some(false),
  367. Doer: ctx.Doer,
  368. }
  369. // --------------------------------------------------------------------------
  370. // Build opts (IssuesOptions), which contains filter information.
  371. // Will eventually be used to retrieve issues relevant for the overview page.
  372. // Note: Non-final states of opts are used in-between, namely for:
  373. // - Keyword search
  374. // - Count Issues by repo
  375. // --------------------------------------------------------------------------
  376. // Get repository IDs where User/Org/Team has access.
  377. if ctx.Org != nil && ctx.Org.Organization != nil {
  378. opts.Owner = ctx.Org.Organization.AsUser()
  379. opts.Team = ctx.Org.Team
  380. issue.PrepareFilterIssueLabels(ctx, 0, ctx.Org.Organization.AsUser())
  381. if ctx.Written() {
  382. return
  383. }
  384. }
  385. // Get filter by author id & assignee id
  386. // the existing "/posters" handlers doesn't work for this case, it is unable to list the related users correctly.
  387. // In the future, we need something like github: "author:user1" to accept usernames directly.
  388. posterUsername := ctx.FormString("poster")
  389. ctx.Data["FilterPosterUsername"] = posterUsername
  390. opts.PosterID = user.GetFilterUserIDByName(ctx, posterUsername)
  391. assigneeUsername := ctx.FormString("assignee")
  392. ctx.Data["FilterAssigneeUsername"] = assigneeUsername
  393. opts.AssigneeID = user.GetFilterUserIDByName(ctx, assigneeUsername)
  394. searchMode := ctx.FormString("search_mode")
  395. // Search all repositories which
  396. //
  397. // As user:
  398. // - Owns the repository.
  399. // - Have collaborator permissions in repository.
  400. //
  401. // As org:
  402. // - Owns the repository.
  403. //
  404. // As team:
  405. // - Team org's owns the repository.
  406. // - Team has read permission to repository.
  407. repoOpts := repo_model.SearchRepoOptions{
  408. Actor: ctx.Doer,
  409. OwnerID: ctxUser.ID,
  410. Private: true,
  411. AllPublic: false,
  412. AllLimited: false,
  413. Collaborate: optional.None[bool](),
  414. UnitType: unitType,
  415. Archived: optional.Some(false),
  416. }
  417. if opts.Team != nil {
  418. repoOpts.TeamID = opts.Team.ID
  419. }
  420. accessibleRepos := container.Set[int64]{}
  421. {
  422. ids, _, err := repo_model.SearchRepositoryIDs(ctx, repoOpts)
  423. if err != nil {
  424. ctx.ServerError("SearchRepositoryIDs", err)
  425. return
  426. }
  427. accessibleRepos.AddMultiple(ids...)
  428. opts.RepoIDs = ids
  429. if len(opts.RepoIDs) == 0 {
  430. // no repos found, don't let the indexer return all repos
  431. opts.RepoIDs = []int64{0}
  432. }
  433. }
  434. if ctx.Doer.ID == ctxUser.ID && filterMode != issues_model.FilterModeYourRepositories {
  435. // If the doer is the same as the context user, which means the doer is viewing his own dashboard,
  436. // it's not enough to show the repos that the doer owns or has been explicitly granted access to,
  437. // because the doer may create issues or be mentioned in any public repo.
  438. // So we need search issues in all public repos.
  439. opts.AllPublic = true
  440. }
  441. switch filterMode {
  442. case issues_model.FilterModeAll:
  443. case issues_model.FilterModeYourRepositories:
  444. case issues_model.FilterModeAssign:
  445. opts.AssigneeID = strconv.FormatInt(ctx.Doer.ID, 10)
  446. case issues_model.FilterModeCreate:
  447. opts.PosterID = strconv.FormatInt(ctx.Doer.ID, 10)
  448. case issues_model.FilterModeMention:
  449. opts.MentionedID = ctx.Doer.ID
  450. case issues_model.FilterModeReviewRequested:
  451. opts.ReviewRequestedID = ctx.Doer.ID
  452. case issues_model.FilterModeReviewed:
  453. opts.ReviewedID = ctx.Doer.ID
  454. }
  455. // keyword holds the search term entered into the search field.
  456. keyword := strings.Trim(ctx.FormString("q"), " ")
  457. ctx.Data["Keyword"] = keyword
  458. // Educated guess: Do or don't show closed issues.
  459. isShowClosed := ctx.FormString("state") == "closed"
  460. opts.IsClosed = optional.Some(isShowClosed)
  461. // Make sure page number is at least 1. Will be posted to ctx.Data.
  462. page := max(ctx.FormInt("page"), 1)
  463. opts.Paginator = &db.ListOptions{
  464. Page: page,
  465. PageSize: setting.UI.IssuePagingNum,
  466. }
  467. // Get IDs for labels (a filter option for issues/pulls).
  468. // Required for IssuesOptions.
  469. selectedLabels := ctx.FormString("labels")
  470. if len(selectedLabels) > 0 && selectedLabels != "0" {
  471. var err error
  472. opts.LabelIDs, err = base.StringsToInt64s(strings.Split(selectedLabels, ","))
  473. if err != nil {
  474. ctx.Flash.Error(ctx.Tr("invalid_data", selectedLabels), true)
  475. }
  476. }
  477. // ------------------------------
  478. // Get issues as defined by opts.
  479. // ------------------------------
  480. // Slice of Issues that will be displayed on the overview page
  481. // USING FINAL STATE OF opts FOR A QUERY.
  482. var issues issues_model.IssueList
  483. {
  484. issueIDs, _, err := issue_indexer.SearchIssues(ctx, issue_indexer.ToSearchOptions(keyword, opts).Copy(
  485. func(o *issue_indexer.SearchOptions) {
  486. o.SearchMode = indexer.SearchModeType(searchMode)
  487. },
  488. ))
  489. if err != nil {
  490. ctx.ServerError("issueIDsFromSearch", err)
  491. return
  492. }
  493. issues, err = issues_model.GetIssuesByIDs(ctx, issueIDs, true)
  494. if err != nil {
  495. ctx.ServerError("GetIssuesByIDs", err)
  496. return
  497. }
  498. }
  499. commitStatuses, lastStatus, err := pull_service.GetIssuesAllCommitStatus(ctx, issues)
  500. if err != nil {
  501. ctx.ServerError("GetIssuesLastCommitStatus", err)
  502. return
  503. }
  504. if !ctx.Repo.CanRead(unit.TypeActions) {
  505. for key := range commitStatuses {
  506. git_model.CommitStatusesHideActionsURL(ctx, commitStatuses[key])
  507. }
  508. }
  509. // -------------------------------
  510. // Fill stats to post to ctx.Data.
  511. // -------------------------------
  512. issueStats, err := getUserIssueStats(ctx, ctxUser, filterMode, issue_indexer.ToSearchOptions(keyword, opts).Copy(
  513. func(o *issue_indexer.SearchOptions) {
  514. o.SearchMode = indexer.SearchModeType(searchMode)
  515. },
  516. ))
  517. if err != nil {
  518. ctx.ServerError("getUserIssueStats", err)
  519. return
  520. }
  521. // Will be posted to ctx.Data.
  522. var shownIssues int
  523. if !isShowClosed {
  524. shownIssues = int(issueStats.OpenCount)
  525. } else {
  526. shownIssues = int(issueStats.ClosedCount)
  527. }
  528. ctx.Data["IsShowClosed"] = isShowClosed
  529. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.FormString("RepoLink"))
  530. if err := issues.LoadAttributes(ctx); err != nil {
  531. ctx.ServerError("issues.LoadAttributes", err)
  532. return
  533. }
  534. ctx.Data["Issues"] = issues
  535. approvalCounts, err := issues.GetApprovalCounts(ctx)
  536. if err != nil {
  537. ctx.ServerError("ApprovalCounts", err)
  538. return
  539. }
  540. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  541. counts, ok := approvalCounts[issueID]
  542. if !ok || len(counts) == 0 {
  543. return 0
  544. }
  545. reviewTyp := issues_model.ReviewTypeApprove
  546. switch typ {
  547. case "reject":
  548. reviewTyp = issues_model.ReviewTypeReject
  549. case "waiting":
  550. reviewTyp = issues_model.ReviewTypeRequest
  551. }
  552. for _, count := range counts {
  553. if count.Type == reviewTyp {
  554. return count.Count
  555. }
  556. }
  557. return 0
  558. }
  559. ctx.Data["CommitLastStatus"] = lastStatus
  560. ctx.Data["CommitStatuses"] = commitStatuses
  561. ctx.Data["IssueStats"] = issueStats
  562. ctx.Data["ViewType"] = viewType
  563. ctx.Data["SortType"] = sortType
  564. ctx.Data["IsShowClosed"] = isShowClosed
  565. ctx.Data["SearchModes"] = issue_indexer.SupportedSearchModes()
  566. ctx.Data["SelectedSearchMode"] = ctx.FormTrim("search_mode")
  567. if isShowClosed {
  568. ctx.Data["State"] = "closed"
  569. } else {
  570. ctx.Data["State"] = "open"
  571. }
  572. pager := context.NewPagination(shownIssues, setting.UI.IssuePagingNum, page, 5)
  573. pager.AddParamFromRequest(ctx.Req)
  574. ctx.Data["Page"] = pager
  575. ctx.HTML(http.StatusOK, tplIssues)
  576. }
  577. // ShowSSHKeys output all the ssh keys of user by uid
  578. func ShowSSHKeys(ctx *context.Context) {
  579. keys, err := db.Find[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
  580. OwnerID: ctx.ContextUser.ID,
  581. })
  582. if err != nil {
  583. ctx.ServerError("ListPublicKeys", err)
  584. return
  585. }
  586. var buf bytes.Buffer
  587. for i := range keys {
  588. buf.WriteString(keys[i].OmitEmail())
  589. buf.WriteString("\n")
  590. }
  591. ctx.PlainTextBytes(http.StatusOK, buf.Bytes())
  592. }
  593. // ShowGPGKeys output all the public GPG keys of user by uid
  594. func ShowGPGKeys(ctx *context.Context) {
  595. keys, err := db.Find[asymkey_model.GPGKey](ctx, asymkey_model.FindGPGKeyOptions{
  596. ListOptions: db.ListOptionsAll,
  597. OwnerID: ctx.ContextUser.ID,
  598. })
  599. if err != nil {
  600. ctx.ServerError("ListGPGKeys", err)
  601. return
  602. }
  603. entities := make([]*openpgp.Entity, 0)
  604. failedEntitiesID := make([]string, 0)
  605. for _, k := range keys {
  606. e, err := asymkey_model.GPGKeyToEntity(ctx, k)
  607. if err != nil {
  608. if asymkey_model.IsErrGPGKeyImportNotExist(err) {
  609. failedEntitiesID = append(failedEntitiesID, k.KeyID)
  610. continue // Skip previous import without backup of imported armored key
  611. }
  612. ctx.ServerError("ShowGPGKeys", err)
  613. return
  614. }
  615. entities = append(entities, e)
  616. }
  617. var buf bytes.Buffer
  618. headers := make(map[string]string)
  619. if len(failedEntitiesID) > 0 { // If some key need re-import to be exported
  620. headers["Note"] = "The keys with the following IDs couldn't be exported and need to be reuploaded " + strings.Join(failedEntitiesID, ", ")
  621. } else if len(entities) == 0 {
  622. headers["Note"] = "This user hasn't uploaded any GPG keys."
  623. }
  624. writer, _ := armor.Encode(&buf, "PGP PUBLIC KEY BLOCK", headers)
  625. for _, e := range entities {
  626. err = e.Serialize(writer) // TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange)
  627. if err != nil {
  628. ctx.ServerError("ShowGPGKeys", err)
  629. return
  630. }
  631. }
  632. writer.Close()
  633. ctx.PlainTextBytes(http.StatusOK, buf.Bytes())
  634. }
  635. func UsernameSubRoute(ctx *context.Context) {
  636. // WORKAROUND to support usernames with "." in it
  637. // https://github.com/go-chi/chi/issues/781
  638. username := ctx.PathParam("username")
  639. reloadParam := func(suffix string) (success bool) {
  640. ctx.SetPathParam("username", strings.TrimSuffix(username, suffix))
  641. context.UserAssignmentWeb()(ctx)
  642. if ctx.Written() {
  643. return false
  644. }
  645. // check view permissions
  646. if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) {
  647. ctx.NotFound(fmt.Errorf("%s", ctx.ContextUser.Name))
  648. return false
  649. }
  650. return true
  651. }
  652. switch {
  653. case strings.HasSuffix(username, ".png"):
  654. if reloadParam(".png") {
  655. AvatarByUsernameSize(ctx)
  656. }
  657. case strings.HasSuffix(username, ".keys"):
  658. if reloadParam(".keys") {
  659. ShowSSHKeys(ctx)
  660. }
  661. case strings.HasSuffix(username, ".gpg"):
  662. if reloadParam(".gpg") {
  663. ShowGPGKeys(ctx)
  664. }
  665. case strings.HasSuffix(username, ".rss"):
  666. if !setting.Other.EnableFeed {
  667. ctx.HTTPError(http.StatusNotFound)
  668. return
  669. }
  670. if reloadParam(".rss") {
  671. feed.ShowUserFeedRSS(ctx)
  672. }
  673. case strings.HasSuffix(username, ".atom"):
  674. if !setting.Other.EnableFeed {
  675. ctx.HTTPError(http.StatusNotFound)
  676. return
  677. }
  678. if reloadParam(".atom") {
  679. feed.ShowUserFeedAtom(ctx)
  680. }
  681. default:
  682. context.UserAssignmentWeb()(ctx)
  683. if !ctx.Written() {
  684. ctx.Data["EnableFeed"] = setting.Other.EnableFeed
  685. OwnerProfile(ctx)
  686. }
  687. }
  688. }
  689. func getUserIssueStats(ctx *context.Context, ctxUser *user_model.User, filterMode int, opts *issue_indexer.SearchOptions) (ret *issues_model.IssueStats, err error) {
  690. ret = &issues_model.IssueStats{}
  691. doerID := ctx.Doer.ID
  692. opts = opts.Copy(func(o *issue_indexer.SearchOptions) {
  693. // If the doer is the same as the context user, which means the doer is viewing his own dashboard,
  694. // it's not enough to show the repos that the doer owns or has been explicitly granted access to,
  695. // because the doer may create issues or be mentioned in any public repo.
  696. // So we need search issues in all public repos.
  697. o.AllPublic = doerID == ctxUser.ID
  698. })
  699. // Open/Closed are for the tabs of the issue list
  700. {
  701. openClosedOpts := opts.Copy()
  702. switch filterMode {
  703. case issues_model.FilterModeAll:
  704. // no-op
  705. case issues_model.FilterModeYourRepositories:
  706. openClosedOpts.AllPublic = false
  707. case issues_model.FilterModeAssign:
  708. openClosedOpts.AssigneeID = strconv.FormatInt(doerID, 10)
  709. case issues_model.FilterModeCreate:
  710. openClosedOpts.PosterID = strconv.FormatInt(doerID, 10)
  711. case issues_model.FilterModeMention:
  712. openClosedOpts.MentionID = optional.Some(doerID)
  713. case issues_model.FilterModeReviewRequested:
  714. openClosedOpts.ReviewRequestedID = optional.Some(doerID)
  715. case issues_model.FilterModeReviewed:
  716. openClosedOpts.ReviewedID = optional.Some(doerID)
  717. }
  718. openClosedOpts.IsClosed = optional.Some(false)
  719. ret.OpenCount, err = issue_indexer.CountIssues(ctx, openClosedOpts)
  720. if err != nil {
  721. return nil, err
  722. }
  723. openClosedOpts.IsClosed = optional.Some(true)
  724. ret.ClosedCount, err = issue_indexer.CountIssues(ctx, openClosedOpts)
  725. if err != nil {
  726. return nil, err
  727. }
  728. }
  729. // Below stats are for the left sidebar
  730. opts = opts.Copy(func(o *issue_indexer.SearchOptions) {
  731. o.AssigneeID = ""
  732. o.PosterID = ""
  733. o.MentionID = nil
  734. o.ReviewRequestedID = nil
  735. o.ReviewedID = nil
  736. })
  737. ret.YourRepositoriesCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.AllPublic = false }))
  738. if err != nil {
  739. return nil, err
  740. }
  741. ret.AssignCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.AssigneeID = strconv.FormatInt(doerID, 10) }))
  742. if err != nil {
  743. return nil, err
  744. }
  745. ret.CreateCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.PosterID = strconv.FormatInt(doerID, 10) }))
  746. if err != nil {
  747. return nil, err
  748. }
  749. ret.MentionCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.MentionID = optional.Some(doerID) }))
  750. if err != nil {
  751. return nil, err
  752. }
  753. ret.ReviewRequestedCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.ReviewRequestedID = optional.Some(doerID) }))
  754. if err != nil {
  755. return nil, err
  756. }
  757. ret.ReviewedCount, err = issue_indexer.CountIssues(ctx, opts.Copy(func(o *issue_indexer.SearchOptions) { o.ReviewedID = optional.Some(doerID) }))
  758. if err != nil {
  759. return nil, err
  760. }
  761. return ret, nil
  762. }