Compare commits

..

96 Commits

Author SHA1 Message Date
ce836cd1e8 notmuch: add tag manipulation 2024-02-11 19:59:20 -08:00
f7010fa278 cargo update 2024-02-11 19:54:35 -08:00
5451dd2056 server: add mutation to mark messages as read 2024-02-11 19:43:34 -08:00
81ed3a8ca2 Linkify URLs missing schema 2024-02-07 19:41:34 -08:00
0f1a60a348 Sanitize html when linkifying plain text. 2024-02-03 11:15:57 -08:00
c59a883351 Address lint. 2024-02-03 11:14:43 -08:00
568d83f029 linkify URLs in plaintext emails. 2024-02-03 11:10:51 -08:00
569781b592 Tweak CSS for viewing body of messages 2024-01-20 08:34:25 -08:00
1b00c9e944 Updated cargo lock 2024-01-20 08:14:59 -08:00
901785e47c Change footer class to prevent conflict with email bodies. 2024-01-20 08:14:37 -08:00
8c47f01758 Improve server side html sanitization. 2024-01-20 08:14:10 -08:00
304819275d Open links in a new tab. 2024-01-19 21:07:24 -08:00
b1ea44963d Lint and cleanup empty file. 2024-01-17 12:31:56 -08:00
181965968c state: auto reload every 30 seconds 2024-01-17 12:31:37 -08:00
5b3eadb7bd Run tests before rebuilding app 2024-01-06 08:53:06 -08:00
28d484117b Change makefile to use variable for app name.
Make this more copypastable.
2024-01-06 08:52:42 -08:00
a0b0689e01 Fix wrapping/sizing of message bodies with long unbreakable text. 2024-01-06 08:52:19 -08:00
33ec63f097 web: update seed_hooks to my copy so I can pin to seed=0.10.0 2023-12-10 19:42:07 -08:00
7b22f85429 web: show union of tags when viewing thread 2023-12-10 17:26:24 -08:00
fa7df55b0e server: send tags on each message in thread 2023-12-10 17:26:04 -08:00
d2cf270dda web: properly truncate long headers on message view 2023-12-10 16:35:51 -08:00
f1b5e78962 web: make debug output hidden by default 2023-12-10 16:11:15 -08:00
fae4e43682 web: show thread count when greater than 1 2023-12-10 15:50:28 -08:00
37eb3d1dfd web: wrap content tree debug so messages aren't super wide 2023-12-07 10:24:39 -08:00
e0890f1181 web: search for unread tags when clicking under Unread section 2023-12-05 20:55:41 -08:00
c31f9d581f web: upgrade to seed-0.10.0 2023-12-05 20:46:59 -08:00
f2347345b4 Version bumps made css_inline uncompilable for wasm 2023-12-05 14:12:15 -08:00
e34f2a1f39 notmuch: fix tests 2023-12-05 12:50:52 -08:00
7a6000be26 server: address lint 2023-12-05 11:26:23 -08:00
dd1a8c2eae procmail2notmuch: WIP update script 2023-12-05 11:23:04 -08:00
42590b3cbc cargo update 2023-12-05 11:04:31 -08:00
94f7ad109a Merge commit 'f6bdf30' 2023-12-05 09:56:55 -08:00
f6bdf302fe server & notmuch: more attachment WIP, stop leaking notmuch processes 2023-12-03 14:01:18 -08:00
b76c535738 web: use log::error, not seed::error 2023-12-03 09:11:31 -08:00
29949c703d web: archive live site before pushing new one 2023-12-03 09:11:15 -08:00
f5f9eb175d server: WIP attachment serving 2023-12-03 09:11:00 -08:00
488c3b86f8 web: truncate raw messages and prep for attachments 2023-12-03 09:03:36 -08:00
be8fd59703 web: rename view_thread to take advantage of new namespaces 2023-12-03 08:49:20 -08:00
071fe2e206 web: show message-ID when viewing thread 2023-12-02 16:35:37 -08:00
ac5660a6d0 web: have trunk proxy /original/ requests to backend 2023-12-02 16:35:18 -08:00
99a104517d notmuch: comment typo 2023-12-02 16:35:05 -08:00
c3692cadec server: add id and header to ShowThreadQuery API 2023-12-02 16:34:44 -08:00
b14000952c server: make unread message counting much faster, remove rayon dep 2023-12-02 15:41:22 -08:00
7a32d5c630 server: include headers in debug output 2023-12-02 15:12:40 -08:00
714b057fdb web: add tablet rendering, listen to window resize events. 2023-12-02 10:56:14 -08:00
4c2526c70b web: remove unnecessary view_mobile_ prefix 2023-12-02 10:13:08 -08:00
a8f4aa03bd web: rename legacy functions to take advantage of mod namespacing 2023-12-02 10:11:56 -08:00
28d5562491 web: move legacy (pre-graphql) rendering to separate mod 2023-12-02 10:07:47 -08:00
e6f20e538a web: move mobile specific code to separate mod 2023-12-02 10:02:12 -08:00
970bb55c73 web: move desktop specific code into separate mod 2023-12-02 09:56:57 -08:00
12f0491455 web: remove stale comments 2023-12-02 09:34:57 -08:00
ef8362d6f2 web: remove some unused code 2023-12-02 09:34:26 -08:00
0a7cdefda3 web: refactor code into separate modules 2023-12-02 09:29:50 -08:00
cfe1446668 web: for tag list to be open when no unread messages 2023-11-29 09:27:53 -08:00
7c38962d21 web: make tag list hidable 2023-11-28 20:03:17 -08:00
7102f26c9e web: conditionally show unread section 2023-11-28 07:32:22 -08:00
71a3315fe8 web: lint and clean up search input handling 2023-11-27 21:11:12 -08:00
7cac81cddb web: update implement_email macro to handle repetition 2023-11-27 20:33:47 -08:00
3a5ca74d71 web: change tag list styling and show unread at the top 2023-11-27 19:48:19 -08:00
71af8179ec web: hierarchical tags list on desktop 2023-11-27 19:16:28 -08:00
d66a7d3d53 web: use singular version of view_address for From 2023-11-27 17:20:11 -08:00
e0fbb0253e web: create implement_email! macro 2023-11-27 17:16:57 -08:00
48466808d3 web & server: plumb debugging info for content type hierarchy.
Also cleanup Email trait.
2023-11-27 13:47:02 -08:00
87dfe4ace7 server: cleanup lint. 2023-11-26 21:31:06 -08:00
d45f223d52 server: fix pagination with small counts and no first/last set 2023-11-26 21:27:57 -08:00
e8c58bdbd0 server: handle multipart/mixed with an html or text subpart 2023-11-26 21:09:56 -08:00
87d687cde5 server: sanitize html using ammonia 2023-11-26 21:00:44 -08:00
c8147ded60 web & server: add handling for google calendar and wellsfargo emails. 2023-11-26 20:51:53 -08:00
1261bdf8a9 web & server: improved debug printing of unhandled mime types 2023-11-26 18:50:32 -08:00
11366b6fac web & server: implement handling for text and html bodies. 2023-11-26 16:37:29 -08:00
1cdabc348b web: better date formatting 2023-11-26 16:01:22 -08:00
02e16b4547 web: more compact output on desktop and mobile 2023-11-26 15:46:03 -08:00
d5a001bf03 web: refresh tags on thread view in addition to search results. 2023-11-26 15:31:51 -08:00
0ae72b63d0 web: add basic graphql view thread, no body support. 2023-11-26 15:27:19 -08:00
447a4a3387 server: basic graphql thread show, no body support yet. 2023-11-26 13:13:04 -08:00
0737f5aac5 web: rewrite frontend to use graphql for search results 2023-11-25 09:06:24 -08:00
3e3024dd5c server: handle search with no first/last better 2023-11-25 09:05:53 -08:00
24414b04bb server: fix backward pagination 2023-11-25 08:39:56 -08:00
f7df834325 notmuch: default empty search to wildcard 2023-11-25 08:39:30 -08:00
bce2c741c4 web: add non-functional graphql. 2023-11-21 14:06:48 -08:00
1b44bc57bb web: Initial commit of graphql schema and helper to update it. 2023-11-21 13:36:11 -08:00
ff6675b08f server: add unread field to tag query.
Optionally fill out unread, as it's expensive.
2023-11-21 13:17:11 -08:00
64912be4eb Hide quoted emails 2023-11-21 12:37:58 -08:00
57ccef18cb Make clicking search results on mobile easier. 2023-11-21 12:27:58 -08:00
2a24a20529 Revert stub show_pretty that will be obsoleted by graphql. 2023-11-21 08:35:35 -08:00
e6692059b4 Fix search pagination and add count RPC. 2023-11-20 21:18:40 -08:00
a7b172099b And graphql search with pagination. 2023-11-20 20:56:16 -08:00
f52a76dba3 Added graphql endpoint and tested with tags implementation. 2023-11-20 18:38:10 -08:00
43e4334890 Set default page size on server to match client side page size. 2023-11-20 17:57:07 -08:00
1d00bdb757 Squelch logging and remove unused variable. 2023-11-20 17:54:50 -08:00
6901c9fde9 Formate today and yesterday better. 2023-11-20 17:53:49 -08:00
6251c54873 Show time of email >1 week 2023-11-20 17:47:06 -08:00
f6c1835b18 Custom formatting of the age string, widen subject column. 2023-11-20 17:41:58 -08:00
95976c2860 Mobile style tweaks. 2023-11-20 15:49:30 -08:00
01589d7136 Add favicon 2023-11-20 15:40:07 -08:00
a2664473c8 Improve density on mobile. 2023-11-14 21:33:09 -08:00
32 changed files with 6420 additions and 1538 deletions

2277
Cargo.lock generated

File diff suppressed because it is too large Load Diff

2
dev.sh
View File

@@ -3,5 +3,5 @@ tmux new-session -d -s letterbox-dev
tmux rename-window web
tmux send-keys "cd web; trunk serve -w ../shared -w ../notmuch -w ./" C-m
tmux new-window -n server
tmux send-keys "cd server; cargo watch -x run -w ../shared -w ../notmuch -w ./" C-m
tmux send-keys "cd server; cargo watch -c -x run -w ../shared -w ../notmuch -w ./" C-m
tmux attach -d -t letterbox-dev

View File

@@ -6,8 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.75"
clap = { version = "4.4.7", features = ["derive"] }
log = "0.4.14"
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["unbounded_depth"] }

View File

