//! Discussions: the list at `/{owner}/{repo}/discussions` and the new-discussion form (GET shows //! it, POST creates the discussion and redirects to it). The other discussion pages are //! `discussion_view` (one discussion) and `discussion_actions` (every POST). While a repo has //! discussions off, every discussion page is 404. Writes need a signed-in viewer on a repo that is //! not archived. Announcements need Maintain or higher. use forge_core::discussions::{ DISCUSSION_CATEGORIES, Discussion, DiscussionCategory, DiscussionFilter, }; use forge_core::{Action, AuditAction, Role, User, authorize}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::RawForm; use topcoat::router::error::{bad_request, forbidden, not_found, see_other}; use topcoat::router::{StatusCode, page, path_param, query_params}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; use crate::i18n::community::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::issue_meta::{can_triage, form_field, form_pairs, refusal_message}; use crate::pages::issue_parts::When; use crate::pages::issues_list::{list_href, state_tab_class}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::render::markdown::mentioned_usernames; use crate::state::AppState; use crate::views::{alert, csrf_field, now_unix, repo_href, shell, user_link}; path_param!(owner); path_param!(repo); /// Discussions per list page. pub(crate) const PER_PAGE: u32 = 25; /// Highest accepted `?page=` value. Anything else falls back to page 1. const MAX_PAGE: u32 = 1000; /// The repo's discussions URL, with `rest` appended (for example a number). pub(crate) fn discussions_href(owner: &str, repo: &str, rest: &str) -> String { repo_href(owner, repo, "discussions", rest) } /// 404 while the repo has discussions off. Every discussion page starts with this. pub(crate) async fn ensure_enabled(state: &AppState, ctx: &RepoCtx) -> Result<()> { if state.store.discussions_enabled(&ctx.repo.id).await? { Ok(()) } else { Err(not_found().into()) } } /// Maintain or higher, the owner, or an instance admin. Only these may post announcements. pub(crate) fn maintains(ctx: &RepoCtx) -> bool { let actor = ctx.viewer.as_ref().map(|(user, _)| user); authorize(actor, &ctx.repo, ctx.role, ctx.org_role, Action::Admin).is_ok() || (ctx.viewer.is_some() && matches!(ctx.role, Some(Role::Maintain))) } /// Whether the viewer may add comments, reactions or replies: signed in, and the repo is not /// archived. A locked discussion takes writes from Triage holders only. pub(crate) fn may_converse(ctx: &RepoCtx, locked: bool) -> bool { ctx.viewer.is_some() && !ctx.repo.archived && (!locked || can_triage(ctx)) } /// Whether the signed-in viewer wrote this row. pub(crate) fn is_author(ctx: &RepoCtx, author_id: &str) -> bool { ctx.viewer .as_ref() .is_some_and(|(user, _)| user.id == author_id) } /// Writes the audit entry for a discussion or comment action. `target_id` is the discussion, or a /// comment of it. The repo's `owner/name` names the target. pub(crate) async fn audit_discussion( cx: &Cx, state: &AppState, user: &User, ctx: &RepoCtx, action: AuditAction, target_id: &str, ) { let name = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); audit::record( &state.store, Some(cx), Actor::User(user), action, Target { kind: "discussion", id: target_id, name: &name, }, serde_json::Value::Null, ) .await; } /// Notifies the users that `text` mentions. Only people who can read the repo, other than the /// actor, get an inbox row. When `old` is given (an edit), only users mentioned newly are notified. /// Never fails: problems are logged. pub(crate) async fn notify_mentions( state: &AppState, ctx: &RepoCtx, discussion_id: &str, actor_id: &str, text: &str, old: Option<&str>, ) { let mut names = mentioned_usernames(text); if let Some(old) = old { let before = mentioned_usernames(old); names.retain(|name| !before.contains(name)); } let mut ids: Vec = Vec::new(); for name in names { let user = match state.store.user_by_username(&name).await { Ok(Some(user)) => user, Ok(None) => continue, Err(e) => { tracing::error!(error = %e, name, "discussions: mention lookup failed"); continue; } }; if user.id == actor_id { continue; } let role = match state.store.collaborator_role(&ctx.repo.id, &user.id).await { Ok(role) => role, Err(e) => { tracing::error!(error = %e, "discussions: role lookup failed"); continue; } }; let org_role = match state .store .org_repo_role(&ctx.repo.owner_id, &user.id, &ctx.repo.id) .await { Ok(role) => role, Err(e) => { tracing::error!(error = %e, "discussions: org role lookup failed"); continue; } }; if authorize(Some(&user), &ctx.repo, role, org_role, Action::Read).is_ok() { ids.push(user.id); } } if let Err(e) = state .store .record_discussion_mentions(&ctx.repo.id, discussion_id, actor_id, &ids) .await { tracing::error!(error = %e, discussion_id, "discussions: mention rows failed"); } } /// The category choices of a select. Announcements appear only for maintainers. pub(crate) struct CategoryOption { pub(crate) value: &'static str, pub(crate) label: &'static str, pub(crate) selected: bool, } pub(crate) fn category_options( lang: Lang, selected: Option, maintainer: bool, ) -> Vec { DISCUSSION_CATEGORIES .iter() .filter(|c| maintainer || **c != DiscussionCategory::Announcements) .map(|c| CategoryOption { value: c.as_str(), label: g::category_label(lang, *c), selected: Some(*c) == selected, }) .collect() } /// The list's query. `category` is a category name; anything else lists every category. #[query_params(error = bad_request)] pub(crate) struct ListQuery { category: Option, page: Option, } /// One row of the list, with the strings already built. struct RowView { href: String, title: String, category: &'static str, author: String, relative: String, absolute: String, iso: String, comments_text: String, } fn row_view( lang: Lang, owner: &str, repo: &str, item: &forge_core::discussions::DiscussionListItem, tz: &str, now: i64, ) -> RowView { let d = &item.discussion; let when = When::new(lang, &d.created_at, tz, now); let comments = d.comment_count.max(0); RowView { href: discussions_href(owner, repo, &d.number.to_string()), title: d.title.clone(), category: g::category_label(lang, d.category), author: item.author.clone(), relative: when.relative, absolute: when.absolute, iso: when.iso, comments_text: g::comments_count(lang, comments), } } #[page("/{owner}/{repo}/discussions")] async fn discussions_list_page(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let query = query_params::(cx)?; let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx); ensure_enabled(state, &ctx).await?; let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); let category = query .category .as_deref() .and_then(DiscussionCategory::parse); let page = query .page .as_deref() .and_then(|p| p.trim().parse::().ok()) .filter(|p| (1..=MAX_PAGE).contains(p)) .unwrap_or(1); let filter = DiscussionFilter { category, page, per_page: PER_PAGE, }; let (items, total) = state.store.list_discussions(&ctx.repo.id, &filter).await?; let owner_name = ctx.repo.owner_name.clone(); let repo_name = ctx.repo.name.clone(); let now = now_unix(); let tz = ctx.viewer_tz().to_owned(); let rows: Vec = items .iter() .map(|item| row_view(lang, &owner_name, &repo_name, item, &tz, now)) .collect(); let base = discussions_href(&owner_name, &repo_name, ""); let selected = category.map_or("", |c| c.as_str()); let all_class = state_tab_class(category.is_none()); let all_href = list_href(&base, &[]); let all_label = g::t(lang, K::AllCategories); let nav_label = g::t(lang, K::CategoriesNav); let tabs: Vec<(&'static str, String, &'static str)> = DISCUSSION_CATEGORIES .iter() .map(|c| { ( g::category_label(lang, *c), list_href(&base, &[("category", c.as_str())]), state_tab_class(category == Some(*c)), ) }) .collect(); let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1); let has_newer = page > 1; let has_older = u64::from(page) < last_page; let page_param = |p: u32| { let text = if p > 1 { p.to_string() } else { String::new() }; list_href(&base, &[("category", selected), ("page", text.as_str())]) }; let newer_href = page_param(page.saturating_sub(1)); let older_href = page_param(page + 1); let page_label = g::page_number(lang, page); let can_start = ctx.viewer.is_some() && !ctx.repo.archived; let new_href = discussions_href(&owner_name, &repo_name, "new"); let title = format!( "{owner_name}/{repo_name} \u{b7} {}", g::t(lang, K::Discussions) ); let empty_text = g::t(lang, K::NoDiscussionsYet); let new_label = g::t(lang, K::NewDiscussion); let (by_before, by_middle, by_after) = g::byline(lang); let newer_label = g::t(lang, K::Newer); let older_label = g::t(lang, K::Older); let header = ctx.head(state, "discussions").await?; Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header)
if can_start { }
if rows.is_empty() {

(empty_text)

} else {
    for row in rows.iter() {
  • (row.title.as_str()) (row.category)
    (by_before) user_link(shown: row.author.as_str(), login: row.author.as_str()) (by_middle) if !by_after.is_empty() { (by_after) }
  • }
} ) }) } /// The values the new-discussion form shows: what was typed, and the message when it failed. #[derive(Default)] struct DraftDiscussion { title: String, body: String, error: Option, } #[component] async fn new_discussion_body( lang: Lang, head: RepoHead, csrf: String, draft: DraftDiscussion, options: Vec, ) -> Result { let action = discussions_href(&head.owner, &head.name, "new"); let cancel = discussions_href(&head.owner, &head.name, ""); Ok(view! { repo_head(head: head)

