Compare commits

..

196 Commits

Author SHA1 Message Date
1106377550 Normalize links and images based on post's URL 2024-07-22 11:27:15 -07:00
b5468bced2 Implement pagination for newsreader 2024-07-22 09:28:12 -07:00
01cbe6c037 web: set reasonable defaults on front page requests 2024-07-22 08:28:12 -07:00
d0a02c2f61 cargo fix lint 2024-07-22 08:19:07 -07:00
c499672dde Rollback attempt to make unread tag queries faster for newsreader 2024-07-22 08:17:46 -07:00
3aa0b94db4 Fix bug in pagination when more than SEARCH_RESULTS_PER_PAGE returned 2024-07-22 08:13:45 -07:00
cdb64ed952 Remove old search URLs 2024-07-22 07:25:15 -07:00
834efc5c94 Handle needs_unread on tag query. Move News to top of tag list 2024-07-22 07:24:28 -07:00
79db94f67f Add pretty site names to search and thread views 2024-07-21 20:50:50 -07:00
ec41f840d5 Store remaining text when parsing query 2024-07-21 15:19:19 -07:00
d9d57c66f8 Sort by title on date tie breaker 2024-07-21 15:18:31 -07:00
9746c9912b Implement newsreader counting 2024-07-21 15:13:09 -07:00
abaaddae3a Implement unread filtering on threads 2024-07-21 15:12:32 -07:00
0bf64004ff server: order tags alphabetically 2024-07-21 13:09:08 -07:00
6fae9cd018 WIP basic news thread rendering 2024-07-21 12:50:21 -07:00
65fcbd4b77 WIP move thread loading for notmuch into nm mod 2024-07-21 09:31:37 -07:00
dd09bc3168 WIP add search 2024-07-21 09:05:03 -07:00
0bf865fdef WIP reading news from app 2024-07-21 07:53:02 -07:00
5c0c45b99f Revert "Make blockquotes fancier"
This reverts commit 221f046664.
2024-07-13 15:21:59 -07:00
221f046664 Make blockquotes fancier 2024-07-13 09:19:52 -07:00
2a9d5b393e Use default styling for lists. 2024-07-13 09:02:35 -07:00
90860e5511 Remove profile from workspace config 2024-07-13 09:02:19 -07:00
0b1f806276 web: visualize blockquote better 2024-07-12 07:44:31 -07:00
0482713241 address cargo udeps 2024-07-07 15:06:04 -07:00
bb3e18519f cargo update 2024-07-07 14:59:10 -07:00
3a4d08facc web: lint 2024-07-07 14:43:58 -07:00
30064d5904 server: fix broken open-link-in-new-tab from recent changes 2024-07-07 14:40:37 -07:00
c288b7fd67 Disable running test 2024-07-06 18:47:55 -07:00
b4d1528612 web: migrate from lib->bin 2024-07-06 18:18:28 -07:00
5fc272054c Put all URLs under /api/ 2024-07-05 20:00:52 -07:00
714e73aeb1 Address a bunch of lint 2024-07-05 10:44:37 -07:00
3dfd2d48b3 Fix compile error 2024-07-05 10:40:14 -07:00
3a5a9bd66a Add support for inline images 2024-07-05 10:38:12 -07:00
55d7aec516 server: handle multipart/related with a multipart/alternative embedded 2024-05-05 19:03:38 -07:00
96d3e4a7d6 Version bump 2024-05-02 09:30:11 -07:00
beb96aba14 web: fix inverted boolean on spam shortcut 2024-04-29 21:04:56 -07:00
48f66c7096 web: when marking spam, also mark it as read 2024-04-14 08:17:36 -07:00
a96b553b08 Version bumps to get fixes to mailparse & data-encoding 2024-04-14 07:55:26 -07:00
31a3ac66b6 web: swap spam and read/unread buttons 2024-04-08 20:51:56 -07:00
a33e1f5d3c Update lock 2024-04-06 16:22:30 -07:00
423ea10d34 web: use upstream human_format 2024-04-06 16:20:15 -07:00
1b221d5c16 web&server: show raw body contents of UnhandledContentType 2024-04-06 10:21:31 -07:00
d4038f40d6 web: add UI to remove tags when viewing messages 2024-04-06 09:38:00 -07:00
dc7b3dd3e8 web: human format attachment size 2024-04-06 08:52:20 -07:00
1f5f10f78d server: properly filter inline vs attaments 2024-04-06 08:34:26 -07:00
7df11639ed web: don't show text on action icons on tablet/mobile 2024-04-06 08:10:04 -07:00
b0305b7411 web: separate spam button from read buttons and color red. 2024-04-06 08:00:35 -07:00
8abf9398e9 web: add mark as spam buttons 2024-04-03 21:10:23 -07:00
1b196a2703 server: add ability to add/remove labels 2024-04-03 21:07:06 -07:00
a24f456136 web: don't show mime type on attachment 2024-04-03 20:28:51 -07:00
d8fef54606 web: add attachment icons 2024-04-03 20:25:42 -07:00
9a5dc20f83 server: add functioning download attachment handler 2024-03-26 08:25:52 -07:00
ff1c3f5791 server: preserve class attribute on sanitized html 2024-03-26 08:25:37 -07:00
c74cd66826 server: add ability to view inline image attachments 2024-03-24 18:11:15 -07:00
c30cfec09d web: cleanup lint 2024-03-05 09:24:41 -08:00
e20e794508 web: remove mostly useless footer 2024-03-05 09:23:59 -08:00
d09efd3a69 web: overflow:auto the body so wide messages behave better 2024-03-05 09:20:31 -08:00
1ac7f5b6dc web: handle empty subjects 2024-03-05 09:04:19 -08:00
fc7a4a747c web: debug search for tag:letterbox instead of is:unread 2024-02-28 19:13:37 -08:00
facea2326e web: make from and date area clickable on search results page 2024-02-27 09:46:23 -08:00
56311bbe05 web: css cleanup for search results table 2024-02-27 09:07:49 -08:00
994631e872 web: display To/CC differently on expansion 2024-02-26 11:24:09 -08:00
43471d162f web: make empty subject line clickable 2024-02-26 11:01:20 -08:00
b997a61da8 web: better wrapping behavior for plain text messages 2024-02-24 09:14:50 -08:00
f69dd0b198 server: debug print unhandled mimetypes for some multipart messages 2024-02-23 16:55:13 -08:00
523584fbbc web: change style for attachments 2024-02-23 16:54:53 -08:00
4139ec38d8 web: add TODO about message and thread id types 2024-02-23 16:10:17 -08:00
5379ae09dc server: replace string literals in a bunch of places with consts 2024-02-23 16:09:58 -08:00
ebb16aef9e web: make mark read/unread icon target much larger 2024-02-23 07:07:20 -08:00
fc87fd702c web: refacter header rendering code, add more detail when message open 2024-02-22 21:19:09 -08:00
42484043a1 web: have colored initials for From
Add scaffolding for profile pics
2024-02-22 20:37:21 -08:00
3f268415e9 web: rework header in thread view, tweak some styles, remove some logging 2024-02-22 18:54:34 -08:00
c2a5fe19e3 web: go back to search page after changing read status 2024-02-21 17:58:12 -08:00
42ce88d931 web: add select all/partial/none for search table 2024-02-21 15:02:58 -08:00
cda99fc7a5 web: improve checkbox style on desktop 2024-02-20 20:20:50 -08:00
b33a252698 web: label read/unread icons 2024-02-20 20:16:25 -08:00
9e3ae22827 web: lint 2024-02-20 19:59:35 -08:00
5923547159 web: handle expand/collapse of messages separate from unread status 2024-02-20 19:58:50 -08:00
fe980c5468 web: lint 2024-02-20 19:25:28 -08:00
f50fe7196e web: add bulk read/unerad functionality 2024-02-20 19:24:56 -08:00
de3f392bd7 web: use bold text to indicate unread messages 2024-02-20 14:29:42 -08:00
02c0d36f90 web: remove a ton of legacy deprecated code 2024-02-20 14:13:06 -08:00
04592ddcc4 web: change up unread message styles 2024-02-20 13:55:54 -08:00
c8e0f68278 web: remove info statement 2024-02-16 19:24:16 -08:00
4957b485a0 web: add mark read button on search result page 2024-02-16 19:23:35 -08:00
7ebe517a34 web: tweak subject line style 2024-02-11 20:48:26 -08:00
516eedb086 web: add per-message unread control and display 2024-02-11 20:29:49 -08:00
ce836cd1e8 notmuch: add tag manipulation 2024-02-11 19:59:20 -08:00
f7010fa278 cargo update 2024-02-11 19:54:35 -08:00
5451dd2056 server: add mutation to mark messages as read 2024-02-11 19:43:34 -08:00
81ed3a8ca2 Linkify URLs missing schema 2024-02-07 19:41:34 -08:00
0f1a60a348 Sanitize html when linkifying plain text. 2024-02-03 11:15:57 -08:00
c59a883351 Address lint. 2024-02-03 11:14:43 -08:00
568d83f029 linkify URLs in plaintext emails. 2024-02-03 11:10:51 -08:00
569781b592 Tweak CSS for viewing body of messages 2024-01-20 08:34:25 -08:00
1b00c9e944 Updated cargo lock 2024-01-20 08:14:59 -08:00
901785e47c Change footer class to prevent conflict with email bodies. 2024-01-20 08:14:37 -08:00
8c47f01758 Improve server side html sanitization. 2024-01-20 08:14:10 -08:00
304819275d Open links in a new tab. 2024-01-19 21:07:24 -08:00
b1ea44963d Lint and cleanup empty file. 2024-01-17 12:31:56 -08:00
181965968c state: auto reload every 30 seconds 2024-01-17 12:31:37 -08:00
5b3eadb7bd Run tests before rebuilding app 2024-01-06 08:53:06 -08:00
28d484117b Change makefile to use variable for app name.
Make this more copypastable.
2024-01-06 08:52:42 -08:00
a0b0689e01 Fix wrapping/sizing of message bodies with long unbreakable text. 2024-01-06 08:52:19 -08:00
33ec63f097 web: update seed_hooks to my copy so I can pin to seed=0.10.0 2023-12-10 19:42:07 -08:00
7b22f85429 web: show union of tags when viewing thread 2023-12-10 17:26:24 -08:00
fa7df55b0e server: send tags on each message in thread 2023-12-10 17:26:04 -08:00
d2cf270dda web: properly truncate long headers on message view 2023-12-10 16:35:51 -08:00
f1b5e78962 web: make debug output hidden by default 2023-12-10 16:11:15 -08:00
fae4e43682 web: show thread count when greater than 1 2023-12-10 15:50:28 -08:00
37eb3d1dfd web: wrap content tree debug so messages aren't super wide 2023-12-07 10:24:39 -08:00
e0890f1181 web: search for unread tags when clicking under Unread section 2023-12-05 20:55:41 -08:00
c31f9d581f web: upgrade to seed-0.10.0 2023-12-05 20:46:59 -08:00
f2347345b4 Version bumps made css_inline uncompilable for wasm 2023-12-05 14:12:15 -08:00
e34f2a1f39 notmuch: fix tests 2023-12-05 12:50:52 -08:00
7a6000be26 server: address lint 2023-12-05 11:26:23 -08:00
dd1a8c2eae procmail2notmuch: WIP update script 2023-12-05 11:23:04 -08:00
42590b3cbc cargo update 2023-12-05 11:04:31 -08:00
94f7ad109a Merge commit 'f6bdf30' 2023-12-05 09:56:55 -08:00
f6bdf302fe server & notmuch: more attachment WIP, stop leaking notmuch processes 2023-12-03 14:01:18 -08:00
b76c535738 web: use log::error, not seed::error 2023-12-03 09:11:31 -08:00
29949c703d web: archive live site before pushing new one 2023-12-03 09:11:15 -08:00
f5f9eb175d server: WIP attachment serving 2023-12-03 09:11:00 -08:00
488c3b86f8 web: truncate raw messages and prep for attachments 2023-12-03 09:03:36 -08:00
be8fd59703 web: rename view_thread to take advantage of new namespaces 2023-12-03 08:49:20 -08:00
071fe2e206 web: show message-ID when viewing thread 2023-12-02 16:35:37 -08:00
ac5660a6d0 web: have trunk proxy /original/ requests to backend 2023-12-02 16:35:18 -08:00
99a104517d notmuch: comment typo 2023-12-02 16:35:05 -08:00
c3692cadec server: add id and header to ShowThreadQuery API 2023-12-02 16:34:44 -08:00
b14000952c server: make unread message counting much faster, remove rayon dep 2023-12-02 15:41:22 -08:00
7a32d5c630 server: include headers in debug output 2023-12-02 15:12:40 -08:00
714b057fdb web: add tablet rendering, listen to window resize events. 2023-12-02 10:56:14 -08:00
4c2526c70b web: remove unnecessary view_mobile_ prefix 2023-12-02 10:13:08 -08:00
a8f4aa03bd web: rename legacy functions to take advantage of mod namespacing 2023-12-02 10:11:56 -08:00
28d5562491 web: move legacy (pre-graphql) rendering to separate mod 2023-12-02 10:07:47 -08:00
e6f20e538a web: move mobile specific code to separate mod 2023-12-02 10:02:12 -08:00
970bb55c73 web: move desktop specific code into separate mod 2023-12-02 09:56:57 -08:00
12f0491455 web: remove stale comments 2023-12-02 09:34:57 -08:00
ef8362d6f2 web: remove some unused code 2023-12-02 09:34:26 -08:00
0a7cdefda3 web: refactor code into separate modules 2023-12-02 09:29:50 -08:00
cfe1446668 web: for tag list to be open when no unread messages 2023-11-29 09:27:53 -08:00
7c38962d21 web: make tag list hidable 2023-11-28 20:03:17 -08:00
7102f26c9e web: conditionally show unread section 2023-11-28 07:32:22 -08:00
71a3315fe8 web: lint and clean up search input handling 2023-11-27 21:11:12 -08:00
7cac81cddb web: update implement_email macro to handle repetition 2023-11-27 20:33:47 -08:00
3a5ca74d71 web: change tag list styling and show unread at the top 2023-11-27 19:48:19 -08:00
71af8179ec web: hierarchical tags list on desktop 2023-11-27 19:16:28 -08:00
d66a7d3d53 web: use singular version of view_address for From 2023-11-27 17:20:11 -08:00
e0fbb0253e web: create implement_email! macro 2023-11-27 17:16:57 -08:00
48466808d3 web & server: plumb debugging info for content type hierarchy.
Also cleanup Email trait.
2023-11-27 13:47:02 -08:00
87dfe4ace7 server: cleanup lint. 2023-11-26 21:31:06 -08:00
d45f223d52 server: fix pagination with small counts and no first/last set 2023-11-26 21:27:57 -08:00
e8c58bdbd0 server: handle multipart/mixed with an html or text subpart 2023-11-26 21:09:56 -08:00
87d687cde5 server: sanitize html using ammonia 2023-11-26 21:00:44 -08:00
c8147ded60 web & server: add handling for google calendar and wellsfargo emails. 2023-11-26 20:51:53 -08:00
1261bdf8a9 web & server: improved debug printing of unhandled mime types 2023-11-26 18:50:32 -08:00
11366b6fac web & server: implement handling for text and html bodies. 2023-11-26 16:37:29 -08:00
1cdabc348b web: better date formatting 2023-11-26 16:01:22 -08:00
02e16b4547 web: more compact output on desktop and mobile 2023-11-26 15:46:03 -08:00
d5a001bf03 web: refresh tags on thread view in addition to search results. 2023-11-26 15:31:51 -08:00
0ae72b63d0 web: add basic graphql view thread, no body support. 2023-11-26 15:27:19 -08:00
447a4a3387 server: basic graphql thread show, no body support yet. 2023-11-26 13:13:04 -08:00
0737f5aac5 web: rewrite frontend to use graphql for search results 2023-11-25 09:06:24 -08:00
3e3024dd5c server: handle search with no first/last better 2023-11-25 09:05:53 -08:00
24414b04bb server: fix backward pagination 2023-11-25 08:39:56 -08:00
f7df834325 notmuch: default empty search to wildcard 2023-11-25 08:39:30 -08:00
bce2c741c4 web: add non-functional graphql. 2023-11-21 14:06:48 -08:00
1b44bc57bb web: Initial commit of graphql schema and helper to update it. 2023-11-21 13:36:11 -08:00
ff6675b08f server: add unread field to tag query.
Optionally fill out unread, as it's expensive.
2023-11-21 13:17:11 -08:00
64912be4eb Hide quoted emails 2023-11-21 12:37:58 -08:00
57ccef18cb Make clicking search results on mobile easier. 2023-11-21 12:27:58 -08:00
2a24a20529 Revert stub show_pretty that will be obsoleted by graphql. 2023-11-21 08:35:35 -08:00
e6692059b4 Fix search pagination and add count RPC. 2023-11-20 21:18:40 -08:00
a7b172099b And graphql search with pagination. 2023-11-20 20:56:16 -08:00
f52a76dba3 Added graphql endpoint and tested with tags implementation. 2023-11-20 18:38:10 -08:00
43e4334890 Set default page size on server to match client side page size. 2023-11-20 17:57:07 -08:00
1d00bdb757 Squelch logging and remove unused variable. 2023-11-20 17:54:50 -08:00
6901c9fde9 Formate today and yesterday better. 2023-11-20 17:53:49 -08:00
6251c54873 Show time of email >1 week 2023-11-20 17:47:06 -08:00
f6c1835b18 Custom formatting of the age string, widen subject column. 2023-11-20 17:41:58 -08:00
95976c2860 Mobile style tweaks. 2023-11-20 15:49:30 -08:00
01589d7136 Add favicon 2023-11-20 15:40:07 -08:00
a2664473c8 Improve density on mobile. 2023-11-14 21:33:09 -08:00
da15ef0f15 Move main.rs to bin/ and stub some message stuff. 2023-11-06 18:41:12 -08:00
035508f3ad Better use of space on search table for desktop. 2023-11-05 08:36:14 -08:00
69558f15b4 Properly perform right data request on fresh page load. 2023-11-05 08:07:14 -08:00
a8f538eddf Show navbar at bottom of page too. 2023-09-24 13:13:26 -07:00
01e5ea14ab URL decode queries. 2023-09-05 09:49:59 -07:00
042d475c75 Style tweaks 2023-09-02 13:10:44 -07:00
dd0af52feb cargo update 2023-09-02 13:10:34 -07:00
130f9bbeba Use Trunk.toml for trunk config. 2023-09-02 13:10:17 -07:00
0a05b32a7a Remove 'TEST' text when viewing certain email types 2023-09-02 09:00:36 -07:00
c3f897c61a Fix pagination and default homepage to unread search. 2023-08-11 16:51:41 -07:00
c62bac037f Reload page on refresh 2023-08-11 14:06:47 -07:00
79a57f3082 Address workspace lint 2023-08-11 13:55:39 -07:00
c33de9d754 cargo update 2023-07-15 16:58:40 -07:00
46 changed files with 9441 additions and 2306 deletions

