16.2 KiB · text History 4ed675a
//! The landing page (`/`): two columns in both layouts. Categories on the
//! left (the visible top level, each with its visible children); on the
//! right a Latest row and, under it, a Popular row, across everything the
//! viewer can see. Classic shows each as the usual topic table; Focus as
//! tiles, with the reader (`&topic=<id>`, plus `&list=popular` for the second
//! row) stepping through that row.
//!
//! Each row's heading opens its full feed, `/p/latest` and `/p/popular`
//! ([`feed`]), in either layout. The full categories page that used to be
//! the landing lives at `/c/` ([`super::forum::categories_index`]).


use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use std::collections::HashMap;

use chrono::Utc;

use super::focus::{self, subtree_count, topic_counts, ListPage, ViewMode};
use super::forum::{build_topic_rows, ise, viewer_of, TopicSort};
use crate::category_tree::{color_widget_css, CategoryTree};
use crate::entities::{post_reactions, posts, topics, users};
use crate::middleware::UserContext;
use crate::AppState;

/// How many topics each landing row shows; the full feeds show [`FEED_LIMIT`].
pub(crate) const LANDING_LATEST: u64 = 12;
pub(crate) const LANDING_POPULAR: usize = 8;
pub(crate) const FEED_LIMIT: u64 = 50;
/// Popular considers topics active within this many days.
const POPULAR_WINDOW_DAYS: i64 = 30;

#[derive(Debug, Deserialize)]
pub struct LandingQuery {
    /// `classic` or `focus` (or the old `list`/`visual`); see
    /// [`focus::resolve_view`].
    pub view: Option<String>,
    /// Focus: open the reader at this topic.
    pub topic: Option<Uuid>,
    /// Focus on the landing: which row the reader steps through
    /// (`popular`; anything else = latest).
    pub list: Option<String>,
}

/// The two feeds.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Feed {
    Latest,
    Popular,
}

impl Feed {
    fn parse(s: Option<&str>) -> Self {
        if s == Some("popular") { Feed::Popular } else { Feed::Latest }
    }
    fn slug(self) -> &'static str {
        match self { Feed::Latest => "latest", Feed::Popular => "popular" }
    }
    fn heading(self) -> &'static str {
        match self { Feed::Latest => "Latest", Feed::Popular => "Popular" }
    }
    fn icon(self) -> &'static str {
        match self { Feed::Latest => "fa-clock", Feed::Popular => "fa-fire" }
    }
    fn blurb(self) -> &'static str {
        match self {
            Feed::Latest => "Topics with the most recent activity.",
            Feed::Popular => "The most engaged-with topics of the last 30 days: replies, reactions and views, with newer activity counting for more.",
        }
    }
}

#[derive(Serialize)]
struct SideCategory {
    name: String,
    slug: String,
    href: String,
    widget_bg: String,
    count: u64,
    children: Vec<SideCategory>,
}

fn user_sort(uc: Option<&UserContext>) -> TopicSort {
    uc.and_then(|c| TopicSort::parse(&c.user.preferred_sort)).unwrap_or(TopicSort::Latest)
}

/// The landing's categories column: visible top-level
/// categories, each with its visible children, linked in the current layout.
fn side_categories(
    tree: &CategoryTree,
    vis: &crate::category_tree::Visible,
    counts: &HashMap<Uuid, u64>,
    is_focus: bool,
    sort: TopicSort,
) -> Vec<SideCategory> {
    let side = |id: Uuid| -> Option<SideCategory> {
        let c = tree.get(id)?;
        Some(SideCategory {
            name: c.name.clone(),
            slug: c.slug.clone(),
            href: if is_focus { focus::focus_url(&c.slug, sort) } else { format!("/c/{}", c.slug) },
            widget_bg: color_widget_css(&tree.widget_colors(id)),
            count: subtree_count(tree, vis, counts, id),
            children: Vec::new(),
        })
    };
    tree.roots()
        .iter()
        .filter(|id| vis.contains(id))
        .filter_map(|&root| {
            let mut row = side(root)?;
            row.children = tree
                .children(root)
                .iter()
                .filter(|id| vis.contains(id))
                .filter_map(|&id| side(id))
                .collect();
            Some(row)
        })
        .collect()
}

/// The Focus rail beside a feed: `..` home, both feeds (this one in focus),
/// then the visible top-level categories.
fn feed_rail(
    tree: &CategoryTree,
    vis: &crate::category_tree::Visible,
    counts: &HashMap<Uuid, u64>,
    current: Feed,
    sort: TopicSort,
    lens: (usize, usize),
) -> (focus::UpLink, Vec<focus::RailItem>) {
    let mut rail = vec![
        focus::rail_feed("Latest", "feed-latest", "/p/latest?view=focus".into(), Feed::Latest.icon(), lens.0 as u64, current == Feed::Latest),
        focus::rail_feed("Popular", "feed-popular", "/p/popular?view=focus".into(), Feed::Popular.icon(), lens.1 as u64, current == Feed::Popular),
    ];
    rail.extend(
        tree.roots()
            .iter()
            .filter(|id| vis.contains(id))
            .filter_map(|&id| {
                let slug = &tree.get(id)?.slug;
                focus::rail_category(tree, id, focus::focus_url(slug, sort), subtree_count(tree, vis, counts, id))
            }),
    );
    (focus::up_link("Home", "/?view=focus"), rail)
}

