1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
use antidote::RwLock;
use irc::client::prelude::*;
use std::thread::{sleep, spawn};
use std::{fmt, sync::Arc, time::Duration};
use chrono::{self, NaiveDateTime};
use time;
use plugin::*;
pub mod database;
mod parser;
use self::database::Database;
use self::parser::CommandParser;
use self::error::*;
use error::ErrorKind as FrippyErrorKind;
use error::FrippyError;
use failure::ResultExt;
fn get_time() -> NaiveDateTime {
let tm = time::now().to_timespec();
NaiveDateTime::from_timestamp(tm.sec, 0u32)
}
fn get_events<T: Database>(db: &RwLock<T>, in_next: chrono::Duration) -> Vec<database::Event> {
loop {
let before = get_time() + in_next;
match db.read().get_events_before(&before) {
Ok(events) => return events,
Err(e) => {
if e.kind() != ErrorKind::NotFound {
error!("Failed to get events: {}", e);
}
}
}
sleep(in_next.to_std().expect("Failed to convert look ahead time"));
}
}
fn run<T: Database>(client: &IrcClient, db: Arc<RwLock<T>>) {
let look_ahead = chrono::Duration::minutes(2);
let mut events = get_events(&db, look_ahead);
let mut sleep_time = look_ahead
.to_std()
.expect("Failed to convert look ahead time");
loop {
let now = get_time();
for event in events {
if event.time <= now {
let msg = format!("Reminder from {}: {}", event.author, event.content);
if let Err(e) = client.send_notice(&event.receiver, &msg) {
error!("Failed to send reminder: {}", e);
} else {
debug!("Sent reminder {:?}", event);
if let Some(repeat) = event.repeat {
let next_time = event.time + chrono::Duration::seconds(repeat as i64);
if let Err(e) = db.write().update_event_time(event.id, &next_time) {
error!("Failed to update reminder: {}", e);
} else {
debug!("Updated time on: {:?}", event);
}
} else if let Err(e) = db.write().delete_event(event.id) {
error!("Failed to delete reminder: {}", e);
}
}
} else {
let until_event = (event.time - now)
.to_std()
.expect("Failed to convert until event time");
if until_event < sleep_time {
sleep_time = until_event + Duration::from_secs(1);
}
}
}
sleep(sleep_time);
sleep_time = Duration::from_secs(120);
events = get_events(&db, look_ahead);
}
}
#[derive(PluginName)]
pub struct Remind<T: 'static + Database> {
events: Arc<RwLock<T>>,
has_reminder: RwLock<bool>,
}
impl<T: 'static + Database> Remind<T> {
pub fn new(db: T) -> Self {
let events = Arc::new(RwLock::new(db));
Remind {
events: events,
has_reminder: RwLock::new(false),
}
}
fn set(&self, command: PluginCommand) -> Result<&str, RemindError> {
let parser = CommandParser::try_from_tokens(command.tokens)?;
debug!("parser: {:?}", parser);
let mut target = parser.get_target();
if target == "me" {
target = &command.source;
}
let event = database::NewEvent {
receiver: target,
content: &parser.get_message(),
author: &command.source,
time: &parser.get_time(Duration::from_secs(120))?,
repeat: parser
.get_repeat(Duration::from_secs(300))?
.map(|d| d.as_secs()),
};
debug!("New event: {:?}", event);
Ok(self.events.write().insert_event(&event).map(|()| "Got it")?)
}
fn list(&self, user: &str) -> Result<String, RemindError> {
let mut events = self.events.read().get_user_events(user)?;
let mut list = events.remove(0).to_string();
for ev in events {
list.push_str("\r\n");
list.push_str(&ev.to_string());
}
Ok(list)
}
fn delete(&self, mut command: PluginCommand) -> Result<&str, RemindError> {
let id = command
.tokens
.remove(0)
.parse::<i64>()
.context(ErrorKind::Parsing)?;
let event = self.events.read().get_event(id)?;
if event.receiver.eq_ignore_ascii_case(&command.source)
|| event.author.eq_ignore_ascii_case(&command.source)
{
self.events
.write()
.delete_event(id)
.map(|()| "Successfully deleted")
} else {
Ok("Only the author or receiver can delete a reminder")
}
}
fn help(&self) -> &str {
"usage: remind <subcommand>\r\n\
subcommands: user, list, delete, help\r\n\
examples\r\n\
remind user foo to sleep in 1 hour\r\n\
remind user bar to leave early on 1.1 at 16:00 every week"
}
}
impl<T: Database> Plugin for Remind<T> {
fn execute(&self, client: &IrcClient, _: &Message) -> ExecutionStatus {
let mut has_reminder = self.has_reminder.write();
if !*has_reminder {
let events = Arc::clone(&self.events);
let client = client.clone();
spawn(move || run(&client, events));
*has_reminder = true;
}
ExecutionStatus::Done
}
fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> {
panic!("Remind should not use frippy's threading")
}
fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), FrippyError> {
if command.tokens.is_empty() {
return Ok(client
.send_notice(&command.source, &ErrorKind::InvalidCommand.to_string())
.context(FrippyErrorKind::Connection)?);
}
let source = command.source.clone();
let sub_command = command.tokens.remove(0);
let response = match sub_command.as_ref() {
"user" => self.set(command).map(|s| s.to_owned()),
"delete" => self.delete(command).map(|s| s.to_owned()),
"list" => self.list(&source),
"help" => Ok(self.help().to_owned()),
_ => Err(ErrorKind::InvalidCommand.into()),
};
let result = match response {
Ok(msg) => client
.send_notice(&source, &msg)
.context(FrippyErrorKind::Connection)?,
Err(e) => {
let message = e.to_string();
client
.send_notice(&source, &message)
.context(FrippyErrorKind::Connection)?;
Err(e).context(FrippyErrorKind::Remind)?
}
};
Ok(result)
}
fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result<String, String> {
Err(String::from(
"Evaluation of commands is not implemented for remind at this time",
))
}
}
impl<T: Database> fmt::Debug for Remind<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Remind {{ ... }}")
}
}
pub mod error {
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail, Error)]
#[error = "RemindError"]
pub enum ErrorKind {
/// Invalid command error
#[fail(display = "Incorrect Command. Send \"currency help\" for help.")]
InvalidCommand,
/// Missing message error
#[fail(display = "Reminder needs to have a description")]
MissingMessage,
/// Missing receiver error
#[fail(display = "Specify who to remind")]
MissingReceiver,
/// Missing time error
#[fail(display = "Reminder needs to have a time")]
MissingTime,
/// Invalid time error
#[fail(display = "Could not parse time")]
InvalidTime,
/// Invalid date error
#[fail(display = "Could not parse date")]
InvalidDate,
/// Parse error
#[fail(display = "Could not parse integers")]
Parsing,
/// Ambigous time error
#[fail(display = "Time specified is ambiguous")]
AmbiguousTime,
/// Time too short error
#[fail(display = "Reminder needs to be in over 2 minutes")]
TimeShort,
/// Repeat time too short error
#[fail(display = "Repeat time needs to be over 5 minutes")]
RepeatTimeShort,
/// Duplicate error
#[fail(display = "Entry already exists")]
Duplicate,
/// Not found error
#[fail(display = "No events found")]
NotFound,
}
}
|