10
.envrc Normal file
View File

@@ -0,0 +1,10 @@
source_up
export DATABASE_USER="newsreader";
export DATABASE_NAME="newsreader";
export DATABASE_HOST="nixos-07.h.xinu.tv";
export DATABASE_URL="postgres://${DATABASE_USER}@${DATABASE_HOST}/${DATABASE_NAME}";
export PROD_DATABASE_USER="newsreader";
export PROD_DATABASE_NAME="newsreader";
export PROD_DATABASE_HOST="postgres.h.xinu.tv";
export PROD_DATABASE_URL="postgres://${PROD_DATABASE_USER}@${PROD_DATABASE_HOST}/${PROD_DATABASE_NAME}";

3565
Cargo.lock generated

File diff suppressed because it is too large Load Diff

4
dev.sh
View File

@@ -1,7 +1,7 @@
cd -- "$( dirname -- "${BASH_SOURCE[0]}" )"
tmux new-session -d -s letterbox-dev
tmux rename-window web
tmux send-keys "cd web; trunk serve --release --address 0.0.0.0 --port 6758 --proxy-backend http://localhost:9345/ --proxy-rewrite=/api/ -w ../shared -w ../notmuch -w ./" C-m
tmux send-keys "cd web; trunk serve -w ../shared -w ../notmuch -w ./" C-m
tmux new-window -n server
tmux send-keys "cd server; cargo watch -x run -w ../shared -w ../notmuch -w ./" C-m
tmux send-keys "cd server; cargo watch -c -x run -w ../shared -w ../notmuch -w ./" C-m
tmux attach -d -t letterbox-dev

View File

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

View File

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

10
procmail2notmuch/update.sh Executable file
View File

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

View File

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

View File

@@ -7,3 +7,4 @@ address = "0.0.0.0"
port = 9345
# Uncomment to make it production like.
#log_level = "critical"
newsreader_database_url = "postgres://newsreader@nixos-07.h.xinu.tv/newsreader"

10
server/sql/count.sql Normal file
View File

@@ -0,0 +1,10 @@
SELECT
COUNT(*) count
FROM
post
WHERE
site = $1
AND (
NOT $2
OR NOT is_read
)

21
server/sql/tags.sql Normal file
View File

@@ -0,0 +1,21 @@
SELECT
site,
name,
count (
NOT is_read
OR NULL
) unread
FROM
post AS p
JOIN feed AS f ON p.site = f.slug --
-- TODO: figure this out to make the query faster when only looking for unread
--WHERE
-- (
-- NOT $1
-- OR NOT is_read
-- )
GROUP BY
1,
2
ORDER BY
site

14
server/sql/thread.sql Normal file
View File

@@ -0,0 +1,14 @@
SELECT
date,
is_read,
link,
site,
summary,
title,
name,
homepage
FROM
post p
JOIN feed f ON p.site = f.slug
WHERE
uid = $1

20
server/sql/threads.sql Normal file
View File

@@ -0,0 +1,20 @@
SELECT
date,
is_read,
title,
uid,
name
FROM
post p
JOIN feed f ON p.site = f.slug
WHERE
site = $1
AND (
NOT $2
OR NOT is_read
)
ORDER BY
date DESC,
title OFFSET $3
LIMIT
$4

View File

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

238
server/src/bin/server.rs Normal file
View File

@@ -0,0 +1,238 @@
#[macro_use]
extern crate rocket;
use std::{error::Error, io::Cursor, str::FromStr};
use async_graphql::{http::GraphiQLSource, EmptySubscription, Schema};
use async_graphql_rocket::{GraphQLQuery, GraphQLRequest, GraphQLResponse};
use glog::Flags;
use notmuch::{Notmuch, NotmuchError, ThreadSet};
use rocket::{
fairing::AdHoc,
http::{ContentType, Header},
request::Request,
response::{content, Debug, Responder},
serde::json::Json,
Response, State,
};
use rocket_cors::{AllowedHeaders, AllowedOrigins};
use serde::Deserialize;
use server::{
error::ServerError,
graphql::{Attachment, GraphqlSchema, Mutation, QueryRoot},
nm::{attachment_bytes, cid_attachment_bytes},
};
use sqlx::postgres::PgPool;
#[derive(Deserialize)]
struct Config {
newsreader_database_url: String,
}
#[get("/refresh")]
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
Ok(Json(String::from_utf8_lossy(&nm.new()?).to_string()))
}
#[get("/show/<query>/pretty")]
async fn show_pretty(
nm: &State<Notmuch>,
query: &str,
) -> Result<Json<ThreadSet>, Debug<ServerError>> {
let query = urlencoding::decode(query).map_err(|e| ServerError::from(NotmuchError::from(e)))?;
let res = nm.show(&query).map_err(ServerError::from)?;
Ok(Json(res))
}
#[get("/show/<query>")]
async fn show(nm: &State<Notmuch>, query: &str) -> Result<Json<ThreadSet>, Debug<NotmuchError>> {
let query = urlencoding::decode(query).map_err(NotmuchError::from)?;
let res = nm.show(&query)?;
Ok(Json(res))
}
struct InlineAttachmentResponder(Attachment);
impl<'r, 'o: 'r> Responder<'r, 'o> for InlineAttachmentResponder {
fn respond_to(self, _: &'r Request<'_>) -> rocket::response::Result<'o> {
let mut resp = Response::build();
if let Some(filename) = self.0.filename {
resp.header(Header::new(
"Content-Disposition",
format!(r#"inline; filename="{}""#, filename),
));
}
if let Some(content_type) = self.0.content_type {
if let Some(ct) = ContentType::parse_flexible(&content_type) {
resp.header(ct);
}
}
resp.sized_body(self.0.bytes.len(), Cursor::new(self.0.bytes))
.ok()
}
}
struct DownloadAttachmentResponder(Attachment);
impl<'r, 'o: 'r> Responder<'r, 'o> for DownloadAttachmentResponder {
fn respond_to(self, _: &'r Request<'_>) -> rocket::response::Result<'o> {
let mut resp = Response::build();
if let Some(filename) = self.0.filename {
resp.header(Header::new(
"Content-Disposition",
format!(r#"attachment; filename="{}""#, filename),
));
}
if let Some(content_type) = self.0.content_type {
if let Some(ct) = ContentType::parse_flexible(&content_type) {
resp.header(ct);
}
}
resp.sized_body(self.0.bytes.len(), Cursor::new(self.0.bytes))
.ok()
}
}
#[get("/cid/<id>/<cid>")]
async fn view_cid(
nm: &State<Notmuch>,
id: &str,
cid: &str,
) -> Result<InlineAttachmentResponder, Debug<ServerError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
info!("view cid attachment {mid} {cid}");
let attachment = cid_attachment_bytes(nm, &mid, &cid)?;
Ok(InlineAttachmentResponder(attachment))
}
#[get("/view/attachment/<id>/<idx>/<_>")]
async fn view_attachment(
nm: &State<Notmuch>,
id: &str,
idx: &str,
) -> Result<InlineAttachmentResponder, Debug<ServerError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
info!("view attachment {mid} {idx}");
let idx: Vec<_> = idx
.split('.')
.map(|s| s.parse().expect("not a usize"))
.collect();
let attachment = attachment_bytes(nm, &mid, &idx)?;
Ok(InlineAttachmentResponder(attachment))
}
#[get("/download/attachment/<id>/<idx>/<_>")]
async fn download_attachment(
nm: &State<Notmuch>,
id: &str,
idx: &str,
) -> Result<DownloadAttachmentResponder, Debug<ServerError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
info!("download attachment {mid} {idx}");
let idx: Vec<_> = idx
.split('.')
.map(|s| s.parse().expect("not a usize"))
.collect();
let attachment = attachment_bytes(nm, &mid, &idx)?;
Ok(DownloadAttachmentResponder(attachment))
}
#[get("/original/<id>")]
async fn original(
nm: &State<Notmuch>,
id: &str,
) -> Result<(ContentType, Vec<u8>), Debug<NotmuchError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
let res = nm.show_original(&mid)?;
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()
.init(Flags {
colorlogtostderr: true,
//alsologtostderr: true, // use logtostderr to only write to stderr and not to files
logtostderr: true,
..Default::default()
})
.unwrap();
let allowed_origins = AllowedOrigins::all();
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec!["Get"]
.into_iter()
.map(|s| FromStr::from_str(s).unwrap())
.collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()?;
let rkt = rocket::build()
.mount(
shared::urls::MOUNT_POINT,
routes![
original,
refresh,
show_pretty,
show,
graphql_query,
graphql_request,
graphiql,
view_cid,
view_attachment,
download_attachment,
],
)
.attach(cors)
.attach(AdHoc::config::<Config>());
let config: Config = rkt.figment().extract()?;
let pool = PgPool::connect(&config.newsreader_database_url).await?;
let schema = Schema::build(QueryRoot, Mutation, EmptySubscription)
.data(Notmuch::default())
.data(pool.clone())
.extension(async_graphql::extensions::Logger)
.finish();
let rkt = rkt.manage(schema).manage(pool).manage(Notmuch::default());
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
rkt.launch().await?;
Ok(())
}

34
server/src/error.rs Normal file
View File