@@ -208,9 +208,9 @@
use std::{
ffi::OsStr,
io::{self, BufRead, BufReader, Lines},
io::{self},
path::{Path, PathBuf},
process::{Child, ChildStdout, Command, Stdio},
process::Command,
};
use log::info;
@@ -480,12 +480,33 @@ impl Notmuch {
self.run_notmuch(std::iter::empty::<&str>())
}
pub fn tags_for_query(&self, query: &str) -> Result<Vec<String>, NotmuchError> {
let res = self.run_notmuch(["search", "--format=json", "--output=tags", query])?;
Ok(serde_json::from_slice(&res)?)
}
pub fn tags(&self) -> Result<Vec<String>, NotmuchError> {
self.tags_for_query("*")
}
pub fn tag_add(&self, tag: &str, search_term: &str) -> Result<(), NotmuchError> {
self.run_notmuch(["tag", &format!("+{tag}"), search_term])?;
Ok(())
}
pub fn tag_remove(&self, tag: &str, search_term: &str) -> Result<(), NotmuchError> {
self.run_notmuch(["tag", &format!("-{tag}"), search_term])?;
Ok(())
}
pub fn search(
&self,
query: &str,
offset: usize,
limit: usize,
) -> Result<SearchSummary, NotmuchError> {
let query = if query.is_empty() { "*" } else { query };
let res = self.run_notmuch([
"search",
"--format=json",
@@ -507,11 +528,11 @@ impl Notmuch {
let slice = self.run_notmuch([
"show",
"--include-html=true",
"--entire-thread=true",
"--entire-thread=false",
"--format=json",
query,
])?;
// Notmuch returns JSON with invalid unicode. So we lossy convert it to a string here an
// Notmuch returns JSON with invalid unicode. So we lossy convert it to a string here and
// use that for parsing in rust.
let s = String::from_utf8_lossy(&slice);
let mut deserializer = serde_json::Deserializer::from_str(&s);
@@ -530,7 +551,7 @@ impl Notmuch {
&format!("--part={}", part),
query,
])?;
// Notmuch returns JSON with invalid unicode. So we lossy convert it to a string here an
// Notmuch returns JSON with invalid unicode. So we lossy convert it to a string here and
// use that for parsing in rust.
let s = String::from_utf8_lossy(&slice);
let mut deserializer = serde_json::Deserializer::from_str(&s);
@@ -549,12 +570,15 @@ impl Notmuch {
Ok(res)
}
pub fn message_ids(&self, query: &str) -> Result<Lines<BufReader<ChildStdout>>, NotmuchError> {
let mut child = self.run_notmuch_pipe(["search", "--output=messages", query])?;
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
pub fn message_ids(&self, query: &str) -> Result<Vec<String>, NotmuchError> {
let res = self.run_notmuch(["search", "--output=messages", "--format=json", query])?;
Ok(serde_json::from_slice(&res)?)
}
// TODO(wathiede): implement tags() based on "notmuch search --output=tags '*'"
pub fn files(&self, query: &str) -> Result<Vec<String>, NotmuchError> {
let res = self.run_notmuch(["search", "--output=files", "--format=json", query])?;
Ok(serde_json::from_slice(&res)?)
}
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
where
@@ -570,21 +594,6 @@ impl Notmuch {
let out = cmd.output()?;
Ok(out.stdout)
}
fn run_notmuch_pipe<I, S>(&self, args: I) -> Result<Child, NotmuchError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut cmd = Command::new("notmuch");
if let Some(config_path) = &self.config_path {
cmd.arg("--config").arg(config_path);
}
cmd.args(args);
info!("{:?}", &cmd);
let child = cmd.stdout(Stdio::piped()).spawn()?;
Ok(child)
}
}
#[cfg(test)]

View File

@@ -1,46 +0,0 @@
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(())
}

View File

@@ -1,11 +1,10 @@
use std::{
error::Error,
io::{stdout, Write},
time::{Duration, Instant},
time::Instant,
};
use itertools::Itertools;
use notmuch::{Notmuch, NotmuchError, SearchSummary, ThreadSet};
use notmuch::Notmuch;
use rayon::iter::{ParallelBridge, ParallelIterator};
#[test]
@@ -23,11 +22,11 @@ fn parse_one() -> Result<(), Box<dyn Error>> {
let total = nm.count("*")? as f32;
let start = Instant::now();
nm.message_ids("*")?
.iter()
.enumerate()
.par_bridge()
.for_each(|(i, msg)| {
let msg = msg.expect("failed to unwrap msg");
let ts = nm
let _ts = nm
.show(&msg)
.expect(&format!("failed to show msg: {}", msg));
//println!("{:?}", ts);
@@ -77,11 +76,9 @@ fn parse_bulk() -> Result<(), Box<dyn Error>> {
.into_iter()
.enumerate()
//.par_bridge()
.for_each(|(i, chunk)| {
let msgs: Result<Vec<_>, _> = chunk.collect();
let msgs = msgs.expect("failed to unwrap msg");
.for_each(|(i, msgs)| {
let query = msgs.join(" OR ");
let ts = nm
let _ts = nm
.show(&query)
.expect(&format!("failed to show msgs: {}", query));
//println!("{:?}", ts);

10
procmail2notmuch/update.sh Executable file
View File

@@ -0,0 +1,10 @@
set -e
cd ~/dotfiles
git diff
scp nasx:.procmailrc procmailrc
git diff
cd ~/src/xinu.tv/letterbox/procmail2notmuch
cargo run > /tmp/notmuch.tags
mv /tmp/notmuch.tags ~/dotfiles/notmuch.tags
cd ~/dotfiles
git diff

View File

@@ -2,13 +2,12 @@
name = "server"
version = "0.1.0"
edition = "2021"
default-bin = "server"
default-run = "server"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
notmuch = { path = "../notmuch" }
shared = { path = "../shared" }
serde_json = "1.0.87"
@@ -18,6 +17,17 @@ log = "0.4.17"
tokio = "1.26.0"
glog = "0.1.0"
urlencoding = "2.1.3"
async-graphql = { version = "6.0.11", features = ["log"] }
async-graphql-rocket = "6.0.11"
rocket_cors = "0.6.0"
memmap = "0.7.0"
mailparse = "0.14.0"
ammonia = "3.3.0"
lol_html = "1.2.0"
css-inline = "0.13.0"
anyhow = "1.0.79"
maplit = "1.0.2"
linkify = "0.10.0"
[dependencies.rocket_contrib]
version = "0.4.11"

View File

@@ -0,0 +1,16 @@
use std::fs;
use server::sanitize_html;
fn main() -> anyhow::Result<()> {
let mut args = std::env::args().skip(1);
let src = args.next().expect("source not specified");
let dst = args.next().expect("destination not specified");
println!("Sanitizing {src} into {dst}");
let bytes = fs::read(src)?;
let html = String::from_utf8_lossy(&bytes);
let html = sanitize_html(&html)?;
fs::write(dst, html)?;
Ok(())
}

View File

@@ -1,25 +1,23 @@
#[macro_use]
extern crate rocket;
use std::{error::Error, io::Cursor, str::FromStr};
use async_graphql::{http::GraphiQLSource, EmptySubscription, Schema};
use async_graphql_rocket::{GraphQLQuery, GraphQLRequest, GraphQLResponse};
use glog::Flags;
use notmuch::{Notmuch, NotmuchError, ThreadSet};
use rocket::{
http::{ContentType, Header},
request::Request,
response::{Debug, Responder},
response::{content, Debug, Responder},
serde::json::Json,
Response, State,
};
use rocket_cors::{AllowedHeaders, AllowedOrigins};
use server::{error::ServerError, nm::threadset_to_messages};
use shared::Message;
#[get("/")]
fn hello() -> &'static str {
"Hello, world!"
}
use server::{
error::ServerError,
graphql::{GraphqlSchema, Mutation, QueryRoot},
};
#[get("/refresh")]
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
@@ -41,7 +39,7 @@ async fn search(
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 results_per_page = results_per_page.unwrap_or(20);
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
info!(" search '{query}'");
let res = shared::SearchResult {
@@ -58,9 +56,9 @@ async fn search(
async fn show_pretty(
nm: &State<Notmuch>,
query: &str,
) -> Result<Json<Vec<Message>>, Debug<ServerError>> {
) -> Result<Json<ThreadSet>, 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)?)?;
let res = nm.show(&query).map_err(ServerError::from)?;
Ok(Json(res))
}
@@ -92,6 +90,24 @@ impl<'r, 'o: 'r> Responder<'r, 'o> for PartResponder {
}
}
#[get("/attachment/<id>/<idx>")]
async fn attachment(
_nm: &State<Notmuch>,
id: &str,
idx: usize,
) -> Result<PartResponder, Debug<NotmuchError>> {
let _idx = idx;
let _mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
let bytes = Vec::new();
let filename = None;
// TODO(wathiede): use walk_attachments from graphql to fill this out
Ok(PartResponder { bytes, filename })
}
#[get("/original/<id>/part/<part>")]
async fn original_part(
nm: &State<Notmuch>,
@@ -125,6 +141,24 @@ async fn original(
Ok((ContentType::Plain, res))
}
#[rocket::get("/")]
fn graphiql() -> content::RawHtml<String> {
content::RawHtml(GraphiQLSource::build().endpoint("/graphql").finish())
}
#[rocket::get("/graphql?<query..>")]
async fn graphql_query(schema: &State<GraphqlSchema>, query: GraphQLQuery) -> GraphQLResponse {
query.execute(schema.inner()).await
}
#[rocket::post("/graphql", data = "<request>", format = "application/json")]
async fn graphql_request(
schema: &State<GraphqlSchema>,
request: GraphQLRequest,
) -> GraphQLResponse {
request.execute(schema.inner()).await
}
#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
glog::new()
@@ -148,21 +182,30 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
.to_cors()?;
let schema = Schema::build(QueryRoot, Mutation, EmptySubscription)
.data(Notmuch::default())
.extension(async_graphql::extensions::Logger)
.finish();
let _ = rocket::build()
.mount(
"/",
routes![
original_part,
original,
hello,
refresh,
search_all,
search,
show_pretty,
show
show,
graphql_query,
graphql_request,
graphiql,
attachment
],
)
.attach(cors)
.manage(schema)
.manage(Notmuch::default())
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
.launch()

651
server/src/graphql.rs Normal file
View File

@@ -0,0 +1,651 @@
use std::{
collections::HashMap,
fs::File,
hash::{DefaultHasher, Hash, Hasher},
str::FromStr,
};
use async_graphql::{
connection::{self, Connection, Edge},
Context, EmptySubscription, Enum, Error, FieldResult, Object, Schema, SimpleObject, Union,
};
use log::{error, info, warn};
use mailparse::{parse_mail, MailHeader, MailHeaderMap, ParsedMail};
use memmap::MmapOptions;
use notmuch::Notmuch;
use rocket::time::Instant;
use crate::{linkify_html, sanitize_html};
/// # Number of seconds since the Epoch
pub type UnixTime = isize;
/// # Thread ID, sans "thread:"
pub type ThreadId = String;
#[derive(Debug, SimpleObject)]
pub struct ThreadSummary {
pub thread: ThreadId,
pub timestamp: UnixTime,
/// user-friendly timestamp
pub date_relative: String,
/// number of matched messages
pub matched: isize,
/// total messages in thread
pub total: isize,
/// comma-separated names with | between matched and unmatched
pub authors: String,
pub subject: String,
pub tags: Vec<String>,
}
#[derive(Debug, SimpleObject)]
pub struct Thread {
thread_id: String,
subject: String,
messages: Vec<Message>,
}
#[derive(Debug, SimpleObject)]
pub struct Message {
// Message-ID for message, prepend `id:<id>` to search in notmuch
pub id: String,
// First From header found in email
pub from: Option<Email>,
// All To headers found in email
pub to: Vec<Email>,
// All CC headers found in email
pub cc: Vec<Email>,
// First Subject header found in email
pub subject: Option<String>,
// Parsed Date header, if found and valid
pub timestamp: Option<i64>,
// Headers
pub headers: Vec<Header>,
// The body contents
pub body: Body,
// On disk location of message
pub path: String,
pub attachments: Vec<Attachment>,
pub tags: Vec<String>,
}
// Content-Type: image/jpeg; name="PXL_20231125_204826860.jpg"
// Content-Disposition: attachment; filename="PXL_20231125_204826860.jpg"
// Content-Transfer-Encoding: base64
// Content-ID: <f_lponoluo1>
// X-Attachment-Id: f_lponoluo1
#[derive(Debug, SimpleObject)]
pub struct Attachment {
filename: String,
content_type: Option<String>,
content_id: Option<String>,
}
#[derive(Debug, Enum, Copy, Clone, Eq, PartialEq)]
enum DispositionType {
Inline,
Attachment,
}
impl FromStr for DispositionType {
type Err = String;
// Required method
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"inline" => DispositionType::Inline,
"attachment" => DispositionType::Attachment,
c => return Err(format!("unknown disposition type: {c}")),
})
}
}
#[derive(Debug, SimpleObject)]
pub struct Header {
key: String,
value: String,
}
#[derive(Debug)]
pub struct UnhandledContentType {
text: String,
}
#[Object]
impl UnhandledContentType {
async fn contents(&self) -> &str {
&self.text
}
}
#[derive(Debug)]
pub struct PlainText {
text: String,
content_tree: String,
}
#[Object]
impl PlainText {
async fn contents(&self) -> &str {
&self.text
}
async fn content_tree(&self) -> &str {
&self.content_tree
}
}
#[derive(Debug)]
pub struct Html {
html: String,
content_tree: String,
}
#[Object]
impl Html {
async fn contents(&self) -> &str {
&self.html
}
async fn content_tree(&self) -> &str {
&self.content_tree
}
async fn headers(&self) -> Vec<Header> {
Vec::new()
}
}
#[derive(Debug, Union)]
pub enum Body {
UnhandledContentType(UnhandledContentType),
PlainText(PlainText),
Html(Html),
}
impl Body {
fn html(html: String) -> Body {
Body::Html(Html {
html,
content_tree: "".to_string(),
})
}
fn text(text: String) -> Body {
Body::PlainText(PlainText {
text,
content_tree: "".to_string(),
})
}
}
#[derive(Debug, SimpleObject)]
pub struct Email {
pub name: Option<String>,
pub addr: Option<String>,
}
#[derive(SimpleObject)]
struct Tag {
name: String,
fg_color: String,
bg_color: String,
unread: usize,
}
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn count<'ctx>(&self, ctx: &Context<'ctx>, query: String) -> Result<usize, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
Ok(nm.count(&query)?)
}
async fn search<'ctx>(
&self,
ctx: &Context<'ctx>,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
query: String,
) -> Result<Connection<usize, ThreadSummary>, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
connection::query(
after,
before,
first,
last,
|after, before, first, last| async move {
let total = nm.count(&query)?;
let (first, last) = if let (None, None) = (first, last) {
info!("neither first nor last set, defaulting first to 20");
(Some(20), None)
} else {
(first, last)
};
let mut start = after.map(|after| after + 1).unwrap_or(0);
let mut end = before.unwrap_or(total);
if let Some(first) = first {
end = (start + first).min(end);
}
if let Some(last) = last {
start = if last > end - start { end } else { end - last };
}
let count = end - start;
let slice: Vec<ThreadSummary> = nm
.search(&query, start, count)?
.0
.into_iter()
.map(|ts| ThreadSummary {
thread: ts.thread,
timestamp: ts.timestamp,
date_relative: ts.date_relative,
matched: ts.matched,
total: ts.total,
authors: ts.authors,
subject: ts.subject,
tags: ts.tags,
})
.collect();
let mut connection = Connection::new(start > 0, end < total);
connection.edges.extend(
slice
.into_iter()
.enumerate()
.map(|(idx, item)| Edge::new(start + idx, item)),
);
Ok::<_, Error>(connection)
},
)
.await
}
async fn tags<'ctx>(&self, ctx: &Context<'ctx>) -> FieldResult<Vec<Tag>> {
let nm = ctx.data_unchecked::<Notmuch>();
let now = Instant::now();
let needs_unread = ctx.look_ahead().field("unread").exists();
let unread_msg_cnt: HashMap<String, usize> = if needs_unread {
// 10000 is an arbitrary number, if there's more than 10k unread messages, we'll
// get an inaccurate count.
nm.search("is:unread", 0, 10000)?
.0
.iter()
.fold(HashMap::new(), |mut m, ts| {
ts.tags.iter().for_each(|t| {
m.entry(t.clone()).and_modify(|c| *c += 1).or_insert(1);
});
m
})
} else {
HashMap::new()
};
let tags = nm
.tags()?
.into_iter()
.map(|tag| {
let mut hasher = DefaultHasher::new();
tag.hash(&mut hasher);
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
let unread = if needs_unread {
*unread_msg_cnt.get(&tag).unwrap_or(&0)
} else {
0
};
Tag {
name: tag,
fg_color: "white".to_string(),
bg_color: hex,
unread,
}
})
.collect();
info!("Fetching tags took {}", now.elapsed());
Ok(tags)
}
async fn thread<'ctx>(&self, ctx: &Context<'ctx>, thread_id: String) -> Result<Thread, Error> {
// TODO(wathiede): normalize all email addresses through an address book with preferred
// display names (that default to the most commonly seen name).
let nm = ctx.data_unchecked::<Notmuch>();
let debug_content_tree = ctx
.look_ahead()
.field("messages")
.field("body")
.field("contentTree")
.exists();
let mut messages = Vec::new();
for (path, id) in std::iter::zip(nm.files(&thread_id)?, nm.message_ids(&thread_id)?) {
let tags = nm.tags_for_query(&format!("id:{id}"))?;
info!("{id}: {tags:?}\nfile: {path}");
let file = File::open(&path)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
let m = parse_mail(&mmap)?;
let from = email_addresses(&path, &m, "from")?;
let from = match from.len() {
0 => None,
1 => from.into_iter().next(),
_ => {
warn!(
"Got {} from addresses in message, truncating: {:?}",
from.len(),
from
);
from.into_iter().next()
}
};
let to = email_addresses(&path, &m, "to")?;
let cc = email_addresses(&path, &m, "cc")?;
let subject = m.headers.get_first_value("subject");
let timestamp = m
.headers
.get_first_value("date")
.and_then(|d| mailparse::dateparse(&d).ok());
let body = match extract_body(&m)? {
Body::PlainText(PlainText { text, content_tree }) => Body::Html(Html {
html: format!(
r#"<p class="view-part-text-plain">{}</p>"#,
sanitize_html(&linkify_html(&text))?
),
content_tree: if debug_content_tree {
render_content_type_tree(&m)
} else {
content_tree
},
}),
Body::Html(Html { html, content_tree }) => Body::Html(Html {
html: sanitize_html(&html)?,
content_tree: if debug_content_tree {
render_content_type_tree(&m)
} else {
content_tree
},
}),
b => b,
};
let headers = m
.headers
.iter()
.map(|h| Header {
key: h.get_key(),
value: h.get_value(),
})
.collect();
// TODO(wathiede): parse message and fill out attachments
let attachments = extract_attachments(&m)?;
messages.push(Message {
id,
from,
to,
cc,
subject,
tags,
timestamp,
headers,
body,
path,
attachments,
});
}
messages.reverse();
// Find the first subject that's set. After reversing the vec, this should be the oldest
// message.
let subject: String = messages
.iter()
.skip_while(|m| m.subject.is_none())
.next()
.and_then(|m| m.subject.clone())
.unwrap_or("(NO SUBJECT)".to_string());
Ok(Thread {
thread_id,
subject,
messages,
})
}
}
pub struct Mutation;
#[Object]
impl Mutation {
async fn set_read_status<'ctx>(
&self,
ctx: &Context<'ctx>,
query: String,
unread: bool,
) -> Result<bool, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
info!("set_read_status({unread})");
if unread {
nm.tag_add("unread", &format!("{query}"))?;
} else {
nm.tag_remove("unread", &format!("{query}"))?;
}
Ok(true)
}
}
fn extract_body(m: &ParsedMail) -> Result<Body, Error> {
let body = m.get_body()?;
let ret = match m.ctype.mimetype.as_str() {
"text/plain" => return Ok(Body::text(body)),
"text/html" => return Ok(Body::html(body)),
"multipart/mixed" => extract_mixed(m),
"multipart/alternative" => extract_alternative(m),
_ => extract_unhandled(m),
};
if let Err(err) = ret {
error!("Failed to extract body: {err:?}");
return Ok(extract_unhandled(m)?);
}
ret
}
fn extract_unhandled(m: &ParsedMail) -> Result<Body, Error> {
let msg = format!(
"Unhandled body content type:\n{}",
render_content_type_tree(m)
);
warn!("{}", msg);
Ok(Body::UnhandledContentType(UnhandledContentType {
text: msg,
}))
}
// multipart/alternative defines multiple representations of the same message, and clients should
// show the fanciest they can display. For this program, the priority is text/html, text/plain,
// then give up.
fn extract_alternative(m: &ParsedMail) -> Result<Body, Error> {
for sp in &m.subparts {
if sp.ctype.mimetype == "text/html" {
let body = sp.get_body()?;
return Ok(Body::html(body));
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "text/plain" {
let body = sp.get_body()?;
return Ok(Body::text(body));
}
}
Err("extract_alternative".into())
}
// multipart/mixed defines multiple types of context all of which should be presented to the user
// 'serially'.
fn extract_mixed(m: &ParsedMail) -> Result<Body, Error> {
for sp in &m.subparts {
if sp.ctype.mimetype == "multipart/alternative" {
return extract_alternative(sp);
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "multipart/related" {
return extract_related(sp);
}
}
for sp in &m.subparts {
let body = sp.get_body()?;
match sp.ctype.mimetype.as_str() {
"text/plain" => return Ok(Body::text(body)),
"text/html" => return Ok(Body::html(body)),
_ => (),
}
}
Err("extract_mixed".into())
}
fn extract_related(m: &ParsedMail) -> Result<Body, Error> {
// TODO(wathiede): collect related things and change return type to new Body arm.
for sp in &m.subparts {
if sp.ctype.mimetype == "text/html" {
let body = sp.get_body()?;
return Ok(Body::html(body));
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == "text/plain" {
let body = sp.get_body()?;
return Ok(Body::text(body));
}
}
Err("extract_related".into())
}
// TODO(wathiede): make this walk_attachments that takes a closure.
// Then implement one closure for building `Attachment` and imlement another that can be used to
// get the bytes for serving attachments of HTTP
fn extract_attachments(m: &ParsedMail) -> Result<Vec<Attachment>, Error> {
let mut attachements = Vec::new();
for sp in &m.subparts {
for h in &sp.headers {
if h.get_key() == "Content-Disposition" {
let v = h.get_value();
if let Some(idx) = v.find(";") {
let dt = &v[..idx];
match DispositionType::from_str(dt) {
Ok(DispositionType::Attachment) => {
attachements.push(Attachment {
filename: get_attachment_filename(&v).to_string(),
content_type: get_content_type(&sp.headers),
content_id: get_content_id(&sp.headers),
});
}
Ok(DispositionType::Inline) => continue,
Err(e) => {
warn!("failed to parse Content-Disposition type '{}'", e);
continue;
}
};
} else {
warn!("header has Content-Disposition missing ';'");
continue;
}
}
}
}
Ok(attachements)
}
fn get_attachment_filename(header_value: &str) -> &str {
// Strip last "
let v = &header_value[..header_value.len() - 1];
if let Some(idx) = v.rfind('"') {
&v[idx + 1..]
} else {
""
}
}
fn get_content_type<'a>(headers: &[MailHeader<'a>]) -> Option<String> {
for h in headers {
if h.get_key() == "Content-Type" {
let v = h.get_value();
if let Some(idx) = v.find(';') {
return Some(v[..idx].to_string());
} else {
return Some(v);
}
}
}
None
}
fn get_content_id<'a>(headers: &[MailHeader<'a>]) -> Option<String> {
for h in headers {
if h.get_key() == "Content-ID" {
return Some(h.get_value());
}
}
None
}
fn render_content_type_tree(m: &ParsedMail) -> String {
const WIDTH: usize = 4;
fn render_rec(m: &ParsedMail, depth: usize) -> String {
let mut parts = Vec::new();
let msg = format!("{} {}", "-".repeat(depth * WIDTH), m.ctype.mimetype);
parts.push(msg);
let indent = " ".repeat(depth * WIDTH);
if !m.ctype.charset.is_empty() {
parts.push(format!("{indent} Character Set: {}", m.ctype.charset));
}
for (k, v) in m.ctype.params.iter() {
parts.push(format!("{indent} {k}: {v}"));
}
if !m.headers.is_empty() {
parts.push(format!("{indent} == headers =="));
for h in &m.headers {
parts.push(format!("{indent} {}: {}", h.get_key(), h.get_value()));
}
}
for sp in &m.subparts {
parts.push(render_rec(sp, depth + 1))
}
parts.join("\n")
}
render_rec(m, 1)
}
pub type GraphqlSchema = Schema<QueryRoot, Mutation, EmptySubscription>;
fn email_addresses(path: &str, m: &ParsedMail, header_name: &str) -> Result<Vec<Email>, Error> {
let mut addrs = Vec::new();
for header_value in m.headers.get_all_values(header_name) {
match mailparse::addrparse(&header_value) {
Ok(mal) => {
for ma in mal.into_inner() {
match ma {
mailparse::MailAddr::Group(gi) => {
if !gi.group_name.contains("ndisclosed") {
println!("[{path}][{header_name}] Group: {gi}");
}
}
mailparse::MailAddr::Single(s) => addrs.push(Email {
name: s.display_name,
addr: Some(s.addr),
}), //println!("Single: {s}"),
}
}
}
Err(_) => {
let v = header_value;
if v.matches('@').count() == 1 {
if v.matches('<').count() == 1 && v.ends_with('>') {
let idx = v.find('<').unwrap();
let addr = &v[idx + 1..v.len() - 1].trim();
let name = &v[..idx].trim();
addrs.push(Email {
name: Some(name.to_string()),
addr: Some(addr.to_string()),
});
}
} else {
addrs.push(Email {
name: Some(v),
addr: None,
});
}
}
}
}
Ok(addrs)
}

