use anyhow::Result; use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use sqlx::{Row, SqlitePool}; use jacquard::api::community_lexicon::calendar::event::{Event, EventLocationsItem}; use jacquard::api::community_lexicon::calendar::rsvp::{Rsvp, RsvpStatus}; pub async fn init(path: &str) -> Result { if let Some(parent) = std::path::Path::new(path).parent() { std::fs::create_dir_all(parent)?; } let options = SqliteConnectOptions::new() .filename(path) .create_if_missing(true); let pool = SqlitePoolOptions::new() .max_connections(5) .connect_with(options) .await?; sqlx::query( r#" CREATE TABLE IF NOT EXISTS events ( uri TEXT PRIMARY KEY, did TEXT NOT NULL, rkey TEXT NOT NULL, cid TEXT, name TEXT NOT NULL, description TEXT, starts_at TEXT, ends_at TEXT, mode TEXT, status TEXT, location_text TEXT, link TEXT, created_at TEXT ); CREATE TABLE IF NOT EXISTS rsvps ( uri TEXT PRIMARY KEY, did TEXT NOT NULL, rkey TEXT NOT NULL, event_uri TEXT NOT NULL, status TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_rsvps_event ON rsvps(event_uri); CREATE INDEX IF NOT EXISTS idx_events_starts ON events(starts_at); CREATE TABLE IF NOT EXISTS indexer_cursor ( id INTEGER PRIMARY KEY CHECK (id = 1), time_us INTEGER NOT NULL ); "#, ) .execute(&pool) .await?; Ok(pool) } pub fn normalize_dt(value: Option<&jacquard::common::types::string::Datetime>) -> Option { let raw = value?.as_str(); chrono::DateTime::parse_from_rfc3339(raw) .ok() .map(|dt| dt.to_utc().format("%Y-%m-%dT%H:%M:%SZ").to_string()) .or_else(|| Some(raw.to_string())) } fn event_parts(event: &Event) -> (Option, Option) { let mut location = None; let mut link = None; if let Some(items) = &event.locations { for item in items { match item { EventLocationsItem::Address(address) => { location = address.name.as_ref().map(|n| n.to_string()); } EventLocationsItem::Uri(uri) => { link = Some(uri.uri.as_str().to_string()); } _ => {} } } } (location, link) } pub async fn upsert_event( pool: &SqlitePool, uri: &str, did: &str, rkey: &str, cid: Option<&str>, event: &Event, ) -> Result<()> { let (location, link) = event_parts(event); sqlx::query( r#" INSERT INTO events (uri, did, rkey, cid, name, description, starts_at, ends_at, mode, status, location_text, link, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13) ON CONFLICT(uri) DO UPDATE SET cid = excluded.cid, name = excluded.name, description = excluded.description, starts_at = excluded.starts_at, ends_at = excluded.ends_at, mode = excluded.mode, status = excluded.status, location_text = excluded.location_text, link = excluded.link "#, ) .bind(uri) .bind(did) .bind(rkey) .bind(cid) .bind(event.name.to_string()) .bind(event.description.as_ref().map(|d| d.to_string())) .bind(normalize_dt(event.starts_at.as_ref())) .bind(normalize_dt(event.ends_at.as_ref())) .bind(event.mode.as_ref().map(|m| short_token(m.as_str()))) .bind(event.status.as_ref().map(|s| short_token(s.as_str()))) .bind(location) .bind(link) .bind(normalize_dt(Some(&event.created_at))) .execute(pool) .await?; Ok(()) } pub async fn delete_event(pool: &SqlitePool, uri: &str) -> Result<()> { sqlx::query("DELETE FROM events WHERE uri = ?1") .bind(uri) .execute(pool) .await?; Ok(()) } pub fn short_token(value: &str) -> String { value.rsplit('#').next().unwrap_or(value).to_string() } pub fn rsvp_status_str(status: &RsvpStatus) -> String { short_token(status.as_str()) } pub async fn upsert_rsvp( pool: &SqlitePool, uri: &str, did: &str, rkey: &str, rsvp: &Rsvp, ) -> Result<()> { sqlx::query( r#" INSERT INTO rsvps (uri, did, rkey, event_uri, status) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(uri) DO UPDATE SET status = excluded.status "#, ) .bind(uri) .bind(did) .bind(rkey) .bind(rsvp.subject.uri.as_str()) .bind(rsvp_status_str(&rsvp.status)) .execute(pool) .await?; Ok(()) } pub async fn delete_rsvp(pool: &SqlitePool, uri: &str) -> Result<()> { sqlx::query("DELETE FROM rsvps WHERE uri = ?1") .bind(uri) .execute(pool) .await?; Ok(()) } pub struct GuestRow { pub did: String, pub status: String, } pub async fn guests_for_event(pool: &SqlitePool, event_uri: &str) -> Result> { let rows = sqlx::query("SELECT did, status FROM rsvps WHERE event_uri = ?1 ORDER BY uri") .bind(event_uri) .fetch_all(pool) .await?; Ok(rows .into_iter() .map(|row| GuestRow { did: row.get("did"), status: row.get("status"), }) .collect()) } pub struct FeedRow { pub did: String, pub rkey: String, pub name: String, pub starts_at: Option, pub location_text: Option, pub going: i64, pub interested: i64, } pub async fn upcoming_events(pool: &SqlitePool, limit: i64) -> Result> { let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); let rows = sqlx::query( r#" SELECT e.uri, e.did, e.rkey, e.name, e.starts_at, e.location_text, COALESCE(SUM(CASE WHEN r.status = 'going' THEN 1 ELSE 0 END), 0) AS going, COALESCE(SUM(CASE WHEN r.status = 'interested' THEN 1 ELSE 0 END), 0) AS interested FROM events e LEFT JOIN rsvps r ON r.event_uri = e.uri WHERE (e.status IS NULL OR e.status != 'cancelled') AND (e.starts_at IS NULL OR e.starts_at >= ?1) GROUP BY e.uri ORDER BY e.starts_at IS NULL, e.starts_at LIMIT ?2 "#, ) .bind(now) .bind(limit) .fetch_all(pool) .await?; Ok(rows .into_iter() .map(|row| FeedRow { did: row.get("did"), rkey: row.get("rkey"), name: row.get("name"), starts_at: row.get("starts_at"), location_text: row.get("location_text"), going: row.get("going"), interested: row.get("interested"), }) .collect()) } pub async fn counts_for_events( pool: &SqlitePool, did: &str, ) -> Result> { let rows = sqlx::query( r#" SELECT r.event_uri, COALESCE(SUM(CASE WHEN r.status = 'going' THEN 1 ELSE 0 END), 0) AS going, COALESCE(SUM(CASE WHEN r.status = 'interested' THEN 1 ELSE 0 END), 0) AS interested FROM rsvps r JOIN events e ON e.uri = r.event_uri WHERE e.did = ?1 GROUP BY r.event_uri "#, ) .bind(did) .fetch_all(pool) .await?; Ok(rows .into_iter() .map(|row| { ( row.get::("event_uri"), (row.get("going"), row.get("interested")), ) }) .collect()) } pub async fn load_cursor(pool: &SqlitePool) -> Result> { let row = sqlx::query("SELECT time_us FROM indexer_cursor WHERE id = 1") .fetch_optional(pool) .await?; Ok(row.map(|r| r.get("time_us"))) } pub async fn store_cursor(pool: &SqlitePool, time_us: i64) -> Result<()> { sqlx::query( "INSERT INTO indexer_cursor (id, time_us) VALUES (1, ?1) ON CONFLICT(id) DO UPDATE SET time_us = excluded.time_us", ) .bind(time_us) .execute(pool) .await?; Ok(()) }