@@ -0,0 +1,34 @@
use std::{convert::Infallible, str::Utf8Error, string::FromUtf8Error};
use mailparse::MailParseError;
use thiserror::Error;
use crate::SanitizeError;
#[derive(Error, Debug)]
pub enum ServerError {
#[error("notmuch: {0}")]
NotmuchError(#[from] notmuch::NotmuchError),
#[error("flatten")]
FlattenError,
#[error("mail parse error: {0}")]
MailParseError(#[from] MailParseError),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
#[error("attachement not found")]
PartNotFound,
#[error("sqlx error: {0}")]
SQLXError(#[from] sqlx::Error),
#[error("html sanitize error: {0}")]
SanitizeError(#[from] SanitizeError),
#[error("UTF8 error: {0}")]
Utf8Error(#[from] Utf8Error),
#[error("FromUTF8 error: {0}")]
FromUtf8Error(#[from] FromUtf8Error),
#[error("error: {0}")]
StringError(String),
#[error("invalid url: {0}")]
UrlParseError(#[from] url::ParseError),
#[error("impossible: {0}")]
InfaillibleError(#[from] Infallible),
}

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

@@ -0,0 +1,308 @@
use async_graphql::{
connection::{Connection},
Context, EmptySubscription, Enum, Error, FieldResult, Object, Schema, SimpleObject, Union,
};
use log::info;
use notmuch::Notmuch;
use sqlx::postgres::PgPool;
use crate::{newsreader, nm};
/// # 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 {
pub thread_id: String,
pub subject: String,
pub 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(Default, Debug, SimpleObject)]
pub struct Attachment {
pub id: String,
pub idx: String,
pub filename: Option<String>,
pub size: usize,
pub content_type: Option<String>,
pub content_id: Option<String>,
pub disposition: DispositionType,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Disposition {
pub r#type: DispositionType,
pub filename: Option<String>,
pub size: Option<usize>,
}
#[derive(Debug, Enum, Copy, Clone, Eq, PartialEq)]
pub enum DispositionType {
Inline,
Attachment,
}
impl From<mailparse::DispositionType> for DispositionType {
fn from(value: mailparse::DispositionType) -> Self {
match value {
mailparse::DispositionType::Inline => DispositionType::Inline,
mailparse::DispositionType::Attachment => DispositionType::Attachment,
dt => panic!("unhandled DispositionType {dt:?}"),
}
}
}
impl Default for DispositionType {
fn default() -> Self {
DispositionType::Attachment
}
}
#[derive(Debug, SimpleObject)]
pub struct Header {
pub key: String,
pub value: String,
}
#[derive(Debug)]
pub struct UnhandledContentType {
pub text: String,
pub content_tree: String,
}
#[Object]
impl UnhandledContentType {
async fn contents(&self) -> &str {
&self.text
}
async fn content_tree(&self) -> &str {
&self.content_tree
}
}
#[derive(Debug)]
pub struct PlainText {
pub text: String,
pub 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 {
pub html: String,
pub 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 {
pub fn html(html: String) -> Body {
Body::Html(Html {
html,
content_tree: "".to_string(),
})
}
pub 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)]
pub(crate) struct Tag {
pub name: String,
pub fg_color: String,
pub bg_color: String,
pub unread: usize,
}
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn count<'ctx>(&self, ctx: &Context<'ctx>, query: String) -> Result<usize, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
let pool = ctx.data_unchecked::<PgPool>();
// TODO: make this search both copra and merge results
if newsreader::is_newsreader_search(&query) {
Ok(newsreader::count(pool, &query).await?)
} else {
Ok(nm::count(nm, &query).await?)
}
}
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> {
info!("search({after:?} {before:?} {first:?} {last:?} {query:?})");
let nm = ctx.data_unchecked::<Notmuch>();
let pool = ctx.data_unchecked::<PgPool>();
// TODO: make this search both copra and merge results
if newsreader::is_newsreader_search(&query) {
Ok(newsreader::search(pool, after, before, first, last, query).await?)
} else {
Ok(nm::search(nm, after, before, first, last, query).await?)
}
}
async fn tags<'ctx>(&self, ctx: &Context<'ctx>) -> FieldResult<Vec<Tag>> {
let nm = ctx.data_unchecked::<Notmuch>();
let pool = ctx.data_unchecked::<PgPool>();
let needs_unread = ctx.look_ahead().field("unread").exists();
let mut tags = newsreader::tags(pool, needs_unread).await?;
tags.append(&mut nm::tags(nm, needs_unread)?);
Ok(tags)
}
async fn thread<'ctx>(&self, ctx: &Context<'ctx>, thread_id: String) -> Result<Thread, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
let pool = ctx.data_unchecked::<PgPool>();
let debug_content_tree = ctx
.look_ahead()
.field("messages")
.field("body")
.field("contentTree")
.exists();
// TODO: look at thread_id and conditionally load newsreader
if newsreader::is_newsreader_thread(&thread_id) {
Ok(newsreader::thread(pool, thread_id).await?)
} else {
Ok(nm::thread(nm, thread_id, debug_content_tree).await?)
}
}
}
pub struct Mutation;
#[Object]
impl Mutation {
async fn set_read_status<'ctx>(
&self,
ctx: &Context<'ctx>,
query: String,
unread: bool,
) -> Result<bool, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
info!("set_read_status({unread})");
if unread {
nm.tag_add("unread", &format!("{query}"))?;
} else {
nm.tag_remove("unread", &format!("{query}"))?;
}
Ok(true)
}
async fn tag_add<'ctx>(
&self,
ctx: &Context<'ctx>,
query: String,
tag: String,
) -> Result<bool, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
info!("tag_add({tag}, {query})");
nm.tag_add(&tag, &query)?;
Ok(true)
}
async fn tag_remove<'ctx>(
&self,
ctx: &Context<'ctx>,
query: String,
tag: String,
) -> Result<bool, Error> {
let nm = ctx.data_unchecked::<Notmuch>();
info!("tag_remove({tag}, {query})");
nm.tag_remove(&tag, &query)?;
Ok(true)
}
}
pub type GraphqlSchema = Schema<QueryRoot, Mutation, EmptySubscription>;

278
server/src/lib.rs Normal file
View File

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

View File

@@ -1,164 +0,0 @@
#[macro_use]
extern crate rocket;
mod error;
mod nm;
use std::{error::Error, io::Cursor, str::FromStr};
use glog::Flags;
use notmuch::{Notmuch, NotmuchError};
use rocket::{
http::{ContentType, Header},
request::Request,
response::{Debug, Responder},
serde::json::Json,
Response, State,
};
use rocket_cors::{AllowedHeaders, AllowedOrigins};
use crate::error::ServerError;
#[get("/")]
fn hello() -> &'static str {
"Hello, world!"
}
#[get("/refresh")]
async fn refresh(nm: &State<Notmuch>) -> Result<Json<String>, Debug<NotmuchError>> {
Ok(Json(String::from_utf8_lossy(&nm.new()?).to_string()))
}
#[get("/search")]
async fn search_all(
nm: &State<Notmuch>,
) -> Result<Json<shared::SearchResult>, Debug<NotmuchError>> {
search(nm, "*", None, None).await
}
#[get("/search/<query>?<page>&<results_per_page>")]
async fn search(
nm: &State<Notmuch>,
query: &str,
page: Option<usize>,
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);
info!(" search '{query}'");
let res = shared::SearchResult {
summary: nm.search(query, page * results_per_page, results_per_page)?,
query: query.to_string(),
page,
results_per_page,
total: nm.count(query)?,
};
Ok(Json(res))
}
#[get("/show/<query>")]
async fn show(
nm: &State<Notmuch>,
query: &str,
) -> Result<Json<Vec<shared::Message>>, Debug<ServerError>> {
let res = nm::threadset_to_messages(nm.show(query).map_err(|e| -> ServerError { e.into() })?)?;
Ok(Json(res))
}
struct PartResponder {
bytes: Vec<u8>,
filename: Option<String>,
}
impl<'r, 'o: 'r> Responder<'r, 'o> for PartResponder {
fn respond_to(self, _: &'r Request<'_>) -> rocket::response::Result<'o> {
let mut resp = Response::build();
if let Some(filename) = self.filename {
info!("filename {:?}", filename);
resp.header(Header::new(
"Content-Disposition",
format!(r#"attachment; filename="{}""#, filename),
))
.header(ContentType::Binary);
}
resp.sized_body(self.bytes.len(), Cursor::new(self.bytes))
.ok()
}
}
#[get("/original/<id>/part/<part>")]
async fn original_part(
nm: &State<Notmuch>,
id: &str,
part: usize,
) -> Result<PartResponder, Debug<NotmuchError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
let meta = nm.show_part(&mid, part)?;
let res = nm.show_original_part(&mid, part)?;
Ok(PartResponder {
bytes: res,
filename: meta.filename,
})
}
#[get("/original/<id>")]
async fn original(
nm: &State<Notmuch>,
id: &str,
) -> Result<(ContentType, Vec<u8>), Debug<NotmuchError>> {
let mid = if id.starts_with("id:") {
id.to_string()
} else {
format!("id:{}", id)
};
let res = nm.show_original(&mid)?;
Ok((ContentType::Plain, res))
}
#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
glog::new()
.init(Flags {
colorlogtostderr: true,
//alsologtostderr: true, // use logtostderr to only write to stderr and not to files
logtostderr: true,
..Default::default()
})
.unwrap();
let allowed_origins = AllowedOrigins::all();
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec!["Get"]
.into_iter()
.map(|s| FromStr::from_str(s).unwrap())
.collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()?;
let _ = rocket::build()
.mount(
"/",
routes![
original_part,
original,
hello,
refresh,
search_all,
search,
show
],
)
.attach(cors)
.manage(Notmuch::default())
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
.launch()
.await?;
Ok(())
}

281
server/src/newsreader.rs Normal file
View File

@@ -0,0 +1,281 @@
use std::{
convert::Infallible,
hash::{DefaultHasher, Hash, Hasher},
str::FromStr,
};
use async_graphql::connection::{self, Connection, Edge};
use log::info;
use sqlx::postgres::PgPool;
use url::Url;
const TAG_PREFIX: &'static str = "News/";
const THREAD_PREFIX: &'static str = "news:";
use crate::{
error::ServerError,
graphql::{Body, Email, Html, Message, Tag, Thread, ThreadSummary},
sanitize_html,
};
pub fn is_newsreader_search(query: &str) -> bool {
query.contains(TAG_PREFIX)
}
pub fn is_newsreader_thread(query: &str) -> bool {
query.starts_with(THREAD_PREFIX)
}
pub async fn count(pool: &PgPool, query: &str) -> Result<usize, ServerError> {
let query: Query = query.parse()?;
let site = query.site.expect("search has no site");
let row = sqlx::query_file!("sql/count.sql", site, query.unread_only)
.fetch_one(pool)
.await?;
Ok(row.count.unwrap_or(0).try_into().unwrap_or(0))
}
pub async fn search(
pool: &PgPool,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
query: String,
) -> Result<Connection<usize, ThreadSummary>, async_graphql::Error> {
let query: Query = query.parse()?;
info!("news search query {query:?}");
let site = query.site.expect("search has no site");
connection::query(
after,
before,
first,
last,
|after: Option<usize>, before: Option<usize>, first, last| async move {
info!("search page info {after:#?}, {before:#?}, {first:#?}, {last:#?}");
let default_page_size = 100;
let (offset, limit) = match (after, before, first, last) {
// Reasonable defaults
(None, None, None, None) => (0, default_page_size),
(None, None, Some(first), None) => (0, first),
(Some(after), None, None, None) => (after, default_page_size),
(Some(after), None, Some(first), None) => (after, first),
(None, Some(before), None, None) => {
(before.saturating_sub(default_page_size), default_page_size)
}
(None, Some(before), None, Some(last)) => (before.saturating_sub(last), last),
(None, None, None, Some(_)) => {
panic!("specifying last and no before doesn't make sense")
}
(None, None, Some(_), Some(_)) => {
panic!("specifying first and last doesn't make sense")
}
(None, Some(_), Some(_), _) => {
panic!("specifying before and first doesn't make sense")
}
(Some(_), Some(_), _, _) => {
panic!("specifying after and before doesn't make sense")
}
(Some(_), None, None, Some(_)) => {
panic!("specifying after and last doesn't make sense")
}
(Some(_), None, Some(_), Some(_)) => {
panic!("specifying after, first and last doesn't make sense")
}
};
// The +1 is to see if there are more pages of data available.
let limit = limit + 1;
info!("search page offset {offset} limit {limit}");
let rows = sqlx::query_file!(
"sql/threads.sql",
site,
query.unread_only,
offset as i64,
limit as i64
)
.fetch_all(pool)
.await?;
let mut slice = rows
.into_iter()
.map(|r| {
let tags = if r.is_read.unwrap_or(false) {
vec![site.clone()]
} else {
vec!["unread".to_string(), site.clone()]
};
ThreadSummary {
thread: format!("{THREAD_PREFIX}{}", r.uid),
timestamp: r
.date
.expect("post missing date")
.assume_utc()
.unix_timestamp() as isize,
date_relative: "TODO date_relative".to_string(),
matched: 0,
total: 1,
authors: r.name.unwrap_or_else(|| site.clone()),
subject: r.title.unwrap_or("NO TITLE".to_string()),
tags,
}
})
.collect::<Vec<_>>();
let has_more = slice.len() == limit;
let mut connection = Connection::new(offset > 0, has_more);
if has_more {
slice.pop();
};
connection.edges.extend(
slice
.into_iter()
.enumerate()
.map(|(idx, item)| Edge::new(offset + idx, item)),
);
Ok::<_, async_graphql::Error>(connection)
},
)
.await
}
pub async fn tags(pool: &PgPool, _needs_unread: bool) -> Result<Vec<Tag>, ServerError> {
// TODO: optimize query by using needs_unread
let tags = sqlx::query_file!("sql/tags.sql").fetch_all(pool).await?;
let tags = tags
.into_iter()
.map(|tag| {
let mut hasher = DefaultHasher::new();
tag.site.hash(&mut hasher);
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
let unread = tag.unread.unwrap_or(0).try_into().unwrap_or(0);
let name = format!("{TAG_PREFIX}{}", tag.site.expect("tag must have site"));
Tag {
name,
fg_color: "white".to_string(),
bg_color: hex,
unread,
}
})
.collect();
Ok(tags)
}
pub async fn thread(pool: &PgPool, thread_id: String) -> Result<Thread, ServerError> {
let id = thread_id
.strip_prefix(THREAD_PREFIX)
.expect("news thread doesn't start with '{THREAD_PREFIX}'")
.to_string();
let r = sqlx::query_file!("sql/thread.sql", id)
.fetch_one(pool)
.await?;
let site = r.site.unwrap_or("NO SITE".to_string());
let tags = if r.is_read.unwrap_or(false) {
vec![site.clone()]
} else {
vec!["unread".to_string(), site.clone()]
};
let default_homepage = "http://no-homepage";
let homepage = Url::parse(
&r.homepage
.map(|h| {
if h.is_empty() {
default_homepage.to_string()
} else {
h
}
})
.unwrap_or(default_homepage.to_string()),
)?;
let link = Url::parse(
&r.link
.as_ref()
.map(|h| {
if h.is_empty() {
default_homepage.to_string()
} else {
h.to_string()
}
})
.unwrap_or(default_homepage.to_string()),
)?;
let addr = r.link.as_ref().map(|link| {
if link.contains('@') {
link.clone()
} else {
if let Ok(url) = homepage.join(&link) {
url.to_string()
} else {
link.clone()
}
}
});
let html = r.summary.unwrap_or("NO SUMMARY".to_string());
// TODO: add site specific cleanups. For example:
// * Grafana does <div class="image-wrapp"><img class="lazyload>"<img src="/media/...>"</img></div>
// * Some sites appear to be HTML encoded, unencode them, i.e. imperialviolet
let html = sanitize_html(&html, "", &link)?;
let body = Body::Html(Html {
html,
content_tree: "".to_string(),
});
let title = r.title.unwrap_or("NO TITLE".to_string());
let from = Some(Email {
name: r.name,
addr: addr.map(|a| a.to_string()),
});
Ok(Thread {
thread_id,
subject: title.clone(),
messages: vec![Message {
id,
from,
to: Vec::new(),
cc: Vec::new(),
subject: Some(title),
timestamp: Some(
r.date
.expect("post missing date")
.assume_utc()
.unix_timestamp(),
),
headers: Vec::new(),
body,
path: "".to_string(),
attachments: Vec::new(),
tags,
}],
})
}
#[derive(Debug)]
struct Query {
unread_only: bool,
site: Option<String>,
remainder: Vec<String>,
}
impl FromStr for Query {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut unread_only = false;
let mut site = None;
let mut remainder = Vec::new();
let site_prefix = format!("tag:{TAG_PREFIX}");
for word in s.split_whitespace() {
if word == "is:unread" {
unread_only = true
} else if word.starts_with(&site_prefix) {
site = Some(word[site_prefix.len()..].to_string())
} else {
remainder.push(word.to_string());
}
}
Ok(Query {
unread_only,
site,
remainder,
})
}
}