View File

@@ -1,2 +1,240 @@
pub mod error;
pub mod graphql;
pub mod nm;
use css_inline::{CSSInliner, InlineError, InlineOptions};
use linkify::{LinkFinder, LinkKind};
use log::error;
use lol_html::{element, errors::RewritingError, rewrite_str, RewriteStrSettings};
use maplit::{hashmap, hashset};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum SanitizeError {
#[error("lol-html rewrite error")]
RewritingError(#[from] RewritingError),
#[error("css inline error")]
InlineError(#[from] InlineError),
}
pub fn linkify_html(text: &str) -> String {
let mut finder = LinkFinder::new();
let finder = finder.url_must_have_scheme(false).kinds(&[LinkKind::Url]);
let mut parts = Vec::new();
for span in finder.spans(text) {
// TODO(wathiede): use Cow<str>?
match span.kind() {
// Text as-is
None => parts.push(span.as_str().to_string()),
// Wrap in anchor tag
Some(LinkKind::Url) => {
let text = span.as_str();
let schema = if text.starts_with("http") {
""
} else {
"http://"
};
let a = format!(r#"<a href="{schema}{0}">{0}</a>"#, text);
parts.push(a);
}
_ => todo!("unhandled kind: {:?}", span.kind().unwrap()),
}
}
parts.join("")
}
pub fn sanitize_html(html: &str) -> Result<String, SanitizeError> {
let element_content_handlers = vec![
// Open links in new tab
element!("a[href]", |el| {
el.set_attribute("target", "_blank").unwrap();
Ok(())
}),
// Only secure image URLs
element!("img[src]", |el| {
let src = el
.get_attribute("src")
.expect("src was required")
.replace("http:", "https:");
el.set_attribute("src", &src)?;
Ok(())
}),
];
let inline_opts = InlineOptions {
inline_style_tags: true,
keep_style_tags: false,
keep_link_tags: false,
base_url: None,
load_remote_stylesheets: false,
extra_css: None,
preallocate_node_capacity: 32,
..InlineOptions::default()
};
let inlined_html = match CSSInliner::new(inline_opts).inline(&html) {
Ok(inlined_html) => inlined_html,
Err(err) => {
error!("failed to inline CSS: {err}");
html.to_string()
}
};
// Default's don't allow style, but we want to preserve that.
let attributes =
hashset!["align", "bgcolor", "color", "height", "lang", "title", "width", "style",];
let tags = hashset![
"a",
"abbr",
"acronym",
"area",
"article",
"aside",
"b",
"bdi",
"bdo",
"blockquote",
"br",
"caption",
"center",
"cite",
"code",
"col",
"colgroup",
"data",
"dd",
"del",
"details",
"dfn",
"div",
"dl",
"dt",
"em",
"figcaption",
"figure",
"footer",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"i",
"img",
"ins",
"kbd",
"kbd",
"li",
"map",
"mark",
"nav",
"ol",
"p",
"pre",
"q",
"rp",
"rt",
"rtc",
"ruby",
"s",
"samp",
"small",
"span",
"strike",
"strong",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"th",
"thead",
"time",
"title", // wathiede
"tr",
"tt",
"u",
"ul",
"var",
"wbr",
];
let tag_attributes = hashmap![
"a" => hashset![
"href", "hreflang"
],
"bdo" => hashset![
"dir"
],
"blockquote" => hashset![
"cite"
],
"col" => hashset![
"align", "char", "charoff", "span"
],
"colgroup" => hashset![
"align", "char", "charoff", "span"
],
"del" => hashset![
"cite", "datetime"
],
"hr" => hashset![
"align", "size", "width"
],
"img" => hashset![
"align", "alt", "height", "src", "width"
],
"ins" => hashset![
"cite", "datetime"
],
"ol" => hashset![
"start"
],
"q" => hashset![
"cite"
],
"table" => hashset![
"align", "border", "cellpadding", "cellspacing", "char", "charoff", "summary",
],
"tbody" => hashset![
"align", "char", "charoff"
],
"td" => hashset![
"align", "char", "charoff", "colspan", "headers", "rowspan"
],
"tfoot" => hashset![
"align", "char", "charoff"
],
"th" => hashset![
"align", "char", "charoff", "colspan", "headers", "rowspan", "scope"
],
"thead" => hashset![
"align", "char", "charoff"
],
"tr" => hashset![
"align", "char", "charoff"
],
];
let clean_html = ammonia::Builder::default()
.tags(tags)
.tag_attributes(tag_attributes)
.generic_attributes(attributes)
.clean(&inlined_html)
.to_string();
//let clean_html = inlined_html;
Ok(rewrite_str(
&clean_html,
RewriteStrSettings {
element_content_handlers,
..RewriteStrSettings::default()
},
)?)
}

View File

@@ -7,9 +7,7 @@ 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!()
}
for _tn in t.0 {}
}
Ok(Vec::new())
}

