Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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