feat: reminders and scheduled tasks (schedule tool, app store and delivery)
The brain gets a schedule tool (add, list, delete the asker's own reminders, timers and tasks) offered only with a schedule backend. The voice worker asks the app through schedule_action and runs fired tasks as reply via task with read-only tools, no MCP and a fresh short-term memory. The app keeps the schedules in config/schedules.json, fires them every 5 s, speaks them when the person is in Jarvis's voice channel and otherwise posts in the chat channel they asked in (or schedule.chatChannel for voice). A feature switch and a 예약 screen list and delete everyone's schedules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
523
app/src/schedule.rs
Normal file
523
app/src/schedule.rs
Normal file
@@ -0,0 +1,523 @@
|
||||
//! Reminders and scheduled tasks (`app/src/admin.spec.md`, "Schedules"): the store in the data
|
||||
//! folder, the next times, the brain's `schedule_action`, and the loop that fires and delivers.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{Datelike, Local, NaiveDateTime, TimeZone, Weekday};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::worker_client::ScheduleAction;
|
||||
|
||||
/// A schedule later than this when its time comes (the app was off, the PC asleep) is not delivered.
|
||||
pub const GRACE_SECS: i64 = 15 * 60;
|
||||
/// Schedules one person may have.
|
||||
pub const PER_PERSON: usize = 50;
|
||||
pub const MAX_TEXT_CHARS: usize = 500;
|
||||
/// How often the loop looks for schedules that are due.
|
||||
pub const TICK: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The store's file is read and written whole; one change at a time in this process (the services'
|
||||
/// loop and the settings screen both use it).
|
||||
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Outcome {
|
||||
pub at: i64,
|
||||
pub ok: bool,
|
||||
/// Why it failed, for the screen (no text of the schedule).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Schedule {
|
||||
pub id: u64,
|
||||
pub user: u64,
|
||||
pub name: String,
|
||||
/// `remind` or `task`.
|
||||
pub kind: String,
|
||||
pub text: String,
|
||||
/// `none`, `daily`, `weekdays` or `weekly`.
|
||||
pub repeat: String,
|
||||
/// When it fires next (Unix seconds); None: it will not fire again (kept to show its outcome).
|
||||
pub next: Option<i64>,
|
||||
/// `voice` or `chat`: where it was asked.
|
||||
pub via: String,
|
||||
/// The chat channel it was asked in (via chat).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub channel: Option<u64>,
|
||||
pub created: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last: Option<Outcome>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct File {
|
||||
next_id: u64,
|
||||
items: Vec<Schedule>,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
file: PathBuf,
|
||||
}
|
||||
|
||||
/// The local time `t` (Unix seconds) one day, a weekday or a week on, at the same wall time.
|
||||
fn step(t: i64, repeat: &str) -> i64 {
|
||||
let local = Local.timestamp_opt(t, 0).single().unwrap_or_else(Local::now);
|
||||
let wall = local.naive_local();
|
||||
let mut day = wall.date();
|
||||
loop {
|
||||
day = day.succ_opt().unwrap_or(day);
|
||||
let ok = match repeat {
|
||||
"weekdays" => !matches!(day.weekday(), Weekday::Sat | Weekday::Sun),
|
||||
"weekly" => day.weekday() == wall.weekday() && day != wall.date(),
|
||||
_ => true,
|
||||
};
|
||||
if ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let at = NaiveDateTime::new(day, wall.time());
|
||||
// A wall time a clock change skips is taken an hour later.
|
||||
Local.from_local_datetime(&at).earliest()
|
||||
.or_else(|| Local.from_local_datetime(&(at + chrono::Duration::hours(1))).earliest())
|
||||
.map(|d| d.timestamp()).unwrap_or(t + 86_400)
|
||||
}
|
||||
|
||||
fn is_weekend(t: i64) -> bool {
|
||||
Local.timestamp_opt(t, 0).single().is_some_and(|d| matches!(d.weekday(), Weekday::Sat | Weekday::Sun))
|
||||
}
|
||||
|
||||
/// The first time a schedule asked for `at` fires: `at` itself, the next weekday for `weekdays`,
|
||||
/// and for a repeating one that has passed, its first time after `now`.
|
||||
pub fn first_time(at: i64, repeat: &str, now: i64) -> i64 {
|
||||
let mut t = at;
|
||||
if repeat == "weekdays" && is_weekend(t) {
|
||||
t = step(t, repeat);
|
||||
}
|
||||
while repeat != "none" && t <= now {
|
||||
t = step(t, repeat);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// What `take_due` hands out to deliver.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Due {
|
||||
pub item: Schedule,
|
||||
/// The time it was due (the item's `next` has moved on for a repeating one).
|
||||
pub due: i64,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(data: &Path) -> Self {
|
||||
Self { file: data.join("config").join("schedules.json") }
|
||||
}
|
||||
|
||||
fn load(&self) -> Result<File, String> {
|
||||
match std::fs::read_to_string(&self.file) {
|
||||
Ok(t) => serde_json::from_str(&t).map_err(|e| format!("예약 파일을 읽을 수 없습니다: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(File::default()),
|
||||
Err(e) => Err(format!("예약 파일을 읽을 수 없습니다: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, f: &File) -> Result<(), String> {
|
||||
let mut text = serde_json::to_string_pretty(f).unwrap();
|
||||
text.push('\n');
|
||||
crate::datadir::write_atomic(&self.file, text.as_bytes()).map_err(|e| format!("예약 파일을 쓸 수 없습니다: {e}"))
|
||||
}
|
||||
|
||||
fn change<T>(&self, f: impl FnOnce(&mut File) -> Result<T, String>) -> Result<T, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut file = self.load()?;
|
||||
let out = f(&mut file)?;
|
||||
self.save(&file)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every schedule, soonest first (those that will not fire again last).
|
||||
pub fn all(&self) -> Result<Vec<Schedule>, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut items = self.load()?.items;
|
||||
items.sort_by_key(|i| (i.next.is_none(), i.next, i.id));
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// One person's schedules, soonest first.
|
||||
pub fn of(&self, user: u64) -> Result<Vec<Schedule>, String> {
|
||||
Ok(self.all()?.into_iter().filter(|i| i.user == user).collect())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add(&self, user: u64, name: &str, kind: &str, text: &str, at: i64, repeat: &str, via: &str,
|
||||
channel: Option<u64>, now: i64) -> Result<Schedule, String> {
|
||||
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if text.is_empty() || text.chars().count() > MAX_TEXT_CHARS {
|
||||
return Err(format!("text must be 1-{MAX_TEXT_CHARS} characters"));
|
||||
}
|
||||
if !["remind", "task"].contains(&kind) {
|
||||
return Err("kind must be remind or task".into());
|
||||
}
|
||||
if !["none", "daily", "weekdays", "weekly"].contains(&repeat) {
|
||||
return Err("repeat must be none, daily, weekdays or weekly".into());
|
||||
}
|
||||
let channel = match via {
|
||||
"voice" => None,
|
||||
"chat" => Some(channel.ok_or("a chat schedule needs the channel it was asked in")?),
|
||||
_ => return Err("via must be voice or chat".into()),
|
||||
};
|
||||
if repeat == "none" && at <= now {
|
||||
return Err("that time has already passed".into());
|
||||
}
|
||||
let next = first_time(at, repeat, now);
|
||||
self.change(|f| {
|
||||
if f.items.iter().filter(|i| i.user == user && i.next.is_some()).count() >= PER_PERSON {
|
||||
return Err(format!("at most {PER_PERSON} schedules per person; delete one first"));
|
||||
}
|
||||
f.next_id += 1;
|
||||
let item = Schedule { id: f.next_id, user, name: name.to_owned(), kind: kind.into(), text,
|
||||
repeat: repeat.into(), next: Some(next), via: via.into(), channel, created: now, last: None };
|
||||
f.items.push(item.clone());
|
||||
Ok(item)
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete a schedule; with `user`, only one of theirs.
|
||||
pub fn delete(&self, id: u64, user: Option<u64>) -> Result<Schedule, String> {
|
||||
self.change(|f| {
|
||||
let pos = f.items.iter().position(|i| i.id == id && user.is_none_or(|u| u == i.user))
|
||||
.ok_or_else(|| "no such schedule of this person".to_string())?;
|
||||
Ok(f.items.remove(pos))
|
||||
})
|
||||
}
|
||||
|
||||
/// The schedules due at `now`. A repeating one moves on to its next time; a one-off one stops
|
||||
/// (`next` None) until `finished` records how it went. One more than `GRACE_SECS` late is not
|
||||
/// handed out and is recorded as missed.
|
||||
pub fn take_due(&self, now: i64) -> Result<Vec<Due>, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut file = self.load()?;
|
||||
let mut due = vec![];
|
||||
let mut changed = false;
|
||||
for item in file.items.iter_mut() {
|
||||
let Some(t) = item.next.filter(|t| *t <= now) else { continue };
|
||||
changed = true;
|
||||
item.next = (item.repeat != "none").then(|| first_time(t, &item.repeat, now));
|
||||
if now - t > GRACE_SECS {
|
||||
item.last = Some(Outcome { at: now, ok: false, note: Some("앱이 꺼져 있어 제때 전하지 못함".into()) });
|
||||
crate::warn_log!("schedule", "Warning: schedule {} missed ({} s late)", item.id, now - t);
|
||||
} else {
|
||||
due.push(Due { item: item.clone(), due: t });
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.save(&file)?;
|
||||
}
|
||||
Ok(due)
|
||||
}
|
||||
|
||||
/// Record how a delivery went. A one-off schedule delivered is removed; one that failed stays
|
||||
/// (not firing again) so the screen shows it.
|
||||
pub fn finished(&self, id: u64, outcome: Outcome) -> Result<(), String> {
|
||||
self.change(|f| {
|
||||
if let Some(pos) = f.items.iter().position(|i| i.id == id) {
|
||||
if outcome.ok && f.items[pos].next.is_none() {
|
||||
f.items.remove(pos);
|
||||
} else {
|
||||
f.items[pos].last = Some(outcome);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A schedule as the brain's tool sees it.
|
||||
pub fn brain_item(s: &Schedule) -> Value {
|
||||
json!({"id": s.id.to_string(), "kind": s.kind, "text": s.text, "repeat": s.repeat,
|
||||
"next": s.next.map(|t| t as f64)})
|
||||
}
|
||||
|
||||
/// Do what the brain's schedule tool asked for the person in `a.user` (named `name`): the item(s)
|
||||
/// for its result, or why not.
|
||||
pub fn act(store: &Store, a: &ScheduleAction, name: &str, now: i64) -> Result<Value, String> {
|
||||
let user: u64 = a.user.parse().map_err(|_| "bad user id".to_string())?;
|
||||
match a.action.as_str() {
|
||||
"list" => Ok(json!({"items": store.of(user)?.iter().filter(|s| s.next.is_some()).map(brain_item).collect::<Vec<_>>()})),
|
||||
"delete" => {
|
||||
let id: u64 = a.schedule.as_deref().and_then(|s| s.trim().parse().ok()).ok_or("delete needs the schedule's id")?;
|
||||
Ok(json!({"item": brain_item(&store.delete(id, Some(user))?)}))
|
||||
}
|
||||
"add" => {
|
||||
let at = a.at.filter(|t| t.is_finite()).ok_or("add needs at")?;
|
||||
let channel = a.channel.as_deref().and_then(|c| c.parse().ok());
|
||||
let s = store.add(user, name, a.kind.as_deref().unwrap_or("remind"), a.text.as_deref().unwrap_or(""),
|
||||
at.round() as i64, a.repeat.as_deref().unwrap_or("none"), &a.via, channel, now)?;
|
||||
crate::info_log!("schedule", "schedule {} added: {} {} by {user}", s.id, s.kind, s.repeat);
|
||||
Ok(json!({"item": brain_item(&s)}))
|
||||
}
|
||||
other => Err(format!("unknown schedule action {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the loop needs to deliver (the Discord core; a fake in tests).
|
||||
#[async_trait::async_trait]
|
||||
pub trait Deliver: Send + Sync {
|
||||
/// The person is in Jarvis's voice channel.
|
||||
fn hears(&self, user: u64) -> bool;
|
||||
/// Speak in the voice channel; false when not in one.
|
||||
fn say(&self, text: &str) -> bool;
|
||||
/// Post in a registered chat channel (never pinging anyone).
|
||||
async fn post(&self, channel: u64, text: &str) -> Result<(), String>;
|
||||
/// Run a task in the brain (read-only tools) and wait for its answer.
|
||||
async fn task(&self, id: &str, user: u64, text: &str) -> Option<String>;
|
||||
}
|
||||
|
||||
/// Deliver one due schedule: a task runs first; then by voice when it was asked by voice and the
|
||||
/// person is in Jarvis's voice channel, else in the chat channel it was asked in, or for voice the
|
||||
/// fallback channel (`schedule.chatChannel`).
|
||||
pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outcome {
|
||||
let s = &due.item;
|
||||
let now = || chrono::Utc::now().timestamp();
|
||||
let fail = |note: &str| Outcome { at: now(), ok: false, note: Some(note.into()) };
|
||||
let body = if s.kind == "task" {
|
||||
match d.task(&format!("s{}-{}", s.id, due.due), s.user, &s.text).await {
|
||||
Some(a) if !a.trim().is_empty() => a,
|
||||
_ => return fail("작업 결과를 만들지 못함"),
|
||||
}
|
||||
} else {
|
||||
s.text.clone()
|
||||
};
|
||||
let text = format!("{}님, {}", s.name, body.trim());
|
||||
if s.via == "voice" && d.hears(s.user) && d.say(&text) {
|
||||
crate::debug_log!("schedule", "schedule {} spoken chars={}", s.id, text.chars().count());
|
||||
return Outcome { at: now(), ok: true, note: None };
|
||||
}
|
||||
let Some(channel) = (if s.via == "chat" { s.channel } else { fallback }) else {
|
||||
return fail("음성 채널에 없고 알림 채팅 채널이 정해지지 않음");
|
||||
};
|
||||
match d.post(channel, &text).await {
|
||||
Ok(()) => {
|
||||
crate::debug_log!("schedule", "schedule {} posted in {channel} chars={}", s.id, text.chars().count());
|
||||
Outcome { at: now(), ok: true, note: None }
|
||||
}
|
||||
Err(e) => {
|
||||
crate::warn_log!("schedule", "Warning: schedule {} could not be posted in {channel}: {e}", s.id);
|
||||
fail("채팅 채널에 보내지 못함")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fire due schedules until the task is aborted. Each delivery runs on its own, so a slow task does
|
||||
/// not hold up a reminder due meanwhile.
|
||||
pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
|
||||
loop {
|
||||
match store.take_due(chrono::Utc::now().timestamp()) {
|
||||
Ok(due) => for item in due {
|
||||
let (store, d) = (store.clone(), d.clone());
|
||||
tokio::spawn(async move {
|
||||
let out = deliver(d.as_ref(), &item, fallback).await;
|
||||
crate::info_log!("schedule", "schedule {} {}", item.item.id, if out.ok { "delivered" } else { "not delivered" });
|
||||
if let Err(e) = store.finished(item.item.id, out) {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
});
|
||||
},
|
||||
Err(e) => {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(TICK).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Timelike;
|
||||
|
||||
fn local(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> i64 {
|
||||
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).earliest().unwrap().timestamp()
|
||||
}
|
||||
|
||||
fn store() -> Store {
|
||||
Store::new(&crate::datadir::temp_dir("schedule"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeats_keep_the_wall_time_and_skip_what_they_leave_out() {
|
||||
// 2026-11-13 is a Friday.
|
||||
let fri = local(2026, 11, 13, 9, 0);
|
||||
assert_eq!(step(fri, "daily"), local(2026, 11, 14, 9, 0));
|
||||
assert_eq!(step(fri, "weekdays"), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(step(fri, "weekly"), local(2026, 11, 20, 9, 0));
|
||||
// Asked for a Saturday on weekdays: Monday. A daily one that passed: its next time.
|
||||
assert_eq!(first_time(local(2026, 11, 14, 9, 0), "weekdays", 0), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(first_time(fri, "daily", local(2026, 11, 15, 10, 0)), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(Local.timestamp_opt(step(fri, "daily"), 0).unwrap().hour(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_person_sees_and_deletes_only_their_own() {
|
||||
let s = store();
|
||||
let a = s.add(1, "가", "remind", " 회의 준비 ", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let b = s.add(2, "나", "task", "날씨", 3000, "daily", "chat", Some(77), 1000).unwrap();
|
||||
assert_eq!(a.text, "회의 준비");
|
||||
assert_eq!(s.of(1).unwrap(), vec![a.clone()]);
|
||||
assert!(s.delete(b.id, Some(1)).is_err());
|
||||
assert_eq!(s.delete(b.id, None).unwrap(), b);
|
||||
assert_eq!(s.all().unwrap(), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_adds_are_refused() {
|
||||
let s = store();
|
||||
for (kind, text, at, repeat, via, channel) in [
|
||||
("remind", "", 2000, "none", "voice", None),
|
||||
("remind", "x", 500, "none", "voice", None),
|
||||
("alarm", "x", 2000, "none", "voice", None),
|
||||
("remind", "x", 2000, "hourly", "voice", None),
|
||||
("remind", "x", 2000, "none", "chat", None),
|
||||
] {
|
||||
assert!(s.add(1, "가", kind, text, at, repeat, via, channel, 1000).is_err(), "{kind} {text} {repeat} {via}");
|
||||
}
|
||||
assert!(s.add(1, "가", "remind", &"x".repeat(MAX_TEXT_CHARS + 1), 2000, "none", "voice", None, 1000).is_err());
|
||||
for _ in 0..PER_PERSON {
|
||||
s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).unwrap();
|
||||
}
|
||||
assert!(s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).is_err());
|
||||
assert!(s.add(2, "나", "remind", "x", 2000, "none", "voice", None, 1000).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_schedules_are_handed_out_once_and_late_ones_are_recorded_as_missed() {
|
||||
let s = store();
|
||||
let once = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let daily = s.add(1, "가", "remind", "b", local(2026, 11, 13, 9, 0), "daily", "voice", None, 0).unwrap();
|
||||
let late = s.add(1, "가", "remind", "c", 1500, "none", "voice", None, 1000).unwrap();
|
||||
assert!(s.take_due(1499).unwrap().is_empty());
|
||||
let now = local(2026, 11, 13, 9, 1);
|
||||
let got: Vec<u64> = s.take_due(now).unwrap().into_iter().map(|d| d.item.id).collect();
|
||||
// `once` and `late` were due long before `now`: missed. The daily one moves to tomorrow.
|
||||
assert_eq!(got, vec![daily.id]);
|
||||
assert!(s.take_due(now).unwrap().is_empty());
|
||||
let all = s.all().unwrap();
|
||||
let find = |id| all.iter().find(|i| i.id == id).unwrap().clone();
|
||||
assert_eq!(find(daily.id).next, Some(local(2026, 11, 14, 9, 0)));
|
||||
for id in [once.id, late.id] {
|
||||
let i = find(id);
|
||||
assert_eq!(i.next, None);
|
||||
assert!(!i.last.unwrap().ok);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delivered_one_off_schedule_is_removed_and_a_failed_one_kept() {
|
||||
let s = store();
|
||||
let a = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let b = s.add(1, "가", "remind", "b", 2000, "none", "voice", None, 1000).unwrap();
|
||||
assert_eq!(s.take_due(2000).unwrap().len(), 2);
|
||||
s.finished(a.id, Outcome { at: 2001, ok: true, note: None }).unwrap();
|
||||
s.finished(b.id, Outcome { at: 2001, ok: false, note: Some("x".into()) }).unwrap();
|
||||
let all = s.all().unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].id, b.id);
|
||||
assert!(!all[0].last.as_ref().unwrap().ok);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
hears: bool,
|
||||
said: Mutex<Vec<String>>,
|
||||
posted: Mutex<Vec<(u64, String)>>,
|
||||
post_fails: bool,
|
||||
answer: Option<String>,
|
||||
tasks: Mutex<Vec<(u64, String)>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Deliver for Fake {
|
||||
fn hears(&self, _user: u64) -> bool {
|
||||
self.hears
|
||||
}
|
||||
fn say(&self, text: &str) -> bool {
|
||||
self.said.lock().unwrap().push(text.into());
|
||||
true
|
||||
}
|
||||
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
|
||||
if self.post_fails {
|
||||
return Err("no".into());
|
||||
}
|
||||
self.posted.lock().unwrap().push((channel, text.into()));
|
||||
Ok(())
|
||||
}
|
||||
async fn task(&self, _id: &str, user: u64, text: &str) -> Option<String> {
|
||||
self.tasks.lock().unwrap().push((user, text.into()));
|
||||
self.answer.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn due(kind: &str, via: &str, channel: Option<u64>) -> Due {
|
||||
Due { item: Schedule { id: 1, user: 5, name: "철수".into(), kind: kind.into(), text: "회의".into(),
|
||||
repeat: "none".into(), next: None, via: via.into(), channel, created: 0, last: None }, due: 10 }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_voice_reminder_is_spoken_to_someone_there_and_posted_otherwise() {
|
||||
let f = Fake { hears: true, ..Default::default() };
|
||||
assert!(deliver(&f, &due("remind", "voice", None), Some(9)).await.ok);
|
||||
assert_eq!(*f.said.lock().unwrap(), vec!["철수님, 회의".to_string()]);
|
||||
let away = Fake::default();
|
||||
assert!(deliver(&away, &due("remind", "voice", None), Some(9)).await.ok);
|
||||
assert_eq!(*away.posted.lock().unwrap(), vec![(9, "철수님, 회의".to_string())]);
|
||||
// Nowhere to go: not delivered, and says why.
|
||||
let out = deliver(&away, &due("remind", "voice", None), None).await;
|
||||
assert!(!out.ok && out.note.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_chat_reminder_goes_to_its_channel_even_when_the_person_is_in_voice() {
|
||||
let f = Fake { hears: true, ..Default::default() };
|
||||
assert!(deliver(&f, &due("remind", "chat", Some(77)), Some(9)).await.ok);
|
||||
assert!(f.said.lock().unwrap().is_empty());
|
||||
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 회의".to_string())]);
|
||||
let fails = Fake { post_fails: true, ..Default::default() };
|
||||
assert!(!deliver(&fails, &due("remind", "chat", Some(77)), None).await.ok);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_task_delivers_the_brains_answer_and_fails_without_one() {
|
||||
let f = Fake { answer: Some("맑아요".into()), ..Default::default() };
|
||||
assert!(deliver(&f, &due("task", "chat", Some(77)), None).await.ok);
|
||||
assert_eq!(*f.tasks.lock().unwrap(), vec![(5, "회의".to_string())]);
|
||||
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 맑아요".to_string())]);
|
||||
let none = Fake::default();
|
||||
let out = deliver(&none, &due("task", "chat", Some(77)), None).await;
|
||||
assert!(!out.ok && none.posted.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brains_actions_are_done_for_the_asker_only() {
|
||||
let s = store();
|
||||
let a = |action: &str, user: &str, extra: Value| -> ScheduleAction {
|
||||
let mut v = json!({"id": "x", "action": action, "user": user, "via": "voice"});
|
||||
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
serde_json::from_value(v).unwrap()
|
||||
};
|
||||
let added = act(&s, &a("add", "1", json!({"kind": "remind", "text": "물", "at": 2000.4, "repeat": "none"})), "가", 1000).unwrap();
|
||||
assert_eq!(added["item"]["id"], "1");
|
||||
assert_eq!(added["item"]["next"], 2000.0);
|
||||
assert_eq!(act(&s, &a("list", "2", json!({})), "나", 1000).unwrap()["items"], json!([]));
|
||||
assert!(act(&s, &a("delete", "2", json!({"schedule": "1"})), "나", 1000).is_err());
|
||||
assert_eq!(act(&s, &a("list", "1", json!({})), "가", 1000).unwrap()["items"].as_array().unwrap().len(), 1);
|
||||
assert!(act(&s, &a("delete", "1", json!({"schedule": "1"})), "가", 1000).is_ok());
|
||||
assert!(act(&s, &a("add", "1", json!({"text": "x", "at": 2000.0, "via": "chat"})), "가", 1000).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user