View File

@@ -9,5 +9,6 @@ pub struct SearchResult {
pub results_per_page: usize,
pub total: usize,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {}

View File

@@ -18,7 +18,8 @@ wasm-bindgen-test = "0.3.33"
[dependencies]
console_error_panic_hook = "0.1.7"
log = "0.4.17"
seed = "0.9.2"
seed = { version = "0.10.0", features = ["routing"] }
#seed = "0.9.2"
console_log = {git = "http://git-private.h.xinu.tv/wathiede/console_log.git"}
serde = { version = "1.0.147", features = ["derive"] }
notmuch = {path = "../notmuch"}
@@ -26,7 +27,12 @@ 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"
chrono = "0.4.31"
graphql_client = "0.13.0"
thiserror = "1.0.50"
seed_hooks = { git = "https://github.com/wathiede/styles_hooks", package = "seed_hooks", branch = "main" }
gloo-net = { version = "0.4.0", features = ["json", "serde_json"] }
[package.metadata.wasm-pack.profile.release]
wasm-opt = ['-Os']

View File

@@ -1,6 +1,8 @@
.PHONY: all
APP=letterbox
# Build in release mode and push to minio for serving.
all:
trunk build --release
mc mirror --overwrite --remove dist/ m/letterbox/
mc mirror m/$(APP)/ /tmp/$(APP)-$(shell date +%s)
mc mirror --overwrite --remove dist/ m/$(APP)/

View File

@@ -9,3 +9,14 @@ port = 6758
[[proxy]]
backend = "http://localhost:9345/"
rewrite= "/api/"
[[proxy]]
backend="http://localhost:9345/original"
[[proxy]]
backend="http://localhost:9345/graphiql"
[[proxy]]
backend="http://localhost:9345/graphql"
[[hooks]]
stage = "pre_build"
command = "cargo"
command_arguments = [ "test" ]

View File

@@ -0,0 +1,25 @@
query FrontPageQuery($query: String!, $after: String $before: String, $first: Int, $last: Int) {
count(query: $query)
search(query: $query, after: $after, before: $before, first: $first, last: $last) {
pageInfo {
hasPreviousPage
hasNextPage
startCursor
endCursor
}
nodes {
thread
total
timestamp
subject
authors
tags
}
}
tags {
name
bgColor
fgColor
unread
}
}

2092
web/graphql/schema.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
query ShowThreadQuery($threadId: String!) {
thread(threadId: $threadId) {
subject
messages {
id
subject
tags
from {
name
addr
}
to {
name
addr
}
cc {
name
addr
}
timestamp
body {
__typename
... on UnhandledContentType {
contents
}
... on PlainText {
contents
contentTree
}
... on Html {
contents
contentTree
}
}
path
attachments {
filename
contentType
contentId
}
}
}
tags {
name
bgColor
fgColor
unread
}
}

4
web/graphql/update_schema.sh Executable file
View File

@@ -0,0 +1,4 @@
DEV_HOST=localhost
DEV_PORT=9345
graphql-client introspect-schema http://${DEV_HOST:?}:${DEV_PORT:?}/graphql --output schema.json
git diff schema.json

View File

@@ -6,22 +6,37 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet", href="https://jenil.github.io/bulmaswatch/cyborg/bulmaswatch.min.css">
<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" />
<link rel="icon" href="https://static.xinu.tv/favicon/letterbox.svg" />
<style>
.message {
padding: 0.5em;*/
display: inline-block;
padding: 0.5em;
width: 100%;
}
.message .headers {
width: 100%;
}
.message .headers .header {
overflow: clip;
text-overflow: ellipsis;
white-space: nowrap;
}
.body {
background: white;
color: black;
padding: 0.5em;
margin-left: -0.5em;
margin-right: -0.5em;
margin-top: 0.5em;
width:0;
min-width:100%;
}
.error {
background-color: red;
}
.view-part-text-plain {
padding: 0.5em;
overflow-wrap: break-word;
white-space: pre-line;
}
iframe {
@@ -37,7 +52,7 @@ iframe {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 15em;
width: 10em;
}
.index .subject {
overflow: hidden;
@@ -45,10 +60,11 @@ iframe {
white-space: nowrap;
}
.index .date {
width: 8em;
width: 10em;
white-space: nowrap;
text-align: right;
}
.footer {
.lb-footer {
background-color: #eee;
color: #222;
position: fixed;
@@ -91,6 +107,73 @@ input, .input {
input::placeholder, .input::placeholder{
color: #555;
}
.mobile .search-results,
.mobile .thread {
padding: 1em;
}
.search-results .row {
border-bottom: 1px #444 solid;
padding-bottom: .5em;
padding-top: .5em;
}
.search-results .row .subject {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .row .from {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .row .tag {
height: 1.5em;
padding-left: .5em;
padding-right: .5em;
}
.float-right {
float: right;
}
/* Hide quoted emails */
/*
div[name="quote"],
blockquote[type="cite"],
.gmail_quote {
background-color: red;
display: none;
}
*/
.desktop .main-content {
display: grid;
grid-template-columns: 12rem 1fr;
}
.tags-menu {
padding: 1rem;
}
.tags-menu .menu-list a {
padding: 0.25em 0.5em;
}
.tags-menu .tag-indent {
padding-left: .5em;
}
.tags-menu .tag-tag {
margin-left: -1em;
padding-right: .25em;
}
.navbar {
border: none;
}
.desktop nav.pagination,
.tablet nav.pagination {
margin-left: .5em;
margin-bottom: 0 !important;
}
.content-tree {
white-space: pre-line;
}
</style>
</head>

55
web/src/api.rs Normal file
View File

@@ -0,0 +1,55 @@
use gloo_net::{http::Request, Error};
use log::info;
use notmuch::ThreadSet;
use seed::Url;
const BASE_URL: &str = "/api";
pub fn refresh() -> String {
format!("{BASE_URL}/refresh")
}
pub fn search(query: &str, page: usize, results_per_page: usize) -> String {
let query = Url::encode_uri_component(query);
format!("{BASE_URL}/search/{query}?page={page}&results_per_page={results_per_page}")
}
pub fn show_pretty(tid: &str) -> String {
format!("{BASE_URL}/show/{tid}/pretty")
}
pub fn original(message_id: &str) -> String {
format!("{BASE_URL}/original/{message_id}")
}
pub 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])
}
}
pub async fn search_request(
query: &str,
page: usize,
results_per_page: usize,
) -> Result<shared::SearchResult, Error> {
Request::get(&search(query, page, results_per_page))
.send()
.await?
.json()
.await
}
pub async fn refresh_request() -> Result<(), Error> {
let t = Request::get(&refresh()).send().await?.text().await?;
info!("refresh {t}");
Ok(())
}
pub async fn show_pretty_request(tid: &str) -> Result<ThreadSet, Error> {
Request::get(&show_pretty(tid)).send().await?.json().await
}

2
web/src/consts.rs Normal file
View File

@@ -0,0 +1,2 @@
pub const SEARCH_RESULTS_PER_PAGE: usize = 20;
pub const USE_GRAPHQL: bool = true;

37
web/src/graphql.rs Normal file
View File

@@ -0,0 +1,37 @@
use gloo_net::{http::Request, Error};
use graphql_client::GraphQLQuery;
use serde::{de::DeserializeOwned, Serialize};
// The paths are relative to the directory where your `Cargo.toml` is located.
// Both json and the GraphQL schema language are supported as sources for the schema
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/front_page.graphql",
response_derives = "Debug"
)]
pub struct FrontPageQuery;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/show_thread.graphql",
response_derives = "Debug"
)]
pub struct ShowThreadQuery;
pub async fn send_graphql<Body, Resp>(body: Body) -> Result<graphql_client::Response<Resp>, Error>
where
Body: Serialize,
Resp: DeserializeOwned + 'static,
{
use web_sys::RequestMode;
Request::post("/graphql/")
.mode(RequestMode::Cors)
.json(&body)?
.send()
.await?
.json()
.await
}

