usenet_reborn 0.2.2

Terminal-based Usenet NNTP client written in Rust with ratatui/crossterm.
use crate::db;
use crate::nntp_client::NntpClient;
use rusqlite::Connection;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Fetch how many new articles each group has by comparing the high water mark to the last_seen ID.
///
/// # Arguments
///
/// * `client` - shared NNTP client
/// * `db` - shared SQLite connection
/// * `subscriptions` - list of newsgroup names
/// * `new_counts` - mutable slice to populate with counts
pub async fn update_new_counts(
    client: &Arc<Mutex<NntpClient>>,
    db: &Arc<Mutex<Connection>>,
    subscriptions: &[String],
    new_counts: &mut [u32],
) {
    for (i, group) in subscriptions.iter().enumerate() {
        // 1) Get the last_seen ID from SQLite (default to 0 on error)
        let last_seen: u32 = {
            let db = db.clone();
            let group = group.clone();
            tokio::task::spawn_blocking(move || {
                db::get_last_seen(&db.blocking_lock(), &group).unwrap_or(0)
            })
            .await
            .unwrap_or(0)
        };

        // 2) Fetch group bounds (low, high) via the GROUP command
        //    Difference high - last_seen = count of new articles
        let new_count = if let Ok((_, high)) = {
            let mut cl = client.lock().await;
            cl.group_bounds(group).await
        } {
            high.saturating_sub(last_seen)
        } else {
            0
        };

        // 3) Write the computed count
        new_counts[i] = new_count;
    }
}

/// Fetch the new‐article count for exactly one group.
pub async fn fetch_new_count_for_group(
    client: &Arc<Mutex<NntpClient>>,
    db: &Arc<Mutex<Connection>>,
    group: &str,
) -> u32 {
    // 1) last_seen
    let last_seen: u32 = {
        let db = db.clone();
        let group = group.to_string();
        tokio::task::spawn_blocking(move || {
            db::get_last_seen(&db.blocking_lock(), &group).unwrap_or(0)
        })
        .await
        .unwrap_or(0)
    };

    // 2) group_bounds
    let new_count = if let Ok((_, high)) = {
        let mut cl = client.lock().await;
        cl.group_bounds(group).await
    } {
        high.saturating_sub(last_seen)
    } else {
        0
    };

    new_count
}