754
server/src/nm.rs Normal file
View File

@@ -0,0 +1,754 @@
use std::{
collections::HashMap,
fs::File,
hash::{DefaultHasher, Hash, Hasher},
time::Instant,
};
use async_graphql::connection::{self, Connection, Edge};
use log::{error, info, warn};
use mailparse::{parse_mail, MailHeader, MailHeaderMap, ParsedMail};
use memmap::MmapOptions;
use notmuch::Notmuch;
use url::Url;
use crate::{
error::ServerError,
graphql::{
Attachment, Body, DispositionType, Email, Header, Html, Message, PlainText, Tag, Thread,
ThreadSummary, UnhandledContentType,
},
linkify_html, sanitize_html,
};
const TEXT_PLAIN: &'static str = "text/plain";
const TEXT_HTML: &'static str = "text/html";
const IMAGE_JPEG: &'static str = "image/jpeg";
const IMAGE_PNG: &'static str = "image/png";
const MULTIPART_ALTERNATIVE: &'static str = "multipart/alternative";
const MULTIPART_MIXED: &'static str = "multipart/mixed";
const MULTIPART_RELATED: &'static str = "multipart/related";
const MAX_RAW_MESSAGE_SIZE: usize = 100_000;
// TODO(wathiede): decide good error type
pub fn threadset_to_messages(thread_set: notmuch::ThreadSet) -> Result<Vec<Message>, ServerError> {
for t in thread_set.0 {
for _tn in t.0 {}
}
Ok(Vec::new())
}
pub async fn count(nm: &Notmuch, query: &str) -> Result<usize, ServerError> {
Ok(nm.count(query)?)
}
pub async fn search(
nm: &Notmuch,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
query: String,
) -> Result<Connection<usize, ThreadSummary>, async_graphql::Error> {
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::<_, async_graphql::Error>(connection)
},
)
.await
}
pub fn tags(nm: &Notmuch, needs_unread: bool) -> Result<Vec<Tag>, ServerError> {
let now = Instant::now();
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 {} seconds", now.elapsed().as_secs_f32());
Ok(tags)
}
pub async fn thread(
nm: &Notmuch,
thread_id: String,
debug_content_tree: bool,
) -> Result<Thread, ServerError> {
// TODO(wathiede): normalize all email addresses through an address book with preferred
// display names (that default to the most commonly seen name).
let mut messages = Vec::new();
for (path, id) in std::iter::zip(nm.files(&thread_id)?, nm.message_ids(&thread_id)?) {
let tags = nm.tags_for_query(&format!("id:{id}"))?;
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 cid_prefix = shared::urls::cid_prefix(None, &id);
let base_url = Url::parse("https://there-should-be-no-relative-urls-in-email").unwrap();
let body = match extract_body(&m, &id)? {
Body::PlainText(PlainText { text, content_tree }) => {
let text = if text.len() > MAX_RAW_MESSAGE_SIZE {
format!(
"{}...\n\nMESSAGE WAS TRUNCATED @ {} bytes",
&text[..MAX_RAW_MESSAGE_SIZE],
MAX_RAW_MESSAGE_SIZE
)
} else {
text
};
Body::Html(Html {
html: format!(
r#"<p class="view-part-text-plain">{}</p>"#,
// Trim newlines to prevent excessive white space at the beginning/end of
// presenation. Leave tabs and spaces incase plain text attempts to center a
// header on the first line.
sanitize_html(
&linkify_html(&text.trim_matches('\n')),
&cid_prefix,
&base_url
)?
),
content_tree: if debug_content_tree {
render_content_type_tree(&m)
} else {
content_tree
},
})
}
Body::Html(Html { html, content_tree }) => Body::Html(Html {
html: sanitize_html(&html, &cid_prefix, &base_url)?,
content_tree: if debug_content_tree {
render_content_type_tree(&m)
} else {
content_tree
},
}),
Body::UnhandledContentType(UnhandledContentType { content_tree, .. }) => {
let body_start = mmap
.windows(2)
.take(20_000)
.position(|w| w == b"\n\n")
.unwrap_or(0);
let body = mmap[body_start + 2..].to_vec();
Body::UnhandledContentType(UnhandledContentType {
text: String::from_utf8(body)?,
content_tree: if debug_content_tree {
render_content_type_tree(&m)
} else {
content_tree
},
})
}
};
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, &id)?;
messages.push(Message {
id,
from,
to,
cc,
subject,
tags,
timestamp,
headers,
body,
path,
attachments,
});
}
messages.reverse();
// Find the first subject that's set. After reversing the vec, this should be the oldest
// message.
let subject: String = messages
.iter()
.skip_while(|m| m.subject.is_none())
.next()
.and_then(|m| m.subject.clone())
.unwrap_or("(NO SUBJECT)".to_string());
Ok(Thread {
thread_id,
subject,
messages,
})
}
fn email_addresses(
path: &str,
m: &ParsedMail,
header_name: &str,
) -> Result<Vec<Email>, ServerError> {
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)
}
pub fn cid_attachment_bytes(nm: &Notmuch, id: &str, cid: &str) -> Result<Attachment, ServerError> {
let files = nm.files(id)?;
let Some(path) = files.first() else {
warn!("failed to find files for message {id}");
return Err(ServerError::PartNotFound);
};
let file = File::open(&path)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
let m = parse_mail(&mmap)?;
if let Some(attachment) = walk_attachments(&m, |sp, _cur_idx| {
info!("{cid} {:?}", get_content_id(&sp.headers));
if let Some(h_cid) = get_content_id(&sp.headers) {
let h_cid = &h_cid[1..h_cid.len() - 1];
if h_cid == cid {
let attachment = extract_attachment(&sp, id, &[]).unwrap_or(Attachment {
..Attachment::default()
});
return Some(attachment);
}
}
None
}) {
return Ok(attachment);
}
Err(ServerError::PartNotFound)
}
pub fn attachment_bytes(nm: &Notmuch, id: &str, idx: &[usize]) -> Result<Attachment, ServerError> {
let files = nm.files(id)?;
let Some(path) = files.first() else {
warn!("failed to find files for message {id}");
return Err(ServerError::PartNotFound);
};
let file = File::open(&path)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
let m = parse_mail(&mmap)?;
if let Some(attachment) = walk_attachments(&m, |sp, cur_idx| {
if cur_idx == idx {
let attachment = extract_attachment(&sp, id, idx).unwrap_or(Attachment {
..Attachment::default()
});
return Some(attachment);
}
None
}) {
return Ok(attachment);
}
Err(ServerError::PartNotFound)
}
fn extract_body(m: &ParsedMail, id: &str) -> Result<Body, ServerError> {
let mut part_addr = Vec::new();
part_addr.push(id.to_string());
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, &mut part_addr),
MULTIPART_ALTERNATIVE => extract_alternative(m, &mut part_addr),
MULTIPART_RELATED => extract_related(m, &mut part_addr),
_ => 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, ServerError> {
let msg = format!(
"Unhandled body content type:\n{}\n{}",
render_content_type_tree(m),
m.get_body()?,
);
Ok(Body::UnhandledContentType(UnhandledContentType {
text: msg,
content_tree: render_content_type_tree(m),
}))
}
// 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, part_addr: &mut Vec<String>) -> Result<Body, ServerError> {
let handled_types = vec![
MULTIPART_ALTERNATIVE,
MULTIPART_MIXED,
MULTIPART_RELATED,
TEXT_HTML,
TEXT_PLAIN,
];
for sp in &m.subparts {
if sp.ctype.mimetype.as_str() == MULTIPART_ALTERNATIVE {
return extract_alternative(sp, part_addr);
}
}
for sp in &m.subparts {
if sp.ctype.mimetype.as_str() == MULTIPART_MIXED {
return extract_related(sp, part_addr);
}
}
for sp in &m.subparts {
if sp.ctype.mimetype.as_str() == MULTIPART_RELATED {
return extract_related(sp, part_addr);
}
}
for sp in &m.subparts {
if sp.ctype.mimetype.as_str() == TEXT_HTML {
let body = sp.get_body()?;
return Ok(Body::html(body));
}
}
for sp in &m.subparts {
if sp.ctype.mimetype.as_str() == TEXT_PLAIN {
let body = sp.get_body()?;
return Ok(Body::text(body));
}
}
Err(ServerError::StringError(format!(
"extract_alternative failed to find suitable subpart, searched: {:?}",
handled_types
)))
}
// multipart/mixed defines multiple types of context all of which should be presented to the user
// 'serially'.
fn extract_mixed(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, ServerError> {
let handled_types = vec![
MULTIPART_ALTERNATIVE,
MULTIPART_RELATED,
TEXT_HTML,
TEXT_PLAIN,
IMAGE_JPEG,
IMAGE_PNG,
];
let mut unhandled_types: Vec<_> = m
.subparts
.iter()
.map(|sp| sp.ctype.mimetype.as_str())
.filter(|mt| !handled_types.contains(&mt))
.collect();
unhandled_types.sort();
if !unhandled_types.is_empty() {
warn!("{MULTIPART_MIXED} contains the following unhandled mimetypes {unhandled_types:?}");
}
let mut parts = Vec::new();
for (idx, sp) in m.subparts.iter().enumerate() {
part_addr.push(idx.to_string());
match sp.ctype.mimetype.as_str() {
MULTIPART_RELATED => parts.push(extract_related(sp, part_addr)?),
MULTIPART_ALTERNATIVE => parts.push(extract_alternative(sp, part_addr)?),
TEXT_PLAIN => parts.push(Body::text(sp.get_body()?)),
TEXT_HTML => parts.push(Body::html(sp.get_body()?)),
IMAGE_JPEG | IMAGE_PNG => {
let pcd = sp.get_content_disposition();
let filename = pcd
.params
.get("filename")
.map(|s| s.clone())
.unwrap_or("".to_string());
// Only add inline images, attachments are handled as an attribute of the top level Message and rendered separate client-side.
if pcd.disposition == mailparse::DispositionType::Inline {
parts.push(Body::html(format!(
r#"<img src="/view/attachment/{}/{}/{filename}">"#,
part_addr[0],
part_addr
.iter()
.skip(1)
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(".")
)));
}
}
_ => (),
}
part_addr.pop();
}
Ok(flatten_body_parts(&parts))
}
fn flatten_body_parts(parts: &[Body]) -> Body {
let html = parts
.iter()
.map(|p| match p {
Body::PlainText(PlainText { text, .. }) => {
format!(
r#"<p class="view-part-text-plain">{}</p>"#,
// Trim newlines to prevent excessive white space at the beginning/end of
// presenation. Leave tabs and spaces incase plain text attempts to center a
// header on the first line.
linkify_html(&text.trim_matches('\n'))
)
}
Body::Html(Html { html, .. }) => html.clone(),
Body::UnhandledContentType(UnhandledContentType { text, .. }) => {
error!("text len {}", text.len());
format!(
r#"<p class="view-part-unhandled">{}</p>"#,
// Trim newlines to prevent excessive white space at the beginning/end of
// presenation. Leave tabs and spaces incase plain text attempts to center a
// header on the first line.
linkify_html(&text.trim_matches('\n'))
)
}
})
.collect::<Vec<_>>()
.join("\n");
info!("flatten_body_parts {} {html}", parts.len());
Body::html(html)
}
fn extract_related(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, ServerError> {
// TODO(wathiede): collect related things and change return type to new Body arm.
let handled_types = vec![
MULTIPART_ALTERNATIVE,
TEXT_HTML,
TEXT_PLAIN,
IMAGE_JPEG,
IMAGE_PNG,
];
let mut unhandled_types: Vec<_> = m
.subparts
.iter()
.map(|sp| sp.ctype.mimetype.as_str())
.filter(|mt| !handled_types.contains(&mt))
.collect();
unhandled_types.sort();
if !unhandled_types.is_empty() {
warn!("{MULTIPART_RELATED} contains the following unhandled mimetypes {unhandled_types:?}");
}
for (i, sp) in m.subparts.iter().enumerate() {
if sp.ctype.mimetype == IMAGE_PNG || sp.ctype.mimetype == IMAGE_JPEG {
info!("sp.ctype {:#?}", sp.ctype);
//info!("sp.headers {:#?}", sp.headers);
if let Some(cid) = sp.headers.get_first_value("Content-Id") {
let mut part_id = part_addr.clone();
part_id.push(i.to_string());
info!("cid: {cid} part_id {part_id:?}");
}
}
}
for sp in &m.subparts {
if sp.ctype.mimetype == MULTIPART_ALTERNATIVE {
return extract_alternative(m, part_addr);
}
}
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(ServerError::StringError(format!(
"extract_related failed to find suitable subpart, searched: {:?}",
handled_types
)))
}
fn walk_attachments<T, F: Fn(&ParsedMail, &[usize]) -> Option<T> + Copy>(
m: &ParsedMail,
visitor: F,
) -> Option<T> {
let mut cur_addr = Vec::new();
walk_attachments_inner(m, visitor, &mut cur_addr)
}
fn walk_attachments_inner<T, F: Fn(&ParsedMail, &[usize]) -> Option<T> + Copy>(
m: &ParsedMail,
visitor: F,
cur_addr: &mut Vec<usize>,
) -> Option<T> {
for (idx, sp) in m.subparts.iter().enumerate() {
cur_addr.push(idx);
let val = visitor(sp, &cur_addr);
if val.is_some() {
return val;
}
let val = walk_attachments_inner(sp, visitor, cur_addr);
if val.is_some() {
return val;
}
cur_addr.pop();
}
None
}
// 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, id: &str) -> Result<Vec<Attachment>, ServerError> {
let mut attachments = Vec::new();
for (idx, sp) in m.subparts.iter().enumerate() {
if let Some(attachment) = extract_attachment(sp, id, &[idx]) {
// Filter out inline attachements, they're flattened into the body of the message.
if attachment.disposition == DispositionType::Attachment {
attachments.push(attachment);
}
}
}
Ok(attachments)
}
fn extract_attachment(m: &ParsedMail, id: &str, idx: &[usize]) -> Option<Attachment> {
let pcd = m.get_content_disposition();
// TODO: do we need to handle empty filename attachments, or should we change the definition of
// Attachment::filename?
let Some(filename) = pcd.params.get("filename").map(|f| f.clone()) else {
return None;
};
// TODO: grab this from somewhere
let content_id = None;
let bytes = match m.get_body_raw() {
Ok(bytes) => bytes,
Err(err) => {
error!("failed to get body for attachment: {err}");
return None;
}
};
return Some(Attachment {
id: id.to_string(),
idx: idx
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join("."),
disposition: pcd.disposition.into(),
filename: Some(filename),
size: bytes.len(),
// TODO: what is the default for ctype?
// TODO: do we want to use m.ctype.params for anything?
content_type: Some(m.ctype.mimetype.clone()),
content_id,
bytes,
});
}
pub fn get_attachment_filename(header_value: &str) -> &str {
info!("get_attachment_filename {header_value}");
// Strip last "
let v = &header_value[..header_value.len() - 1];
if let Some(idx) = v.rfind('"') {
&v[idx + 1..]
} else {
""
}
}
pub fn get_content_type<'a>(headers: &[MailHeader<'a>]) -> Option<String> {
if let Some(v) = headers.get_first_value("Content-Type") {
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> {
headers.get_first_value("Content-Id")
}
fn render_content_type_tree(m: &ParsedMail) -> String {
const WIDTH: usize = 4;
const SKIP_HEADERS: [&str; 4] = [
"Authentication-Results",
"DKIM-Signature",
"Received",
"Received-SPF",
];
fn render_ct_rec(m: &ParsedMail, depth: usize) -> String {
let mut parts = Vec::new();
let msg = format!("{} {}", "-".repeat(depth * WIDTH), m.ctype.mimetype);
parts.push(msg);
for sp in &m.subparts {
parts.push(render_ct_rec(sp, depth + 1))
}
parts.join("\n")
}
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 {
if h.get_key().starts_with('X') {
continue;
}
if SKIP_HEADERS.contains(&h.get_key().as_str()) {
continue;
}
parts.push(format!("{indent} {}: {}", h.get_key_ref(), h.get_value()));
}
}
for sp in &m.subparts {
parts.push(render_rec(sp, depth + 1))
}
parts.join("\n")
}
format!(
"Outline:\n{}\n\nDetailed:\n{}\n\nNot showing headers:\n {}\n X.*",
render_ct_rec(m, 1),
render_rec(m, 1),
SKIP_HEADERS.join("\n ")
)
}