View File

@@ -2,787 +2,15 @@
// - 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.)
#![allow(clippy::wildcard_imports)]
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use itertools::Itertools;
use log::{debug, error, info, Level};
use notmuch::{Content, Part, Thread, ThreadNode, ThreadSet};
use seed::{prelude::*, *};
use serde::de::Deserialize;
use wasm_timer::Instant;
use log::Level;
use seed::{prelude::wasm_bindgen, App};
const SEARCH_RESULTS_PER_PAGE: usize = 20;
// ------ ------
// Init
// ------ ------
// `init` describes what should happen when your app started.
fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
if url.hash().is_none() {
orders.request_url(urls::search("is:unread", 0));
} else {
orders.notify(subs::UrlRequested::new(url));
};
orders.subscribe(on_url_changed);
Model {
context: Context::None,
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
// ------ ------
enum Context {
None,
Search(shared::SearchResult),
Thread(Vec<shared::Message>),
}
// `Model` describes our app state.
struct Model {
query: String,
context: Context,
refreshing_state: RefreshingState,
}
#[derive(Debug, PartialEq)]
enum RefreshingState {
None,
Loading,
Error(String),
}
// ------ ------
// Update
// ------ ------
// (Remove the line below once any of your `Msg` variants doesn't implement `Copy`.)
// `Msg` describes the different events you can modify state with.
enum Msg {
Noop,
// Tell the client to refresh its state
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),
ShowResult(fetch::Result<ThreadSet>),
ShowPrettyRequest(String),
ShowPrettyResult(fetch::Result<Vec<shared::Message>>),
NextPage,
PreviousPage,
}
// `update` describes how to handle each `Msg`.
fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
match msg {
Msg::Noop => {}
Msg::RefreshStart => {
model.refreshing_state = RefreshingState::Loading;
orders.perform_cmd(async move { Msg::RefreshDone(refresh_request().await.err()) });
}
Msg::RefreshDone(err) => {
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)) => {
debug!("fetch ok {:#?}", response_data);
model.context = Context::Search(response_data);
}
Msg::SearchResult(Err(fetch_error)) => {
error!("fetch failed {:?}", fetch_error);
}
Msg::ShowRequest(tid) => {
orders
.skip()
.perform_cmd(async move { Msg::ShowResult(show_request(&tid).await) });
}
// TODO(wathiede): remove
Msg::ShowResult(Ok(response_data)) => {
debug!("fetch ok {:#?}", response_data);
//model.context = Context::Thread(response_data);
}
Msg::ShowResult(Err(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,
page: usize,
results_per_page: usize,
) -> fetch::Result<shared::SearchResult> {
Request::new(api::search(query, page, results_per_page))
.method(Method::Get)
.fetch()
.await?
.check_status()?
.json()
.await
}
mod api {
use seed::Url;
const BASE_URL: &str = "/api";
pub fn refresh() -> String {
format!("{BASE_URL}/refresh")
}
pub fn search(query: &str, page: usize, results_per_page: usize) -> String {
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 {
format!("{BASE_URL}/original/{message_id}")
}
}
async fn refresh_request() -> fetch::Result<()> {
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)
.fetch()
.await?
.check_status()?
.json()
.await
}
// ------ ------
// View
// ------ ------
// <subject>
// <tags>
//
// <from1> <date>
// <to1>
// <content1>
// <zippy>
// <children1>
// </zippy>
//
// <from2> <date>
// <to2>
// <body2>
fn view_message(thread: &ThreadNode) -> Node<Msg> {
let message = thread.0.as_ref().expect("ThreadNode missing Message");
let children = &thread.1;
div![
C!["message"],
/* TODO(wathiede): collect all the tags and show them here. */
/* TODO(wathiede): collect all the attachments from all the subparts */
div![C!["header"], "From: ", &message.headers.from],
div![C!["header"], "Date: ", &message.headers.date],
div![C!["header"], "To: ", &message.headers.to],
div![
C!["body"],
match &message.body {
Some(body) => view_body(body.as_slice()),
None => div!["<no body>"],
},
],
children.iter().map(view_message)
]
}
fn view_body(body: &[Part]) -> Node<Msg> {
div![body.iter().map(view_part)]
}
fn view_text_plain(content: &Option<Content>) -> Node<Msg> {
match &content {
Some(Content::String(content)) => p![C!["view-part-text-plain"], content],
_ => div![
C!["error"],
format!("Unhandled content enum for text/plain"),
],
}
}
fn view_part(part: &Part) -> Node<Msg> {
match part.content_type.as_str() {
"text/plain" => view_text_plain(&part.content),
"text/html" => {
if let Some(Content::String(html)) = &part.content {
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 {
div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
]
}
}
// https://en.wikipedia.org/wiki/MIME#alternative
// RFC1341 states: In general, user agents that compose multipart/alternative entities
// should place the body parts in increasing order of preference, that is, with the
// preferred format last.
"multipart/alternative" => {
if let Some(Content::Multipart(parts)) = &part.content {
for part in parts.iter().rev() {
if part.content_type == "text/html" {
if let Some(Content::String(html)) = &part.content {
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" {
return view_text_plain(&part.content);
}
}
div!["No known multipart/alternative parts"]
} else {
div![
C!["error"],
format!("multipart/alternative with non-multipart content"),
]
}
}
"multipart/mixed" => match &part.content {
Some(Content::Multipart(parts)) => div![parts.iter().map(view_part)],
_ => div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
],
},
_ => div![
C!["error"],
format!("Unhandled content type: {}", part.content_type)
],
}
}
fn first_subject(thread: &ThreadNode) -> Option<String> {
if let Some(msg) = &thread.0 {
return Some(msg.headers.subject.clone());
} else {
for tn in &thread.1 {
if let Some(s) = first_subject(&tn) {
return Some(s);
}
}
}
None
}
fn set_title(title: &str) {
seed::document().set_title(&format!("lb: {}", title));
}
fn tags_chiclet(tags: &[String], is_mobile: bool) -> impl Iterator<Item = Node<Msg>> + '_ {
tags.iter().map(move |tag| {
let mut hasher = DefaultHasher::new();
tag.hash(&mut hasher);
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
let style = style! {St::BackgroundColor=>hex};
let classes = C!["tag", IF!(is_mobile => "is-small")];
let tag = tag.clone();
a![
attrs! {
At::Href => urls::search(&format!("tag:{tag}"), 0)
},
match tag.as_str() {
"attachment" => span![classes, style, "📎"],
"replied" => span![classes, style, i![C!["fa-solid", "fa-reply"]]],
_ => span![classes, style, &tag],
},
ev(Ev::Click, move |_| Msg::SearchRequest {
query: format!("tag:{tag}"),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
})
]
})
}
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.
fn view(model: &Model) -> Node<Msg> {
info!("refreshing {:?}", model.refreshing_state);
let is_mobile = seed::window()
.match_media("(max-width: 768px)")
.expect("failed media query")
.map(|mql| mql.matches())
.unwrap_or(false);
let start = Instant::now();
info!("view called");
div![
if is_mobile {
view_mobile(model)
} else {
view_desktop(model)
},
view_footer(start.elapsed().as_millis())
]
}
// ------ ------
// Start
// ------ ------
mod api;
mod consts;
mod graphql;
mod state;
mod view;
// (This function is invoked by `init` function in `index.html`.)
#[wasm_bindgen(start)]
@@ -795,5 +23,5 @@ pub fn start() {
let lvl = Level::Info;
console_log::init_with_level(lvl).expect("failed to initialize console logging");
// Mount the `app` to the element with the `id` "app".
App::start("app", init, update, view);
App::start("app", state::init, state::update, view::view);
}

