7.2 KiB · text History 3d71adc
//! Tags, search, bookmarks, notifications — each through the same visibility
//! filter as its web page (`tags::visible_tags` / `tag_topics` /
//! `search_topics`, `bookmarks::visible_bookmarks`,
//! `notifications::visible_notifications`).
use std::collections::HashMap;

use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use sea_orm::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::forum::summaries;
use super::views::{utc, Author, Tag, TopicSummary};
use super::{ApiPath, ApiResult};
use crate::actions::viewer;
use crate::category_tree::CategoryTree;
use crate::entities::{topics, users};
use crate::handlers::{bookmarks, notifications as web_notifications, tags};
use crate::middleware::UserContext;
use crate::AppState;

#[derive(Serialize)]
pub struct TagCount {
    pub name: String,
    pub slug: String,
    /// Live topics with it that this user can see.
    pub count: i64,
}

#[derive(Serialize)]
pub struct TagsIndex {
    pub tags: Vec<TagCount>,
}

/// `GET /tags` — most used first; tags used only where you can't look are
/// left out.
pub async fn index(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<TagsIndex>> {
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    let vis = tree.visible_category_ids(viewer(&uc.user));
    let tags = tags::visible_tags(&state, &vis)
        .await?
        .into_iter()
        .map(|t| TagCount { name: t.name, slug: t.slug, count: t.cnt })
        .collect();
    Ok(Json(TagsIndex { tags }))
}

#[derive(Serialize)]
pub struct TagPage {
    pub tag: Tag,
    pub topics: Vec<TopicSummary>,
}

/// `GET /tags/{slug}`
pub async fn show(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(slug): ApiPath<String>,
) -> ApiResult<Json<TagPage>> {
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    let vis = tree.visible_category_ids(viewer(&uc.user));
    let (tag, loaded) = tags::tag_topics(&state, &slug, &vis).await?;
    Ok(Json(TagPage {
        tag: Tag { name: tag.name, slug: tag.slug },
        topics: summaries(&state, &tree, loaded, uc.user.id).await?,
    }))
}

#[derive(Debug, Deserialize)]
pub struct SearchQuery {
    pub q: Option<String>,
}

#[derive(Serialize)]
pub struct SearchResults {
    pub q: String,
    /// At most 50; empty under two characters.
    pub topics: Vec<TopicSummary>,
}

/// `GET /search?q=` — titles, post bodies, tag names.
pub async fn search(
    State(state): State<AppState>,
    uc: UserContext,
    Query(q): Query<SearchQuery>,
) -> ApiResult<Json<SearchResults>> {
    let q = q.q.unwrap_or_default().trim().to_string();
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    let vis = tree.visible_category_ids(viewer(&uc.user));
    let loaded = tags::search_topics(&state, &q, &vis).await?;
    Ok(Json(SearchResults { topics: summaries(&state, &tree, loaded, uc.user.id).await?, q }))
}

#[derive(Serialize)]
pub struct Bookmark {
    pub post_id: Uuid,
    pub topic_id: Uuid,
    pub topic_title: String,
    pub post_number: i32,
    /// The post's HTML; empty once it's removed.
    pub cooked: String,
    pub deleted: bool,
    pub created_at: DateTime<Utc>,
}

#[derive(Serialize)]
pub struct Bookmarks {
    pub bookmarks: Vec<Bookmark>,
}

/// `GET /bookmarks` — newest first.
pub async fn bookmarks(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<Bookmarks>> {
    let (loaded, topic_map, _) = bookmarks::visible_bookmarks(&state, &uc).await?;
    let bookmarks = loaded
        .into_iter()
        .filter_map(|(b, p)| {
            let p = p?;
            let (topic, _) = topic_map.get(&p.topic_id)?;
            if topic.deleted_at.is_some() {
                return None;
            }
            let deleted = p.deleted_at.is_some();
            Some(Bookmark {
                post_id: p.id,
                topic_id: p.topic_id,
                topic_title: topic.title.clone(),
                post_number: p.post_number,
                cooked: if deleted || p.hidden_at.is_some() { String::new() } else { p.cooked },
                deleted,
                created_at: utc(b.created_at),
            })
        })
        .collect();
    Ok(Json(Bookmarks { bookmarks }))
}

#[derive(Serialize)]
pub struct Notification {
    pub id: Uuid,
    /// `new_topic` or `reaction`.
    pub kind: String,
    pub topic_id: Option<Uuid>,
    pub post_id: Option<Uuid>,
    pub topic_title: Option<String>,
    pub actor: Option<Author>,
    pub is_read: bool,
    pub created_at: DateTime<Utc>,
}

#[derive(Serialize)]
pub struct Notifications {
    pub unread: u64,
    pub notifications: Vec<Notification>,
}

async fn unread_count(state: &AppState, uc: &UserContext) -> ApiResult<u64> {
    // Counted over the same visible list the page shows, so the badge never
    // promises something the list then hides.
    Ok(web_notifications::visible_notifications(state, uc, 1000)
        .await?
        .iter()
        .filter(|n| !n.is_read)
        .count() as u64)
}

/// `GET /notifications` — the 50 newest you can still see.
pub async fn notifications(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<Notifications>> {
    let list = web_notifications::visible_notifications(&state, &uc, 50).await?;
    let topic_ids: Vec<Uuid> = list.iter().filter_map(|n| n.topic_id).collect();
    let actor_ids: Vec<Uuid> = list.iter().filter_map(|n| n.actor_id).collect();
    let titles: HashMap<Uuid, String> = topics::Entity::find()
        .filter(topics::Column::Id.is_in(topic_ids))
        .all(state.db.as_ref())
        .await?
        .into_iter()
        .map(|t| (t.id, t.title))
        .collect();
    let actors: HashMap<Uuid, String> = users::Entity::find()
        .filter(users::Column::Id.is_in(actor_ids))
        .all(state.db.as_ref())
        .await?
        .into_iter()
        .map(|u| (u.id, u.username))
        .collect();
    let notifications = list
        .into_iter()
        .map(|n| Notification {
            id: n.id,
            kind: n.kind,
            topic_title: n.topic_id.and_then(|t| titles.get(&t).cloned()),
            topic_id: n.topic_id,
            post_id: n.post_id,
            actor: n.actor_id.and_then(|a| actors.get(&a).map(|name| Author::new(a, name.clone()))),
            is_read: n.is_read,
            created_at: utc(n.created_at),
        })
        .collect();
    Ok(Json(Notifications { unread: unread_count(&state, &uc).await?, notifications }))
}

#[derive(Serialize)]
pub struct Unread {
    pub unread: u64,
}

/// `GET /notifications/unread` — the badge.
pub async fn unread(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<Unread>> {
    Ok(Json(Unread { unread: unread_count(&state, &uc).await? }))
}

/// `POST /notifications/{id}/read`
pub async fn mark_read(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
) -> ApiResult<StatusCode> {
    crate::actions::mark_notification_read(&state, uc.user.id, id).await?;
    Ok(StatusCode::NO_CONTENT)
}

/// `POST /notifications/read` — all of them.
pub async fn mark_all_read(State(state): State<AppState>, uc: UserContext) -> ApiResult<StatusCode> {
    crate::actions::mark_all_notifications_read(&state, uc.user.id).await?;
    Ok(StatusCode::NO_CONTENT)
}