mostr/src/main.rs

449 lines
15 KiB
Rust
Raw Normal View History

2024-08-01 11:07:40 +00:00
use std::cell::RefCell;
use std::env::{args, var};
2024-07-24 13:03:34 +00:00
use std::fmt::Display;
use std::fs;
2024-07-26 09:58:09 +00:00
use std::fs::File;
use std::io::{BufRead, BufReader, stdin, stdout, Write};
use std::ops::Sub;
use std::path::PathBuf;
2024-07-24 13:03:34 +00:00
use std::str::FromStr;
use std::sync::mpsc;
use std::sync::mpsc::Sender;
2024-07-09 14:56:08 +00:00
use chrono::DateTime;
use colored::Colorize;
2024-07-29 18:06:23 +00:00
use log::{debug, error, info, trace, warn};
use nostr_sdk::prelude::*;
use xdg::BaseDirectories;
use crate::kinds::TRACKING_KIND;
use crate::task::State;
use crate::tasks::Tasks;
mod task;
mod tasks;
mod kinds;
2024-08-01 11:07:40 +00:00
type Events = Vec<Event>;
2024-07-26 18:45:29 +00:00
#[derive(Debug, Clone)]
2024-07-24 12:47:24 +00:00
struct EventSender {
2024-08-01 11:07:40 +00:00
tx: Sender<Events>,
2024-07-24 12:47:24 +00:00
keys: Keys,
2024-08-01 11:07:40 +00:00
queue: RefCell<Events>,
2024-07-24 12:47:24 +00:00
}
impl EventSender {
fn submit(&self, event_builder: EventBuilder) -> Result<Event> {
{
2024-08-06 14:57:01 +00:00
// Always flush if oldest event older than a minute or newer than now
let borrow = self.queue.borrow();
2024-08-06 14:57:01 +00:00
let min = Timestamp::now().sub(60u64);
if borrow.iter().any(|e| e.created_at < min || e.created_at > Timestamp::now()) {
drop(borrow);
2024-08-06 14:57:01 +00:00
debug!("Flushing event queue because it is older than a minute");
self.force_flush();
}
}
let mut queue = self.queue.borrow_mut();
Ok(event_builder.to_event(&self.keys).inspect(|event| {
2024-08-06 08:34:18 +00:00
if event.kind.as_u16() == TRACKING_KIND {
queue.retain(|e| {
2024-08-06 08:34:18 +00:00
e.kind.as_u16() != TRACKING_KIND
});
}
queue.push(event.clone());
})?)
2024-08-01 11:07:40 +00:00
}
/// Sends all pending events
fn force_flush(&self) {
debug!("Flushing {} events from queue", self.queue.borrow().len());
or_print(self.tx.send(self.clear()));
}
/// Sends all pending events if there is a non-tracking event
fn flush(&self) {
2024-08-06 08:34:18 +00:00
if self.queue.borrow().iter().any(|event| event.kind.as_u16() != TRACKING_KIND) {
self.force_flush()
}
2024-08-01 11:07:40 +00:00
}
fn clear(&self) -> Events {
trace!("Cleared queue: {:?}", self.queue.borrow());
2024-08-01 11:07:40 +00:00
self.queue.replace(Vec::with_capacity(3))
2024-07-24 12:47:24 +00:00
}
pub(crate) fn pubkey(&self) -> PublicKey {
self.keys.public_key()
}
2024-07-24 12:47:24 +00:00
}
2024-08-01 11:07:40 +00:00
impl Drop for EventSender {
fn drop(&mut self) {
self.force_flush()
2024-08-01 11:07:40 +00:00
}
}
2024-07-24 12:47:24 +00:00
fn some_non_empty(str: &str) -> Option<String> {
if str.is_empty() { None } else { Some(str.to_owned()) }
}
2024-07-24 12:47:24 +00:00
fn or_print<T, U: Display>(result: Result<T, U>) -> Option<T> {
match result {
Ok(value) => Some(value),
Err(error) => {
2024-07-29 18:06:23 +00:00
warn!("{}", error);
2024-07-24 12:47:24 +00:00
None
}
}
}
fn prompt(prompt: &str) -> Option<String> {
print!("{} ", prompt);
stdout().flush().unwrap();
match stdin().lines().next() {
Some(Ok(line)) => Some(line),
_ => None,
}
}
2024-07-09 14:56:08 +00:00
#[tokio::main]
async fn main() {
2024-07-29 18:06:23 +00:00
colog::init();
let config_dir = or_print(BaseDirectories::new())
.and_then(|d| or_print(d.create_config_directory("mostr")))
.unwrap_or(PathBuf::new());
let keysfile = config_dir.join("key");
let relayfile = config_dir.join("relays");
let keys = match fs::read_to_string(&keysfile).map(|s| Keys::from_str(&s)) {
Ok(Ok(key)) => key,
_ => {
2024-07-29 18:06:23 +00:00
warn!("Could not read keys from {}", keysfile.to_string_lossy());
let keys = prompt("Secret Key?")
.and_then(|s| or_print(Keys::from_str(&s)))
.unwrap_or_else(|| Keys::generate());
or_print(fs::write(&keysfile, keys.secret_key().unwrap().to_string()));
keys
}
};
2024-07-09 14:56:08 +00:00
let client = Client::new(&keys);
2024-07-29 18:06:23 +00:00
info!("My public key: {}", keys.public_key());
match var("MOSTR_RELAY") {
Ok(relay) => {
or_print(client.add_relay(relay).await);
2024-07-26 09:58:09 +00:00
}
_ => match File::open(&relayfile).map(|f| BufReader::new(f).lines().flatten()) {
Ok(lines) => {
for line in lines {
or_print(client.add_relay(line).await);
}
}
Err(e) => {
2024-07-29 18:06:23 +00:00
warn!("Could not read relays file: {}", e);
if let Some(line) = prompt("Relay?") {
let url = if line.contains("://") {
line
} else {
"wss://".to_string() + &line
};
or_print(client.add_relay(url.clone()).await).map(|bool| {
if bool {
or_print(fs::write(&relayfile, url));
}
});
};
}
},
2024-07-26 09:58:09 +00:00
}
//let proxy = Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9050)));
2024-07-23 10:27:36 +00:00
//client
2024-07-09 14:56:08 +00:00
// .add_relay_with_opts(
// "wss://relay.nostr.info",
// RelayOptions::new().proxy(proxy).flags(RelayServiceFlags::default().remove(RelayServiceFlags::WRITE)),
// )
// .await?;
2024-07-23 10:27:36 +00:00
//client
2024-07-09 14:56:08 +00:00
// .add_relay_with_opts(
// "ws://jgqaglhautb4k6e6i2g34jakxiemqp6z4wynlirltuukgkft2xuglmqd.onion",
// RelayOptions::new().proxy(proxy),
// )
// .await?;
//let metadata = Metadata::new()
// .name("username")
// .display_name("My Username")
// .about("Description")
// .picture(Url::parse("https://example.com/avatar.png")?)
// .banner(Url::parse("https://example.com/banner.png")?)
// .nip05("username@example.com")
// .lud16("yuki@getalby.com")
// .custom_field("custom_field", "my value");
2024-07-23 10:27:36 +00:00
//client.set_metadata(&metadata).await?;
2024-07-09 14:56:08 +00:00
2024-07-23 10:27:36 +00:00
client.connect().await;
2024-07-09 14:56:08 +00:00
2024-08-01 11:07:40 +00:00
let (tx, rx) = mpsc::channel();
2024-07-24 13:03:34 +00:00
let mut tasks: Tasks = Tasks::from(EventSender {
2024-08-01 11:07:40 +00:00
keys,
2024-07-24 13:03:34 +00:00
tx,
2024-08-01 11:07:40 +00:00
queue: Default::default(),
2024-07-24 13:03:34 +00:00
});
2024-07-18 10:20:25 +00:00
2024-08-06 08:34:18 +00:00
let sub_id = client.subscribe(vec![Filter::new()], None).await;
info!("Subscribed with {:?}", sub_id);
2024-07-23 10:27:36 +00:00
let mut notifications = client.notifications();
2024-07-19 18:04:21 +00:00
2024-07-24 13:03:34 +00:00
/*println!("Finding existing events");
let _ = client
.get_events_of(vec![Filter::new()], Some(Duration::from_secs(5)))
2024-07-19 13:49:23 +00:00
.map_ok(|res| {
println!("Found {} events", res.len());
2024-07-24 13:03:34 +00:00
let (mut task_events, props): (Vec<Event>, Vec<Event>) =
res.into_iter().partition(|e| e.kind.as_u32() == 1621);
2024-07-19 13:49:23 +00:00
task_events.sort_unstable();
for event in task_events {
2024-07-19 18:04:21 +00:00
print_event(&event);
2024-07-19 13:49:23 +00:00
tasks.add_task(event);
}
for event in props {
2024-07-19 18:04:21 +00:00
print_event(&event);
tasks.add_prop(&event);
2024-07-19 13:49:23 +00:00
}
})
2024-07-24 13:03:34 +00:00
.await;*/
2024-07-19 13:49:23 +00:00
2024-07-24 13:03:34 +00:00
let sender = tokio::spawn(async move {
while let Ok(e) = rx.recv() {
2024-08-01 11:07:40 +00:00
trace!("Sending {:?}", e);
// TODO batch up further
let _ = client.batch_event(e, RelaySendOptions::new()).await;
2024-07-24 13:03:34 +00:00
}
2024-07-29 18:06:23 +00:00
info!("Stopping listeners...");
2024-07-24 13:03:34 +00:00
client.unsubscribe_all().await;
});
for argument in args().skip(1) {
tasks.make_task(&argument);
}
2024-07-19 13:49:23 +00:00
println!();
2024-07-26 18:45:29 +00:00
let mut lines = stdin().lines();
loop {
2024-07-30 06:02:56 +00:00
or_print(tasks.print_tasks());
2024-07-24 13:03:34 +00:00
print!(
"{}",
format!(
2024-07-30 06:02:56 +00:00
" {}{}) ",
tasks.get_task_path(tasks.get_position()),
tasks.get_prompt_suffix()
2024-07-31 17:08:33 +00:00
).italic()
);
stdout().flush().unwrap();
2024-07-26 18:45:29 +00:00
match lines.next() {
Some(Ok(input)) => {
2024-07-29 18:06:23 +00:00
let mut count = 0;
2024-07-26 08:07:47 +00:00
while let Ok(notification) = notifications.try_recv() {
if let RelayPoolNotification::Event {
subscription_id,
event,
..
} = notification
{
print_event(&event);
tasks.add(*event);
2024-07-29 18:06:23 +00:00
count += 1;
2024-07-26 08:07:47 +00:00
}
}
2024-07-30 06:02:56 +00:00
if count > 0 {
2024-07-29 18:06:23 +00:00
info!("Received {count} updates");
}
2024-07-26 08:07:47 +00:00
let mut iter = input.chars();
2024-07-18 17:48:51 +00:00
let op = iter.next();
let arg = if input.len() > 1 {
input[1..].trim()
} else {
""
};
2024-07-18 17:48:51 +00:00
match op {
2024-08-01 11:07:40 +00:00
None => {
debug!("Flushing Tasks because of empty command");
2024-08-01 11:07:40 +00:00
tasks.flush()
}
2024-07-18 17:48:51 +00:00
Some(':') => match iter.next().and_then(|s| s.to_digit(10)) {
Some(digit) => {
let index = digit as usize;
let remaining = iter.collect::<String>().trim().to_string();
if remaining.is_empty() {
tasks.properties.remove(index);
continue;
}
2024-07-29 06:18:28 +00:00
let value = input[2..].trim().to_string();
2024-07-23 20:04:55 +00:00
if tasks.properties.get(index) == Some(&value) {
tasks.properties.remove(index);
} else {
tasks.properties.insert(index, value);
}
}
None => {
2024-07-31 17:08:33 +00:00
if arg.is_empty() {
println!("Available properties:
- `id`
- `parentid`
- `name`
- `state`
- `hashtags`
- `tags` - values of all nostr tags associated with the event, except event tags
- `desc` - last note on the task
- `description` - accumulated notes on the task
- `path` - name including parent tasks
- `rpath` - name including parent tasks up to active task
- `time` - time tracked on this task
- `rtime` - time tracked on this tasks and all recursive subtasks
- `progress` - recursive subtask completion in percent
- `subtasks` - how many direct subtasks are complete");
continue;
}
2024-07-29 06:18:28 +00:00
let pos = tasks.properties.iter().position(|s| s == arg);
match pos {
None => {
2024-07-29 06:18:28 +00:00
tasks.properties.push(arg.to_string());
}
Some(i) => {
2024-07-18 22:15:11 +00:00
tasks.properties.remove(i);
}
}
}
},
2024-07-25 07:55:29 +00:00
Some(',') => tasks.make_note(arg),
2024-07-18 17:48:51 +00:00
Some('>') => {
2024-08-01 11:07:40 +00:00
tasks.update_state(arg, State::Done);
tasks.move_up();
}
Some('<') => {
2024-08-01 11:07:40 +00:00
tasks.update_state(arg, State::Closed);
tasks.move_up();
2024-07-18 17:48:51 +00:00
}
2024-07-26 08:07:47 +00:00
2024-08-01 11:07:40 +00:00
Some('@') => {
tasks.undo();
}
Some('?') => {
tasks.set_state_filter(some_non_empty(arg).filter(|s| !s.is_empty()));
2024-08-01 11:07:40 +00:00
}
Some('!') => match tasks.get_position() {
None => {
2024-07-29 18:06:23 +00:00
warn!("First select a task to set its state!");
}
Some(id) => {
2024-08-01 11:07:40 +00:00
tasks.set_state_for(id, arg, match arg {
"Closed" => State::Closed,
"Done" => State::Done,
_ => State::Open,
});
}
},
Some('#') | Some('+') => {
2024-07-29 06:18:28 +00:00
tasks.add_tag(arg.to_string());
info!("Added tag filter for #{arg}")
2024-07-25 19:40:35 +00:00
}
Some('-') => {
tasks.remove_tag(arg.to_string());
info!("Removed tag filter for #{arg}")
}
Some('*') => {
if let Ok(num) = arg.parse::<i64>() {
2024-08-06 08:34:18 +00:00
tasks.track_at(Timestamp::from(Timestamp::now().as_u64().saturating_add_signed(num)));
} else if let Ok(date) = DateTime::parse_from_rfc3339(arg) {
tasks.track_at(Timestamp::from(date.to_utc().timestamp() as u64));
} else {
warn!("Cannot parse {arg}");
}
}
2024-07-18 17:48:51 +00:00
Some('.') => {
let mut dots = 1;
2024-07-18 22:15:11 +00:00
let mut pos = tasks.get_position();
for _ in iter.take_while(|c| c == &'.') {
dots += 1;
2024-08-01 11:07:40 +00:00
pos = tasks.get_parent(pos).cloned();
}
let slice = &input[dots..];
2024-07-24 21:26:29 +00:00
if slice.is_empty() {
tasks.move_to(pos);
continue;
}
if let Ok(depth) = slice.parse::<i8>() {
tasks.move_to(pos);
tasks.depth = depth;
} else {
tasks.filter_or_create(slice).map(|id| tasks.move_to(Some(id)));
}
}
2024-07-18 17:48:51 +00:00
2024-08-01 18:40:15 +00:00
Some('/') => {
let mut dots = 1;
let mut pos = tasks.get_position();
for _ in iter.take_while(|c| c == &'/') {
dots += 1;
pos = tasks.get_parent(pos).cloned();
}
let slice = &input[dots..].to_ascii_lowercase();
if slice.is_empty() {
tasks.move_to(pos);
continue;
}
if let Ok(depth) = slice.parse::<i8>() {
tasks.move_to(pos);
tasks.depth = depth;
} else {
let filtered = tasks
.children_of(pos)
.into_iter()
.filter_map(|child| tasks.get_by_id(&child))
.filter(|t| t.event.content.to_ascii_lowercase().starts_with(slice))
.map(|t| t.event.id)
.collect::<Vec<_>>();
if filtered.len() == 1 {
tasks.move_to(filtered.into_iter().nth(0));
} else {
tasks.move_to(pos);
tasks.set_filter(filtered);
}
}
}
_ => {
tasks.filter_or_create(&input);
2024-07-18 12:19:12 +00:00
}
2024-07-17 19:55:25 +00:00
}
}
2024-07-29 18:06:23 +00:00
Some(Err(e)) => warn!("{}", e),
2024-07-18 15:25:09 +00:00
None => break,
}
}
println!();
2024-07-18 17:48:51 +00:00
tasks.move_to(None);
2024-07-24 13:03:34 +00:00
drop(tasks);
2024-07-23 10:27:36 +00:00
2024-07-29 18:06:23 +00:00
info!("Submitting pending changes...");
2024-07-24 13:03:34 +00:00
or_print(sender.await);
2024-07-23 10:27:36 +00:00
}
fn print_event(event: &Event) {
2024-07-29 18:06:23 +00:00
debug!(
"At {} found {} kind {} \"{}\" {:?}",
2024-07-24 13:03:34 +00:00
event.created_at, event.id, event.kind, event.content, event.tags
);
2024-07-23 10:27:36 +00:00
}