View File

@@ -11,25 +11,25 @@ pub struct SearchResult {
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ShowResult {
messages: Vec<Message>,
}
pub type AttachementId = String;
/// # Number of seconds since the Epoch
pub type UnixTime = isize;
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Message {
pub from: String,
pub to: Option<String>,
pub cc: Option<String>,
pub timestamp: UnixTime, // date header as unix time
pub date_relative: String, // user-friendly timestamp
pub tags: Vec<String>,
// HTML formatted body
pub body: String,
pub attachment: Vec<AttachementId>,
pub struct Message {}
pub mod urls {
pub const MOUNT_POINT: &'static str = "/api";
pub fn cid_prefix(host: Option<&str>, cid: &str) -> String {
if let Some(host) = host {
format!("//{host}/api/cid/{cid}/")
} else {
format!("/api/cid/{cid}/")
}
}
pub fn download_attachment(host: Option<&str>, id: &str, idx: &str, filename: &str) -> String {
if let Some(host) = host {
format!(
"//{host}/api/download/attachment/{}/{}/{}",
id, idx, filename
)
} else {
format!("/api/download/attachment/{}/{}/{}", id, idx, filename)
}
}
}

View File

@@ -9,24 +9,26 @@ license = "MIT"
readme = "./README.md"
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dev-dependencies]
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"}
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"] }
human_format = "1.1.0"
[package.metadata.wasm-pack.profile.release]
wasm-opt = ['-Os']

View File

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

15
web/Trunk.toml Normal file
View File

@@ -0,0 +1,15 @@
[build]
release = true
[serve]
# The address to serve on.
address = "0.0.0.0"
port = 6758
[[proxy]]
backend = "http://localhost:9345/api/"
#[[hooks]]
#stage = "pre_build"
#command = "cargo"
#command_arguments = [ "test" ]

View File

@@ -0,0 +1,3 @@
mutation AddTagMutation($query: String!, $tag: String!) {
tagAdd(query:$query, tag:$tag)
}

View File

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

View File

@@ -0,0 +1,3 @@
mutation MarkReadMutation($query: String!, $unread: Boolean!) {
setReadStatus(query:$query, unread:$unread)
}

View File

@@ -0,0 +1,3 @@
mutation RemoveTagMutation($query: String!, $tag: String!) {
tagRemove(query:$query, tag:$tag)
}

2379
web/graphql/schema.json Normal file

File diff suppressed because it is too large Load Diff

View File

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

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

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

View File

@@ -2,91 +2,30 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="modulepreload" href="/pkg/package.js" as="script" type="text/javascript">
<link rel="preload" href="/pkg/package_bg.wasm" as="fetch" type="application/wasm" crossorigin="anonymous">
<link rel="stylesheet", href="https://jenil.github.io/bulmaswatch/cyborg/bulmaswatch.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
.message {
padding-left: 0.5em;
}
.body {
background: white;
color: black;
padding-bottom: 1em;
}
.error {
background-color: red;
}
.view-part-text-plain {
white-space: pre-line;
}
iframe {
height: 100%;
width: 100%;
}
.index .from {
width: 200px;
}
.index .subject {
}
.index .date {
white-space: nowrap;
}
.footer {
background-color: #eee;
color: #222;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 3em;
padding: 1em;
}
.tag {
margin-right: 2px;
}
.debug ul {
padding-left: 2em;
}
.debug li {
}
.loading {
animation-name: spin;
animation-duration: 1000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {
transform:rotate(0deg);
}
to {
transform:rotate(360deg);
}
}
@media (max-width: 768px) {
.section {
padding: 1.5em;
}
}
input, .input {
color: #000;
}
input::placeholder, .input::placeholder{
color: #555;
}
</style>
<meta charset="utf-8">
<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://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
-->
<!--
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1.0.0/css/bulma.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" />
<link data-trunk rel="css" href="static/style.css" />
<!-- Pretty checkboxes from https://justboil.github.io/bulma-checkbox/ -->
<link data-trunk rel="css" href="static/main.css" />
<!-- tall thin font for user icon -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@700&display=swap" rel="stylesheet">
</head>
<body>
<section id="app"></section>
<script type="module">
import init from '/pkg/package.js';
init('/pkg/package_bg.wasm');
</script>
<section id="app"></section>
</body>
</html>

View File

@@ -1,16 +1,27 @@
use seed::Url;
use gloo_net::{http::Request, Error};
use log::info;
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 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 fn show(tid: &str) -> String {
format!("{BASE_URL}/show/{tid}")
}
pub fn original(message_id: &str) -> String {
format!("{BASE_URL}/original/{message_id}")
pub async fn refresh_request() -> Result<(), Error> {
let t = Request::get(&refresh()).send().await?.text().await?;
info!("refresh {t}");
Ok(())
}

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

@@ -0,0 +1 @@
pub const SEARCH_RESULTS_PER_PAGE: usize = 20;

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

@@ -0,0 +1,61 @@
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;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/mark_read.graphql",
response_derives = "Debug"
)]
pub struct MarkReadMutation;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/add_tag.graphql",
response_derives = "Debug"
)]
pub struct AddTagMutation;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/schema.json",
query_path = "graphql/remove_tag.graphql",
response_derives = "Debug"
)]
pub struct RemoveTagMutation;
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("/api/graphql/")
.mode(RequestMode::Cors)
.json(&body)?
.send()
.await?
.json()
.await
}

View File