/// The newest-activity live topics in categories the viewer can see.
pub(crate) async fn latest_topics(
    state: &AppState,
    vis: &crate::category_tree::Visible,
    limit: u64,
) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
    if vis.is_empty() {
        return Ok(Vec::new());
    }
    topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(vis.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .filter(vis.viewer.topic_condition())
        .order_by_desc(topics::Column::BumpedAt)
        .limit(limit)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load latest topics"))
}

/// Engagement score for Popular: replies weigh most, then reactions, then
/// views, all decayed by how long ago the topic was last active.
pub(crate) fn popular_score(replies: i64, reactions: i64, views: i64, hours_since_bump: f64) -> f64 {
    let engagement = 3.0 * replies.max(0) as f64 + 2.0 * reactions.max(0) as f64 + views.max(0) as f64 / 10.0;
    engagement / (hours_since_bump.max(0.0) + 2.0).powf(1.2)
}

/// Live topics the viewer can see, active in the last
/// [`POPULAR_WINDOW_DAYS`], ranked by [`popular_score`]. Pinned topics get
/// no special place here.
pub(crate) async fn popular_topics(
    state: &AppState,
    vis: &crate::category_tree::Visible,
    limit: usize,
) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
    if vis.is_empty() {
        return Ok(Vec::new());
    }
    let since = Utc::now() - chrono::Duration::days(POPULAR_WINDOW_DAYS);
    let loaded = topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(vis.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .filter(vis.viewer.topic_condition())
        .filter(topics::Column::BumpedAt.gte(since))
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load popular candidates"))?;
    let ids: Vec<Uuid> = loaded.iter().map(|(t, _)| t.id).collect();
    let reactions: HashMap<Uuid, i64> = if ids.is_empty() {
        HashMap::new()
    } else {
        post_reactions::Entity::find()
            .select_only()
            .column(posts::Column::TopicId)
            .column_as(post_reactions::Column::Id.count(), "n")
            .join(JoinType::InnerJoin, post_reactions::Relation::Posts.def())
            .filter(posts::Column::TopicId.is_in(ids))
            .filter(posts::Column::DeletedAt.is_null())
            .group_by(posts::Column::TopicId)
            .into_tuple::<(Uuid, i64)>()
            .all(state.db.as_ref())
            .await
            .map_err(ise("count reactions per topic"))?
            .into_iter()
            .collect()
    };
    let now = Utc::now();
    let mut scored: Vec<(f64, (topics::Model, Option<users::Model>))> = loaded
        .into_iter()
        .map(|(t, u)| {
            let hours = (now - t.bumped_at.with_timezone(&Utc)).num_seconds() as f64 / 3600.0;
            let score = popular_score(
                (t.posts_count - 1) as i64,
                reactions.get(&t.id).copied().unwrap_or(0),
                t.views as i64,
                hours,
            );
            (score, (t, u))
        })
        .collect();
    scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)
        .then_with(|| b.1 .0.bumped_at.cmp(&a.1 .0.bumped_at)));
    Ok(scored.into_iter().take(limit).filter(|(s, _)| *s > 0.0).map(|(_, r)| r).collect())
}

async fn feed_topics(
    state: &AppState,
    vis: &crate::category_tree::Visible,
    feed: Feed,
    limit: usize,
) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
    match feed {
        Feed::Latest => latest_topics(state, vis, limit as u64).await,
        Feed::Popular => popular_topics(state, vis, limit).await,
    }
}

#[derive(Debug, Deserialize)]
pub struct FeedQuery {
    pub view: Option<String>,
    pub topic: Option<Uuid>,
}

