Compare commits
6 Commits
cfe1446668
...
server-sid
| Author | SHA1 | Date | |
|---|---|---|---|
| 39bef1ea87 | |||
| 458bd356dd | |||
| 8420e4b4d3 | |||
| 8b04bd8059 | |||
| fc83d56c0c | |||
| f8e86dc5cc |
1465
Cargo.lock
generated
1465
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
4
dev.sh
4
dev.sh
@@ -1,7 +1,7 @@
|
||||
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
|
||||
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 send-keys "cd web; trunk serve --release --address 0.0.0.0 --port 6758 --proxy-backend http://localhost:9345/ --proxy-rewrite=/api/ -w ../shared -w ../notmuch -w ./" C-m
|
||||
tmux new-window -n server
|
||||
tmux send-keys "cd server; cargo watch -c -x run -w ../shared -w ../notmuch -w ./" C-m
|
||||
tmux send-keys "cd server; cargo watch -x run -w ../shared -w ../notmuch -w ./" C-m
|
||||
tmux attach -d -t letterbox-dev
|
||||
|
||||
@@ -454,8 +454,6 @@ pub enum NotmuchError {
|
||||
SerdeJson(#[from] serde_json::Error),
|
||||
#[error("failed to parse bytes as str")]
|
||||
Utf8Error(#[from] std::str::Utf8Error),
|
||||
#[error("failed to parse bytes as String")]
|
||||
StringUtf8Error(#[from] std::string::FromUtf8Error),
|
||||
#[error("failed to parse str as int")]
|
||||
ParseIntError(#[from] std::num::ParseIntError),
|
||||
}
|
||||
@@ -480,19 +478,12 @@ impl Notmuch {
|
||||
self.run_notmuch(std::iter::empty::<&str>())
|
||||
}
|
||||
|
||||
pub fn tags(&self) -> Result<Vec<String>, NotmuchError> {
|
||||
let res = self.run_notmuch(["search", "--format=json", "--output=tags", "*"])?;
|
||||
Ok(serde_json::from_slice(&res)?)
|
||||
}
|
||||
|
||||
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",
|
||||
@@ -561,10 +552,7 @@ impl Notmuch {
|
||||
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
|
||||
}
|
||||
|
||||
pub fn files(&self, query: &str) -> Result<Lines<BufReader<ChildStdout>>, NotmuchError> {
|
||||
let mut child = self.run_notmuch_pipe(["search", "--output=files", query])?;
|
||||
Ok(BufReader::new(child.stdout.take().unwrap()).lines())
|
||||
}
|
||||
// TODO(wathiede): implement tags() based on "notmuch search --output=tags '*'"
|
||||
|
||||
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
|
||||
where
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
name = "server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
default-bin = "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"
|
||||
@@ -16,14 +16,6 @@ serde = { version = "1.0.147", features = ["derive"] }
|
||||
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"
|
||||
rayon = "1.8.0"
|
||||
memmap = "0.7.0"
|
||||
mailparse = "0.14.0"
|
||||
ammonia = "3.3.0"
|
||||
|
||||
[dependencies.rocket_contrib]
|
||||
version = "0.4.11"
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ServerError {
|
||||
#[error("notmuch")]
|
||||
NotmuchError(#[from] notmuch::NotmuchError),
|
||||
#[error("flatten")]
|
||||
FlattenError,
|
||||
}
|
||||
@@ -1,464 +0,0 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
};
|
||||
|
||||
use async_graphql::{
|
||||
connection::{self, Connection, Edge},
|
||||
Context, EmptyMutation, EmptySubscription, Error, FieldResult, Object, Schema, SimpleObject,
|
||||
Union,
|
||||
};
|
||||
use log::{error, info, warn};
|
||||
use mailparse::{parse_mail, MailHeaderMap, ParsedMail};
|
||||
use memmap::MmapOptions;
|
||||
use notmuch::Notmuch;
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub struct QueryRoot;
|
||||
|
||||
/// # 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 {
|
||||
subject: String,
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
#[derive(Debug, SimpleObject)]
|
||||
pub struct Message {
|
||||
// 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>,
|
||||
// The body contents
|
||||
pub body: Body,
|
||||
// On disk location of message
|
||||
pub path: 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
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
#[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>();
|
||||
Ok(nm
|
||||
.tags()?
|
||||
.into_par_iter()
|
||||
.map(|tag| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
tag.hash(&mut hasher);
|
||||
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
|
||||
let unread = if ctx.look_ahead().field("unread").exists() {
|
||||
nm.count(&format!("tag:{tag} is:unread")).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Tag {
|
||||
name: tag,
|
||||
fg_color: "white".to_string(),
|
||||
bg_color: hex,
|
||||
unread,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
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 in nm.files(&thread_id)? {
|
||||
let path = 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::PlainText(PlainText {
|
||||
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: ammonia::clean(&html),
|
||||
content_tree: if debug_content_tree {
|
||||
render_content_type_tree(&m)
|
||||
} else {
|
||||
content_tree
|
||||
},
|
||||
}),
|
||||
b => b,
|
||||
};
|
||||
messages.push(Message {
|
||||
from,
|
||||
to,
|
||||
cc,
|
||||
subject,
|
||||
timestamp,
|
||||
body,
|
||||
path,
|
||||
});
|
||||
}
|
||||
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 { subject, messages })
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}))
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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);
|
||||
if !m.ctype.charset.is_empty() {
|
||||
parts.push(format!(
|
||||
"{} Character Set: {}",
|
||||
" ".repeat(depth * WIDTH),
|
||||
m.ctype.charset
|
||||
));
|
||||
}
|
||||
for (k, v) in m.ctype.params.iter() {
|
||||
parts.push(format!("{} {k}: {v}", " ".repeat(depth * WIDTH),));
|
||||
}
|
||||
for sp in &m.subparts {
|
||||
parts.push(render_rec(sp, depth + 1))
|
||||
}
|
||||
parts.join("\n")
|
||||
}
|
||||
render_rec(m, 1)
|
||||
}
|
||||
|
||||
pub type GraphqlSchema = Schema<QueryRoot, EmptyMutation, 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)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub mod error;
|
||||
pub mod graphql;
|
||||
pub mod nm;
|
||||
@@ -1,23 +1,27 @@
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
mod error;
|
||||
mod nm;
|
||||
|
||||
use std::{error::Error, io::Cursor, str::FromStr};
|
||||
|
||||
use async_graphql::{http::GraphiQLSource, EmptyMutation, EmptySubscription, Schema};
|
||||
use async_graphql_rocket::{GraphQLQuery, GraphQLRequest, GraphQLResponse};
|
||||
use glog::Flags;
|
||||
use notmuch::{Notmuch, NotmuchError, ThreadSet};
|
||||
use notmuch::{Notmuch, NotmuchError};
|
||||
use rocket::{
|
||||
http::{ContentType, Header},
|
||||
request::Request,
|
||||
response::{content, Debug, Responder},
|
||||
response::{Debug, Responder},
|
||||
serde::json::Json,
|
||||
Response, State,
|
||||
};
|
||||
use rocket_cors::{AllowedHeaders, AllowedOrigins};
|
||||
use server::{
|
||||
error::ServerError,
|
||||
graphql::{GraphqlSchema, QueryRoot},
|
||||
};
|
||||
|
||||
use crate::error::ServerError;
|
||||
|
||||
#[get("/")]
|
||||
fn hello() -> &'static str {
|
||||
"Hello, world!"
|
||||
}
|
||||
|
||||
#[get("/refresh")]
|
||||
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
|
||||
@@ -39,33 +43,24 @@ 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(20);
|
||||
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
|
||||
let results_per_page = results_per_page.unwrap_or(10);
|
||||
info!(" search '{query}'");
|
||||
let res = shared::SearchResult {
|
||||
summary: nm.search(&query, page * results_per_page, results_per_page)?,
|
||||
summary: nm.search(query, page * results_per_page, results_per_page)?,
|
||||
query: query.to_string(),
|
||||
page,
|
||||
results_per_page,
|
||||
total: nm.count(&query)?,
|
||||
total: nm.count(query)?,
|
||||
};
|
||||
Ok(Json(res))
|
||||
}
|
||||
|
||||
#[get("/show/<query>/pretty")]
|
||||
async fn show_pretty(
|
||||
#[get("/show/<query>")]
|
||||
async fn show(
|
||||
nm: &State<Notmuch>,
|
||||
query: &str,
|
||||
) -> Result<Json<ThreadSet>, Debug<ServerError>> {
|
||||
let query = urlencoding::decode(query).map_err(|e| ServerError::from(NotmuchError::from(e)))?;
|
||||
let res = nm.show(&query).map_err(ServerError::from)?;
|
||||
Ok(Json(res))
|
||||
}
|
||||
|
||||
#[get("/show/<query>")]
|
||||
async fn show(nm: &State<Notmuch>, query: &str) -> Result<Json<ThreadSet>, Debug<NotmuchError>> {
|
||||
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
|
||||
let res = nm.show(&query)?;
|
||||
) -> Result<Json<Vec<shared::Message>>, Debug<ServerError>> {
|
||||
let res = nm::threadset_to_messages(nm.show(query).map_err(|e| -> ServerError { e.into() })?)?;
|
||||
Ok(Json(res))
|
||||
}
|
||||
|
||||
@@ -123,24 +118,6 @@ 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()
|
||||
@@ -164,29 +141,20 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
.to_cors()?;
|
||||
|
||||
let schema = Schema::build(QueryRoot, EmptyMutation, 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,
|
||||
graphql_query,
|
||||
graphql_request,
|
||||
graphiql
|
||||
show
|
||||
],
|
||||
)
|
||||
.attach(cors)
|
||||
.manage(schema)
|
||||
.manage(Notmuch::default())
|
||||
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
|
||||
.launch()
|
||||
@@ -1,13 +0,0 @@
|
||||
use shared::Message;
|
||||
|
||||
use crate::error;
|
||||
|
||||
// TODO(wathiede): decide good error type
|
||||
pub fn threadset_to_messages(
|
||||
thread_set: notmuch::ThreadSet,
|
||||
) -> Result<Vec<Message>, error::ServerError> {
|
||||
for t in thread_set.0 {
|
||||
for _tn in t.0 {}
|
||||
}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
@@ -11,4 +11,25 @@ pub struct SearchResult {
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Message {}
|
||||
pub struct ShowResult {
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
pub type AttachementId = String;
|
||||
|
||||
/// # Number of seconds since the Epoch
|
||||
pub type UnixTime = isize;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Default)]
|
||||
pub struct Message {
|
||||
pub from: String,
|
||||
pub to: Option<String>,
|
||||
pub cc: Option<String>,
|
||||
pub timestamp: UnixTime, // date header as unix time
|
||||
pub date_relative: String, // user-friendly timestamp
|
||||
pub tags: Vec<String>,
|
||||
|
||||
// HTML formatted body
|
||||
pub body: String,
|
||||
pub attachment: Vec<AttachementId>,
|
||||
}
|
||||
|
||||
@@ -27,11 +27,6 @@ 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/seed-rs/styles_hooks", package = "seed_hooks", branch = "main" }
|
||||
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ['-Os']
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
[build]
|
||||
release = true
|
||||
|
||||
[serve]
|
||||
# The address to serve on.
|
||||
address = "0.0.0.0"
|
||||
port = 6758
|
||||
|
||||
[[proxy]]
|
||||
backend = "http://localhost:9345/"
|
||||
rewrite= "/api/"
|
||||
[[proxy]]
|
||||
backend="http://localhost:9345/graphiql"
|
||||
[[proxy]]
|
||||
backend="http://localhost:9345/graphql"
|
||||
@@ -1,24 +0,0 @@
|
||||
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
|
||||
timestamp
|
||||
subject
|
||||
authors
|
||||
tags
|
||||
}
|
||||
}
|
||||
tags {
|
||||
name
|
||||
bgColor
|
||||
fgColor
|
||||
unread
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,42 +0,0 @@
|
||||
query ShowThreadQuery($threadId: String!) {
|
||||
thread(threadId: $threadId) {
|
||||
subject
|
||||
messages {
|
||||
subject
|
||||
from {
|
||||
name
|
||||
addr
|
||||
}
|
||||
to {
|
||||
name
|
||||
addr
|
||||
}
|
||||
cc {
|
||||
name
|
||||
addr
|
||||
}
|
||||
timestamp
|
||||
body {
|
||||
__typename
|
||||
... on UnhandledContentType {
|
||||
contents
|
||||
}
|
||||
... on PlainText {
|
||||
contents
|
||||
contentTree
|
||||
}
|
||||
... on Html {
|
||||
contents
|
||||
contentTree
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
}
|
||||
tags {
|
||||
name
|
||||
bgColor
|
||||
fgColor
|
||||
unread
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
DEV_HOST=localhost
|
||||
DEV_PORT=9345
|
||||
graphql-client introspect-schema http://${DEV_HOST:?}:${DEV_PORT:?}/graphql --output schema.json
|
||||
git diff schema.json
|
||||
@@ -4,21 +4,18 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<link rel="modulepreload" href="/pkg/package.js" as="script" type="text/javascript">
|
||||
<link rel="preload" href="/pkg/package_bg.wasm" as="fetch" type="application/wasm" crossorigin="anonymous">
|
||||
<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;*/
|
||||
padding-left: 0.5em;
|
||||
}
|
||||
.body {
|
||||
background: white;
|
||||
color: black;
|
||||
padding: 0.5em;
|
||||
margin-left: -0.5em;
|
||||
margin-right: -0.5em;
|
||||
margin-top: 0.5em;
|
||||
padding-bottom: 1em;
|
||||
}
|
||||
.error {
|
||||
background-color: red;
|
||||
@@ -30,26 +27,13 @@ iframe {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.index {
|
||||
table-layout: fixed;
|
||||
width: 100%;
|
||||
}
|
||||
.index .from {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
width: 10em;
|
||||
width: 200px;
|
||||
}
|
||||
.index .subject {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.index .date {
|
||||
width: 10em;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
}
|
||||
.footer {
|
||||
background-color: #eee;
|
||||
@@ -94,70 +78,15 @@ 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;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<section id="app"></section>
|
||||
<script type="module">
|
||||
import init from '/pkg/package.js';
|
||||
init('/pkg/package_bg.wasm');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
16
web/src/api.rs
Normal file
16
web/src/api.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
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 original(message_id: &str) -> String {
|
||||
format!("{BASE_URL}/original/{message_id}")
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
use graphql_client::GraphQLQuery;
|
||||
use seed::{
|
||||
fetch,
|
||||
fetch::{Header, Method, Request},
|
||||
};
|
||||
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) -> fetch::Result<graphql_client::Response<Resp>>
|
||||
where
|
||||
Body: Serialize,
|
||||
Resp: DeserializeOwned + 'static,
|
||||
{
|
||||
use web_sys::RequestMode;
|
||||
|
||||
Request::new("/graphql/")
|
||||
.method(Method::Post)
|
||||
.header(Header::content_type("application/json"))
|
||||
.mode(RequestMode::Cors)
|
||||
.json(&body)?
|
||||
.fetch()
|
||||
.await?
|
||||
.check_status()?
|
||||
.json()
|
||||
.await
|
||||
}
|
||||
1000
web/src/lib.rs
1000
web/src/lib.rs
File diff suppressed because it is too large
Load Diff
193
web/src/nm.rs
Normal file
193
web/src/nm.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
use notmuch::{Content, Part, Thread, ThreadNode, ThreadSet};
|
||||
use seed::{prelude::*, *};
|
||||
use serde::de::Deserialize;
|
||||
|
||||
use crate::{api, set_title, Msg};
|
||||
|
||||
pub 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)))?)
|
||||
}
|
||||
|
||||
pub fn view_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![
|
||||
h1![subject],
|
||||
a![
|
||||
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
|
||||
"Original"
|
||||
],
|
||||
view_message(&thread_node),
|
||||
div![
|
||||
C!["debug"],
|
||||
"Add zippy for debug dump",
|
||||
view_debug_thread_set(thread_set)
|
||||
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
|
||||
]
|
||||
}
|
||||
|
||||
// <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],
|
||||
hr![],
|
||||
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"], div!["TEST"], 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 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)
|
||||
])
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user