@@ -1,580 +0,0 @@
mod api;
mod nm;
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use itertools::Itertools;
use log::{debug, error, info, Level};
use notmuch::ThreadSet;
use seed::{prelude::*, *};
use serde::Deserialize;
use wasm_timer::Instant;
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 {
orders
.subscribe(on_url_changed)
.notify(subs::UrlChanged(url.clone()));
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::ShowRequest(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.
pub enum Msg {
Noop,
RefreshStart,
RefreshDone(Option<FetchError>),
SearchRequest {
query: String,
page: usize,
results_per_page: usize,
},
SearchResult(fetch::Result<shared::SearchResult>),
ShowRequest(String),
ShowResult(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 {
// If looking at search page, refresh the search to view update on the server side.
if let Context::Search(sr) = &model.context {
let query = sr.query.clone();
let page = sr.page;
let results_per_page = sr.results_per_page;
orders.perform_cmd(async move {
Msg::SearchResult(search_request(&query, page, results_per_page).await)
});
}
RefreshingState::None
};
}
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) });
}
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::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?)
};
}
}
}
pub async fn show_request(tid: &str) -> fetch::Result<Vec<shared::Message>> {
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(Vec::<shared::Message>::deserialize(&mut deserializer)
.map_err(|_| FetchError::JsonError(fetch::JsonError::Serde(JsValue::NULL)))?)
}
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
}
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(())
}
// ------ ------
// View
// ------ ------
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::ShowRequest(tid)),
]
*/
let tid = r.thread.clone();
div![
div![
C!["subject"],
&r.subject,
ev(Ev::Click, move |_| Msg::ShowRequest(tid)),
],
div![
span![C!["from"], pretty_authors(&r.authors)],
span![C!["tags"], tags_chiclet(&r.tags, true)],
],
span![C!["date"], &r.date_relative],
hr![],
]
});
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 => "is-static"),
IF!(is_first => "is-info"),
],
"<",
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_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_thread(messages: &[shared::Message]) -> Node<Msg> {
div![
"MESSAGES GO HERE",
ol![messages.iter().map(|msg| li![format!("{:?}", msg)])]
]
}
fn view_desktop(model: &Model) -> Node<Msg> {
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(thread_set) => view_thread(thread_set),
Context::Search(search_results) => view_search_results(&model.query, search_results),
};
div![
view_header(&model.query, &model.refreshing_state),
section![C!["section"], div![C!["container"], content],]
]
}
fn view_mobile(model: &Model) -> Node<Msg> {
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::Thread(thread_set) => view_thread(thread_set),
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` 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
// ------ ------
// (This function is invoked by `init` function in `index.html`.)
#[wasm_bindgen(start)]
pub fn start() {
// This provides better error messages in debug mode.
// It's disabled in release mode so it doesn't bloat up the file size.
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
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);
}

25
web/src/main.rs Normal file
View File

@@ -0,0 +1,25 @@
// (Lines like the one below ignore selected Clippy rules
// - 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 log::Level;
use seed::App;
mod api;
mod consts;
mod graphql;
mod state;
mod view;
fn main() {
// This provides better error messages in debug mode.
// It's disabled in release mode so it doesn't bloat up the file size.
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
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", state::init, state::update, view::view);
}

View File

@@ -1,193 +0,0 @@
use notmuch::{Content, Part, Thread, ThreadNode, ThreadSet};
use seed::{prelude::*, *};
use serde::de::Deserialize;
use crate::{api, set_title, Msg};
pub async fn show_request(tid: &str) -> fetch::Result<ThreadSet> {
let b = Request::new(api::show(tid))
.method(Method::Get)
.fetch()
.await?
.check_status()?
.bytes()
.await?;
let mut deserializer = serde_json::Deserializer::from_slice(&b);
deserializer.disable_recursion_limit();
Ok(ThreadSet::deserialize(&mut deserializer)
.map_err(|_| FetchError::JsonError(fetch::JsonError::Serde(JsValue::NULL)))?)
}
pub fn view_thread(thread_set: &ThreadSet) -> Node<Msg> {
assert_eq!(thread_set.0.len(), 1);
let thread = &thread_set.0[0];
assert_eq!(thread.0.len(), 1);
let thread_node = &thread.0[0];
let subject = first_subject(&thread_node).unwrap_or("<No subject>".to_string());
set_title(&subject);
div![
h1![subject],
a![
attrs! {At::Href=>api::original(&thread_node.0.as_ref().expect("message missing").id)},
"Original"
],
view_message(&thread_node),
div![
C!["debug"],
"Add zippy for debug dump",
view_debug_thread_set(thread_set)
] /* pre![format!("Thread: {:#?}", thread_set).replace(" ", " ")] */
]
}
// <subject>
// <tags>
//
// <from1> <date>
// <to1>
// <content1>
// <zippy>
// <children1>
// </zippy>
//
// <from2> <date>
// <to2>
// <body2>
fn view_message(thread: &ThreadNode) -> Node<Msg> {
let message = thread.0.as_ref().expect("ThreadNode missing Message");
let children = &thread.1;
div![
C!["message"],
/* TODO(wathiede): collect all the tags and show them here. */
/* TODO(wathiede): collect all the attachments from all the subparts */
div![C!["header"], "From: ", &message.headers.from],
div![C!["header"], "Date: ", &message.headers.date],
div![C!["header"], "To: ", &message.headers.to],
hr![],
div![
C!["body"],
match &message.body {
Some(body) => view_body(body.as_slice()),
None => div!["<no body>"],
},
],
children.iter().map(view_message)
]
}
fn view_body(body: &[Part]) -> Node<Msg> {
div![body.iter().map(view_part)]
}
fn view_text_plain(content: &Option<Content>) -> Node<Msg> {
match &content {
Some(Content::String(content)) => p![C!["view-part-text-plain"], content],
_ => div![
C!["error"],
format!("Unhandled content enum for text/plain"),
],
}
}
fn view_part(part: &Part) -> Node<Msg> {
match part.content_type.as_str() {
"text/plain" => view_text_plain(&part.content),
"text/html" => {
if let Some(Content::String(html)) = &part.content {
let inliner = css_inline::CSSInliner::options()
.load_remote_stylesheets(false)
.remove_style_tags(true)
.build();
let inlined = inliner.inline(html).expect("failed to inline CSS");
return div![C!["view-part-text-html"], div!["TEST"], raw![&inlined]];
} else {
div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
]
}
}
// https://en.wikipedia.org/wiki/MIME#alternative
// RFC1341 states: In general, user agents that compose multipart/alternative entities
// should place the body parts in increasing order of preference, that is, with the
// preferred format last.
"multipart/alternative" => {
if let Some(Content::Multipart(parts)) = &part.content {
for part in parts.iter().rev() {
if part.content_type == "text/html" {
if let Some(Content::String(html)) = &part.content {
let inliner = css_inline::CSSInliner::options()
.load_remote_stylesheets(false)
.remove_style_tags(true)
.build();
let inlined = inliner.inline(html).expect("failed to inline CSS");
return div![Node::from_html(None, &inlined)];
}
}
if part.content_type == "text/plain" {
return view_text_plain(&part.content);
}
}
div!["No known multipart/alternative parts"]
} else {
div![
C!["error"],
format!("multipart/alternative with non-multipart content"),
]
}
}
"multipart/mixed" => match &part.content {
Some(Content::Multipart(parts)) => div![parts.iter().map(view_part)],
_ => div![
C!["error"],
format!("Unhandled content enum for multipart/mixed"),
],
},
_ => div![
C!["error"],
format!("Unhandled content type: {}", part.content_type)
],
}
}
fn first_subject(thread: &ThreadNode) -> Option<String> {
if let Some(msg) = &thread.0 {
return Some(msg.headers.subject.clone());
} else {
for tn in &thread.1 {
if let Some(s) = first_subject(&tn) {
return Some(s);
}
}
}
None
}
fn view_debug_thread_set(thread_set: &ThreadSet) -> Node<Msg> {
ul![thread_set
.0
.iter()
.enumerate()
.map(|(i, t)| { li!["t", i, ": ", view_debug_thread(t),] })]
}
fn view_debug_thread(thread: &Thread) -> Node<Msg> {
ul![thread
.0
.iter()
.enumerate()
.map(|(i, tn)| { li!["tn", i, ": ", view_debug_thread_node(tn),] })]
}
fn view_debug_thread_node(thread_node: &ThreadNode) -> Node<Msg> {
ul![
IF!(thread_node.0.is_some()=>li!["tn id:", &thread_node.0.as_ref().unwrap().id]),
thread_node.1.iter().enumerate().map(|(i, tn)| li![
"tn",
i,
": ",
view_debug_thread_node(tn)
])
]
}

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

@@ -0,0 +1,554 @@
use std::collections::HashSet;
use graphql_client::GraphQLQuery;
use log::{error, info};
use seed::{prelude::*, *};
use thiserror::Error;
use crate::{
api,
api::urls,
consts::SEARCH_RESULTS_PER_PAGE,
graphql,
graphql::{front_page_query::*, send_graphql, show_thread_query::*},
};
/// Used to fake the unread string while in development
pub fn unread_query() -> &'static str {
let host = seed::window()
.location()
.host()
.expect("failed to get host");
if host.starts_with("6758.") {
return "tag:letterbox";
}
"is:unread"
}
// `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(unread_query(), 0));
} else {
orders.notify(subs::UrlRequested::new(url));
};
orders.stream(streams::window_event(Ev::Resize, |_| Msg::OnResize));
// TODO(wathiede): only do this while viewing the index? Or maybe add a new message that force
// 'notmuch new' on the server periodically?
orders.stream(streams::interval(30_000, || Msg::RefreshStart));
orders.subscribe(on_url_changed);
Model {
context: Context::None,
query: "".to_string(),
refreshing_state: RefreshingState::None,
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] => Msg::ShowThreadRequest {
thread_id: tid.to_string(),
},
["s", query] => {
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
Msg::FrontPageRequest {
query,
after: None,
before: None,
first: None,
last: None,
}
}
["s", query, page] => {
let query = Url::decode_uri_component(query).unwrap_or("".to_string());
let page = page[1..].parse().unwrap_or(0);
Msg::FrontPageRequest {
query,
after: Some(page.to_string()),
before: None,
first: None,
last: None,
}
}
p => {
if !p.is_empty() {
info!("Unhandled path '{p:?}'");
}
Msg::FrontPageRequest {
query: "".to_string(),
after: None,
before: None,
first: None,
last: None,
}
}
}
}
// `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::NextPage => {
match &model.context {
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::ThreadResult { .. } => (), // do nothing (yet?)
Context::None => (), // do nothing (yet?)
};
}
Msg::PreviousPage => {
match &model.context {
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::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::SetUnread(query, unread) => {
let search_url = urls::search(&model.query, 0).to_string();
orders.skip().perform_cmd(async move {
let res: Result<
graphql_client::Response<graphql::mark_read_mutation::ResponseData>,
gloo_net::Error,
> = send_graphql(graphql::MarkReadMutation::build_query(
graphql::mark_read_mutation::Variables {
query: query.clone(),
unread,
},
))
.await;
if let Err(e) = res {
error!("Failed to set read for {query} to {unread}: {e}");
}
seed::window()
.location()
.set_href(&search_url)
.expect("failed to change location");
Msg::Noop
});
}
Msg::AddTag(query, tag) => {
let search_url = urls::search(&model.query, 0).to_string();
orders.skip().perform_cmd(async move {
let res: Result<
graphql_client::Response<graphql::add_tag_mutation::ResponseData>,
gloo_net::Error,
> = send_graphql(graphql::AddTagMutation::build_query(
graphql::add_tag_mutation::Variables {
query: query.clone(),
tag: tag.clone(),
},
))
.await;
if let Err(e) = res {
error!("Failed to add tag {tag} to {query}: {e}");
}
seed::window()
.location()
.set_href(&search_url)
.expect("failed to change location");
Msg::Noop
});
}
Msg::RemoveTag(query, tag) => {
let search_url = urls::search(&model.query, 0).to_string();
orders.skip().perform_cmd(async move {
let res: Result<
graphql_client::Response<graphql::remove_tag_mutation::ResponseData>,
gloo_net::Error,
> = send_graphql(graphql::RemoveTagMutation::build_query(
graphql::remove_tag_mutation::Variables {
query: query.clone(),
tag: tag.clone(),
},
))
.await;
if let Err(e) = res {
error!("Failed to remove tag {tag} to {query}: {e}");
}
// TODO: reconsider this behavior
seed::window()
.location()
.set_href(&search_url)
.expect("failed to change location");
Msg::Noop
});
}
Msg::FrontPageRequest {
query,
after,
before,
first,
last,
} => {
let (after, before, first, last) = match (after.as_ref(), before.as_ref(), first, last)
{
// If no pagination set, set reasonable defaults
(None, None, None, None) => {
(None, None, Some(SEARCH_RESULTS_PER_PAGE as i64), None)
}
_ => (after, before, first, 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,
selected_threads: HashSet::new(),
};
}
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(),
);
let mut open_messages: HashSet<_> = data
.thread
.messages
.iter()
.filter(|msg| msg.tags.iter().any(|t| t == "unread"))
.map(|msg| msg.id.clone())
.collect();
if open_messages.is_empty() {
open_messages = data
.thread
.messages
.iter()
.map(|msg| msg.id.clone())
.collect();
}
model.context = Context::ThreadResult {
thread: data.thread,
open_messages,
};
}
Msg::ShowThreadResult(bad) => {
error!("show_thread_query error: {bad:#?}");
}
Msg::SelectionSetNone => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
*selected_threads = HashSet::new();
}
}
Msg::SelectionSetAll => {
if let Context::SearchResult {
results,
selected_threads,
..
} = &mut model.context
{
*selected_threads = results.iter().map(|node| node.thread.clone()).collect();
}
}
Msg::SelectionAddTag(tag) => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
let threads = selected_threads
.iter()
.map(|tid| format!("thread:{tid}"))
.collect::<Vec<_>>()
.join(" ");
orders
.skip()
.perform_cmd(async move { Msg::AddTag(threads, tag) });
}
}
Msg::SelectionRemoveTag(tag) => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
let threads = selected_threads
.iter()
.map(|tid| format!("thread:{tid}"))
.collect::<Vec<_>>()
.join(" ");
orders
.skip()
.perform_cmd(async move { Msg::RemoveTag(threads, tag) });
}
}
Msg::SelectionMarkAsRead => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
let threads = selected_threads
.iter()
.map(|tid| format!("thread:{tid}"))
.collect::<Vec<_>>()
.join(" ");
orders
.skip()
.perform_cmd(async move { Msg::SetUnread(threads, false) });
}
}
Msg::SelectionMarkAsUnread => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
let threads = selected_threads
.iter()
.map(|tid| format!("thread:{tid}"))
.collect::<Vec<_>>()
.join(" ");
orders
.skip()
.perform_cmd(async move { Msg::SetUnread(threads, true) });
}
}
Msg::SelectionAddThread(tid) => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
selected_threads.insert(tid);
}
}
Msg::SelectionRemoveThread(tid) => {
if let Context::SearchResult {
selected_threads, ..
} = &mut model.context
{
selected_threads.remove(&tid);
}
}
Msg::MessageCollapse(id) => {
if let Context::ThreadResult { open_messages, .. } = &mut model.context {
open_messages.remove(&id);
}
}
Msg::MessageExpand(id) => {
if let Context::ThreadResult { open_messages, .. } = &mut model.context {
open_messages.insert(id);
}
}
Msg::MultiMsg(msgs) => msgs.into_iter().for_each(|msg| update(msg, model, orders)),
}
}
// `Model` describes our app state.
pub struct Model {
pub query: String,
pub context: Context,
pub refreshing_state: RefreshingState,
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,
SearchResult {
query: String,
results: Vec<FrontPageQuerySearchNodes>,
count: usize,
pager: FrontPageQuerySearchPageInfo,
selected_threads: HashSet<String>,
},
ThreadResult {
thread: ShowThreadQueryThread,
open_messages: HashSet<String>,
},
}
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>),
NextPage,
PreviousPage,
UpdateQuery(String),
SearchQuery(String),
SetUnread(String, bool),
AddTag(String, String),
RemoveTag(String, 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>,
),
SelectionSetNone,
SelectionSetAll,
SelectionAddTag(String),
SelectionRemoveTag(String),
SelectionMarkAsRead,
SelectionMarkAsUnread,
SelectionAddThread(String),
SelectionRemoveThread(String),
MessageCollapse(String),
MessageExpand(String),
MultiMsg(Vec<Msg>),
}

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

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

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