(g::t(lang, K::NewDiscussion))

if let Some(message) = draft.error { alert(message: message.as_str()) }
csrf_field(token: csrf.as_str())
(g::t(lang, K::Cancel))
}) } #[page("/{owner}/{repo}/discussions/new")] async fn discussion_new_page(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx); ensure_enabled(state, &ctx).await?; let viewer = require_user(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); if ctx.repo.archived { return Err(forbidden().into()); } let header = ctx.head(state, "discussions").await?; let title = format!( "{}/{} \u{b7} {}", ctx.repo.owner_name, ctx.repo.name, g::t(lang, K::NewDiscussion) ); let csrf = viewer.1.csrf_token.clone(); let options = category_options(lang, Some(DiscussionCategory::General), maintains(&ctx)); Ok(view! { shell(title: title.as_str(), viewer: Some(&viewer), new_discussion_body(lang: lang, head: header, csrf: csrf, draft: DraftDiscussion::default(), options: options)) }) } #[page(POST "/{owner}/{repo}/discussions/new")] async fn discussion_create(cx: &Cx, RawForm(raw): RawForm) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx); ensure_enabled(state, &ctx).await?; let fields = form_pairs(&raw[..]); let viewer = require_csrf(cx, &form_field(&fields, "csrf")).await?; let lang = i18n::lang(cx, Some(&viewer.0)); if ctx.repo.archived { return Err(forbidden().into()); } let category = match DiscussionCategory::parse(&form_field(&fields, "category")) { Some(category) => category, None => return Err(bad_request("unknown category").into()), }; if category == DiscussionCategory::Announcements && !maintains(&ctx) { return Err(forbidden().into()); } let typed_title = form_field(&fields, "title"); let typed_body = form_field(&fields, "body"); match state .store .create_discussion( &ctx.repo.id, &viewer.0.id, category, &typed_title, &typed_body, ) .await { Ok(discussion) => { audit_discussion( cx, state, &viewer.0, &ctx, AuditAction::DiscussionCreated, &discussion.id, ) .await; notify_mentions(state, &ctx, &discussion.id, &viewer.0.id, &typed_body, None).await; let location = discussions_href( &ctx.repo.owner_name, &ctx.repo.name, &discussion.number.to_string(), ); Err(see_other(location).into()) } Err(e) => { let message = refusal_message(e)?; let header = ctx.head(state, "discussions").await?; let title = format!( "{}/{} \u{b7} {}", ctx.repo.owner_name, ctx.repo.name, g::t(lang, K::NewDiscussion) ); let csrf = viewer.1.csrf_token.clone(); let draft = DraftDiscussion { title: typed_title, body: typed_body, error: Some(message), }; let options = category_options(lang, Some(category), maintains(&ctx)); Ok(view! { (StatusCode::UNPROCESSABLE_ENTITY) shell(title: title.as_str(), viewer: Some(&viewer), new_discussion_body(lang: lang, head: header, csrf: csrf, draft: draft, options: options)) }) } } } /// The discussion with this number in the repo, or 404. pub(crate) async fn discussion_by_number( state: &AppState, ctx: &RepoCtx, number: &str, ) -> Result { let Some(n) = number.parse::().ok() else { return Err(not_found().into()); }; match state.store.discussion_by_number(&ctx.repo.id, n).await? { Some(discussion) => Ok(discussion), None => Err(not_found().into()), } }