Compare commits
82 Commits
pretty
...
5b3eadb7bd
| Author | SHA1 | Date | |
|---|---|---|---|
| 5b3eadb7bd | |||
| 28d484117b | |||
| a0b0689e01 | |||
| 33ec63f097 | |||
| 7b22f85429 | |||
| fa7df55b0e | |||
| d2cf270dda | |||
| f1b5e78962 | |||
| fae4e43682 | |||
| 37eb3d1dfd | |||
| e0890f1181 | |||
| c31f9d581f | |||
| f2347345b4 | |||
| e34f2a1f39 | |||
| 7a6000be26 | |||
| dd1a8c2eae | |||
| 42590b3cbc | |||
| 94f7ad109a | |||
| f6bdf302fe | |||
| b76c535738 | |||
| 29949c703d | |||
| f5f9eb175d | |||
| 488c3b86f8 | |||
| be8fd59703 | |||
| 071fe2e206 | |||
| ac5660a6d0 | |||
| 99a104517d | |||
| c3692cadec | |||
| b14000952c | |||
| 7a32d5c630 | |||
| 714b057fdb | |||
| 4c2526c70b | |||
| a8f4aa03bd | |||
| 28d5562491 | |||
| e6f20e538a | |||
| 970bb55c73 | |||
| 12f0491455 | |||
| ef8362d6f2 | |||
| 0a7cdefda3 | |||
| cfe1446668 | |||
| 7c38962d21 | |||
| 7102f26c9e | |||
| 71a3315fe8 | |||
| 7cac81cddb | |||
| 3a5ca74d71 | |||
| 71af8179ec | |||
| d66a7d3d53 | |||
| e0fbb0253e | |||
| 48466808d3 | |||
| 87dfe4ace7 | |||
| d45f223d52 | |||
| e8c58bdbd0 | |||
| 87d687cde5 | |||
| c8147ded60 | |||
| 1261bdf8a9 | |||
| 11366b6fac | |||
| 1cdabc348b | |||
| 02e16b4547 | |||
| d5a001bf03 | |||
| 0ae72b63d0 | |||
| 447a4a3387 | |||
| 0737f5aac5 | |||
| 3e3024dd5c | |||
| 24414b04bb | |||
| f7df834325 | |||
| bce2c741c4 | |||
| 1b44bc57bb | |||
| ff6675b08f | |||
| 64912be4eb | |||
| 57ccef18cb | |||
| 2a24a20529 | |||
| e6692059b4 | |||
| a7b172099b | |||
| f52a76dba3 | |||
| 43e4334890 | |||
| 1d00bdb757 | |||
| 6901c9fde9 | |||
| 6251c54873 | |||
| f6c1835b18 | |||
| 95976c2860 | |||
| 01589d7136 | |||
| a2664473c8 |
1999
Cargo.lock
generated
1999
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
2
dev.sh
2
dev.sh
@@ -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
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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,19 @@ 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",
|
||||
@@ -511,7 +518,7 @@ impl Notmuch {
|
||||
"--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 +537,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 +556,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 +580,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)]
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -23,10 +23,10 @@ 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
|
||||
.show(&msg)
|
||||
.expect(&format!("failed to show msg: {}", msg));
|
||||
@@ -77,9 +77,7 @@ 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
|
||||
.show(&query)
|
||||
|
||||
10
procmail2notmuch/update.sh
Executable file
10
procmail2notmuch/update.sh
Executable 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
|
||||
@@ -8,7 +8,6 @@ default-bin = "server"
|
||||
|
||||
[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,12 @@ 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"
|
||||
|
||||
[dependencies.rocket_contrib]
|
||||
version = "0.4.11"
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
|
||||
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 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, 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, 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
|
||||
show,
|
||||
graphql_query,
|
||||
graphql_request,
|
||||
graphiql,
|
||||
attachment
|
||||
],
|
||||
)
|
||||
.attach(cors)
|
||||
.manage(schema)
|
||||
.manage(Notmuch::default())
|
||||
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
|
||||
.launch()
|
||||
|
||||
628
server/src/graphql.rs
Normal file
628
server/src/graphql.rs
Normal file
@@ -0,0 +1,628 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use async_graphql::{
|
||||
connection::{self, Connection, Edge},
|
||||
Context, EmptyMutation, 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;
|
||||
|
||||
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 {
|
||||
// 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,
|
||||
}
|
||||
|
||||
#[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)?) {
|
||||
info!("{id}\nfile: {path}");
|
||||
let msg = nm.show(&format!("id:{id}"))?;
|
||||
let tags = msg.0[0].0[0]
|
||||
.0
|
||||
.as_ref()
|
||||
.map(|m| m.tags.clone())
|
||||
.unwrap_or_else(Vec::default);
|
||||
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,
|
||||
};
|
||||
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 { 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,
|
||||
}))
|
||||
}
|
||||
|
||||
// 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, 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,2 +1,3 @@
|
||||
pub mod error;
|
||||
pub mod graphql;
|
||||
pub mod nm;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -9,5 +9,6 @@ pub struct SearchResult {
|
||||
pub results_per_page: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Message {}
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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)/
|
||||
|
||||
@@ -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" ]
|
||||
|
||||
25
web/graphql/front_page.graphql
Normal file
25
web/graphql/front_page.graphql
Normal 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
2092
web/graphql/schema.json
Normal file
File diff suppressed because it is too large
Load Diff
49
web/graphql/show_thread.graphql
Normal file
49
web/graphql/show_thread.graphql
Normal 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
4
web/graphql/update_schema.sh
Executable 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
|
||||
@@ -6,9 +6,21 @@
|
||||
<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;
|
||||
@@ -17,12 +29,15 @@
|
||||
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 {
|
||||
white-space: pre-line;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
iframe {
|
||||
height: 100%;
|
||||
@@ -37,7 +52,7 @@ iframe {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
width: 15em;
|
||||
width: 10em;
|
||||
}
|
||||
.index .subject {
|
||||
overflow: hidden;
|
||||
@@ -45,8 +60,9 @@ iframe {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.index .date {
|
||||
width: 8em;
|
||||
width: 10em;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
}
|
||||
.footer {
|
||||
background-color: #eee;
|
||||
@@ -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
55
web/src/api.rs
Normal 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
2
web/src/consts.rs
Normal 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
37
web/src/graphql.rs
Normal 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
|
||||
}
|
||||
788
web/src/lib.rs
788
web/src/lib.rs
@@ -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);
|
||||
}
|
||||
|
||||
1
web/src/model.rs
Normal file
1
web/src/model.rs
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
396
web/src/state.rs
Normal file
396
web/src/state.rs
Normal file
@@ -0,0 +1,396 @@
|
||||
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));
|
||||
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>,
|
||||
),
|
||||
}
|
||||
127
web/src/view/desktop.rs
Normal file
127
web/src/view/desktop.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use log::info;
|
||||
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,
|
||||
));
|
||||
}
|
||||
last = parts[..parts.len() - 1].to_vec();
|
||||
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
270
web/src/view/legacy.rs
Normal 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
71
web/src/view/mobile.rs
Normal 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
489
web/src/view/mod.rs
Normal 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!["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
30
web/src/view/tablet.rs
Normal 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),
|
||||
]
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user