@@ -0,0 +1,113 @@
use std::collections::HashSet;
use seed::{prelude::*, *};
use crate::{
api::urls,
graphql::front_page_query::*,
state::{Context, Model, Msg},
view::{self, human_age, pretty_authors, search_toolbar, set_title, tags_chiclet, view_header},
};
pub(super) fn view(model: &Model) -> Node<Msg> {
log::info!("tablet::view");
let show_icon_text = false;
let content = match &model.context {
Context::None => div![h1!["Loading"]],
Context::ThreadResult {
thread,
open_messages,
} => view::thread(thread, open_messages, show_icon_text),
Context::SearchResult {
query,
results,
count,
pager,
selected_threads,
} => search_results(
&query,
results.as_slice(),
*count,
pager,
selected_threads,
show_icon_text,
),
};
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,
selected_threads: &HashSet<String>,
show_icon_text: bool,
) -> 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 check_tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
let unread_idx = r.tags.iter().position(|e| e == &"unread");
let mut tags = r.tags.clone();
if let Some(idx) = unread_idx {
tags.remove(idx);
};
div![
C!["row"],
label![
C!["b-checkbox", "checkbox", "is-large"],
input![attrs! {
At::Type=>"checkbox",
At::Checked=>selected_threads.contains(&tid).as_at_value(),
}],
span![C!["check"]],
ev(Ev::Input, move |e| {
if let Some(input) = e
.target()
.as_ref()
.expect("failed to get reference to target")
.dyn_ref::<web_sys::HtmlInputElement>()
{
if input.checked() {
Msg::SelectionAddThread(check_tid)
} else {
Msg::SelectionRemoveThread(check_tid)
}
} else {
Msg::Noop
}
}),
],
a![
C!["has-text-light", "summary"],
IF!(unread_idx.is_some() => C!["unread"]),
attrs! {
At::Href => urls::thread(&tid)
},
div![C!["subject"], &r.subject],
span![C!["from", "is-size-7"], pretty_authors(&r.authors)],
div![
span![C!["is-size-7"], tags_chiclet(&tags, true)],
span![C!["is-size-7", "float-right", "date"], datetime]
]
]
]
});
let show_bulk_edit = !selected_threads.is_empty();
div![
C!["search-results"],
search_toolbar(count, pager, show_bulk_edit, show_icon_text),
div![C!["index"], rows],
search_toolbar(count, pager, show_bulk_edit, show_icon_text),
]
}

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

