mostr/src/main.rs

389 lines
13 KiB
Rust
Raw Normal View History

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::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 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::task::State;
use crate::tasks::Tasks;
mod task;
mod tasks;
2024-07-24 12:47:24 +00:00
static TASK_KIND: u64 = 1621;
static TRACKING_KIND: u64 = 1650;
2024-07-26 18:45:29 +00:00
#[derive(Debug, Clone)]
2024-07-24 12:47:24 +00:00
struct EventSender {
tx: Sender<Event>,
keys: Keys,
}
impl EventSender {
fn submit(&self, event_builder: EventBuilder) -> Option<Event> {
or_print(event_builder.to_event(&self.keys)).inspect(|event| {
2024-07-24 12:47:24 +00:00
or_print(self.tx.send(event.clone()));
})
}
}
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-07-24 13:03:34 +00:00
let (tx, rx) = mpsc::channel::<Event>();
let mut tasks: Tasks = Tasks::from(EventSender {
keys: keys.clone(),
2024-07-24 13:03:34 +00:00
tx,
});
2024-07-18 10:20:25 +00:00
2024-07-23 10:27:36 +00:00
let sub_id: SubscriptionId = client.subscribe(vec![Filter::new()], None).await;
2024-07-29 18:06:23 +00:00
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-07-29 18:06:23 +00:00
trace!("Sending {}", e.id);
// TODO send in batches
2024-07-24 13:03:34 +00:00
let _ = client.send_event(e).await;
}
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()
)
.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 {
None => {}
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 => {
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
2024-07-26 08:07:47 +00:00
Some('?') => {
2024-07-26 18:45:29 +00:00
tasks.set_state_filter(Some(arg.to_string()).filter(|s| !s.is_empty()));
2024-07-26 08:07:47 +00:00
}
2024-07-29 06:18:28 +00:00
Some('-') => tasks.add_note(arg),
2024-07-18 17:48:51 +00:00
Some('>') => {
tasks.update_state(arg, |_| Some(State::Done));
tasks.move_up();
}
Some('<') => {
tasks.update_state(arg, |_| Some(State::Closed));
tasks.move_up();
2024-07-18 17:48:51 +00:00
}
2024-07-26 08:07:47 +00:00
Some('|') | 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) => {
tasks.set_state_for(&id, arg);
tasks.move_to(tasks.get_position());
}
},
2024-07-25 19:40:35 +00:00
Some('#') => {
2024-07-29 06:18:28 +00:00
tasks.add_tag(arg.to_string());
2024-07-25 19:40:35 +00:00
}
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-07-26 18:45:29 +00:00
pos = tasks.get_parent(pos);
}
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;
continue;
}
pos = EventId::parse(slice).ok().or_else(|| {
// TODO check what is more intuitive:
// currently resets filters before filtering again, maybe keep them
tasks.move_to(pos);
let mut filtered: Vec<EventId> = tasks
2024-07-24 21:26:29 +00:00
.current_tasks()
.into_iter()
.filter(|t| t.event.content.starts_with(slice))
.map(|t| t.event.id)
.collect();
if filtered.is_empty() {
let lowercase = slice.to_ascii_lowercase();
filtered = tasks
.current_tasks()
.into_iter()
.filter(|t| {
t.event.content.to_ascii_lowercase().starts_with(&lowercase)
})
.map(|t| t.event.id)
.collect();
}
2024-07-24 21:26:29 +00:00
match filtered.len() {
0 => {
// No match, new task
tasks.make_task(slice)
}
1 => {
// One match, activate
Some(filtered.first().unwrap().clone())
}
_ => {
// Multiple match, filter
tasks.set_filter(filtered);
None
2024-07-19 13:49:23 +00:00
}
}
2024-07-24 21:26:29 +00:00
});
if pos != None {
2024-07-18 22:15:11 +00:00
tasks.move_to(pos);
}
}
2024-07-18 17:48:51 +00:00
_ => {
2024-07-24 13:03:34 +00:00
tasks.make_task(&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
2024-07-29 19:56:30 +00:00
// TODO optionally continue
2024-07-24 13:03:34 +00:00
tasks.update_state("", |t| {
if t.pure_state() == State::Active {
Some(State::Open)
} else {
None
}
});
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!(
2024-07-24 13:03:34 +00:00
"At {} found {} kind {} '{}' {:?}",
event.created_at, event.id, event.kind, event.content, event.tags
);
2024-07-23 10:27:36 +00:00
}