399
web/src/state.rs Normal file
View File

@@ -0,0 +1,399 @@
use graphql_client::GraphQLQuery;
use log::{debug, error, info};
use notmuch::ThreadSet;
use seed::{app::subs, prelude::*, *};
use thiserror::Error;
use crate::{
api,
api::urls,
consts::{SEARCH_RESULTS_PER_PAGE, USE_GRAPHQL},
graphql,
graphql::{front_page_query::*, send_graphql, show_thread_query::*},
};
// `init` describes what should happen when your app started.
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
if url.hash().is_none() {
orders.request_url(urls::search("is:unread", 0));
} else {
orders.notify(subs::UrlRequested::new(url));
};
orders.stream(streams::window_event(Ev::Resize, |_| Msg::OnResize));
// TODO(wathiede): only do this while viewing the index? Or maybe add a new message that force
// 'notmuch new' on the server periodically?
orders.stream(streams::interval(30_000, || Msg::RefreshStart));
orders.subscribe(on_url_changed);
Model {
context: Context::None,
query: "".to_string(),
refreshing_state: RefreshingState::None,
ui_error: UIError::NoError,
tags: 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] => {
if USE_GRAPHQL {
Msg::ShowThreadRequest {
thread_id: tid.to_string(),
}
} else {
Msg::ShowPrettyRequest(tid.to_string())
}
}
["s", query] => {
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
if USE_GRAPHQL {
Msg::FrontPageRequest {
query,
after: None,
before: None,
first: None,
last: None,
}
} else {
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);
if USE_GRAPHQL {
Msg::FrontPageRequest {
query,
after: Some(page.to_string()),
before: None,
first: None,
last: None,
}
} else {
Msg::SearchRequest {
query,
page,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}
}
p => {
if !p.is_empty() {
info!("Unhandled path '{p:?}'");
}
if USE_GRAPHQL {
Msg::FrontPageRequest {
query: "".to_string(),
after: None,
before: None,
first: None,
last: None,
}
} else {
Msg::SearchRequest {
query: "".to_string(),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}
}
}
}
// `update` describes how to handle each `Msg`.
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
match msg {
Msg::Noop => {}
Msg::RefreshStart => {
model.refreshing_state = RefreshingState::Loading;
orders.perform_cmd(async move { Msg::RefreshDone(api::refresh_request().await.err()) });
}
Msg::RefreshDone(err) => {
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::OnResize => (),
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(api::search_request(&query, page, results_per_page).await)
});
}
Msg::SearchResult(Ok(response_data)) => {
debug!("fetch ok {:#?}", response_data);
model.context = Context::Search(response_data);
}
Msg::SearchResult(Err(fetch_error)) => {
error!("fetch failed {:?}", fetch_error);
}
Msg::ShowPrettyRequest(tid) => {
orders.skip().perform_cmd(async move {
Msg::ShowPrettyResult(api::show_pretty_request(&tid).await)
});
}
Msg::ShowPrettyResult(Ok(response_data)) => {
debug!("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::SearchResult { query, pager, .. } => {
let query = query.to_string();
let after = pager.end_cursor.clone();
orders.perform_cmd(async move {
Msg::FrontPageRequest {
query,
after,
before: None,
first: Some(SEARCH_RESULTS_PER_PAGE as i64),
last: None,
}
});
}
Context::Thread(_) => (), // do nothing (yet?)
Context::ThreadResult(_) => (), // 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::SearchResult { query, pager, .. } => {
let query = query.to_string();
let before = pager.start_cursor.clone();
orders.perform_cmd(async move {
Msg::FrontPageRequest {
query,
after: None,
before,
first: None,
last: Some(SEARCH_RESULTS_PER_PAGE as i64),
}
});
}
Context::Thread(_) => (), // do nothing (yet?)
Context::ThreadResult(_) => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
};
}
Msg::UpdateQuery(query) => model.query = query,
Msg::SearchQuery(query) => {
orders.request_url(urls::search(&query, 0));
}
Msg::FrontPageRequest {
query,
after,
before,
first,
last,
} => {
info!("making FrontPageRequest: {query} after:{after:?} before:{before:?} first:{first:?} last:{last:?}");
model.query = query.clone();
orders.skip().perform_cmd(async move {
Msg::FrontPageResult(
send_graphql(graphql::FrontPageQuery::build_query(
graphql::front_page_query::Variables {
query,
after,
before,
first,
last,
},
))
.await,
)
});
}
Msg::FrontPageResult(Err(e)) => error!("error FrontPageResult: {e:?}"),
Msg::FrontPageResult(Ok(graphql_client::Response {
data: None,
errors: None,
..
})) => {
error!("FrontPageResult no data or errors, should not happen");
}
Msg::FrontPageResult(Ok(graphql_client::Response {
data: None,
errors: Some(e),
..
})) => {
error!("FrontPageResult error: {e:?}");
}
Msg::FrontPageResult(Ok(graphql_client::Response {
data: Some(data), ..
})) => {
model.tags = Some(
data.tags
.into_iter()
.map(|t| Tag {
name: t.name,
bg_color: t.bg_color,
fg_color: t.fg_color,
unread: t.unread,
})
.collect(),
);
model.context = Context::SearchResult {
query: model.query.clone(),
results: data.search.nodes,
count: data.count as usize,
pager: data.search.page_info,
};
}
Msg::ShowThreadRequest { thread_id } => {
orders.skip().perform_cmd(async move {
Msg::ShowThreadResult(
send_graphql(graphql::ShowThreadQuery::build_query(
graphql::show_thread_query::Variables { thread_id },
))
.await,
)
});
}
Msg::ShowThreadResult(Ok(graphql_client::Response {
data: Some(data), ..
})) => {
model.tags = Some(
data.tags
.into_iter()
.map(|t| Tag {
name: t.name,
bg_color: t.bg_color,
fg_color: t.fg_color,
unread: t.unread,
})
.collect(),
);
model.context = Context::ThreadResult(data.thread);
}
Msg::ShowThreadResult(bad) => {
error!("show_thread_query error: {bad:#?}");
}
}
}
// `Model` describes our app state.
pub struct Model {
pub query: String,
pub context: Context,
pub refreshing_state: RefreshingState,
pub ui_error: UIError,
pub tags: Option<Vec<Tag>>,
}
#[derive(Error, Debug)]
#[allow(dead_code)] // Remove once the UI is showing errors
pub enum UIError {
#[error("No error, this should never be presented to user")]
NoError,
#[error("failed to fetch {0}: {1:?}")]
FetchError(&'static str, gloo_net::Error),
#[error("{0} error decoding: {1:?}")]
FetchDecodeError(&'static str, Vec<graphql_client::Error>),
#[error("no data or errors for {0}")]
NoData(&'static str),
}
pub enum Context {
None,
Search(shared::SearchResult),
SearchResult {
query: String,
results: Vec<FrontPageQuerySearchNodes>,
count: usize,
pager: FrontPageQuerySearchPageInfo,
},
Thread(ThreadSet),
ThreadResult(ShowThreadQueryThread),
}
pub struct Tag {
pub name: String,
pub bg_color: String,
pub fg_color: String,
pub unread: i64,
}
#[derive(Debug, PartialEq)]
pub enum RefreshingState {
None,
Loading,
Error(String),
}
// `Msg` describes the different events you can modify state with.
pub enum Msg {
Noop,
// Tell the client to refresh its state
Reload,
// Window has changed size
OnResize,
// Tell the server to update state
RefreshStart,
RefreshDone(Option<gloo_net::Error>),
SearchRequest {
query: String,
page: usize,
results_per_page: usize,
},
SearchResult(Result<shared::SearchResult, gloo_net::Error>),
ShowPrettyRequest(String),
ShowPrettyResult(Result<ThreadSet, gloo_net::Error>),
NextPage,
PreviousPage,
UpdateQuery(String),
SearchQuery(String),
FrontPageRequest {
query: String,
after: Option<String>,
before: Option<String>,
first: Option<i64>,
last: Option<i64>,
},
FrontPageResult(
Result<graphql_client::Response<graphql::front_page_query::ResponseData>, gloo_net::Error>,
),
ShowThreadRequest {
thread_id: String,
},
ShowThreadResult(
Result<graphql_client::Response<graphql::show_thread_query::ResponseData>, gloo_net::Error>,
),
}

125
web/src/view/desktop.rs Normal file
View File

@@ -0,0 +1,125 @@
use seed::{prelude::*, *};
use seed_hooks::{state_access::CloneState, topo, use_state};
use crate::{
api::urls,
state::{Context, Model, Msg, Tag},
view::{self, legacy, view_header, view_search_results},
};
#[topo::nested]
pub(super) fn view(model: &Model) -> Node<Msg> {
// Do two queries, one without `unread` so it loads fast, then a second with unread.
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(thread_set) => legacy::thread(thread_set),
Context::ThreadResult(thread) => view::thread(thread),
Context::Search(search_results) => legacy::search_results(&model.query, search_results),
Context::SearchResult {
query,
results,
count,
pager,
} => view_search_results(&query, results.as_slice(), *count, pager),
};
fn view_tag_li(display_name: &str, indent: usize, t: &Tag, search_unread: bool) -> Node<Msg> {
let href = if search_unread {
urls::search(&format!("is:unread tag:{}", t.name), 0)
} else {
urls::search(&format!("tag:{}", t.name), 0)
};
li![a![
attrs! {
At::Href => href
},
(0..indent).map(|_| span![C!["tag-indent"], ""]),
i![
C!["tag-tag", "fa-solid", "fa-tag"],
style! {
//"--fa-primary-color" => t.fg_color,
St::Color => t.bg_color,
},
],
display_name,
IF!(t.unread>0 => format!(" ({})", t.unread))
]]
}
fn matches(a: &[&str], b: &[&str]) -> usize {
std::iter::zip(a.iter(), b.iter())
.take_while(|(a, b)| a == b)
.count()
}
fn view_tag_list<'a>(
tags: impl Iterator<Item = &'a Tag>,
search_unread: bool,
) -> Vec<Node<Msg>> {
let mut lis = Vec::new();
let mut last = Vec::new();
for t in tags {
let parts: Vec<_> = t.name.split('/').collect();
let mut n = matches(&last, &parts);
if n <= parts.len() - 2 && parts.len() > 1 {
// Synthesize fake tags for proper indenting.
for i in n..parts.len() - 1 {
let display_name = parts[n];
lis.push(view_tag_li(
&display_name,
n,
&Tag {
name: parts[..i + 1].join("/"),
bg_color: "#fff".to_string(),
fg_color: "#000".to_string(),
unread: 0,
},
search_unread,
));
}
n = parts.len() - 1;
}
let display_name = parts[n];
lis.push(view_tag_li(&display_name, n, t, search_unread));
last = parts;
}
lis
}
let unread = model
.tags
.as_ref()
.map(|tags| tags.iter().filter(|t| t.unread > 0).collect())
.unwrap_or(Vec::new());
let tags_open = use_state(|| false);
let force_tags_open = unread.is_empty();
div![
C!["main-content"],
aside![
C!["tags-menu", "menu"],
IF!(!unread.is_empty() => p![C!["menu-label"], "Unread"]),
IF!(!unread.is_empty() => ul![C!["menu-list"], view_tag_list(unread.into_iter(),true)]),
p![
C!["menu-label"],
IF!(!force_tags_open =>
i![C![
"fa-solid",
if tags_open.get() {
"fa-angle-up"
} else {
"fa-angle-down"
}
]]),
" Tags",
ev(Ev::Click, move |_| {
tags_open.set(!tags_open.get());
})
],
ul![
C!["menu-list"],
IF!(force_tags_open||tags_open.get() => model.tags.as_ref().map(|tags| view_tag_list(tags.iter(),false))),
]
],
div![
view_header(&model.query, &model.refreshing_state),
content,
view_header(&model.query, &model.refreshing_state),
]
]
}

270
web/src/view/legacy.rs Normal file
View File

@@ -0,0 +1,270 @@
use notmuch::{Content, Part, ThreadNode, ThreadSet};
use seed::{prelude::*, *};
use crate::{
api,
api::urls,
consts::SEARCH_RESULTS_PER_PAGE,
state::Msg,
view::{human_age, pretty_authors, set_title, tags_chiclet},
};
pub(super) fn 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();
let datetime = human_age(r.timestamp as i64);
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"], datetime]
]
});
let first = search_results.page * search_results.results_per_page;
div![
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]
],
search_pager(first, summaries.len(), search_results.total)
]
}
fn 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)],
],
]
}
pub(super) fn thread(thread_set: &ThreadSet) -> Node<Msg> {
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"
],
]
}
pub(super) fn 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();
let datetime = human_age(r.timestamp as i64);
a![
C!["has-text-light"],
attrs! {
At::Href => urls::thread(&tid)
},
div![
C!["row"],
div![C!["subject"], &r.subject],
span![C!["from", "is-size-7"], pretty_authors(&r.authors)],
div![
span![C!["is-size-7"], tags_chiclet(&r.tags, true)],
span![C!["is-size-7", "float-right", "date"], datetime]
]
]
]
});
let first = search_results.page * search_results.results_per_page;
div![
C!["search-results"],
search_pager(first, summaries.len(), search_results.total),
rows,
search_pager(first, summaries.len(), search_results.total)
]
}
fn view_message(thread: &ThreadNode) -> Node<Msg> {
let message = thread.0.as_ref().expect("ThreadNode missing Message");
let children = &thread.1;
div![
C!["message"],
/* TODO(wathiede): collect all the tags and show them here. */
/* TODO(wathiede): collect all the attachments from all the subparts */
div![C!["header"], "From: ", &message.headers.from],
div![C!["header"], "Date: ", &message.headers.date],
div![C!["header"], "To: ", &message.headers.to],
div![
C!["body"],
match &message.body {
Some(body) => view_body(body.as_slice()),
None => div!["<no body>"],
},
],
children.iter().map(view_message)
]
}
fn view_body(body: &[Part]) -> Node<Msg> {
div![body.iter().map(view_part)]
}
fn view_text_plain(content: &Option<Content>) -> Node<Msg> {
match &content {
Some(Content::String(content)) => p![C!["view-part-text-plain"], content],
_ => div![
C!["error"],
format!("Unhandled content enum for text/plain"),
],
}
}
fn view_part(part: &Part) -> Node<Msg> {
match part.content_type.as_str() {
"text/plain" => view_text_plain(&part.content),
"text/html" => {
if let Some(Content::String(html)) = &part.content {
/* Build problems w/ css_inline. TODO(wathiede): move to server
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![&html]];
} else {
div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
]
}
}
// https://en.wikipedia.org/wiki/MIME#alternative
// RFC1341 states: In general, user agents that compose multipart/alternative entities
// should place the body parts in increasing order of preference, that is, with the
// preferred format last.
"multipart/alternative" => {
if let Some(Content::Multipart(parts)) = &part.content {
for part in parts.iter().rev() {
if part.content_type == "text/html" {
if let Some(Content::String(html)) = &part.content {
/*
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, &html)];
}
}
if part.content_type == "text/plain" {
return view_text_plain(&part.content);
}
}
div!["No known multipart/alternative parts"]
} else {
div![
C!["error"],
format!("multipart/alternative with non-multipart content"),
]
}
}
"multipart/mixed" => match &part.content {
Some(Content::Multipart(parts)) => div![parts.iter().map(view_part)],
_ => div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
],
},
_ => div![
C!["error"],
format!("Unhandled content type: {}", part.content_type)
],
}
}
fn first_subject(thread: &ThreadNode) -> Option<String> {
if let Some(msg) = &thread.0 {
return Some(msg.headers.subject.clone());
} else {
for tn in &thread.1 {
if let Some(s) = first_subject(&tn) {
return Some(s);
}
}
}
None
}

71
web/src/view/mobile.rs Normal file
View File

@@ -0,0 +1,71 @@
use seed::{prelude::*, *};
use crate::{
api::urls,
graphql::front_page_query::*,
state::{Context, Model, Msg},
view::{
self, human_age, legacy, pretty_authors, set_title, tags_chiclet, view_header,
view_search_pager,
},
};
pub(super) fn view(model: &Model) -> Node<Msg> {
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(thread_set) => legacy::thread(thread_set),
Context::ThreadResult(thread) => view::thread(thread),
Context::Search(search_results) => {
legacy::mobile_search_results(&model.query, search_results)
}
Context::SearchResult {
query,
results,
count,
pager,
} => search_results(&query, results.as_slice(), *count, pager),
};
div![
view_header(&model.query, &model.refreshing_state),
content,
view_header(&model.query, &model.refreshing_state),
]
}
fn search_results(
query: &str,
results: &[FrontPageQuerySearchNodes],
count: usize,
pager: &FrontPageQuerySearchPageInfo,
) -> Node<Msg> {
if query.is_empty() {
set_title("all mail");
} else {
set_title(query);
}
let rows = results.iter().map(|r| {
let tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
a![
C!["has-text-light"],
attrs! {
At::Href => urls::thread(&tid)
},
div![
C!["row"],
div![C!["subject"], &r.subject],
span![C!["from", "is-size-7"], pretty_authors(&r.authors)],
div![
span![C!["is-size-7"], tags_chiclet(&r.tags, true)],
span![C!["is-size-7", "float-right", "date"], datetime]
]
]
]
});
div![
C!["search-results"],
view_search_pager(count, pager),
rows,
view_search_pager(count, pager),
]
}

489
web/src/view/mod.rs Normal file
View File

@@ -0,0 +1,489 @@
use std::{
collections::{hash_map::DefaultHasher, HashSet},
hash::{Hash, Hasher},
};
use chrono::{DateTime, Datelike, Duration, Local, Utc};
use itertools::Itertools;
use log::{error, info};
use seed::{prelude::*, *};
use seed_hooks::{state_access::CloneState, topo, use_state};
use wasm_timer::Instant;
use crate::{
api::urls,
consts::{SEARCH_RESULTS_PER_PAGE, USE_GRAPHQL},
graphql::{front_page_query::*, show_thread_query::*},
state::{Model, Msg, RefreshingState},
};
mod desktop;
mod legacy;
mod mobile;
mod tablet;
const MAX_RAW_MESSAGE_SIZE: usize = 100_000;
fn set_title(title: &str) {
seed::document().set_title(&format!("lb: {}", title));
}
fn tags_chiclet(tags: &[String], is_mobile: bool) -> impl Iterator<Item = Node<Msg>> + '_ {
tags.iter().map(move |tag| {
let mut hasher = DefaultHasher::new();
tag.hash(&mut hasher);
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
let style = style! {St::BackgroundColor=>hex};
let classes = C!["tag", IF!(is_mobile => "is-small")];
let tag = tag.clone();
a![
attrs! {
At::Href => urls::search(&format!("tag:{tag}"), 0)
},
match tag.as_str() {
"attachment" => span![classes, style, "📎"],
"replied" => span![classes, style, i![C!["fa-solid", "fa-reply"]]],
_ => span![classes, style, &tag],
},
ev(Ev::Click, move |_| Msg::SearchRequest {
query: format!("tag:{tag}"),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
})
]
})
}
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 human_age(timestamp: i64) -> String {
let now = Local::now();
let yesterday = now - Duration::days(1);
let ts = DateTime::<Utc>::from_timestamp(timestamp, 0)
.unwrap()
.with_timezone(&Local);
let age = now - ts;
let datetime = if age < Duration::minutes(1) {
format!("{} min. ago", age.num_seconds())
} else if age < Duration::hours(1) {
format!("{} min. ago", age.num_minutes())
} else if ts.date_naive() == now.date_naive() {
ts.format("Today %H:%M").to_string()
} else if ts.date_naive() == yesterday.date_naive() {
ts.format("Yest. %H:%M").to_string()
} else if age < Duration::weeks(1) {
ts.format("%a %H:%M").to_string()
} else if ts.year() == now.year() {
ts.format("%b %d %H:%M").to_string()
} else {
ts.format("%b %d, %Y %H:%M").to_string()
};
datetime
}
fn view_search_results(
query: &str,
results: &[FrontPageQuerySearchNodes],
count: usize,
pager: &FrontPageQuerySearchPageInfo,
) -> Node<Msg> {
info!("pager {pager:?}");
if query.is_empty() {
set_title("all mail");
} else {
set_title(query);
}
let rows = results.iter().map(|r| {
let tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
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"], datetime]
]
});
div![
view_search_pager(count, pager),
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(count, pager)
]
}
fn view_search_pager(count: usize, pager: &FrontPageQuerySearchPageInfo) -> Node<Msg> {
let start = pager
.start_cursor
.as_ref()
.map(|i| i.parse().unwrap_or(0))
.unwrap_or(0);
nav![
C!["pagination"],
a![
C![
"pagination-previous",
"button",
//IF!(!pager.has_previous_page => "is-static"),
],
IF!(!pager.has_previous_page => attrs!{ At::Disabled=>true }),
"<",
IF!(pager.has_previous_page => ev(Ev::Click, |_| Msg::PreviousPage)),
],
a![
C![
"pagination-next",
"button",
//IF!(!pager.has_next_page => "is-static")
],
IF!(!pager.has_next_page => attrs!{ At::Disabled=>true }),
">",
IF!(pager.has_next_page => ev(Ev::Click, |_| Msg::NextPage))
],
ul![
C!["pagination-list"],
li![format!(
"{} - {} of {}",
start,
count.min(start + SEARCH_RESULTS_PER_PAGE),
count
)],
],
]
}
trait Email {
fn name(&self) -> Option<&str>;
fn addr(&self) -> Option<&str>;
}
impl<T: Email> Email for &'_ T {
fn name(&self) -> Option<&str> {
return (*self).name();
}
fn addr(&self) -> Option<&str> {
return (*self).addr();
}
}
macro_rules! implement_email {
( $($t:ty),+ ) => {$(
impl Email for $t {
fn name(&self) -> Option<&str> {
self.name.as_deref()
}
fn addr(&self) -> Option<&str> {
self.addr.as_deref()
}
}
)+};
}
implement_email!(
ShowThreadQueryThreadMessagesTo,
ShowThreadQueryThreadMessagesCc,
ShowThreadQueryThreadMessagesFrom
);
fn view_address(email: impl Email) -> Node<Msg> {
span![
C!["tag", "is-black"],
email.addr().as_ref().map(|a| attrs! {At::Title=>a}),
email
.name()
.as_ref()
.unwrap_or(&email.addr().unwrap_or("(UNKNOWN)"))
]
}
fn view_addresses(addrs: &[impl Email]) -> Vec<Node<Msg>> {
addrs.into_iter().map(view_address).collect::<Vec<_>>()
}
fn raw_text_message(contents: &str) -> Node<Msg> {
let (contents, truncated_msg) = if contents.len() > MAX_RAW_MESSAGE_SIZE {
(
&contents[..MAX_RAW_MESSAGE_SIZE],
Some(div!["... contents truncated"]),
)
} else {
(contents, None)
};
div![C!["view-part-text-plain"], contents, truncated_msg,]
}
fn thread(thread: &ShowThreadQueryThread) -> Node<Msg> {
// TODO(wathiede): show per-message subject if it changes significantly from top-level subject
set_title(&thread.subject);
let mut tags: Vec<_> = thread
.messages
.iter()
.fold(HashSet::new(), |mut tags, msg| {
tags.extend(msg.tags.clone());
tags
})
.into_iter()
.collect();
tags.sort();
let messages = thread.messages.iter().map(|msg| {
div![
C!["message"],
div![
C!["headers"],
/* TODO(wathiede): collect all the tags and show them here. */
msg.from
.as_ref()
.map(|from| div![C!["header"], "From: ", view_address(&from)]),
msg.timestamp
.map(|ts| div![C!["header"], "Date: ", human_age(ts)]),
div![C!["header"], "Message-ID: ", &msg.id],
div![
C!["header"],
IF!(!msg.to.is_empty() => span!["To: ", view_addresses(&msg.to)]),
IF!(!msg.cc.is_empty() => span!["CC: ", view_addresses(&msg.cc)])
],
],
div![
C!["body"],
match &msg.body {
ShowThreadQueryThreadMessagesBody::UnhandledContentType(
ShowThreadQueryThreadMessagesBodyOnUnhandledContentType { contents },
) => pre![C!["error"], contents],
ShowThreadQueryThreadMessagesBody::PlainText(
ShowThreadQueryThreadMessagesBodyOnPlainText {
contents,
content_tree,
},
) => div![
raw_text_message(&contents),
view_content_tree(&content_tree),
],
ShowThreadQueryThreadMessagesBody::Html(
ShowThreadQueryThreadMessagesBodyOnHtml {
contents,
content_tree,
},
) => div![
C!["view-part-text-html"],
raw![contents],
IF!(!msg.attachments.is_empty() =>
div![
C!["attachments"],
br![],
h2!["Attachments"],
msg.attachments
.iter()
.map(|a| div!["Filename: ", &a.filename, " ", &a.content_type])
]),
view_content_tree(&content_tree),
],
}
],
]
});
div![
C!["thread"],
p![
C!["is-size-4"],
&thread.subject,
" ",
tags_chiclet(&tags, false)
],
messages,
/* TODO(wathiede): plumb in orignal id
a![
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
"Original"
],
*/
]
}
#[topo::nested]
fn view_content_tree(content_tree: &str) -> Node<Msg> {
let debug_open = use_state(|| false);
div![
hr![],
small![
i![C![
"fa-solid",
if debug_open.get() {
"fa-angle-up"
} else {
"fa-angle-down"
}
]],
" Debug",
ev(Ev::Click, move |_| {
debug_open.set(!debug_open.get());
})
],
IF!(debug_open.get() =>
pre![C!["content-tree"], content_tree]),
]
}
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| if USE_GRAPHQL {
Msg::UpdateQuery(q)
} else {
Msg::SearchRequest {
query: Url::encode_uri_component(if q.is_empty() {
"*".to_string()
} else {
q
}),
page: 0,
results_per_page: SEARCH_RESULTS_PER_PAGE,
}
}),
// Send search on enter.
keyboard_ev(Ev::KeyUp, move |e| if e.key_code() == 0x0d {
if USE_GRAPHQL {
Msg::SearchQuery(query)
} else {
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!["lb-footer"],
div![
C!["content", "has-text-right", "is-size-7"],
format!("Render time {} ms", render_time_ms)
]
]
}
// `view` describes what to display.
pub fn view(model: &Model) -> Node<Msg> {
let start = Instant::now();
info!("refreshing {:?}", model.refreshing_state);
let win = seed::window();
let w = win
.inner_width()
.expect("window width")
.as_f64()
.expect("window width f64");
let h = win
.inner_height()
.expect("window height")
.as_f64()
.expect("window height f64");
info!("win: {w}x{h}");
info!("view called");
div![
match w {
w if w < 800. => div![C!["mobile"], mobile::view(model)],
w if w < 1024. => div![C!["tablet"], tablet::view(model)],
_ => div![C!["desktop"], desktop::view(model)],
},
view_footer(start.elapsed().as_millis()),
]
}

30
web/src/view/tablet.rs Normal file
View File

@@ -0,0 +1,30 @@
use seed::{prelude::*, *};
use crate::{
state::{Context, Model, Msg},
view::{self, view_header, view_search_results},
};
pub(super) fn view(model: &Model) -> Node<Msg> {
// Do two queries, one without `unread` so it loads fast, then a second with unread.
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(_) => unimplemented!("tablet legacy thread view"),
Context::ThreadResult(thread) => view::thread(thread),
Context::Search(_) => unimplemented!("tablet legacy search results view"),
Context::SearchResult {
query,
results,
count,
pager,
} => view_search_results(&query, results.as_slice(), *count, pager),
};
div![
C!["main-content"],
div![
view_header(&model.query, &model.refreshing_state),
content,
view_header(&model.query, &model.refreshing_state),
]
]
}