@@ -0,0 +1,972 @@
use std::{
collections::{hash_map::DefaultHasher, HashSet},
hash::{Hash, Hasher},
};
use chrono::{DateTime, Datelike, Duration, Local, Utc};
use human_format::{Formatter, Scales};
use itertools::Itertools;
use log::error;
use seed::{prelude::*, *};
use seed_hooks::{state_access::CloneState, topo, use_state};
use crate::{
api::urls,
graphql::{front_page_query::*, show_thread_query::*},
state::{unread_query, Model, Msg, RefreshingState},
};
mod desktop;
mod mobile;
mod tablet;
// TODO(wathiede): create a QueryString enum that wraps single and multiple message ids and thread
// ids, and has a to_query_string() that knows notmuch's syntax. Then remove the smattering of
// format!() calls all over with magic strings representing notmuch specific syntax.
const MAX_RAW_MESSAGE_SIZE: usize = 100_000;
fn set_title(title: &str) {
seed::document().set_title(&format!("lb: {}", title));
}
fn compute_color(data: &str) -> String {
let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
format!("#{:06x}", hasher.finish() % (1 << 24))
}
fn tags_chiclet(tags: &[String], is_mobile: bool) -> impl Iterator<Item = Node<Msg>> + '_ {
tags.iter().map(move |tag| {
let hex = compute_color(tag);
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::FrontPageRequest {
query: format!("tag:{tag}"),
after: None,
before: None,
first: None,
last: None,
})
]
})
}
fn removable_tags_chiclet<'a>(
thread_id: &'a str,
tags: &'a [String],
is_mobile: bool,
) -> Node<Msg> {
div![
C![
"message-tags",
"field",
"is-grouped",
"is-grouped-multiline"
],
tags.iter().map(move |tag| {
let hex = compute_color(tag);
let style = style! {St::BackgroundColor=>hex};
let classes = C!["tag", IF!(is_mobile => "is-small")];
let attrs = attrs! {
At::Href => urls::search(&format!("tag:{tag}"), 0)
};
let tag = tag.clone();
let rm_tag = tag.clone();
let thread_id = format!("thread:{thread_id}");
div![
C!["control"],
div![
C!["tags", "has-addons"],
a![
classes,
attrs,
style,
match tag.as_str() {
"attachment" => span!["📎"],
"replied" => span![i![C!["fa-solid", "fa-reply"]]],
_ => span![&tag],
},
ev(Ev::Click, move |_| Msg::FrontPageRequest {
query: format!("tag:{tag}"),
after: None,
before: None,
first: None,
last: None,
})
],
a![
C!["tag", "is-delete"],
ev(Ev::Click, move |_| Msg::RemoveTag(thread_id, rm_tag))
]
]
]
})
]
}
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,
selected_threads: &HashSet<String>,
show_icon_text: bool,
) -> Node<Msg> {
if query.is_empty() {
set_title("all mail");
} else {
set_title(query);
}
let show_bulk_edit = !selected_threads.is_empty();
let all_checked = selected_threads.len() == results.len();
let partially_checked = !selected_threads.is_empty() && !all_checked;
let rows = results.iter().map(|r| {
let tid = r.thread.clone();
let check_tid = r.thread.clone();
let datetime = human_age(r.timestamp as i64);
let unread_idx = r.tags.iter().position(|e| e == &"unread");
let mut tags = r.tags.clone();
if let Some(idx) = unread_idx {
tags.remove(idx);
};
let subject = if r.subject.is_empty() {
"(no subject)"
} else {
&r.subject
};
tr![
IF!(unread_idx.is_some() => C!["unread"]),
td![label![
C!["b-checkbox", "checkbox"],
input![attrs! {
At::Type=>"checkbox",
At::Checked=>selected_threads.contains(&tid).as_at_value(),
}],
span![C!["check"]],
ev(Ev::Input, move |e| {
if let Some(input) = e
.target()
.as_ref()
.expect("failed to get reference to target")
.dyn_ref::<web_sys::HtmlInputElement>()
{
if input.checked() {
Msg::SelectionAddThread(check_tid)
} else {
Msg::SelectionRemoveThread(check_tid)
}
} else {
Msg::Noop
}
}),
]],
td![
C!["from"],
a![
C!["has-text-light", "text"],
attrs! {
At::Href => urls::thread(&tid)
},
pretty_authors(&r.authors),
IF!(r.total>1 => small![" ", r.total.to_string()]),
]
],
td![
C!["subject"],
tags_chiclet(&tags, false),
" ",
a![
C!["has-text-light", "text"],
attrs! {
At::Href => urls::thread(&tid)
},
&subject,
]
],
td![
C!["date"],
a![
C!["has-text-light", "text"],
attrs! {
At::Href => urls::thread(&tid)
},
datetime
]
]
]
});
div![
C!["search-results"],
search_toolbar(count, pager, show_bulk_edit, show_icon_text),
table![
C![
"table",
"index",
"is-fullwidth",
"is-hoverable",
"is-narrow",
"is-striped",
],
thead![tr![
th![
C!["edit"],
label![
C!["b-checkbox", "checkbox"],
input![
IF!(partially_checked => C!["is-indeterminate"]),
attrs! {
At::Type=>"checkbox",
At::Checked=>all_checked.as_at_value(),
}
],
span![C!["check"]],
ev(Ev::Click, move |_| if all_checked {
Msg::SelectionSetNone
} else {
Msg::SelectionSetAll
})
]
],
th![C!["from"], "From"],
th![C!["subject"], "Subject"],
th![C!["date"], "Date"]
]],
tbody![rows]
],
search_toolbar(count, pager, show_bulk_edit, show_icon_text)
]
}
fn search_toolbar(
count: usize,
pager: &FrontPageQuerySearchPageInfo,
show_bulk_edit: bool,
show_icon_text: bool,
) -> Node<Msg> {
let start = pager
.start_cursor
.as_ref()
.map(|i| i.parse().unwrap_or(0))
.unwrap_or(0)
+ 1;
let end = pager
.end_cursor
.as_ref()
.map(|i| i.parse().unwrap_or(count))
.unwrap_or(count)
+ 1;
nav![
C!["level", "is-mobile"],
IF!(show_bulk_edit =>
div![
C!["level-left"],
div![
C!["level-item"],
div![C!["buttons", "has-addons"],
button![
C!["button", "mark-read"],
attrs!{At::Title => "Mark as read"},
span![C!["icon", "is-small"], i![C!["far", "fa-envelope-open"]]],
IF!(show_icon_text=>span!["Read"]),
ev(Ev::Click, |_| Msg::SelectionMarkAsRead)
],
button![
C!["button", "mark-unread"],
attrs!{At::Title => "Mark as unread"},
span![C!["icon", "is-small"], i![C!["far", "fa-envelope"]]],
IF!(show_icon_text=>span!["Unread"]),
ev(Ev::Click, |_| Msg::SelectionMarkAsUnread)
]
]
],
div![
C!["level-item"],
div![C!["buttons", "has-addons"],
button![
C!["button", "spam"],
attrs!{At::Title => "Mark as spam"},
span![C!["icon", "is-small"], i![C!["far", "fa-hand"]]],
IF!(show_icon_text=>span!["Spam"]),
ev(Ev::Click, |_|
Msg::MultiMsg(vec![
Msg::SelectionAddTag("Spam".to_string()),
Msg::SelectionMarkAsRead
])
)
],
],
]
]),
div![
C!["level-right"],
nav![
C!["level-item", "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, end, 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 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 has_unread(tags: &[String]) -> bool {
tags.contains(&String::from("unread"))
}
fn render_avatar(avatar: Option<String>, from: &str) -> Node<Msg> {
let initials: String = from
.to_lowercase()
.split(" ")
.map(|word| word.chars().next().unwrap())
// Limit to 2 characters because more characters don't fit in the box
.take(2)
.collect();
if let Some(src) = avatar {
img![attrs! {At::Src=>src}]
} else {
let w = 64;
let h = 64;
let from_color = compute_color(from);
svg![
attrs! {At::ViewBox=>format!("0 0 {w} {h}") },
style! {
St::Display => "block",
St::FontFamily => "Poppins",
St::FontSize => pt(32),
},
g![
rect![attrs! {
At::Fill=>from_color,
At::Stroke=>"black",
At::StrokeWidth=>"1",
// Round corners
//At::Rx => px(10),
At::X => 0,
At::Y => 0,
At::Width => h,
At::Height => h,
}],
text![
attrs! {
At::Fill => "white",
At::X => percent(50),
At::Y => percent(50),
At::DominantBaseline => "middle",
At::TextAnchor => "middle"
},
initials
]
]
]
}
}
fn render_open_header(msg: &ShowThreadQueryThreadMessages) -> Node<Msg> {
let (from, from_detail) = match &msg.from {
Some(ShowThreadQueryThreadMessagesFrom {
name: Some(name),
addr,
}) => (name.to_string(), addr.clone()),
Some(ShowThreadQueryThreadMessagesFrom {
addr: Some(addr), ..
}) => (addr.to_string(), None),
_ => (String::from("UNKNOWN"), None),
};
// TODO(wathiede): get this from server
let avatar: Option<String> = None;
//let avatar: Option<String> = Some(String::from("https://bulma.io/images/placeholders/64x64.png"));
let id = msg.id.clone();
let is_unread = has_unread(&msg.tags);
let img = render_avatar(avatar, &from);
article![
C!["media"],
figure![C!["media-left"], p![C!["image", "is-64x64"], img]],
div![
C!["media-content"],
div![
C!["content"],
p![
strong![from],
br![],
small![from_detail],
table![
IF!(!msg.to.is_empty() =>
tr![
td![ "To:" ],
//td![ if i==0 { "To" }else { "" } ],
td![
msg.to.iter().enumerate().map(|(i, to)|
small![
if i>0 { ", " }else { "" },
match to {
ShowThreadQueryThreadMessagesTo {
name: Some(name),
addr:Some(addr),
} => format!("{name} <{addr}>"),
ShowThreadQueryThreadMessagesTo {
name: Some(name),
addr:None
} => format!("{name}"),
ShowThreadQueryThreadMessagesTo {
addr: Some(addr), ..
} => format!("{addr}"),
_ => String::from("UNKNOWN"),
}
])
]
]),
IF!(!msg.cc.is_empty() =>
tr![
td![ "CC:" ],
td![
msg.cc.iter().enumerate().map(|(i, cc)|
small![
if i>0 { ", " }else { "" },
match cc {
ShowThreadQueryThreadMessagesCc {
name: Some(name),
addr:Some(addr),
} => format!("{name} <{addr}>"),
ShowThreadQueryThreadMessagesCc {
name: Some(name),
addr:None
} => format!("{name}"),
ShowThreadQueryThreadMessagesCc {
addr: Some(addr), ..
} => format!("<{addr}>"),
_ => String::from("UNKNOWN"),
}
])
]
]),
tr![td![
attrs! {At::ColSpan=>2},
msg.timestamp.map(|ts| span![C!["header"], human_age(ts)])
]]
],
],
],
],
div![
C!["media-right"],
span![
C!["read-status"],
i![C![
"far",
if is_unread {
"fa-envelope"
} else {
"fa-envelope-open"
},
]]
],
ev(Ev::Click, move |e| {
e.stop_propagation();
Msg::SetUnread(format!("id:{id}"), !is_unread)
})
]
]
}
fn render_closed_header(msg: &ShowThreadQueryThreadMessages) -> Node<Msg> {
let from: String = match &msg.from {
Some(ShowThreadQueryThreadMessagesFrom {
name: Some(name), ..
}) => name.to_string(),
Some(ShowThreadQueryThreadMessagesFrom {
addr: Some(addr), ..
}) => addr.to_string(),
_ => String::from("UNKNOWN"),
};
// TODO(wathiede): get this from server
let avatar: Option<String> = None;
//let avatar: Option<String> = Some(String::from("https://bulma.io/images/placeholders/64x64.png"));
let id = msg.id.clone();
let is_unread = has_unread(&msg.tags);
let img = render_avatar(avatar, &from);
article![
C!["media"],
figure![C!["media-left"], p![C!["image", "is-64x64"], img]],
div![
C!["media-content"],
div![
C!["content"],
p![
strong![from],
br![],
IF!(!msg.to.is_empty() =>
nodes![
small![" to "],
msg.to.iter().enumerate().map(|(i, to)| small![
if i > 0 { ", " } else { "" },
to.name()
.as_ref()
.unwrap_or(&to.addr().unwrap_or("(UNKNOWN)"))
]).collect::<Vec<_>>()
]),
IF!(!msg.cc.is_empty() =>
nodes![
small![" cc "],
msg.cc.iter().enumerate().map(|(i, cc)| small![
if i > 0 { ", " } else { "" },
cc.name()
.as_ref()
.unwrap_or(&cc.addr().unwrap_or("(UNKNOWN)"))
]).collect::<Vec<_>>()
]),
br![],
msg.timestamp.map(|ts| span![C!["header"], human_age(ts)]),
],
],
],
div![
C!["media-right"],
span![
C!["read-status"],
i![
C![
"far",
if is_unread {
"fa-envelope"
} else {
"fa-envelope-open"
},
],
ev(Ev::Click, move |e| {
e.stop_propagation();
Msg::SetUnread(format!("id:{id}"), !is_unread)
})
]
]
]
]
}
fn message_render(msg: &ShowThreadQueryThreadMessages, open: bool) -> Node<Msg> {
let expand_id = msg.id.clone();
div![
C!["message"],
div![
C!["header"],
if open {
render_open_header(&msg)
} else {
render_closed_header(&msg)
},
ev(Ev::Click, move |e| {
e.stop_propagation();
if open {
Msg::MessageCollapse(expand_id)
} else {
Msg::MessageExpand(expand_id)
}
})
],
IF!(open =>
div![
C!["body"],
match &msg.body {
ShowThreadQueryThreadMessagesBody::UnhandledContentType(
ShowThreadQueryThreadMessagesBodyOnUnhandledContentType { contents ,content_tree},
) => div![
raw_text_message(&contents),
div![C!["error"],
view_content_tree(&content_tree),
]
],
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"],
hr![],
h2!["Attachments"],
div![C!["grid","is-col-min-6"],
msg.attachments
.iter()
.map(|a| {
let default = "UNKNOWN_FILE".to_string();
let filename = a.filename.as_ref().unwrap_or(&default);
let host = seed::window().location().host().expect("couldn't get host");
let url = shared::urls::download_attachment(Some(&host), &a.id, &a.idx, filename);
let mut fmtr = Formatter::new();
fmtr.with_separator(" ");
fmtr.with_scales(Scales::Binary());
div![
C!["attachment", "card"],
a.content_type.as_ref().map(|content_type|
IF!(content_type.starts_with("image/") =>
div![C!["card-image","is-1by1"],
div![
C!["image","is-1by1"],
style!{
St::BackgroundImage=>format!(r#"url("{url}");"#),
St::BackgroundSize=>"cover",
St::BackgroundPosition=>"center",
}
]
]
)),
div![C!["card-content"],
div![C!["content"],
&a.filename, br![],
small![ fmtr.format(a.size as f64),"B"]
]
],
footer![
C!["card-footer"],
a![C!["card-footer-item"],span![C!["icon"], i![C!["fas", "fa-download"]]],
ev(Ev::Click, move |_| {
seed::window().location().set_href(&url
).expect("failed to set URL");
})
]
]
]
})
]
]),
view_content_tree(&content_tree),
],
}
])
]
}
#[topo::nested]
fn thread(
thread: &ShowThreadQueryThread,
open_messages: &HashSet<String>,
show_icon_text: bool,
) -> Node<Msg> {
// TODO(wathiede): show per-message subject if it changes significantly from top-level subject
let subject = if thread.subject.is_empty() {
"(no subject)"
} else {
&thread.subject
};
set_title(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| {
let open = open_messages.contains(&msg.id);
message_render(&msg, open)
});
let read_thread_id = thread.thread_id.clone();
let unread_thread_id = thread.thread_id.clone();
let spam_thread_id = thread.thread_id.clone();
div![
C!["thread"],
h3![C!["is-size-5"], subject],
span![
C!["tags"],
removable_tags_chiclet(&thread.thread_id, &tags, false)
],
div![
C!["level", "is-mobile"],
div![
C!["level-item"],
div![
C!["buttons", "has-addons"],
button![
C!["button", "mark-read"],
attrs! {At::Title => "Mark as read"},
span![C!["icon", "is-small"], i![C!["far", "fa-envelope-open"]]],
IF!(show_icon_text=>span!["Read"]),
ev(Ev::Click, move |_| Msg::SetUnread(
format!("thread:{read_thread_id}"),
false
)),
],
button![
C!["button", "mark-unread"],
attrs! {At::Title => "Mark as unread"},
span![C!["icon", "is-small"], i![C!["far", "fa-envelope"]]],
IF!(show_icon_text=>span!["Unread"]),
ev(Ev::Click, move |_| Msg::SetUnread(
format!("thread:{unread_thread_id}"),
true
)),
],
],
],
div![
C!["level-item"],
div![
C!["buttons", "has-addons"],
button![
C!["button", "spam"],
attrs! {At::Title => "Spam"},
span![C!["icon", "is-small"], i![C!["far", "fa-hand"]]],
IF!(show_icon_text=>span!["Spam"]),
ev(Ev::Click, move |_| Msg::MultiMsg(vec![
Msg::AddTag(format!("thread:{spam_thread_id}"), "Spam".to_string()),
Msg::SetUnread(format!("thread:{spam_thread_id}"), 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![
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(unread_query(), 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::UpdateQuery(q)),
// Send search on enter.
keyboard_ev(Ev::KeyUp, move |e| if e.key_code() == 0x0d {
Msg::SearchQuery(query)
} else {
Msg::Noop
}),
]
]
]
}
// `view` describes what to display.
pub fn view(model: &Model) -> Node<Msg> {
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");
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)],
},]
}

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

@@ -0,0 +1,41 @@
use seed::{prelude::*, *};
use crate::{
state::{Context, Model, Msg},
view::{self, view_header, view_search_results},
};
pub(super) fn view(model: &Model) -> Node<Msg> {
log::info!("tablet::view");
let show_icon_text = false;
// 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::ThreadResult {
thread,
open_messages,
} => view::thread(thread, open_messages, show_icon_text),
Context::SearchResult {
query,
results,
count,
pager,
selected_threads,
} => view_search_results(
&query,
results.as_slice(),
*count,
pager,
selected_threads,
show_icon_text,
),
};
div![
C!["main-content"],
div![
view_header(&model.query, &model.refreshing_state),
content,
view_header(&model.query, &model.refreshing_state),
]
]
}

268
web/static/main.css Normal file
View File

@@ -0,0 +1,268 @@
/* Bulma Utilities */
.b-checkbox.checkbox {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Box-shadow on hover */
.b-checkbox.checkbox {
outline: none;
display: inline-flex;
align-items: center;
}
.b-checkbox.checkbox:not(.button) {
margin-right: 0.5em;
}
.b-checkbox.checkbox:not(.button) + .checkbox:last-child {
margin-right: 0;
}
.b-checkbox.checkbox input[type=checkbox] {
position: absolute;
left: 0;
opacity: 0;
outline: none;
z-index: -1;
}
.b-checkbox.checkbox input[type=checkbox] + .check {
width: 1.25em;
height: 1.25em;
flex-shrink: 0;
border-radius: 4px;
border: 2px solid #7a7a7a;
transition: background 150ms ease-out;
background: transparent;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check {
background: #00d1b2 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #00d1b2;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-white {
background: white url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%230a0a0a' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: white;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-black {
background: #0a0a0a url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:white' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #0a0a0a;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-light {
background: whitesmoke url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:rgba(0, 0, 0, 0.7)' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: whitesmoke;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-dark {
background: #363636 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #363636;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-primary {
background: #00d1b2 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #00d1b2;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-link {
background: #485fc7 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #485fc7;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-info {
background: #3e8ed0 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #3e8ed0;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-success {
background: #48c78e url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #48c78e;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-warning {
background: #ffe08a url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:rgba(0, 0, 0, 0.7)' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #ffe08a;
}
.b-checkbox.checkbox input[type=checkbox]:checked + .check.is-danger {
background: #f14668 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Cpath style='fill:%23fff' d='M 0.04038059,0.6267767 0.14644661,0.52071068 0.42928932,0.80355339 0.3232233,0.90961941 z M 0.21715729,0.80355339 0.85355339,0.16715729 0.95961941,0.2732233 0.3232233,0.90961941 z'%3E%3C/path%3E%3C/svg%3E") no-repeat center center;
border-color: #f14668;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check {
background: #00d1b2 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #00d1b2;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-white, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-white {
background: white url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%230a0a0a' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: white;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-black, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-black {
background: #0a0a0a url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:white' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #0a0a0a;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-light, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-light {
background: whitesmoke url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:rgba(0, 0, 0, 0.7)' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: whitesmoke;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-dark, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-dark {
background: #363636 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #363636;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-primary, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-primary {
background: #00d1b2 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #00d1b2;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-link, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-link {
background: #485fc7 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #485fc7;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-info, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-info {
background: #3e8ed0 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #3e8ed0;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-success, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-success {
background: #48c78e url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #48c78e;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-warning, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-warning {
background: #ffe08a url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:rgba(0, 0, 0, 0.7)' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #ffe08a;
}
.b-checkbox.checkbox input[type=checkbox]:indeterminate + .check.is-danger, .b-checkbox.checkbox input[type=checkbox].is-indeterminate + .check.is-danger {
background: #f14668 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect style='fill:%23fff' width='0.7' height='0.2' x='.15' y='.4'%3E%3C/rect%3E%3C/svg%3E") no-repeat center center;
border-color: #f14668;
}
.b-checkbox.checkbox input[type=checkbox]:focus + .check {
box-shadow: 0 0 0.5em rgba(122, 122, 122, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check {
box-shadow: 0 0 0.5em rgba(0, 209, 178, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-white {
box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-black {
box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-light {
box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-dark {
box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-primary {
box-shadow: 0 0 0.5em rgba(0, 209, 178, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-link {
box-shadow: 0 0 0.5em rgba(72, 95, 199, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-info {
box-shadow: 0 0 0.5em rgba(62, 142, 208, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-success {
box-shadow: 0 0 0.5em rgba(72, 199, 142, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-warning {
box-shadow: 0 0 0.5em rgba(255, 224, 138, 0.8);
}
.b-checkbox.checkbox input[type=checkbox]:focus:checked + .check.is-danger {
box-shadow: 0 0 0.5em rgba(241, 70, 104, 0.8);
}
.b-checkbox.checkbox .control-label {
padding-left: calc(0.75em - 1px);
}
.b-checkbox.checkbox.button {
display: flex;
}
.b-checkbox.checkbox[disabled] {
opacity: 0.5;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check {
border-color: #00d1b2;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-white {
border-color: white;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-black {
border-color: #0a0a0a;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-light {
border-color: whitesmoke;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-dark {
border-color: #363636;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-primary {
border-color: #00d1b2;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-link {
border-color: #485fc7;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-info {
border-color: #3e8ed0;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-success {
border-color: #48c78e;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-warning {
border-color: #ffe08a;
}
.b-checkbox.checkbox:hover input[type=checkbox]:not(:disabled) + .check.is-danger {
border-color: #f14668;
}
.b-checkbox.checkbox.is-small {
border-radius: 2px;
font-size: 0.75rem;
}
.b-checkbox.checkbox.is-medium {
font-size: 1.25rem;
}
.b-checkbox.checkbox.is-large {
font-size: 1.5rem;
}

1
web/static/main.min.css vendored Normal file

File diff suppressed because one or more lines are too long

302
web/static/style.css Normal file
View File

@@ -0,0 +1,302 @@
.message {
display: inline-block;
padding: 0.5em;
width: 100%;
}
.message .header table td {
border: 0;
padding: 0;
}
.message .header .media-right {
padding: 1rem;
}
.message .headers {
position: relative;
width: 100%;
}
.message .headers .read-status {
position: absolute;
right: 1em;
top: 0em;
}
.message .headers .header {
overflow: clip;
text-overflow: ellipsis;
white-space: nowrap;
}
.message .body {
background: white;
color: black;
margin-top: 0.5em;
padding: 1em;
width: 0;
min-width: 100%;
overflow: auto;
overflow-wrap: break-word;
}
.message .body .attachments hr {
border: none;
border-top: 1px dashed #888;
background-color: #f000;
margin: 0.5rem 0;
}
.message .body blockquote {
padding-left: 1em;
border-left: 2px solid #ddd;
}
.message .body ul,
.message .body ol,
.message .body li {
margin: revert;
padding: revert;
}
.error {
background-color: red;
}
.view-part-text-plain {
padding: 0.5em;
overflow-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
word-wrap: break-word;
}
iframe {
height: 100%;
width: 100%;
}
.index {
table-layout: fixed;
width: 100%;
}
.index .edit {
width: 2em;
}
.index .unread {
font-weight: bold;
}
.index .from {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 10em;
}
.index .subject {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.index .date {
width: 7em;
white-space: nowrap;
text-align: right;
}
.lb-footer {
background-color: #eee;
color: #222;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 3em;
padding: 1em;
}
.tag {
margin-right: 2px;
}
.debug ul {
padding-left: 2em;
}
.debug li {}
.loading {
animation-name: spin;
animation-duration: 1000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (max-width: 768px) {
.section {
padding: 1.5em;
}
}
input,
.input {
color: #000;
}
input::placeholder,
.input::placeholder {
color: #555;
}
.mobile .search-results {
padding: 1em;
}
.tablet .thread h3,
.mobile .thread h3 {
overflow-wrap: break-word;
padding: 1em 1em 0;
}
.tablet .thread .message-tags,
.mobile .thread .message-tags {
padding: 0 1em;
}
.search-results .row {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
border-bottom: 1px #444 solid;
padding-bottom: .5em;
padding-top: .5em;
width: 100%;
}
.search-results .row .checkbox {}
.search-results .row .summary {
min-width: 0;
width: 100%;
}
.search-results .row .subject {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results td.subject {}
.search-results .subject .tag {}
.search-results .subject .text {
padding-left: 0.5rem;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .row .from {
display: inline-block;
width: 100%;
}
.search-results .from a {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-results .from a {
display: inline-block;
width: 100%;
}
.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-wrap;
word-break: break-word;
word-wrap: break-word;
}
.attachment {
margin: .25em;
display: inline-block;
}
.attachment .card-content {
padding: 0.5rem 1.5rem;
}
.button.spam {
color: #f00;
}