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

home.go 24KB

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