use std::collections::HashSet; use common::{ call::CreatePoll, error::Error, model::{Id, Poll, PollOption}, time::now_ms, }; use super::{Connection, all, maybe, run}; use crate::error::{ServerError, ensure_with}; pub async fn create(message_id: Id, poll: &CreatePoll, db: &Connection) -> Result<(), ServerError> { let CreatePoll { question, options, multiple, public, duration, .. } = poll; let ends_at = duration.map(|seconds| (now_ms() + u64::from(seconds) * 1000) as i64); run( db, "INSERT INTO poll (message_id, question, multiple, public, ends_at) VALUES (?1, ?2, ?3, ?4, ?5)", (message_id, question.as_str(), *multiple, *public, ends_at), ) .await?; for (position, text) in (0u32..).zip(options) { run( db, "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", (message_id, position, text.as_str()), ) .await?; } Ok(()) } pub async fn of(message_id: Id, db: &Connection) -> Result, ServerError> { let Some((question, multiple, closed, public, ends_at)) = maybe( db, "SELECT question, multiple, closed, public, ends_at FROM poll WHERE message_id = ?1", (message_id,), |r| { Ok(( r.get::()?, r.get::()?, r.get::()?, r.get::()?, r.get::>()?, )) }, ) .await? else { return Ok(None); }; let mut options: Vec = all( db, "SELECT text FROM poll_option WHERE message_id = ?1 ORDER BY position", (message_id,), |r| { Ok(PollOption { text: r.get()?, votes: 0, voter_ids: Vec::new(), }) }, ) .await?; let votes: Vec<(u32, Id)> = all( db, "SELECT position, user_id FROM poll_vote WHERE message_id = ?1 ORDER BY position, user_id", (message_id,), |r| Ok((r.get()?, r.get()?)), ) .await?; let voters = votes .iter() .map(|(_, user_id)| user_id) .collect::>() .len() as u32; for (position, user_id) in votes { if let Some(option) = options.get_mut(position as usize) { option.votes += 1; if public { option.voter_ids.push(user_id); } } } let ends_at = ends_at.map(|ms| ms as u64); let closed = closed || ends_at.is_some_and(|end| end <= now_ms()); Ok(Some(Poll { question, options, multiple, closed, public, voters, ends_at, })) } pub async fn set_votes( message_id: Id, user_id: Id, positions: &[u32], db: &Connection, ) -> Result<(), ServerError> { run( db, "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", (message_id, user_id), ) .await?; for position in positions { run( db, "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", (message_id, *position, user_id), ) .await?; } Ok(()) } pub async fn my_votes( message_id: Id, user_id: Id, db: &Connection, ) -> Result, ServerError> { all( db, "SELECT position FROM poll_vote WHERE message_id = ?1 AND user_id = ?2 ORDER BY position", (message_id, user_id), |r| r.get(), ) .await } pub async fn close(message_id: Id, db: &Connection) -> Result<(), ServerError> { ensure_with( run( db, "UPDATE poll SET closed = 1 WHERE message_id = ?1", (message_id,), ) .await? == 1, Error::NotFound, ) }