/// `/p/latest` and `/p/popular`: the full feed in the viewer's layout
/// (Classic table or Focus tiles with the reader).
async fn feed(
    state: AppState,
    feed: Feed,
    q: FeedQuery,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let uc = user_context.as_ref();
    let view = focus::view_for(&state, q.view.as_deref(), uc, &headers);
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let loaded = feed_topics(&state, &vis, feed, FEED_LIMIT as usize).await?;
    let path = format!("/p/{}", feed.slug());
    let is_focus = view.is_focus();
    if is_focus && focus::wants_reader(&headers) {
        let (_, reader) = focus::tiles_and_reader(&state, &tree, loaded, uc, &headers, q.topic).await?;
        let base = format!("{path}?view=focus");
        return Ok(view.respond(focus::reader_fragment(&state, reader, &base, uc)?));
    }
    if is_focus {
        let counts = topic_counts(&state).await?;
        let sort = user_sort(uc);
        // The other feed's size, for its square on the rail.
        let other = match feed {
            Feed::Latest => Feed::Popular,
            Feed::Popular => Feed::Latest,
        };
        let other_len = feed_topics(&state, &vis, other, FEED_LIMIT as usize).await?.len();
        let lens = match feed {
            Feed::Latest => (loaded.len(), other_len),
            Feed::Popular => (other_len, loaded.len()),
        };
        let rail = feed_rail(&tree, &vis, &counts, feed, sort, lens);
        let (tiles, reader) = focus::tiles_and_reader(&state, &tree, loaded, uc, &headers, q.topic).await?;
        let mut page = ListPage::new(feed.slug(), feed.heading(), path);
        page.heading_icon = feed.icon();
        page.subheading = Some(feed.blurb().into());
        page.empty = "Nothing here yet.".into();
        page.rail = Some(rail);
        page.rail_label = "Feeds and categories";
        let html = page.render(&state, tiles, reader, uc, &headers)?;
        return Ok(view.respond(html));
    }
    let rows = build_topic_rows(&state, &tree, loaded).await?;
    let page = super::render(
        &state,
        "forum/feed.html",
        context! {
            title => feed.heading(),
            app_name => state.config.app_name,
            user => uc.map(|c| c.user.clone()),
            heading => feed.heading(),
            heading_icon => feed.icon(),
            blurb => feed.blurb(),
            toggle_base => path,
            topics => rows,
        },
    )?;
    Ok(view.respond(page))
}

pub async fn feed_latest(
    State(state): State<AppState>,
    Query(q): Query<FeedQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    feed(state, Feed::Latest, q, headers, user_context).await
}

pub async fn feed_popular(
    State(state): State<AppState>,
    Query(q): Query<FeedQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    feed(state, Feed::Popular, q, headers, user_context).await
}

pub async fn home(
    State(state): State<AppState>,
    Query(q): Query<LandingQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let uc = user_context.as_ref();
    let view = focus::view_for(&state, q.view.as_deref(), uc, &headers);
    let is_focus = view.mode == ViewMode::Focus;

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let latest = latest_topics(&state, &vis, LANDING_LATEST).await?;
    let popular = popular_topics(&state, &vis, LANDING_POPULAR).await?;

    // Focus: the reader steps through the row its tile came from.
    let reader_feed = Feed::parse(q.list.as_deref());
    let latest_base = "/?view=focus".to_string();
    let popular_base = "/?view=focus&list=popular".to_string();
    if is_focus && focus::wants_reader(&headers) {
        let (loaded, base) = match reader_feed {
            Feed::Latest => (latest, &latest_base),
            Feed::Popular => (popular, &popular_base),
        };
        let (_, reader) = focus::tiles_and_reader(&state, &tree, loaded, uc, &headers, q.topic).await?;
        return Ok(view.respond(focus::reader_fragment(&state, reader, base, uc)?));
    }

    let counts = topic_counts(&state).await?;
    let categories = side_categories(&tree, &vis, &counts, is_focus, user_sort(uc));

    let user = uc.map(|c| c.user.clone());
    let can_write = uc.is_some_and(|c| super::may_write(&state, &c.user));
    let page = if is_focus {
        // Only the row named by `list` can open the reader.
        let (latest_open, popular_open) = match reader_feed {
            Feed::Latest => (q.topic, None),
            Feed::Popular => (None, q.topic),
        };
        let (latest_tiles, latest_reader) =
            focus::tiles_and_reader(&state, &tree, latest, uc, &headers, latest_open).await?;
        let (popular_tiles, popular_reader) =
            focus::tiles_and_reader(&state, &tree, popular, uc, &headers, popular_open).await?;
        let (reader, base) = match reader_feed {
            Feed::Latest => (latest_reader, latest_base.clone()),
            Feed::Popular => (popular_reader, popular_base.clone()),
        };
        super::render(
            &state,
            "forum/landing_focus.html",
            context! {
                title => "Home",
                app_name => state.config.app_name,
                user => user,
                can_write => can_write,
                categories => categories,
                latest => latest_tiles,
                popular => popular_tiles,
                latest_base => latest_base,
                popular_base => popular_base,
                reader => reader,
                base => base,
            },
        )?
    } else {
        let latest_rows = build_topic_rows(&state, &tree, latest).await?;
        let popular_rows = build_topic_rows(&state, &tree, popular).await?;
        super::render(
            &state,
            "forum/landing.html",
            context! {
                title => "Home",
                app_name => state.config.app_name,
                user => user,
                can_write => can_write,
                categories => categories,
                latest => latest_rows,
                popular => popular_rows,
            },
        )?
    };
    Ok(view.respond(page))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn popular_prefers_engagement_and_freshness() {
        // More engagement wins at the same age.
        assert!(popular_score(10, 5, 200, 24.0) > popular_score(2, 0, 40, 24.0));
        // The same engagement counts for less as it ages.
        assert!(popular_score(5, 5, 100, 2.0) > popular_score(5, 5, 100, 240.0));
        // Nothing at all scores zero (and is left out).
        assert_eq!(popular_score(0, 0, 0, 1.0), 0.0);
        assert_eq!(Feed::parse(Some("popular")).slug(), "popular");
        assert_eq!(Feed::parse(Some("bogus")).slug(), "latest");
    }
}