Compare commits
49 Commits
08728f6501
...
pretty
| Author | SHA1 | Date | |
|---|---|---|---|
| 98df04527d | |||
| da15ef0f15 | |||
| 035508f3ad | |||
| 69558f15b4 | |||
| a8f538eddf | |||
| 01e5ea14ab | |||
| 042d475c75 | |||
| dd0af52feb | |||
| 130f9bbeba | |||
| 0a05b32a7a | |||
| c3f897c61a | |||
| c62bac037f | |||
| 79a57f3082 | |||
| c33de9d754 | |||
| 72622032ad | |||
| ec1a12ca11 | |||
| f5f4d666d5 | |||
| 7bfef154d9 | |||
| fbe7dade54 | |||
| 321eca38e2 | |||
| 1a86204561 | |||
| fd721c53d8 | |||
| 4390d24492 | |||
| cb8b00f8d1 | |||
| eba362a7f2 | |||
| f16860dd09 | |||
| e7a0e5b662 | |||
| 371a8b98eb | |||
| 57ded3c076 | |||
| 332225b9d4 | |||
| 0d0a9d88ae | |||
| 24cf7d12f1 | |||
| 6adb567cd6 | |||
| 9e4b97e2e5 | |||
| e17751a992 | |||
| 3a47385be1 | |||
| 0b4cfadf88 | |||
| c33f901f48 | |||
| 369e88880a | |||
| d8275debdc | |||
| 25541bc1ca | |||
| e5a27f82f9 | |||
| 19ee6f338d | |||
| de2b79fa2a | |||
| 576973c6e6 | |||
| 453c0bd93f | |||
| b008cadecd | |||
| ce3c027e9a | |||
| 1a2b7dfc89 |
2207
Cargo.lock
generated
2207
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,11 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
members = [
|
members = [
|
||||||
"web",
|
"web",
|
||||||
"server",
|
"server",
|
||||||
"notmuch",
|
"notmuch",
|
||||||
|
"procmail2notmuch",
|
||||||
|
"shared"
|
||||||
]
|
]
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
|
|||||||
5
dev.sh
5
dev.sh
@@ -1,6 +1,7 @@
|
|||||||
|
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||||
tmux new-session -d -s letterbox-dev
|
tmux new-session -d -s letterbox-dev
|
||||||
tmux rename-window web
|
tmux rename-window web
|
||||||
tmux send-keys "cd web; trunk serve --address 0.0.0.0" C-m
|
tmux send-keys "cd web; trunk serve -w ../shared -w ../notmuch -w ./" C-m
|
||||||
tmux new-window -n server
|
tmux new-window -n server
|
||||||
tmux send-keys "cd server; cargo watch -x run" C-m
|
tmux send-keys "cd server; cargo watch -x run -w ../shared -w ../notmuch -w ./" C-m
|
||||||
tmux attach -d -t letterbox-dev
|
tmux attach -d -t letterbox-dev
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
anyhow = "1.0.75"
|
||||||
|
clap = { version = "4.4.7", features = ["derive"] }
|
||||||
log = "0.4.14"
|
log = "0.4.14"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = { version = "1.0", features = ["unbounded_depth"] }
|
serde_json = { version = "1.0", features = ["unbounded_depth"] }
|
||||||
|
|||||||
@@ -425,14 +425,14 @@ pub struct SearchTags(pub Vec<String>);
|
|||||||
pub struct ThreadSummary {
|
pub struct ThreadSummary {
|
||||||
pub thread: ThreadId,
|
pub thread: ThreadId,
|
||||||
pub timestamp: UnixTime,
|
pub timestamp: UnixTime,
|
||||||
pub date_relative: String,
|
|
||||||
/// user-friendly timestamp
|
/// user-friendly timestamp
|
||||||
pub matched: isize,
|
pub date_relative: String,
|
||||||
/// number of matched messages
|
/// number of matched messages
|
||||||
pub total: isize,
|
pub matched: isize,
|
||||||
/// total messages in thread
|
/// total messages in thread
|
||||||
pub authors: String,
|
pub total: isize,
|
||||||
/// comma-separated names with | between matched and unmatched
|
/// comma-separated names with | between matched and unmatched
|
||||||
|
pub authors: String,
|
||||||
pub subject: String,
|
pub subject: String,
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
|
|
||||||
@@ -454,6 +454,8 @@ pub enum NotmuchError {
|
|||||||
SerdeJson(#[from] serde_json::Error),
|
SerdeJson(#[from] serde_json::Error),
|
||||||
#[error("failed to parse bytes as str")]
|
#[error("failed to parse bytes as str")]
|
||||||
Utf8Error(#[from] std::str::Utf8Error),
|
Utf8Error(#[from] std::str::Utf8Error),
|
||||||
|
#[error("failed to parse bytes as String")]
|
||||||
|
StringUtf8Error(#[from] std::string::FromUtf8Error),
|
||||||
#[error("failed to parse str as int")]
|
#[error("failed to parse str as int")]
|
||||||
ParseIntError(#[from] std::num::ParseIntError),
|
ParseIntError(#[from] std::num::ParseIntError),
|
||||||
}
|
}
|
||||||
@@ -478,8 +480,19 @@ impl Notmuch {
|
|||||||
self.run_notmuch(std::iter::empty::<&str>())
|
self.run_notmuch(std::iter::empty::<&str>())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn search(&self, query: &str) -> Result<SearchSummary, NotmuchError> {
|
pub fn search(
|
||||||
let res = self.run_notmuch(["search", "--format=json", "--limit=20", query])?;
|
&self,
|
||||||
|
query: &str,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<SearchSummary, NotmuchError> {
|
||||||
|
let res = self.run_notmuch([
|
||||||
|
"search",
|
||||||
|
"--format=json",
|
||||||
|
&format!("--offset={offset}"),
|
||||||
|
&format!("--limit={limit}"),
|
||||||
|
query,
|
||||||
|
])?;
|
||||||
Ok(serde_json::from_slice(&res)?)
|
Ok(serde_json::from_slice(&res)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -541,6 +554,8 @@ impl Notmuch {
|
|||||||
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
|
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO(wathiede): implement tags() based on "notmuch search --output=tags '*'"
|
||||||
|
|
||||||
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
|
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
|
||||||
where
|
where
|
||||||
I: IntoIterator<Item = S>,
|
I: IntoIterator<Item = S>,
|
||||||
@@ -595,7 +610,7 @@ mod tests {
|
|||||||
fn search() -> Result<(), NotmuchError> {
|
fn search() -> Result<(), NotmuchError> {
|
||||||
let nm = Notmuch::with_config("testdata/notmuch.config");
|
let nm = Notmuch::with_config("testdata/notmuch.config");
|
||||||
nm.new()?;
|
nm.new()?;
|
||||||
let res = nm.search("goof")?;
|
let res = nm.search("goof", 0, 100)?;
|
||||||
assert_eq!(res.0.len(), 1);
|
assert_eq!(res.0.len(), 1);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
46
notmuch/src/main.rs
Normal file
46
notmuch/src/main.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use clap::{Parser, Subcommand};
|
||||||
|
use notmuch::Notmuch;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(author, version, about, long_about = None)]
|
||||||
|
#[command(propagate_version = true)]
|
||||||
|
struct Cli {
|
||||||
|
/// Optional notmuch config file
|
||||||
|
#[arg(short, long)]
|
||||||
|
config: Option<PathBuf>,
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Commands,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum Commands {
|
||||||
|
/// Show given search term
|
||||||
|
Show { search_term: String },
|
||||||
|
/// Search for given search term
|
||||||
|
Search { search_term: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
let cli = Cli::parse();
|
||||||
|
|
||||||
|
let nm = if let Some(config_path) = cli.config {
|
||||||
|
Notmuch::with_config(config_path)
|
||||||
|
} else {
|
||||||
|
Notmuch::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// You can check for the existence of subcommands, and if found use their
|
||||||
|
// matches just as you would the top level cmd
|
||||||
|
match &cli.command {
|
||||||
|
Commands::Search { search_term } => {
|
||||||
|
println!("{:#?}", nm.search(&search_term, 0, 10)?);
|
||||||
|
}
|
||||||
|
Commands::Show { search_term } => {
|
||||||
|
println!("{:#?}", nm.show(&search_term)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -5,12 +5,11 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
use notmuch::{Notmuch, NotmuchError, SearchSummary, ThreadSet};
|
||||||
use rayon::iter::{ParallelBridge, ParallelIterator};
|
use rayon::iter::{ParallelBridge, ParallelIterator};
|
||||||
|
|
||||||
use notmuch::{Notmuch, NotmuchError, SearchSummary, ThreadSet};
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore] // it is too expensive
|
#[ignore] // it is too expensive, run with `cargo test -- --ignored`
|
||||||
fn parse_one() -> Result<(), Box<dyn Error>> {
|
fn parse_one() -> Result<(), Box<dyn Error>> {
|
||||||
// take_hook() returns the default hook in case when a custom one is not set
|
// take_hook() returns the default hook in case when a custom one is not set
|
||||||
let orig_hook = std::panic::take_hook();
|
let orig_hook = std::panic::take_hook();
|
||||||
|
|||||||
9
procmail2notmuch/Cargo.toml
Normal file
9
procmail2notmuch/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
[package]
|
||||||
|
name = "procmail2notmuch"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.69"
|
||||||
255
procmail2notmuch/src/main.rs
Normal file
255
procmail2notmuch/src/main.rs
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
use std::{convert::Infallible, io::Write, str::FromStr};
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
enum MatchType {
|
||||||
|
From,
|
||||||
|
Sender,
|
||||||
|
To,
|
||||||
|
Cc,
|
||||||
|
Subject,
|
||||||
|
List,
|
||||||
|
DeliveredTo,
|
||||||
|
XForwardedTo,
|
||||||
|
ReplyTo,
|
||||||
|
XOriginalTo,
|
||||||
|
XSpam,
|
||||||
|
Body,
|
||||||
|
#[default]
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Match {
|
||||||
|
match_type: MatchType,
|
||||||
|
needle: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Rule {
|
||||||
|
matches: Vec<Match>,
|
||||||
|
tags: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unescape(s: &str) -> String {
|
||||||
|
s.replace('\\', "")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup_match(prefix: &str, s: &str) -> String {
|
||||||
|
unescape(&s[prefix.len()..]).replace(".*", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
mod matches {
|
||||||
|
pub const TO: &'static str = "TO";
|
||||||
|
pub const CC: &'static str = "Cc";
|
||||||
|
pub const TOCC: &'static str = "(TO|Cc)";
|
||||||
|
pub const FROM: &'static str = "From";
|
||||||
|
pub const SENDER: &'static str = "Sender";
|
||||||
|
pub const SUBJECT: &'static str = "Subject";
|
||||||
|
pub const DELIVERED_TO: &'static str = "Delivered-To";
|
||||||
|
pub const X_FORWARDED_TO: &'static str = "X-Forwarded-To";
|
||||||
|
pub const REPLY_TO: &'static str = "Reply-To";
|
||||||
|
pub const X_ORIGINAL_TO: &'static str = "X-Original-To";
|
||||||
|
pub const LIST_ID: &'static str = "List-ID";
|
||||||
|
pub const X_SPAM: &'static str = "X-Spam";
|
||||||
|
pub const X_SPAM_FLAG: &'static str = "X-Spam-Flag";
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for Match {
|
||||||
|
type Err = Infallible;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
// Examples:
|
||||||
|
// "* 1^0 ^TOsonyrewards.com@xinu.tv"
|
||||||
|
// "* ^TOsonyrewards.com@xinu.tv"
|
||||||
|
let mut it = s.split_whitespace().skip(1);
|
||||||
|
let mut needle = it.next().unwrap();
|
||||||
|
if needle == "1^0" {
|
||||||
|
needle = it.next().unwrap();
|
||||||
|
}
|
||||||
|
let mut needle = vec![needle];
|
||||||
|
needle.extend(it);
|
||||||
|
let needle = needle.join(" ");
|
||||||
|
let first = needle.chars().nth(0).unwrap_or(' ');
|
||||||
|
use matches::*;
|
||||||
|
if first == '^' {
|
||||||
|
let needle = &needle[1..];
|
||||||
|
if needle.starts_with(TO) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::To,
|
||||||
|
needle: cleanup_match(TO, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(FROM) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::From,
|
||||||
|
needle: cleanup_match(FROM, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(CC) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::Cc,
|
||||||
|
needle: cleanup_match(CC, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(TOCC) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::To,
|
||||||
|
needle: cleanup_match(TOCC, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(SENDER) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::Sender,
|
||||||
|
needle: cleanup_match(SENDER, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(SUBJECT) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::Subject,
|
||||||
|
needle: cleanup_match(SUBJECT, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(X_ORIGINAL_TO) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::XOriginalTo,
|
||||||
|
needle: cleanup_match(X_ORIGINAL_TO, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(LIST_ID) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::List,
|
||||||
|
needle: cleanup_match(LIST_ID, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(REPLY_TO) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::ReplyTo,
|
||||||
|
needle: cleanup_match(REPLY_TO, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(X_SPAM_FLAG) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::XSpam,
|
||||||
|
needle: '*'.to_string(),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(X_SPAM) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::XSpam,
|
||||||
|
needle: '*'.to_string(),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(DELIVERED_TO) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::DeliveredTo,
|
||||||
|
needle: cleanup_match(DELIVERED_TO, needle),
|
||||||
|
});
|
||||||
|
} else if needle.starts_with(X_FORWARDED_TO) {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::XForwardedTo,
|
||||||
|
needle: cleanup_match(X_FORWARDED_TO, needle),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
unreachable!("needle: '{needle}'")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Ok(Match {
|
||||||
|
match_type: MatchType::Body,
|
||||||
|
needle: cleanup_match("", &needle),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notmuch_from_rules<W: Write>(mut w: W, rules: &[Rule]) -> anyhow::Result<()> {
|
||||||
|
// TODO(wathiede): if reindexing this many tags is too slow, see if combining rules per tag is
|
||||||
|
// faster.
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
for r in rules {
|
||||||
|
for m in &r.matches {
|
||||||
|
for t in &r.tags {
|
||||||
|
if let MatchType::Unknown = m.match_type {
|
||||||
|
eprintln!("rule has unknown match {:?}", r);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let rule = match m.match_type {
|
||||||
|
MatchType::From => "from:",
|
||||||
|
// TODO(wathiede): something more specific?
|
||||||
|
MatchType::Sender => "from:",
|
||||||
|
MatchType::To => "to:",
|
||||||
|
MatchType::Cc => "to:",
|
||||||
|
MatchType::Subject => "subject:",
|
||||||
|
MatchType::List => "List-ID:",
|
||||||
|
MatchType::Body => "",
|
||||||
|
// TODO(wathiede): these will probably require adding fields to notmuch
|
||||||
|
// index. Handle them later.
|
||||||
|
MatchType::DeliveredTo
|
||||||
|
| MatchType::XForwardedTo
|
||||||
|
| MatchType::ReplyTo
|
||||||
|
| MatchType::XOriginalTo
|
||||||
|
| MatchType::XSpam => continue,
|
||||||
|
MatchType::Unknown => unreachable!(),
|
||||||
|
};
|
||||||
|
// Preserve unread status if run with --remove-all
|
||||||
|
lines.push(format!(
|
||||||
|
r#"-unprocessed +{} +unread -- is:unread tag:unprocessed {}"{}""#,
|
||||||
|
t, rule, m.needle
|
||||||
|
));
|
||||||
|
lines.push(format!(
|
||||||
|
// TODO(wathiede): this assumes `notmuch new` is configured to add
|
||||||
|
// `tag:unprocessed` to all new mail.
|
||||||
|
r#"-unprocessed +{} -- tag:unprocessed {}"{}""#,
|
||||||
|
t, rule, m.needle
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.sort();
|
||||||
|
for l in lines {
|
||||||
|
writeln!(w, "{l}")?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> anyhow::Result<()> {
|
||||||
|
let input = "/home/wathiede/dotfiles/procmailrc";
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
let mut cur_rule = Rule::default();
|
||||||
|
for l in std::fs::read_to_string(input)?.lines() {
|
||||||
|
let l = if let Some(idx) = l.find('#') {
|
||||||
|
&l[..idx]
|
||||||
|
} else {
|
||||||
|
l
|
||||||
|
}
|
||||||
|
.trim();
|
||||||
|
if l.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if l.find('=').is_some() {
|
||||||
|
// Probably a variable assignment, skip line
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let first = l.chars().nth(0).unwrap_or(' ');
|
||||||
|
match first {
|
||||||
|
':' => {
|
||||||
|
// start of rule
|
||||||
|
}
|
||||||
|
'*' => {
|
||||||
|
// add to current rule
|
||||||
|
let m: Match = l.parse()?;
|
||||||
|
cur_rule.matches.push(m);
|
||||||
|
}
|
||||||
|
'.' => {
|
||||||
|
// delivery to folder
|
||||||
|
cur_rule.tags.push(cleanup_match(
|
||||||
|
"",
|
||||||
|
&l.replace('.', "/")
|
||||||
|
.replace(' ', "")
|
||||||
|
.trim_matches('/')
|
||||||
|
.to_string(),
|
||||||
|
));
|
||||||
|
rules.push(cur_rule);
|
||||||
|
cur_rule = Rule::default();
|
||||||
|
}
|
||||||
|
'|' => cur_rule = Rule::default(), // external command
|
||||||
|
'$' => {
|
||||||
|
// TODO(wathiede): tag messages with no other tag as 'inbox'
|
||||||
|
cur_rule.tags.push(cleanup_match("", "inbox"));
|
||||||
|
rules.push(cur_rule);
|
||||||
|
cur_rule = Rule::default();
|
||||||
|
} // variable, should only be $DEFAULT in my config
|
||||||
|
_ => panic!("Unhandled first character '{}' {}", first, l),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notmuch_from_rules(std::io::stdout(), &rules)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
name = "server"
|
name = "server"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
default-bin = "server"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
@@ -9,10 +10,14 @@ edition = "2021"
|
|||||||
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
|
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
|
||||||
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
|
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
|
||||||
notmuch = { path = "../notmuch" }
|
notmuch = { path = "../notmuch" }
|
||||||
|
shared = { path = "../shared" }
|
||||||
serde_json = "1.0.87"
|
serde_json = "1.0.87"
|
||||||
thiserror = "1.0.37"
|
thiserror = "1.0.37"
|
||||||
serde = { version = "1.0.147", features = ["derive"] }
|
serde = { version = "1.0.147", features = ["derive"] }
|
||||||
log = "0.4.17"
|
log = "0.4.17"
|
||||||
|
tokio = "1.26.0"
|
||||||
|
glog = "0.1.0"
|
||||||
|
urlencoding = "2.1.3"
|
||||||
|
|
||||||
[dependencies.rocket_contrib]
|
[dependencies.rocket_contrib]
|
||||||
version = "0.4.11"
|
version = "0.4.11"
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ extern crate rocket;
|
|||||||
|
|
||||||
use std::{error::Error, io::Cursor, str::FromStr};
|
use std::{error::Error, io::Cursor, str::FromStr};
|
||||||
|
|
||||||
use notmuch::{Notmuch, NotmuchError, SearchSummary, ThreadSet};
|
use glog::Flags;
|
||||||
|
use notmuch::{Notmuch, NotmuchError, ThreadSet};
|
||||||
use rocket::{
|
use rocket::{
|
||||||
http::{ContentType, Header},
|
http::{ContentType, Header},
|
||||||
request::Request,
|
request::Request,
|
||||||
@@ -12,29 +13,61 @@ use rocket::{
|
|||||||
Response, State,
|
Response, State,
|
||||||
};
|
};
|
||||||
use rocket_cors::{AllowedHeaders, AllowedOrigins};
|
use rocket_cors::{AllowedHeaders, AllowedOrigins};
|
||||||
|
use server::{error::ServerError, nm::threadset_to_messages};
|
||||||
|
use shared::Message;
|
||||||
|
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
fn hello() -> &'static str {
|
fn hello() -> &'static str {
|
||||||
"Hello, world!"
|
"Hello, world!"
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/search")]
|
#[get("/refresh")]
|
||||||
async fn search_all(nm: &State<Notmuch>) -> Result<Json<SearchSummary>, Debug<NotmuchError>> {
|
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
|
||||||
search(nm, "*").await
|
Ok(Json(String::from_utf8_lossy(&nm.new()?).to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/search/<query>")]
|
#[get("/search")]
|
||||||
|
async fn search_all(
|
||||||
|
nm: &State<Notmuch>,
|
||||||
|
) -> Result<Json<shared::SearchResult>, Debug<NotmuchError>> {
|
||||||
|
search(nm, "*", None, None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/search/<query>?<page>&<results_per_page>")]
|
||||||
async fn search(
|
async fn search(
|
||||||
nm: &State<Notmuch>,
|
nm: &State<Notmuch>,
|
||||||
query: &str,
|
query: &str,
|
||||||
) -> Result<Json<SearchSummary>, Debug<NotmuchError>> {
|
page: Option<usize>,
|
||||||
let res = nm.search(query)?;
|
results_per_page: Option<usize>,
|
||||||
|
) -> Result<Json<shared::SearchResult>, Debug<NotmuchError>> {
|
||||||
|
let page = page.unwrap_or(0);
|
||||||
|
let results_per_page = results_per_page.unwrap_or(10);
|
||||||
|
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
|
||||||
|
info!(" search '{query}'");
|
||||||
|
let res = shared::SearchResult {
|
||||||
|
summary: nm.search(&query, page * results_per_page, results_per_page)?,
|
||||||
|
query: query.to_string(),
|
||||||
|
page,
|
||||||
|
results_per_page,
|
||||||
|
total: nm.count(&query)?,
|
||||||
|
};
|
||||||
|
Ok(Json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/show/<query>/pretty")]
|
||||||
|
async fn show_pretty(
|
||||||
|
nm: &State<Notmuch>,
|
||||||
|
query: &str,
|
||||||
|
) -> Result<Json<Vec<Message>>, Debug<ServerError>> {
|
||||||
|
let query = urlencoding::decode(query).map_err(|e| ServerError::from(NotmuchError::from(e)))?;
|
||||||
|
let res = threadset_to_messages(nm.show(&query).map_err(ServerError::from)?)?;
|
||||||
Ok(Json(res))
|
Ok(Json(res))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/show/<query>")]
|
#[get("/show/<query>")]
|
||||||
async fn show(nm: &State<Notmuch>, query: &str) -> Result<Json<ThreadSet>, Debug<NotmuchError>> {
|
async fn show(nm: &State<Notmuch>, query: &str) -> Result<Json<ThreadSet>, Debug<NotmuchError>> {
|
||||||
let res = nm.show(query)?;
|
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
|
||||||
|
let res = nm.show(&query)?;
|
||||||
Ok(Json(res))
|
Ok(Json(res))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +127,14 @@ async fn original(
|
|||||||
|
|
||||||
#[rocket::main]
|
#[rocket::main]
|
||||||
async fn main() -> Result<(), Box<dyn Error>> {
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
glog::new()
|
||||||
|
.init(Flags {
|
||||||
|
colorlogtostderr: true,
|
||||||
|
//alsologtostderr: true, // use logtostderr to only write to stderr and not to files
|
||||||
|
logtostderr: true,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
let allowed_origins = AllowedOrigins::all();
|
let allowed_origins = AllowedOrigins::all();
|
||||||
let cors = rocket_cors::CorsOptions {
|
let cors = rocket_cors::CorsOptions {
|
||||||
allowed_origins,
|
allowed_origins,
|
||||||
@@ -110,7 +151,16 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let _ = rocket::build()
|
let _ = rocket::build()
|
||||||
.mount(
|
.mount(
|
||||||
"/",
|
"/",
|
||||||
routes![original_part, original, hello, search_all, search, show],
|
routes![
|
||||||
|
original_part,
|
||||||
|
original,
|
||||||
|
hello,
|
||||||
|
refresh,
|
||||||
|
search_all,
|
||||||
|
search,
|
||||||
|
show_pretty,
|
||||||
|
show
|
||||||
|
],
|
||||||
)
|
)
|
||||||
.attach(cors)
|
.attach(cors)
|
||||||
.manage(Notmuch::default())
|
.manage(Notmuch::default())
|
||||||
9
server/src/error.rs
Normal file
9
server/src/error.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum ServerError {
|
||||||
|
#[error("notmuch")]
|
||||||
|
NotmuchError(#[from] notmuch::NotmuchError),
|
||||||
|
#[error("flatten")]
|
||||||
|
FlattenError,
|
||||||
|
}
|
||||||
2
server/src/lib.rs
Normal file
2
server/src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod error;
|
||||||
|
pub mod nm;
|
||||||
15
server/src/nm.rs
Normal file
15
server/src/nm.rs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
use shared::Message;
|
||||||
|
|
||||||
|
use crate::error;
|
||||||
|
|
||||||
|
// TODO(wathiede): decide good error type
|
||||||
|
pub fn threadset_to_messages(
|
||||||
|
thread_set: notmuch::ThreadSet,
|
||||||
|
) -> Result<Vec<Message>, error::ServerError> {
|
||||||
|
for t in thread_set.0 {
|
||||||
|
for tn in t.0 {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Vec::new())
|
||||||
|
}
|
||||||
10
shared/Cargo.toml
Normal file
10
shared/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "shared"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
notmuch = { path = "../notmuch" }
|
||||||
|
serde = { version = "1.0.147", features = ["derive"] }
|
||||||
13
shared/src/lib.rs
Normal file
13
shared/src/lib.rs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
use notmuch::SearchSummary;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
pub struct SearchResult {
|
||||||
|
pub summary: SearchSummary,
|
||||||
|
pub query: String,
|
||||||
|
pub page: usize,
|
||||||
|
pub results_per_page: usize,
|
||||||
|
pub total: usize,
|
||||||
|
}
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
pub struct Message {}
|
||||||
@@ -22,6 +22,18 @@ seed = "0.9.2"
|
|||||||
console_log = {git = "http://git-private.h.xinu.tv/wathiede/console_log.git"}
|
console_log = {git = "http://git-private.h.xinu.tv/wathiede/console_log.git"}
|
||||||
serde = { version = "1.0.147", features = ["derive"] }
|
serde = { version = "1.0.147", features = ["derive"] }
|
||||||
notmuch = {path = "../notmuch"}
|
notmuch = {path = "../notmuch"}
|
||||||
|
shared = {path = "../shared"}
|
||||||
|
itertools = "0.10.5"
|
||||||
|
serde_json = { version = "1.0.93", features = ["unbounded_depth"] }
|
||||||
|
wasm-timer = "0.2.5"
|
||||||
|
css-inline = "0.8.5"
|
||||||
|
|
||||||
[package.metadata.wasm-pack.profile.release]
|
[package.metadata.wasm-pack.profile.release]
|
||||||
wasm-opt = ['-Os']
|
wasm-opt = ['-Os']
|
||||||
|
|
||||||
|
[dependencies.web-sys]
|
||||||
|
version = "0.3.58"
|
||||||
|
features = [
|
||||||
|
"MediaQueryList",
|
||||||
|
"Window"
|
||||||
|
]
|
||||||
|
|||||||
6
web/Makefile
Normal file
6
web/Makefile
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
.PHONY: all
|
||||||
|
|
||||||
|
# Build in release mode and push to minio for serving.
|
||||||
|
all:
|
||||||
|
trunk build --release
|
||||||
|
mc mirror --overwrite --remove dist/ m/letterbox/
|
||||||
11
web/Trunk.toml
Normal file
11
web/Trunk.toml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[build]
|
||||||
|
release = true
|
||||||
|
|
||||||
|
[serve]
|
||||||
|
# The address to serve on.
|
||||||
|
address = "0.0.0.0"
|
||||||
|
port = 6758
|
||||||
|
|
||||||
|
[[proxy]]
|
||||||
|
backend = "http://localhost:9345/"
|
||||||
|
rewrite= "/api/"
|
||||||
@@ -4,30 +4,98 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||||
<link rel="modulepreload" href="/pkg/package.js" as="script" type="text/javascript">
|
<link rel="stylesheet", href="https://jenil.github.io/bulmaswatch/cyborg/bulmaswatch.min.css">
|
||||||
<link rel="preload" href="/pkg/package_bg.wasm" as="fetch" type="application/wasm" crossorigin="anonymous">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
|
||||||
<style>
|
<style>
|
||||||
.message {
|
.message {
|
||||||
padding-left: 0.5em;
|
padding: 0.5em;*/
|
||||||
}
|
}
|
||||||
.body {
|
.body {
|
||||||
padding-bottom: 1em;
|
background: white;
|
||||||
|
color: black;
|
||||||
|
padding: 0.5em;
|
||||||
|
margin-left: -0.5em;
|
||||||
|
margin-right: -0.5em;
|
||||||
|
margin-top: 0.5em;
|
||||||
}
|
}
|
||||||
.error {
|
.error {
|
||||||
background-color: red;
|
background-color: red;
|
||||||
}
|
}
|
||||||
.text_plain {
|
.view-part-text-plain {
|
||||||
white-space: pre-line;
|
white-space: pre-line;
|
||||||
}
|
}
|
||||||
|
iframe {
|
||||||
|
height: 100%;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.index {
|
||||||
|
table-layout: fixed;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.index .from {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
width: 15em;
|
||||||
|
}
|
||||||
|
.index .subject {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.index .date {
|
||||||
|
width: 8em;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.footer {
|
||||||
|
background-color: #eee;
|
||||||
|
color: #222;
|
||||||
|
position: fixed;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
height: 3em;
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
.tag {
|
||||||
|
margin-right: 2px;
|
||||||
|
}
|
||||||
|
.debug ul {
|
||||||
|
padding-left: 2em;
|
||||||
|
}
|
||||||
|
.debug li {
|
||||||
|
}
|
||||||
|
.loading {
|
||||||
|
animation-name: spin;
|
||||||
|
animation-duration: 1000ms;
|
||||||
|
animation-iteration-count: infinite;
|
||||||
|
animation-timing-function: linear;
|
||||||
|
}
|
||||||
|
@keyframes spin {
|
||||||
|
from {
|
||||||
|
transform:rotate(0deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform:rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.section {
|
||||||
|
padding: 1.5em;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input, .input {
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
input::placeholder, .input::placeholder{
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<section id="app"></section>
|
<section id="app"></section>
|
||||||
<script type="module">
|
|
||||||
import init from '/pkg/package.js';
|
|
||||||
init('/pkg/package_bg.wasm');
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
717
web/src/lib.rs
717
web/src/lib.rs
@@ -2,36 +2,116 @@
|
|||||||
// - it's useful when you want to check your code with `cargo make verify`
|
// - it's useful when you want to check your code with `cargo make verify`
|
||||||
// but some rules are too "annoying" or are not applicable for your case.)
|
// but some rules are too "annoying" or are not applicable for your case.)
|
||||||
#![allow(clippy::wildcard_imports)]
|
#![allow(clippy::wildcard_imports)]
|
||||||
|
use std::{
|
||||||
|
collections::hash_map::DefaultHasher,
|
||||||
|
hash::{Hash, Hasher},
|
||||||
|
};
|
||||||
|
|
||||||
|
use itertools::Itertools;
|
||||||
use log::{debug, error, info, Level};
|
use log::{debug, error, info, Level};
|
||||||
use notmuch::{Content, Part, SearchSummary, ThreadNode, ThreadSet};
|
use notmuch::{Content, Part, Thread, ThreadNode, ThreadSet};
|
||||||
use seed::{prelude::*, *};
|
use seed::{prelude::*, *};
|
||||||
|
use serde::de::Deserialize;
|
||||||
|
use wasm_timer::Instant;
|
||||||
|
|
||||||
|
const SEARCH_RESULTS_PER_PAGE: usize = 20;
|
||||||
|
|
||||||
// ------ ------
|
// ------ ------
|
||||||
// Init
|
// Init
|
||||||
// ------ ------
|
// ------ ------
|
||||||
|
|
||||||
// `init` describes what should happen when your app started.
|
// `init` describes what should happen when your app started.
|
||||||
fn init(_: Url, orders: &mut impl Orders<Msg>) -> Model {
|
fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
||||||
orders
|
if url.hash().is_none() {
|
||||||
.skip()
|
orders.request_url(urls::search("is:unread", 0));
|
||||||
.perform_cmd(async { Msg::SearchResult(search_request("*").await) });
|
} else {
|
||||||
|
orders.notify(subs::UrlRequested::new(url));
|
||||||
|
};
|
||||||
|
orders.subscribe(on_url_changed);
|
||||||
|
|
||||||
Model {
|
Model {
|
||||||
search_results: None,
|
context: Context::None,
|
||||||
show_results: None,
|
|
||||||
query: "".to_string(),
|
query: "".to_string(),
|
||||||
|
refreshing_state: RefreshingState::None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_url_changed(uc: subs::UrlChanged) -> Msg {
|
||||||
|
let mut url = uc.0;
|
||||||
|
info!(
|
||||||
|
"url changed '{}', history {}",
|
||||||
|
url,
|
||||||
|
history().length().unwrap_or(0)
|
||||||
|
);
|
||||||
|
let hpp = url.remaining_hash_path_parts();
|
||||||
|
match hpp.as_slice() {
|
||||||
|
["t", tid] => Msg::ShowPrettyRequest(tid.to_string()),
|
||||||
|
["s", query] => {
|
||||||
|
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
|
||||||
|
Msg::SearchRequest {
|
||||||
|
query,
|
||||||
|
page: 0,
|
||||||
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
["s", query, page] => {
|
||||||
|
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
|
||||||
|
let page = page[1..].parse().unwrap_or(0);
|
||||||
|
Msg::SearchRequest {
|
||||||
|
query,
|
||||||
|
page,
|
||||||
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p => {
|
||||||
|
if !p.is_empty() {
|
||||||
|
info!("Unhandled path '{p:?}'");
|
||||||
|
}
|
||||||
|
Msg::SearchRequest {
|
||||||
|
query: "".to_string(),
|
||||||
|
page: 0,
|
||||||
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod urls {
|
||||||
|
use seed::Url;
|
||||||
|
pub fn search(query: &str, page: usize) -> Url {
|
||||||
|
let query = Url::encode_uri_component(query);
|
||||||
|
if page > 0 {
|
||||||
|
Url::new().set_hash_path(["s", &query, &format!("p{page}")])
|
||||||
|
} else {
|
||||||
|
Url::new().set_hash_path(["s", &query])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn thread(tid: &str) -> Url {
|
||||||
|
Url::new().set_hash_path(["t", tid])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------ ------
|
// ------ ------
|
||||||
// Model
|
// Model
|
||||||
// ------ ------
|
// ------ ------
|
||||||
|
enum Context {
|
||||||
|
None,
|
||||||
|
Search(shared::SearchResult),
|
||||||
|
Thread(Vec<shared::Message>),
|
||||||
|
}
|
||||||
|
|
||||||
// `Model` describes our app state.
|
// `Model` describes our app state.
|
||||||
struct Model {
|
struct Model {
|
||||||
search_results: Option<SearchSummary>,
|
|
||||||
show_results: Option<ThreadSet>,
|
|
||||||
query: String,
|
query: String,
|
||||||
|
context: Context,
|
||||||
|
refreshing_state: RefreshingState,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
enum RefreshingState {
|
||||||
|
None,
|
||||||
|
Loading,
|
||||||
|
Error(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------ ------
|
// ------ ------
|
||||||
@@ -42,52 +122,117 @@ struct Model {
|
|||||||
// `Msg` describes the different events you can modify state with.
|
// `Msg` describes the different events you can modify state with.
|
||||||
enum Msg {
|
enum Msg {
|
||||||
Noop,
|
Noop,
|
||||||
SearchRequest(String),
|
// Tell the client to refresh its state
|
||||||
SearchResult(fetch::Result<SearchSummary>),
|
Reload,
|
||||||
|
// Tell the server to update state
|
||||||
|
RefreshStart,
|
||||||
|
RefreshDone(Option<FetchError>),
|
||||||
|
SearchRequest {
|
||||||
|
query: String,
|
||||||
|
page: usize,
|
||||||
|
results_per_page: usize,
|
||||||
|
},
|
||||||
|
SearchResult(fetch::Result<shared::SearchResult>),
|
||||||
ShowRequest(String),
|
ShowRequest(String),
|
||||||
ShowResult(fetch::Result<ThreadSet>),
|
ShowResult(fetch::Result<ThreadSet>),
|
||||||
|
ShowPrettyRequest(String),
|
||||||
|
ShowPrettyResult(fetch::Result<Vec<shared::Message>>),
|
||||||
|
NextPage,
|
||||||
|
PreviousPage,
|
||||||
}
|
}
|
||||||
|
|
||||||
// `update` describes how to handle each `Msg`.
|
// `update` describes how to handle each `Msg`.
|
||||||
fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||||
match msg {
|
match msg {
|
||||||
Msg::Noop => {}
|
Msg::Noop => {}
|
||||||
Msg::SearchRequest(query) => {
|
Msg::RefreshStart => {
|
||||||
model.show_results = None;
|
model.refreshing_state = RefreshingState::Loading;
|
||||||
model.query = query.clone();
|
orders.perform_cmd(async move { Msg::RefreshDone(refresh_request().await.err()) });
|
||||||
orders
|
}
|
||||||
.skip()
|
Msg::RefreshDone(err) => {
|
||||||
.perform_cmd(async move { Msg::SearchResult(search_request(&query).await) });
|
model.refreshing_state = if let Some(err) = err {
|
||||||
|
RefreshingState::Error(format!("{:?}", err))
|
||||||
|
} else {
|
||||||
|
RefreshingState::None
|
||||||
|
};
|
||||||
|
orders.perform_cmd(async move { Msg::Reload });
|
||||||
|
}
|
||||||
|
Msg::Reload => {
|
||||||
|
orders.perform_cmd(async move { on_url_changed(subs::UrlChanged(Url::current())) });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Msg::SearchRequest {
|
||||||
|
query,
|
||||||
|
page,
|
||||||
|
results_per_page,
|
||||||
|
} => {
|
||||||
|
info!("searching for '{query}' pg {page} # / pg {results_per_page}");
|
||||||
|
model.query = query.clone();
|
||||||
|
orders.skip().perform_cmd(async move {
|
||||||
|
Msg::SearchResult(search_request(&query, page, results_per_page).await)
|
||||||
|
});
|
||||||
|
}
|
||||||
Msg::SearchResult(Ok(response_data)) => {
|
Msg::SearchResult(Ok(response_data)) => {
|
||||||
debug!("fetch ok {:#?}", response_data);
|
debug!("fetch ok {:#?}", response_data);
|
||||||
model.search_results = Some(response_data);
|
model.context = Context::Search(response_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
Msg::SearchResult(Err(fetch_error)) => {
|
Msg::SearchResult(Err(fetch_error)) => {
|
||||||
error!("fetch failed {:?}", fetch_error);
|
error!("fetch failed {:?}", fetch_error);
|
||||||
}
|
}
|
||||||
Msg::ShowRequest(query) => {
|
|
||||||
model.show_results = None;
|
Msg::ShowRequest(tid) => {
|
||||||
orders
|
orders
|
||||||
.skip()
|
.skip()
|
||||||
.perform_cmd(async move { Msg::ShowResult(show_request(&query).await) });
|
.perform_cmd(async move { Msg::ShowResult(show_request(&tid).await) });
|
||||||
}
|
}
|
||||||
|
// TODO(wathiede): remove
|
||||||
Msg::ShowResult(Ok(response_data)) => {
|
Msg::ShowResult(Ok(response_data)) => {
|
||||||
debug!("fetch ok {:#?}", response_data);
|
debug!("fetch ok {:#?}", response_data);
|
||||||
model.show_results = Some(response_data);
|
//model.context = Context::Thread(response_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
Msg::ShowResult(Err(fetch_error)) => {
|
Msg::ShowResult(Err(fetch_error)) => {
|
||||||
error!("fetch failed {:?}", fetch_error);
|
error!("fetch failed {:?}", fetch_error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Msg::ShowPrettyRequest(tid) => {
|
||||||
|
orders
|
||||||
|
.skip()
|
||||||
|
.perform_cmd(async move { Msg::ShowPrettyResult(show_pretty_request(&tid).await) });
|
||||||
|
}
|
||||||
|
Msg::ShowPrettyResult(Ok(response_data)) => {
|
||||||
|
info!("fetch ok {:#?}", response_data);
|
||||||
|
model.context = Context::Thread(response_data);
|
||||||
|
}
|
||||||
|
Msg::ShowPrettyResult(Err(fetch_error)) => {
|
||||||
|
error!("fetch failed {:?}", fetch_error);
|
||||||
|
}
|
||||||
|
Msg::NextPage => {
|
||||||
|
match &model.context {
|
||||||
|
Context::Search(sr) => {
|
||||||
|
orders.request_url(urls::search(&sr.query, sr.page + 1));
|
||||||
|
}
|
||||||
|
Context::Thread(_) => (), // do nothing (yet?)
|
||||||
|
Context::None => (), // do nothing (yet?)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Msg::PreviousPage => {
|
||||||
|
match &model.context {
|
||||||
|
Context::Search(sr) => {
|
||||||
|
orders.request_url(urls::search(&sr.query, sr.page.saturating_sub(1)));
|
||||||
|
}
|
||||||
|
Context::Thread(_) => (), // do nothing (yet?)
|
||||||
|
Context::None => (), // do nothing (yet?)
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn search_request(query: &str) -> fetch::Result<SearchSummary> {
|
async fn search_request(
|
||||||
Request::new(api::search(query))
|
query: &str,
|
||||||
|
page: usize,
|
||||||
|
results_per_page: usize,
|
||||||
|
) -> fetch::Result<shared::SearchResult> {
|
||||||
|
Request::new(api::search(query, page, results_per_page))
|
||||||
.method(Method::Get)
|
.method(Method::Get)
|
||||||
.fetch()
|
.fetch()
|
||||||
.await?
|
.await?
|
||||||
@@ -97,20 +242,55 @@ async fn search_request(query: &str) -> fetch::Result<SearchSummary> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod api {
|
mod api {
|
||||||
const BASE_URL: &str = "http://nixos-07:9345";
|
use seed::Url;
|
||||||
pub fn search(query: &str) -> String {
|
|
||||||
format!("{}/search/{}", BASE_URL, query)
|
const BASE_URL: &str = "/api";
|
||||||
|
pub fn refresh() -> String {
|
||||||
|
format!("{BASE_URL}/refresh")
|
||||||
}
|
}
|
||||||
pub fn show(query: &str) -> String {
|
pub fn search(query: &str, page: usize, results_per_page: usize) -> String {
|
||||||
format!("{}/show/{}", BASE_URL, query)
|
let query = Url::encode_uri_component(query);
|
||||||
|
format!("{BASE_URL}/search/{query}?page={page}&results_per_page={results_per_page}")
|
||||||
|
}
|
||||||
|
pub fn show(tid: &str) -> String {
|
||||||
|
format!("{BASE_URL}/show/{tid}")
|
||||||
|
}
|
||||||
|
pub fn show_pretty(tid: &str) -> String {
|
||||||
|
format!("{BASE_URL}/show/{tid}/pretty")
|
||||||
}
|
}
|
||||||
pub fn original(message_id: &str) -> String {
|
pub fn original(message_id: &str) -> String {
|
||||||
format!("{}/original/{}", BASE_URL, message_id)
|
format!("{BASE_URL}/original/{message_id}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn show_request(query: &str) -> fetch::Result<ThreadSet> {
|
async fn refresh_request() -> fetch::Result<()> {
|
||||||
Request::new(api::show(query))
|
let t = Request::new(api::refresh())
|
||||||
|
.method(Method::Get)
|
||||||
|
.fetch()
|
||||||
|
.await?
|
||||||
|
.check_status()?
|
||||||
|
.text()
|
||||||
|
.await?;
|
||||||
|
info!("refresh {t}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show_request(tid: &str) -> fetch::Result<ThreadSet> {
|
||||||
|
let b = Request::new(api::show(tid))
|
||||||
|
.method(Method::Get)
|
||||||
|
.fetch()
|
||||||
|
.await?
|
||||||
|
.check_status()?
|
||||||
|
.bytes()
|
||||||
|
.await?;
|
||||||
|
let mut deserializer = serde_json::Deserializer::from_slice(&b);
|
||||||
|
deserializer.disable_recursion_limit();
|
||||||
|
Ok(ThreadSet::deserialize(&mut deserializer)
|
||||||
|
.map_err(|_| FetchError::JsonError(fetch::JsonError::Serde(JsValue::NULL)))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show_pretty_request(tid: &str) -> fetch::Result<Vec<shared::Message>> {
|
||||||
|
Request::new(api::show_pretty(tid))
|
||||||
.method(Method::Get)
|
.method(Method::Get)
|
||||||
.fetch()
|
.fetch()
|
||||||
.await?
|
.await?
|
||||||
@@ -146,7 +326,6 @@ fn view_message(thread: &ThreadNode) -> Node<Msg> {
|
|||||||
div![C!["header"], "From: ", &message.headers.from],
|
div![C!["header"], "From: ", &message.headers.from],
|
||||||
div![C!["header"], "Date: ", &message.headers.date],
|
div![C!["header"], "Date: ", &message.headers.date],
|
||||||
div![C!["header"], "To: ", &message.headers.to],
|
div![C!["header"], "To: ", &message.headers.to],
|
||||||
hr![],
|
|
||||||
div![
|
div![
|
||||||
C!["body"],
|
C!["body"],
|
||||||
match &message.body {
|
match &message.body {
|
||||||
@@ -164,7 +343,7 @@ fn view_body(body: &[Part]) -> Node<Msg> {
|
|||||||
|
|
||||||
fn view_text_plain(content: &Option<Content>) -> Node<Msg> {
|
fn view_text_plain(content: &Option<Content>) -> Node<Msg> {
|
||||||
match &content {
|
match &content {
|
||||||
Some(Content::String(content)) => p![C!["text_plain"], content],
|
Some(Content::String(content)) => p![C!["view-part-text-plain"], content],
|
||||||
_ => div![
|
_ => div![
|
||||||
C!["error"],
|
C!["error"],
|
||||||
format!("Unhandled content enum for text/plain"),
|
format!("Unhandled content enum for text/plain"),
|
||||||
@@ -177,7 +356,13 @@ fn view_part(part: &Part) -> Node<Msg> {
|
|||||||
"text/plain" => view_text_plain(&part.content),
|
"text/plain" => view_text_plain(&part.content),
|
||||||
"text/html" => {
|
"text/html" => {
|
||||||
if let Some(Content::String(html)) = &part.content {
|
if let Some(Content::String(html)) = &part.content {
|
||||||
return div![Node::from_html(None, &html)];
|
let inliner = css_inline::CSSInliner::options()
|
||||||
|
.load_remote_stylesheets(false)
|
||||||
|
.remove_style_tags(true)
|
||||||
|
.build();
|
||||||
|
let inlined = inliner.inline(html).expect("failed to inline CSS");
|
||||||
|
|
||||||
|
return div![C!["view-part-text-html"], raw![&inlined]];
|
||||||
} else {
|
} else {
|
||||||
div![
|
div![
|
||||||
C!["error"],
|
C!["error"],
|
||||||
@@ -195,7 +380,12 @@ fn view_part(part: &Part) -> Node<Msg> {
|
|||||||
for part in parts.iter().rev() {
|
for part in parts.iter().rev() {
|
||||||
if part.content_type == "text/html" {
|
if part.content_type == "text/html" {
|
||||||
if let Some(Content::String(html)) = &part.content {
|
if let Some(Content::String(html)) = &part.content {
|
||||||
return div![Node::from_html(None, &html)];
|
let inliner = css_inline::CSSInliner::options()
|
||||||
|
.load_remote_stylesheets(false)
|
||||||
|
.remove_style_tags(true)
|
||||||
|
.build();
|
||||||
|
let inlined = inliner.inline(html).expect("failed to inline CSS");
|
||||||
|
return div![Node::from_html(None, &inlined)];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if part.content_type == "text/plain" {
|
if part.content_type == "text/plain" {
|
||||||
@@ -236,114 +426,357 @@ fn first_subject(thread: &ThreadNode) -> Option<String> {
|
|||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
/*
|
|
||||||
let msg = thread.0.as_ref();
|
fn set_title(title: &str) {
|
||||||
if let Some(msg) = msg {
|
seed::document().set_title(&format!("lb: {}", title));
|
||||||
div![
|
}
|
||||||
a![attrs! {At::Href=>api::original(&msg.id)}, "Original"],
|
|
||||||
table![
|
fn tags_chiclet(tags: &[String], is_mobile: bool) -> impl Iterator<Item = Node<Msg>> + '_ {
|
||||||
tr![th!["Subject"], td![&msg.headers.subject],],
|
tags.iter().map(move |tag| {
|
||||||
tr![th!["From"], td![&msg.headers.from],],
|
let mut hasher = DefaultHasher::new();
|
||||||
tr![th!["To"], td![&msg.headers.to],],
|
tag.hash(&mut hasher);
|
||||||
tr![th!["CC"], td![&msg.headers.cc],],
|
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
|
||||||
tr![th!["BCC"], td![&msg.headers.bcc],],
|
let style = style! {St::BackgroundColor=>hex};
|
||||||
tr![th!["Reply-To"], td![&msg.headers.reply_to],],
|
let classes = C!["tag", IF!(is_mobile => "is-small")];
|
||||||
tr![th!["Date"], td![&msg.headers.date],],
|
let tag = tag.clone();
|
||||||
],
|
a![
|
||||||
table![
|
attrs! {
|
||||||
tr![th!["MessageId"], td![&msg.id],],
|
At::Href => urls::search(&format!("tag:{tag}"), 0)
|
||||||
tr![
|
},
|
||||||
th!["Match"],
|
match tag.as_str() {
|
||||||
td![if msg.r#match { "true" } else { "false" }],
|
"attachment" => span![classes, style, "📎"],
|
||||||
],
|
"replied" => span![classes, style, i![C!["fa-solid", "fa-reply"]]],
|
||||||
tr![
|
_ => span![classes, style, &tag],
|
||||||
th!["Excluded"],
|
},
|
||||||
td![if msg.excluded { "true" } else { "false" }],
|
ev(Ev::Click, move |_| Msg::SearchRequest {
|
||||||
],
|
query: format!("tag:{tag}"),
|
||||||
tr![th!["Filename"], td![&msg.filename],],
|
page: 0,
|
||||||
tr![th!["Timestamp"], td![msg.timestamp.to_string()],],
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
tr![th!["Date"], td![&msg.date_relative],],
|
})
|
||||||
tr![th!["Tags"], td![format!("{:?}", msg.tags)],],
|
]
|
||||||
],
|
})
|
||||||
]
|
}
|
||||||
} else {
|
|
||||||
div![h2!["No message"]]
|
fn pretty_authors(authors: &str) -> impl Iterator<Item = Node<Msg>> + '_ {
|
||||||
|
let one_person = authors.matches(',').count() == 0;
|
||||||
|
let authors = authors.split(',');
|
||||||
|
|
||||||
|
Itertools::intersperse(
|
||||||
|
authors.filter_map(move |author| {
|
||||||
|
if one_person {
|
||||||
|
return Some(span![
|
||||||
|
attrs! {
|
||||||
|
At::Title => author.trim()},
|
||||||
|
author
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
author.split_whitespace().nth(0).map(|first| {
|
||||||
|
span![
|
||||||
|
attrs! {
|
||||||
|
At::Title => author.trim()},
|
||||||
|
first
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
span![", "],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_mobile_search_results(query: &str, search_results: &shared::SearchResult) -> Node<Msg> {
|
||||||
|
if query.is_empty() {
|
||||||
|
set_title("all mail");
|
||||||
|
} else {
|
||||||
|
set_title(query);
|
||||||
|
}
|
||||||
|
let summaries = &search_results.summary.0;
|
||||||
|
let rows = summaries.iter().map(|r| {
|
||||||
|
/*
|
||||||
|
let tid = r.thread.clone();
|
||||||
|
tr![
|
||||||
|
td![
|
||||||
|
C!["from"],
|
||||||
|
pretty_authors(&r.authors),
|
||||||
|
IF!(r.total>1 => small![" ", r.total.to_string()]),
|
||||||
|
],
|
||||||
|
td![C!["subject"], tags_chiclet(&r.tags), " ", &r.subject],
|
||||||
|
td![C!["date"], &r.date_relative],
|
||||||
|
ev(Ev::Click, move |_| Msg::ShowPrettyRequest(tid)),
|
||||||
|
]
|
||||||
|
*/
|
||||||
|
let tid = r.thread.clone();
|
||||||
|
div![
|
||||||
|
div![
|
||||||
|
C!["subject"],
|
||||||
|
&r.subject,
|
||||||
|
ev(Ev::Click, move |_| Msg::ShowPrettyRequest(tid)),
|
||||||
|
],
|
||||||
|
div![
|
||||||
|
span![C!["from"], pretty_authors(&r.authors)],
|
||||||
|
span![C!["tags"], tags_chiclet(&r.tags, true)],
|
||||||
|
],
|
||||||
|
span![C!["date"], &r.date_relative],
|
||||||
|
]
|
||||||
|
});
|
||||||
|
let first = search_results.page * search_results.results_per_page;
|
||||||
|
div![
|
||||||
|
h1!["Search results"],
|
||||||
|
view_search_pager(first, summaries.len(), search_results.total),
|
||||||
|
rows,
|
||||||
|
view_search_pager(first, summaries.len(), search_results.total)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_search_results(query: &str, search_results: &shared::SearchResult) -> Node<Msg> {
|
||||||
|
if query.is_empty() {
|
||||||
|
set_title("all mail");
|
||||||
|
} else {
|
||||||
|
set_title(query);
|
||||||
|
}
|
||||||
|
let summaries = &search_results.summary.0;
|
||||||
|
let rows = summaries.iter().map(|r| {
|
||||||
|
let tid = r.thread.clone();
|
||||||
|
tr![
|
||||||
|
td![
|
||||||
|
C!["from"],
|
||||||
|
pretty_authors(&r.authors),
|
||||||
|
IF!(r.total>1 => small![" ", r.total.to_string()]),
|
||||||
|
],
|
||||||
|
td![
|
||||||
|
C!["subject"],
|
||||||
|
tags_chiclet(&r.tags, false),
|
||||||
|
" ",
|
||||||
|
a![
|
||||||
|
C!["has-text-light"],
|
||||||
|
attrs! {
|
||||||
|
At::Href => urls::thread(&tid)
|
||||||
|
},
|
||||||
|
&r.subject,
|
||||||
|
]
|
||||||
|
],
|
||||||
|
td![C!["date"], &r.date_relative]
|
||||||
|
]
|
||||||
|
});
|
||||||
|
let first = search_results.page * search_results.results_per_page;
|
||||||
|
div![
|
||||||
|
view_search_pager(first, summaries.len(), search_results.total),
|
||||||
|
table![
|
||||||
|
C![
|
||||||
|
"table",
|
||||||
|
"index",
|
||||||
|
"is-fullwidth",
|
||||||
|
"is-hoverable",
|
||||||
|
"is-narrow",
|
||||||
|
"is-striped",
|
||||||
|
],
|
||||||
|
thead![tr![
|
||||||
|
th![C!["from"], "From"],
|
||||||
|
th![C!["subject"], "Subject"],
|
||||||
|
th![C!["date"], "Date"]
|
||||||
|
]],
|
||||||
|
tbody![rows]
|
||||||
|
],
|
||||||
|
view_search_pager(first, summaries.len(), search_results.total)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_search_pager(start: usize, count: usize, total: usize) -> Node<Msg> {
|
||||||
|
let is_first = start <= 0;
|
||||||
|
let is_last = (start + SEARCH_RESULTS_PER_PAGE) >= total;
|
||||||
|
nav![
|
||||||
|
C!["pagination"],
|
||||||
|
a![
|
||||||
|
C!["pagination-previous", "button",],
|
||||||
|
IF!(is_first => attrs!{ At::Disabled=>true }),
|
||||||
|
"<",
|
||||||
|
ev(Ev::Click, |_| Msg::PreviousPage)
|
||||||
|
],
|
||||||
|
a![
|
||||||
|
C!["pagination-next", "button", IF!(is_last => "is-static")],
|
||||||
|
IF!(is_last => attrs!{ At::Disabled=>true }),
|
||||||
|
">",
|
||||||
|
ev(Ev::Click, |_| Msg::NextPage)
|
||||||
|
],
|
||||||
|
ul![
|
||||||
|
C!["pagination-list"],
|
||||||
|
li![format!("{} - {} of {}", start, start + count, total)],
|
||||||
|
],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_thread(messages: &[shared::Message]) -> Node<Msg> {
|
||||||
|
div!["TODO(wathiede): view_thread(messages)"]
|
||||||
|
/*
|
||||||
|
assert_eq!(thread_set.0.len(), 1);
|
||||||
|
let thread = &thread_set.0[0];
|
||||||
|
assert_eq!(thread.0.len(), 1);
|
||||||
|
let thread_node = &thread.0[0];
|
||||||
|
let subject = first_subject(&thread_node).unwrap_or("<No subject>".to_string());
|
||||||
|
set_title(&subject);
|
||||||
|
div![
|
||||||
|
C!["container"],
|
||||||
|
h1![C!["title"], subject],
|
||||||
|
view_message(&thread_node),
|
||||||
|
a![
|
||||||
|
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
|
||||||
|
"Original"
|
||||||
|
],
|
||||||
|
/*
|
||||||
|
div![
|
||||||
|
C!["debug"],
|
||||||
|
"Add zippy for debug dump",
|
||||||
|
view_debug_thread_set(thread_set)
|
||||||
|
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
|
||||||
|
*/
|
||||||
|
]
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_debug_thread_set(thread_set: &ThreadSet) -> Node<Msg> {
|
||||||
|
ul![thread_set
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, t)| { li!["t", i, ": ", view_debug_thread(t),] })]
|
||||||
|
}
|
||||||
|
fn view_debug_thread(thread: &Thread) -> Node<Msg> {
|
||||||
|
ul![thread
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, tn)| { li!["tn", i, ": ", view_debug_thread_node(tn),] })]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_debug_thread_node(thread_node: &ThreadNode) -> Node<Msg> {
|
||||||
|
ul![
|
||||||
|
IF!(thread_node.0.is_some()=>li!["tn id:", &thread_node.0.as_ref().unwrap().id]),
|
||||||
|
thread_node.1.iter().enumerate().map(|(i, tn)| li![
|
||||||
|
"tn",
|
||||||
|
i,
|
||||||
|
": ",
|
||||||
|
view_debug_thread_node(tn)
|
||||||
|
])
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_header(query: &str, refresh_request: &RefreshingState) -> Node<Msg> {
|
||||||
|
let is_loading = refresh_request == &RefreshingState::Loading;
|
||||||
|
let is_error = if let RefreshingState::Error(err) = refresh_request {
|
||||||
|
error!("Failed to refresh: {err:?}");
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
|
||||||
|
nav![
|
||||||
|
C!["navbar"],
|
||||||
|
attrs! {At::Role=>"navigation"},
|
||||||
|
div![
|
||||||
|
C!["navbar-start"],
|
||||||
|
a![
|
||||||
|
C!["navbar-item", "button", IF![is_error => "is-danger"]],
|
||||||
|
span![i![C![
|
||||||
|
"fa-solid",
|
||||||
|
"fa-arrow-rotate-right",
|
||||||
|
"refresh",
|
||||||
|
IF![is_loading => "loading"],
|
||||||
|
]]],
|
||||||
|
ev(Ev::Click, |_| Msg::RefreshStart),
|
||||||
|
],
|
||||||
|
a![
|
||||||
|
C!["navbar-item", "button"],
|
||||||
|
attrs! {
|
||||||
|
At::Href => urls::search("is:unread", 0)
|
||||||
|
},
|
||||||
|
"Unread",
|
||||||
|
],
|
||||||
|
a![
|
||||||
|
C!["navbar-item", "button"],
|
||||||
|
attrs! {
|
||||||
|
At::Href => urls::search("", 0)
|
||||||
|
},
|
||||||
|
"All",
|
||||||
|
],
|
||||||
|
input![
|
||||||
|
C!["navbar-item", "input"],
|
||||||
|
attrs! {
|
||||||
|
At::Placeholder => "Search";
|
||||||
|
At::AutoFocus => true.as_at_value();
|
||||||
|
At::Value => query,
|
||||||
|
},
|
||||||
|
input_ev(Ev::Input, |q| Msg::SearchRequest {
|
||||||
|
query: Url::encode_uri_component(q),
|
||||||
|
page: 0,
|
||||||
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
|
}),
|
||||||
|
// Resend search on enter.
|
||||||
|
keyboard_ev(Ev::KeyUp, move |e| if e.key_code() == 0x0d {
|
||||||
|
Msg::SearchRequest {
|
||||||
|
query: Url::encode_uri_component(query),
|
||||||
|
page: 0,
|
||||||
|
results_per_page: SEARCH_RESULTS_PER_PAGE,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Msg::Noop
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_footer(render_time_ms: u128) -> Node<Msg> {
|
||||||
|
footer![
|
||||||
|
C!["footer"],
|
||||||
|
div![
|
||||||
|
C!["content", "has-text-right", "is-size-7"],
|
||||||
|
format!("Render time {} ms", render_time_ms)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_desktop(model: &Model) -> Node<Msg> {
|
||||||
|
let content = match &model.context {
|
||||||
|
Context::None => div![h1!["Loading"]],
|
||||||
|
Context::Thread(messages) => view_thread(messages),
|
||||||
|
Context::Search(search_results) => view_search_results(&model.query, search_results),
|
||||||
|
};
|
||||||
|
div![
|
||||||
|
view_header(&model.query, &model.refreshing_state),
|
||||||
|
section![C!["section"], content],
|
||||||
|
view_header(&model.query, &model.refreshing_state),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_mobile(model: &Model) -> Node<Msg> {
|
||||||
|
let content = match &model.context {
|
||||||
|
Context::None => div![h1!["Loading"]],
|
||||||
|
Context::Thread(messages) => view_thread(messages),
|
||||||
|
Context::Search(search_results) => view_mobile_search_results(&model.query, search_results),
|
||||||
|
};
|
||||||
|
div![
|
||||||
|
view_header(&model.query, &model.refreshing_state),
|
||||||
|
section![C!["section"], div![C!["content"], content]],
|
||||||
|
view_header(&model.query, &model.refreshing_state),
|
||||||
|
]
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
// `view` describes what to display.
|
// `view` describes what to display.
|
||||||
fn view(model: &Model) -> Node<Msg> {
|
fn view(model: &Model) -> Node<Msg> {
|
||||||
let content = if let Some(show_results) = &model.show_results {
|
info!("refreshing {:?}", model.refreshing_state);
|
||||||
assert_eq!(show_results.0.len(), 1);
|
let is_mobile = seed::window()
|
||||||
let thread = &show_results.0[0];
|
.match_media("(max-width: 768px)")
|
||||||
assert_eq!(thread.0.len(), 1);
|
.expect("failed media query")
|
||||||
let thread_node = &thread.0[0];
|
.map(|mql| mql.matches())
|
||||||
div![
|
.unwrap_or(false);
|
||||||
h1![first_subject(&thread_node)],
|
|
||||||
a![
|
let start = Instant::now();
|
||||||
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
|
info!("view called");
|
||||||
"Original"
|
|
||||||
],
|
|
||||||
view_message(&thread_node),
|
|
||||||
/*
|
|
||||||
show_results
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(thread_idx, thread)| div![
|
|
||||||
h2![format!("thread {}", thread_idx)],
|
|
||||||
thread
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(thread_node_idx, thread_node)| div![
|
|
||||||
h3![format!("thread node {}", thread_node_idx)],
|
|
||||||
view_message(thread_node)
|
|
||||||
])
|
|
||||||
]),
|
|
||||||
*/
|
|
||||||
pre!["Add zippy for debug dump"] /* pre![format!("Thread: {:#?}", show_results).replace(" ", " ")] */
|
|
||||||
]
|
|
||||||
} else if let Some(search_results) = &model.search_results {
|
|
||||||
let rows = search_results.0.iter().map(|r| {
|
|
||||||
let tid = r.thread.clone();
|
|
||||||
tr![
|
|
||||||
td![
|
|
||||||
&r.authors,
|
|
||||||
IF!(r.total>1 => small![" ", r.total.to_string()]),
|
|
||||||
IF!(r.tags.contains(&"attachment".to_string()) => "📎"),
|
|
||||||
],
|
|
||||||
td![&r.subject],
|
|
||||||
td![&r.date_relative],
|
|
||||||
ev(Ev::Click, move |_| Msg::ShowRequest(tid)),
|
|
||||||
]
|
|
||||||
});
|
|
||||||
div![table![tr![th!["From"], th!["Subject"], th!["Date"]], rows]]
|
|
||||||
} else {
|
|
||||||
div![h1!["Loading"]]
|
|
||||||
};
|
|
||||||
let query = model.query.clone();
|
|
||||||
div![
|
div![
|
||||||
button![
|
if is_mobile {
|
||||||
"Unread",
|
view_mobile(model)
|
||||||
ev(Ev::Click, |_| Msg::SearchRequest("is:unread".to_string())),
|
} else {
|
||||||
],
|
view_desktop(model)
|
||||||
button!["All", ev(Ev::Click, |_| Msg::SearchRequest("".to_string())),],
|
},
|
||||||
input![
|
view_footer(start.elapsed().as_millis())
|
||||||
attrs! {
|
|
||||||
At::Placeholder => "Search";
|
|
||||||
At::AutoFocus => true.as_at_value();
|
|
||||||
At::Value => query,
|
|
||||||
},
|
|
||||||
input_ev(Ev::Input, Msg::SearchRequest),
|
|
||||||
// Resend search on enter.
|
|
||||||
keyboard_ev(Ev::KeyUp, |e| if e.key_code() == 0x0d {
|
|
||||||
Msg::SearchRequest(query)
|
|
||||||
} else {
|
|
||||||
Msg::Noop
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
content
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user