feat: news notifications for the background collection and a collectedNews tool
Each collection target can announce new items at once or in a daily digest (off by default) in collect.notifyChannel, as titles and links only, with no LLM; each post is recorded in the activity log. The brain gets a read-only collectedNews tool (every target's newest items by default, fenced as untrusted web content), offered with the app's collection file and the collection feature, and available to scheduled tasks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -60,7 +60,7 @@ manages the MCP servers it connects.
|
||||
|
||||
- `features` (new section): `weather` (`getWeather`), `webSearch` (`webSearch`, `fetchWebPage`) and
|
||||
`meals` (`logMeal`, `fetchMeals`, `deleteMeal`), each on by default; `collect` (background
|
||||
collection, below; no brain tool) and `browser` (the bot browser, below "Bot browser", and its
|
||||
collection, below, and the brain tool `collectedNews`) and `browser` (the bot browser, below "Bot browser", and its
|
||||
brain tool `botBrowser`, `src/jarvis/tools/builtin/bot_browser.spec.md`), also on by default;
|
||||
`browserShare` (봇용 크롬창 화면공유 선택 표시, the bot browser on the virtual monitor, below
|
||||
"Virtual monitor"), off by default; `schedule` (reminders and scheduled tasks, below
|
||||
@@ -183,8 +183,8 @@ editable on the 사람별 지침 screen.
|
||||
|
||||
`docs/v2/proactive.md` (제안 5). What Jarvis did outside its answers, for the 한 일 screen: each chat
|
||||
channel action the brain's tool asked for (`chat.send`, `chat.edit`, `chat.react`, `chat.delete`,
|
||||
`chat.pin`, `chat.unpin`) and each schedule delivery (`schedule.remind`, `schedule.task`), done or
|
||||
failed. PC control actions join it with M7. Ordinary answers are not recorded.
|
||||
`chat.pin`, `chat.unpin`), each schedule delivery (`schedule.remind`, `schedule.task`) and each
|
||||
news notification (`collect.notify`), done or failed. PC control actions join it with M7. Ordinary answers are not recorded.
|
||||
|
||||
- One JSON line per action in `activity/<YYYY-MM-DD>.jsonl` (the folder is made at the first one):
|
||||
`{at, kind, target, by, ok, note}`. `target` is the channel (and message) id or `예약 <id>`; `by`
|
||||
@@ -197,6 +197,28 @@ failed. PC control actions join it with M7. Ordinary answers are not recorded.
|
||||
stops the action.
|
||||
- `activity_list` `{limit}` (1-1000, default 200) reads the newest first.
|
||||
|
||||
## News notifications (`app/src/collect_notify.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 2). New items of the background collection announced in a chat
|
||||
channel, titles and links only (no LLM, nothing Jarvis writes about them).
|
||||
|
||||
- Each collection target has `notify` (`off` by default, `now`, `daily`); `collect.notifyChannel`
|
||||
(a registered chat channel with sending on, anything else refused; null by default: nothing is
|
||||
announced) and `collect.digestHour` (0-23, default 9, local time). Nothing is announced with
|
||||
`features.collect` off.
|
||||
- While the services run, every minute: a target whose notifications just began only marks what it
|
||||
has as seen (nothing old is announced); a `now` target posts what is new since its last post; a
|
||||
`daily` target posts once a day in the digest hour what came since its last digest (nothing when
|
||||
nothing came). The state is `config/collect-notify.json` (per target the newest item announced and
|
||||
the day of its last digest).
|
||||
- A post is `수집 소식: <target> 새 글 N건` (`수집 소식 하루 요약: ...` for the digest), then at most 10
|
||||
items as `- <title> <link>` (titles at most 200 characters; the link in `<>` so Discord shows no
|
||||
preview), then `외 N건`. Posts ping nobody. Each is recorded in the activity (`collect.notify`,
|
||||
target `수집 <name> → 채널 <id>`, outcome); a failed post is not tried again.
|
||||
- The 백그라운드 수집 screen has the channel, the hour and a "새 글 알림" column in the targets table.
|
||||
- The brain's `collectedNews` tool reads the same results
|
||||
(`src/jarvis/tools/builtin/collected_news.spec.md`); it is behind `features.collect` too.
|
||||
|
||||
## Secrets (`app/src/secrets.rs`)
|
||||
|
||||
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers'
|
||||
|
||||
205
app/src/collect_notify.rs
Normal file
205
app/src/collect_notify.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
//! News notifications (`app/src/admin.spec.md`, "News notifications"; `docs/v2/proactive.md` 제안 2):
|
||||
//! new items of the background collection announced in a chat channel, at once or once a day, as
|
||||
//! titles and links only (no LLM, nothing written by Jarvis about them).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{DateTime, Local, Timelike};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::settings::Settings;
|
||||
|
||||
/// Items listed per target in one message; the rest are counted.
|
||||
pub const LISTED: usize = 10;
|
||||
const TITLE_CHARS: usize = 200;
|
||||
pub const TICK: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct State {
|
||||
/// Per target: the `at` of the newest item announced (or seen when its notifications began).
|
||||
#[serde(default)]
|
||||
seen: HashMap<String, String>,
|
||||
/// Per daily target: the day its digest last went out (YYYY-MM-DD).
|
||||
#[serde(default)]
|
||||
digest_day: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Message {
|
||||
pub target: String,
|
||||
pub count: usize,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
fn state_file(data: &Path) -> PathBuf {
|
||||
data.join("config").join("collect-notify.json")
|
||||
}
|
||||
|
||||
pub fn load(data: &Path) -> State {
|
||||
std::fs::read_to_string(state_file(data)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save(data: &Path, s: &State) -> std::io::Result<()> {
|
||||
crate::datadir::write_atomic(&state_file(data), serde_json::to_string_pretty(s).unwrap().as_bytes())
|
||||
}
|
||||
|
||||
fn line(item: &Value) -> String {
|
||||
let title: String = item["title"].as_str().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
.chars().take(TITLE_CHARS).collect();
|
||||
let url = item["url"].as_str().unwrap_or("");
|
||||
let title = if title.is_empty() { "(제목 없음)".to_owned() } else { title };
|
||||
// <url> keeps Discord from showing a preview for every link.
|
||||
if url.starts_with("http://") || url.starts_with("https://") { format!("- {title} <{url}>") } else { format!("- {title}") }
|
||||
}
|
||||
|
||||
fn message(target: &str, new: &[Value], daily: bool) -> Message {
|
||||
let head = if daily { format!("수집 소식 하루 요약: {target} 새 글 {}건", new.len()) }
|
||||
else { format!("수집 소식: {target} 새 글 {}건", new.len()) };
|
||||
let mut lines = vec![head];
|
||||
lines.extend(new.iter().take(LISTED).map(line));
|
||||
if new.len() > LISTED {
|
||||
lines.push(format!("외 {}건", new.len() - LISTED));
|
||||
}
|
||||
Message { target: target.to_owned(), count: new.len(), text: lines.join("\n") }
|
||||
}
|
||||
|
||||
/// The messages due at `now`, updating `state`. Nothing without the feature or a channel. A target
|
||||
/// whose notifications just began only marks what it has as seen; `now` targets announce what is
|
||||
/// new since then; `daily` ones once a day at `digest_hour`, what came since their last digest.
|
||||
pub fn due(data: &Path, s: &Settings, now: DateTime<Local>, state: &mut State) -> Vec<Message> {
|
||||
if !s.features.collect || s.collect.notify_channel.is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let today = now.date_naive().to_string();
|
||||
let mut out = vec![];
|
||||
for t in s.collect.targets.iter().filter(|t| t.enabled && t.notify != "off") {
|
||||
let items = crate::collect::results(data, Some(&t.name), 500).unwrap_or_default();
|
||||
let newest = items.first().and_then(|i| i["at"].as_str()).map(str::to_owned);
|
||||
let Some(last) = state.seen.get(&t.name).cloned() else {
|
||||
state.seen.insert(t.name.clone(), newest.unwrap_or_else(|| now.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)));
|
||||
if t.notify == "daily" {
|
||||
state.digest_day.insert(t.name.clone(), today.clone());
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if t.notify == "daily" && (now.hour() != s.collect.digest_hour || state.digest_day.get(&t.name) == Some(&today)) {
|
||||
continue;
|
||||
}
|
||||
// `at` is the local time with its offset in one format, so text order is time order.
|
||||
let new: Vec<Value> = items.into_iter().filter(|i| i["at"].as_str().is_some_and(|a| a > last.as_str())).collect();
|
||||
if t.notify == "daily" {
|
||||
state.digest_day.insert(t.name.clone(), today.clone());
|
||||
}
|
||||
if new.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = new[0]["at"].as_str() {
|
||||
state.seen.insert(t.name.clone(), n.to_owned());
|
||||
}
|
||||
out.push(message(&t.name, &new, t.notify == "daily"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Announce due news every minute until aborted; each post is recorded in the activity log.
|
||||
pub async fn run(data: PathBuf, settings: Settings, d: std::sync::Arc<dyn crate::schedule::Deliver>,
|
||||
activity: std::sync::Arc<crate::activity::Activity>) {
|
||||
loop {
|
||||
let mut state = load(&data);
|
||||
let msgs = due(&data, &settings, Local::now(), &mut state);
|
||||
if let Err(e) = save(&data, &state) {
|
||||
crate::warn_log!("conversation", "Warning: could not save the news notification state: {e}");
|
||||
}
|
||||
if let Some(channel) = settings.collect.notify_channel {
|
||||
for m in msgs {
|
||||
let posted = d.post(channel, &m.text).await;
|
||||
crate::info_log!("conversation", "news {} items={} posted={}", m.target, m.count, posted.is_ok());
|
||||
activity.record("collect.notify", &format!("수집 {} → 채널 {channel}", m.target), None, posted.is_ok(),
|
||||
posted.err().map(|_| "채팅 채널에 보내지 못함".to_owned()));
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(TICK).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
use serde_json::json;
|
||||
|
||||
fn settings(notify: &str) -> Settings {
|
||||
crate::settings::parse_settings(&json!({
|
||||
"chatChannels": [{"id": "123456789012345678"}],
|
||||
"collect": {"notifyChannel": "123456789012345678", "digestHour": 9, "targets": [
|
||||
{"name": "뉴스", "kind": "rss", "value": "https://feed.example/rss", "notify": notify}]}})).unwrap()
|
||||
}
|
||||
|
||||
fn write(data: &Path, day: &str, items: &[(&str, &str)]) {
|
||||
let dir = data.join("collect").join("뉴스");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut text = std::fs::read_to_string(dir.join(format!("{day}.jsonl"))).unwrap_or_default();
|
||||
for (at, title) in items {
|
||||
text.push_str(&json!({"at": at, "title": title, "url": format!("https://e.example/{title}")}).to_string());
|
||||
text.push('\n');
|
||||
}
|
||||
std::fs::write(dir.join(format!("{day}.jsonl")), text).unwrap();
|
||||
}
|
||||
|
||||
fn at(h: u32, m: u32) -> DateTime<Local> {
|
||||
Local.with_ymd_and_hms(2026, 11, 14, h, m, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_once_announces_only_what_is_new_since_notifications_began() {
|
||||
let data = crate::datadir::temp_dir("news-now");
|
||||
let s = settings("now");
|
||||
write(&data, "2026-11-14", &[("2026-11-14T08:00:00+09:00", "old")]);
|
||||
let mut st = State::default();
|
||||
assert!(due(&data, &s, at(8, 30), &mut st).is_empty(), "what was there before is not announced");
|
||||
write(&data, "2026-11-14", &[("2026-11-14T08:40:00+09:00", "new one")]);
|
||||
let m = due(&data, &s, at(8, 41), &mut st);
|
||||
assert_eq!(m.len(), 1);
|
||||
assert_eq!(m[0].count, 1);
|
||||
assert!(m[0].text.contains("new one <https://e.example/new one>") && !m[0].text.contains("old"), "{}", m[0].text);
|
||||
assert!(due(&data, &s, at(8, 42), &mut st).is_empty(), "each item once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_daily_digest_goes_out_once_at_its_hour_with_everything_since_the_last() {
|
||||
let data = crate::datadir::temp_dir("news-daily");
|
||||
let s = settings("daily");
|
||||
let mut st = State::default();
|
||||
assert!(due(&data, &s, at(7, 0), &mut st).is_empty());
|
||||
let many: Vec<(String, String)> = (0..12).map(|i| (format!("2026-11-14T08:{i:02}:00+09:00"), format!("t{i}"))).collect();
|
||||
write(&data, "2026-11-14", &many.iter().map(|(a, t)| (a.as_str(), t.as_str())).collect::<Vec<_>>());
|
||||
assert!(due(&data, &s, at(8, 59), &mut st).is_empty(), "not before its hour");
|
||||
// The first day's digest was marked when notifications began; the next day's goes out.
|
||||
let next = Local.with_ymd_and_hms(2026, 11, 15, 9, 0, 0).unwrap();
|
||||
let m = due(&data, &s, next, &mut st);
|
||||
assert_eq!(m.len(), 1);
|
||||
assert_eq!(m[0].count, 12);
|
||||
assert!(m[0].text.contains("외 2건"), "{}", m[0].text);
|
||||
assert!(due(&data, &s, next + chrono::Duration::minutes(30), &mut st).is_empty(), "once a day");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_announced_without_a_channel_the_feature_or_with_notify_off() {
|
||||
let data = crate::datadir::temp_dir("news-off");
|
||||
write(&data, "2026-11-14", &[("2026-11-14T08:00:00+09:00", "x")]);
|
||||
let mut off = settings("now");
|
||||
off.collect.notify_channel = None;
|
||||
let mut nofeature = settings("now");
|
||||
nofeature.features.collect = false;
|
||||
for s in [off, nofeature, settings("off")] {
|
||||
let mut st = State::default();
|
||||
due(&data, &s, at(8, 0), &mut st);
|
||||
write(&data, "2026-11-14", &[("2026-11-14T08:30:00+09:00", "y")]);
|
||||
assert!(due(&data, &s, at(8, 31), &mut st).is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ pub const FEATURE_TOOLS: &[(&str, &[&str])] = &[
|
||||
("browser", &["botBrowser"]),
|
||||
("schedule", &["schedule"]),
|
||||
("notes", &["personalNotes"]),
|
||||
("collect", &["collectedNews"]),
|
||||
];
|
||||
|
||||
/// The built-in tools of the features that are off.
|
||||
@@ -29,6 +30,7 @@ pub fn disabled_tools(f: &FeatureSettings) -> Vec<&'static str> {
|
||||
"browser" => f.browser,
|
||||
"schedule" => f.schedule,
|
||||
"notes" => f.notes,
|
||||
"collect" => f.collect,
|
||||
_ => f.meals,
|
||||
};
|
||||
FEATURE_TOOLS.iter().filter(|(k, _)| !on(k)).flat_map(|(_, tools)| tools.iter().copied()).collect()
|
||||
@@ -109,7 +111,7 @@ mod tests {
|
||||
let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: true, schedule: true, notes: true };
|
||||
assert!(disabled_tools(&all_on).is_empty());
|
||||
let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false, browser_share: false, schedule: false, notes: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser", "schedule", "personalNotes"]);
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser", "schedule", "personalNotes", "collectedNews"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,6 +8,7 @@ pub mod calls;
|
||||
pub mod channel_sync;
|
||||
pub mod chat;
|
||||
pub mod collect;
|
||||
pub mod collect_notify;
|
||||
pub mod control;
|
||||
pub mod conversation;
|
||||
pub mod dashboard;
|
||||
|
||||
@@ -29,6 +29,8 @@ pub struct Services {
|
||||
pub perf: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
/// Fires the reminders and scheduled tasks (admin.spec.md, "Schedules").
|
||||
pub schedules: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
/// Announces new collected items (admin.spec.md, "News notifications").
|
||||
pub news: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// The bot browser of a run (admin.spec.md, "Bot browser").
|
||||
@@ -75,6 +77,11 @@ impl Services {
|
||||
s.abort();
|
||||
let _ = s.await;
|
||||
}
|
||||
let news = self.news.lock().unwrap().take();
|
||||
if let Some(n) = news {
|
||||
n.abort();
|
||||
let _ = n.await;
|
||||
}
|
||||
self.game.stop();
|
||||
self.core.close().await;
|
||||
self.worker.close();
|
||||
@@ -199,6 +206,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
let (calls, response) = (settings.call.clone(), settings.response.clone());
|
||||
let chat_calls = conversation::ChatCalls::from_settings(&settings);
|
||||
let schedule_channel = settings.schedule_channel;
|
||||
let news_settings = settings.clone();
|
||||
let (core, core_events) = DiscordCore::new(settings, token, worker.clone(), worker_events);
|
||||
let schedule_store = Arc::new(crate::schedule::Store::new(data_dir));
|
||||
core.set_schedules(schedule_store.clone());
|
||||
@@ -216,11 +224,13 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
return Err(after_stop(&llm, &browser, e.to_string()).await.into());
|
||||
}
|
||||
crate::info_log!("app", "services started");
|
||||
let schedules = std::sync::Mutex::new(Some(tokio::spawn(crate::schedule::run(schedule_store, activity,
|
||||
let schedules = std::sync::Mutex::new(Some(tokio::spawn(crate::schedule::run(schedule_store, activity.clone(),
|
||||
Arc::new(core.clone()), schedule_channel))));
|
||||
let news = std::sync::Mutex::new(Some(tokio::spawn(crate::collect_notify::run(data_dir.to_path_buf(), news_settings,
|
||||
Arc::new(core.clone()), activity))));
|
||||
let on = { let g = game.clone(); Arc::new(move || g.on()) };
|
||||
let perf = std::sync::Mutex::new(Some(tokio::spawn(perf_loop(perf_settings, llm.clone(), Arc::new(worker.clone()), on, RETRY_AFTER))));
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf, schedules })
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf, schedules, news })
|
||||
}
|
||||
|
||||
/// The brain as the performance stages see it: told the LLM's state, and asked to finish what it is
|
||||
|
||||
@@ -136,6 +136,11 @@ impl GameSettings {
|
||||
pub struct CollectSettings {
|
||||
pub keep_days: u32,
|
||||
pub targets: Vec<CollectTarget>,
|
||||
/// The registered chat channel new items are announced in (admin.spec.md, "News
|
||||
/// notifications"); None: nothing is announced.
|
||||
pub notify_channel: Option<u64>,
|
||||
/// The hour (0-23, local) the daily digest goes out (default 9).
|
||||
pub digest_hour: u32,
|
||||
}
|
||||
|
||||
/// One thing to collect: `kind` is `site`, `search` or `rss`; `value` its address or words.
|
||||
@@ -146,6 +151,8 @@ pub struct CollectTarget {
|
||||
pub value: String,
|
||||
pub every_minutes: u32,
|
||||
pub enabled: bool,
|
||||
/// New items announced: `off` (default), `now` or `daily`.
|
||||
pub notify: String,
|
||||
}
|
||||
|
||||
/// How freely Jarvis may do one kind of action on the PC (`app/src/permissions.rs`).
|
||||
@@ -255,7 +262,7 @@ impl Default for Settings {
|
||||
llm: LlmSettings { url: None, port: 8080, context: 32768 },
|
||||
features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true, notes: true },
|
||||
mcp_servers: vec![],
|
||||
collect: CollectSettings { keep_days: 30, targets: vec![] },
|
||||
collect: CollectSettings { keep_days: 30, targets: vec![], notify_channel: None, digest_hour: 9 },
|
||||
game: GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false },
|
||||
schedule_channel: None,
|
||||
pc_control: PcControlSettings { allowed_users: vec![], view: Level::Auto, click: Level::Ask,
|
||||
@@ -535,6 +542,10 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
sync_discord: get_bool(Some(m), "syncDiscord", &path, true)?,
|
||||
});
|
||||
}
|
||||
let collect = parse_collect(raw, &d.collect)?;
|
||||
if collect.notify_channel.is_some_and(|c| !chat_channels.iter().any(|x| x.id == c && x.send)) {
|
||||
return err("collect.notifyChannel must be a registered chat channel with sending on");
|
||||
}
|
||||
let schedule_channel = opt_snowflake(section(raw, "schedule")?, "chatChannel", "schedule", None, "a Discord channel ID")?;
|
||||
if schedule_channel.is_some_and(|c| !chat_channels.iter().any(|x| x.id == c && x.send)) {
|
||||
return err("schedule.chatChannel must be a registered chat channel with sending on");
|
||||
@@ -589,7 +600,7 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
}
|
||||
},
|
||||
mcp_servers: parse_mcp_servers(raw)?,
|
||||
collect: parse_collect(raw, &d.collect)?,
|
||||
collect,
|
||||
game: parse_game(raw, &d.game)?,
|
||||
schedule_channel,
|
||||
pc_control: parse_pc_control(raw, &d.pc_control)?,
|
||||
@@ -668,8 +679,10 @@ fn parse_game(raw: &Map<String, Value>, d: &GameSettings) -> Result<GameSettings
|
||||
fn parse_collect(raw: &Map<String, Value>, d: &CollectSettings) -> Result<CollectSettings, SettingsError> {
|
||||
let c = section(raw, "collect")?;
|
||||
let keep_days = get_uint(c, "keepDays", "collect", d.keep_days, 1, 365)?;
|
||||
let notify_channel = opt_snowflake(c, "notifyChannel", "collect", d.notify_channel, "a Discord channel ID")?;
|
||||
let digest_hour = get_uint(c, "digestHour", "collect", d.digest_hour, 0, 23)?;
|
||||
let list = match c.and_then(|m| m.get("targets")) {
|
||||
None => return Ok(CollectSettings { keep_days, targets: vec![] }),
|
||||
None => return Ok(CollectSettings { keep_days, targets: vec![], notify_channel, digest_hour }),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return err("collect.targets must be a list"),
|
||||
};
|
||||
@@ -701,9 +714,13 @@ fn parse_collect(raw: &Map<String, Value>, d: &CollectSettings) -> Result<Collec
|
||||
value,
|
||||
every_minutes: get_uint(Some(m), "everyMinutes", &path, 60, 15, 10080)?,
|
||||
enabled: get_bool(Some(m), "enabled", &path, true)?,
|
||||
notify: match get_str(Some(m), "notify", &path, "off")?.as_str() {
|
||||
n @ ("off" | "now" | "daily") => n.to_owned(),
|
||||
_ => return err(format!("{path}.notify must be off, now or daily")),
|
||||
},
|
||||
});
|
||||
}
|
||||
Ok(CollectSettings { keep_days, targets })
|
||||
Ok(CollectSettings { keep_days, targets, notify_channel, digest_hour })
|
||||
}
|
||||
|
||||
/// An MCP server name: 1-32 letters, digits, `-` or `_`, without `__` (the brain names a server's
|
||||
@@ -999,17 +1016,27 @@ mod tests {
|
||||
#[test]
|
||||
fn collection_targets_are_read_and_checked() {
|
||||
let s = parse_settings(&json!({})).unwrap();
|
||||
assert_eq!(s.collect, CollectSettings { keep_days: 30, targets: vec![] });
|
||||
let s = parse_settings(&json!({"features": {"collect": false}, "collect": {"keepDays": 7, "targets": [
|
||||
{"name": "뉴스_1", "kind": "rss", "value": " https://feed.example/rss "},
|
||||
// News notifications are off by default, with no channel, the digest at 9.
|
||||
assert_eq!(s.collect, CollectSettings { keep_days: 30, targets: vec![], notify_channel: None, digest_hour: 9 });
|
||||
let s = parse_settings(&json!({"features": {"collect": false},
|
||||
"chatChannels": [{"id": "123456789012345678"}],
|
||||
"collect": {"keepDays": 7, "notifyChannel": "123456789012345678", "digestHour": 21, "targets": [
|
||||
{"name": "뉴스_1", "kind": "rss", "value": " https://feed.example/rss ", "notify": "daily"},
|
||||
{"name": "rust", "kind": "search", "value": "rust release", "everyMinutes": 1440, "enabled": false}]}})).unwrap();
|
||||
assert!(!s.features.collect);
|
||||
assert_eq!(s.collect, CollectSettings { keep_days: 7, targets: vec![
|
||||
assert_eq!(s.collect, CollectSettings { keep_days: 7, notify_channel: Some(123456789012345678), digest_hour: 21,
|
||||
targets: vec![
|
||||
CollectTarget { name: "뉴스_1".into(), kind: "rss".into(), value: "https://feed.example/rss".into(),
|
||||
every_minutes: 60, enabled: true },
|
||||
every_minutes: 60, enabled: true, notify: "daily".into() },
|
||||
CollectTarget { name: "rust".into(), kind: "search".into(), value: "rust release".into(),
|
||||
every_minutes: 1440, enabled: false },
|
||||
every_minutes: 1440, enabled: false, notify: "off".into() },
|
||||
]});
|
||||
// The channel must be a registered one Jarvis may send in.
|
||||
for raw in [json!({"collect": {"notifyChannel": "123456789012345678"}}),
|
||||
json!({"chatChannels": [{"id": "123456789012345678", "send": false}],
|
||||
"collect": {"notifyChannel": "123456789012345678"}})] {
|
||||
assert!(parse_settings(&raw).unwrap_err().0.contains("collect.notifyChannel"), "{raw}");
|
||||
}
|
||||
let t = |extra: Value| {
|
||||
let mut m = json!({"name": "a", "kind": "site", "value": "https://a.example"});
|
||||
m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
@@ -1029,6 +1056,8 @@ mod tests {
|
||||
(t(json!({"kind": "search", "value": " "})), "collect.targets[0].value"),
|
||||
(t(json!({"everyMinutes": 14})), "collect.targets[0].everyMinutes"),
|
||||
(t(json!({"everyMinutes": 10081})), "collect.targets[0].everyMinutes"),
|
||||
(t(json!({"notify": "hourly"})), "collect.targets[0].notify"),
|
||||
(json!({"collect": {"digestHour": 24}}), "collect.digestHour"),
|
||||
(json!({"collect": {"targets": [{"name": "a", "kind": "rss", "value": "https://a"},
|
||||
{"name": "a", "kind": "rss", "value": "https://b"}]}}), "collect.targets[1].name"),
|
||||
(json!({"collect": {"targets": [{"name": "News", "kind": "rss", "value": "https://a"},
|
||||
|
||||
@@ -137,6 +137,8 @@ pub fn fields() -> Vec<Field> {
|
||||
// Background collection (admin.spec.md, "Background collection"): no targets by default.
|
||||
f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"),
|
||||
f("collect.keepDays", Collect, Int { min: 1, max: 365 }, json!(30), "보관 기간(일)"),
|
||||
f("collect.notifyChannel", Collect, Id, Value::Null, "새 글을 알릴 채팅 채널(등록한 채널, 비우면 알리지 않음)"),
|
||||
f("collect.digestHour", Collect, Int { min: 0, max: 23 }, json!(9), "하루 요약을 보낼 시각(시)"),
|
||||
// Schedules (admin.spec.md, "Schedules").
|
||||
f("schedule.chatChannel", Schedule, Id, Value::Null,
|
||||
"음성으로 맡긴 알림을 그 사람이 음성 채널에 없을 때 보낼 채팅 채널(등록한 채널)"),
|
||||
|
||||
Reference in New Issue
Block a user