Compare commits
516 Commits
slurp-toml
...
letterbox-
| Author | SHA1 | Date | |
|---|---|---|---|
| acd590111e | |||
| b5f24ba1f2 | |||
| 79ed24135f | |||
| a4949a25b5 | |||
| f16edef124 | |||
| 2fd6479cb9 | |||
| 85a6b3a9a4 | |||
| 9ac5216d6e | |||
| 82987dbd20 | |||
| 29de7c0727 | |||
| 5f6580fa2f | |||
| 5d4732d75d | |||
| a13bac813a | |||
| 85dcc9f7bd | |||
| b696629ad9 | |||
| b9e3128718 | |||
| 88fac4c2bc | |||
| 1fad5ec536 | |||
| 8e7214d531 | |||
| 333c4a3ebb | |||
| b9ba5a3bea | |||
| 2a0989e74d | |||
| e9319dc491 | |||
| 57481a77cd | |||
| 44915cce54 | |||
| 1225483b57 | |||
| daeb8c88a1 | |||
| 8a6b3ff501 | |||
| a6fffeafdc | |||
| d791b4ce49 | |||
| 8a0e4eb441 | |||
| fc84562419 | |||
| 37ebe1ebb3 | |||
| 2d06f070ea | |||
| 527a62069a | |||
| 40afafe1a8 | |||
| e3acf9ae6d | |||
| a68d067a68 | |||
| 5547c65af0 | |||
| b622bb7d7d | |||
| 43efdf18a0 | |||
| c71ab8e9e8 | |||
| 408d6ed8ba | |||
| 1411961e36 | |||
| dfd7ef466c | |||
| 2aa3dfbd0f | |||
| fba10e27cf | |||
| 5417c74f9c | |||
| eb0b0dbe81 | |||
| 561f522658 | |||
| 32d2ffeb3d | |||
| d41946e0a5 | |||
| 61402858f4 | |||
| 17de318645 | |||
| 3aa0144e8d | |||
| f9eafff4c7 | |||
| 4c6d67901d | |||
| e9aa97a089 | |||
| a82b047f75 | |||
| 9a8b44a8df | |||
| a96693004c | |||
| ed9fe11fbf | |||
| 09fb14a796 | |||
| 58a7936bba | |||
| cd0ee361f5 | |||
| 77bd5abe0d | |||
| 450c5496b3 | |||
| 4411e45a3c | |||
| e7d20896d5 | |||
| 32a1115abd | |||
| 4982057500 | |||
| 8977f8bab5 | |||
| 0962a6b3cf | |||
| 3c72929a4f | |||
| e4eb495a70 | |||
| 00e8b0342e | |||
| b1f9867c06 | |||
| 77943b3570 | |||
| 45e4edb1dd | |||
| 9bf53afebf | |||
| e1a502ac4b | |||
| 9346c46e62 | |||
| 1452746305 | |||
| 2e526dace1 | |||
| 76be5b7cac | |||
| 3f0b2caedf | |||
| ec6dc35ca8 | |||
| 01e1ca927e | |||
| 1cc52d6c96 | |||
| e6b3a5b5a9 | |||
| bc4b15a5aa | |||
| 00f61cf6be | |||
| 52e24437bd | |||
| 393ffc8506 | |||
| 2b6cb6ec6e | |||
| 0cba3a624c | |||
| 73433711ca | |||
| 965afa6871 | |||
| e70dbaf917 | |||
| 6b4ce11743 | |||
| d1980a55a7 | |||
| 8b78b39d4c | |||
| ae17651eb5 | |||
| 22fd8409f6 | |||
| d0a4ba417f | |||
| 7b09b098a4 | |||
| bd4c10a8fb | |||
| ed3c5f152e | |||
| 63232d1e92 | |||
| 4a3eba80d5 | |||
| 71d3745342 | |||
| 5fdc98633d | |||
| 57877f268d | |||
| 871a93d58f | |||
| 4b7cbd4f9b | |||
| aa2a9815df | |||
| 2e5b18a008 | |||
| d0a38114cc | |||
| ccc1d516c7 | |||
| 246b710fdd | |||
| 1a21c9fa8e | |||
| 9fd912b1d4 | |||
| 9ded32f97b | |||
| 10aac046bc | |||
| f4527baf89 | |||
| 11ec5bf747 | |||
| 6a53679755 | |||
| 7bedec0692 | |||
| 78feb95811 | |||
| 3aad2bb80e | |||
| 0df8de3661 | |||
| 83ecc73fbd | |||
| c10313cd12 | |||
| 4c98bcd9cb | |||
| 004de235a8 | |||
| 90dbeb6f20 | |||
| 9aa298febe | |||
| 5a13a497dc | |||
| 37711e14dd | |||
| e89fd28707 | |||
| 7a91ee2f49 | |||
| 4b76ea5392 | |||
| d2a81b7bd9 | |||
| 9dd39509b5 | |||
| d605bcfe7a | |||
| 73abdb535a | |||
| ab9506c4f6 | |||
| 994a629401 | |||
| 00c55160a7 | |||
| e3c6edb894 | |||
| 4574c016cd | |||
| ca6c19f4c8 | |||
| 0f51f6e71f | |||
| 4bd672bf94 | |||
| 136fd77f3b | |||
| ee9b6be95e | |||
| 38c553d385 | |||
| 1b073665a7 | |||
| 2076596f50 | |||
| d1beaded09 | |||
| 2562bdfedf | |||
| 86c6face7d | |||
| 4a7ff8bf7b | |||
| 8c280d3616 | |||
| eb4d4164ef | |||
| c7740811bf | |||
| 55679cf61b | |||
| 1b1c80b1b8 | |||
| 8743b1f56b | |||
| eb6f1b5346 | |||
| 6bb6d380a9 | |||
| 39eea04bf6 | |||
| 2711147cd6 | |||
| 083b7c9f1c | |||
| 5ade886a72 | |||
| 52575e13f6 | |||
| 3aaee8add3 | |||
| 5e188a70f9 | |||
| f9e5c87d2b | |||
| 7d40cf8a4a | |||
| 1836026736 | |||
| 79db0f8cfa | |||
| 95c29dc73c | |||
| 2b0ee42cdc | |||
| c90ac1d4fc | |||
| a9803bb6a1 | |||
| 74219ad333 | |||
| 2073b7b132 | |||
| 58dae5df6f | |||
| c89fc9b6d4 | |||
| f7ab08c1e6 | |||
| 221fead7dc | |||
| 3491cb9593 | |||
| 037b3231ac | |||
| 75f38c1e94 | |||
| 977bcd0bf4 | |||
| 838459e5a8 | |||
| d208a31348 | |||
| 0a640bea6f | |||
| 84a2962561 | |||
| 6c71be7a3a | |||
| 77562505b4 | |||
| c83d3dcf1d | |||
| 081077d2c2 | |||
| 4cfc6a73fc | |||
| f1c132830f | |||
| 5aff7c6e85 | |||
| 2c09713e20 | |||
| 3d544feeb5 | |||
| 5830ed0bb1 | |||
| 83aed683f5 | |||
| 72385b3987 | |||
| f21893b52e | |||
| 0b81529509 | |||
| 9790bbea83 | |||
| 7aa620a9da | |||
| 2e67db0b4e | |||
| cd777b2894 | |||
| 049e9728a2 | |||
| 0952cdf9cb | |||
| 5f4a4e81cb | |||
| 38c2c508e8 | |||
| 4cd3664e32 | |||
| 71996f6c48 | |||
| 6e227de00f | |||
| 3576e67af7 | |||
| 19f0f60653 | |||
| 3502eeb711 | |||
| fd770d03ab | |||
| d99b7ae34c | |||
| f18aa8c8d4 | |||
| dcdcb5b5a3 | |||
| 884e4b5831 | |||
| 5981356492 | |||
| 386b6915c5 | |||
| 5a6f04536f | |||
| ae1d9e6db7 | |||
| 24d50c21f5 | |||
| b4d72da639 | |||
| dacb258289 | |||
| 5c674d4603 | |||
| 2e9753e91d | |||
| 971e1049c7 | |||
| 11c76332f3 | |||
| 52d03ae964 | |||
| c4043f6c56 | |||
| dfbac38281 | |||
| f857c38625 | |||
| 23823cd85e | |||
| 30b5d0ff9f | |||
| 60a3b1ef88 | |||
| a46390d110 | |||
| 5baac0c77a | |||
| e6181d41ed | |||
| 6a228cfd5e | |||
| 8d81067206 | |||
| b2e47a9bd4 | |||
| 4eaf50cde4 | |||
| f20afe5447 | |||
| 53093f4cce | |||
| 9324a34d31 | |||
| eecc4bc3ef | |||
| 795029cb06 | |||
| bc0135106f | |||
| bd2803f81c | |||
| 215addc2c0 | |||
| 69f8e24689 | |||
| 0817a7a51b | |||
| 200933591a | |||
| 8b7c819b17 | |||
| dce433ab5a | |||
| eb4f2d8b5d | |||
| 2008457911 | |||
| f6b57e63fd | |||
| d681612e8e | |||
| 80454cbc7e | |||
| 78cf59333e | |||
| ab47f32b52 | |||
| d9d58afed9 | |||
| d01f9a7e08 | |||
| c6aabf88b9 | |||
| 29bf6d9b6d | |||
| 92bf45bd15 | |||
| 12c8e0e33b | |||
| c7aa32b922 | |||
| 94be4ec572 | |||
| 66c299bc4c | |||
| d5c4176392 | |||
| bd00542c28 | |||
| 19f029cb6b | |||
| 198db1492a | |||
| f6665b6b6e | |||
| ee93d725ba | |||
| 70fb635eda | |||
| b9fbefe05c | |||
| 46f823baae | |||
| cc1e998ec5 | |||
| fb73d8272e | |||
| 87321fb669 | |||
| 44b60d5070 | |||
| 89897aa48f | |||
| b2879211e4 | |||
| 6b3567fb1b | |||
| c27bcac549 | |||
| 25d31a6ce7 | |||
| ea280dd366 | |||
| 9842c8c99c | |||
| 906ebd73b2 | |||
| de95781ce7 | |||
| c58234fa2e | |||
| 4099bbe732 | |||
| c693d4e78a | |||
| f90ff72316 | |||
| bed6ae01f2 | |||
| 087d6b9a60 | |||
| b04caa9d5d | |||
| 17b1125ea3 | |||
| a8ac79d396 | |||
| 30cbc260dc | |||
| 4601b7e6d3 | |||
| 28b6f565fd | |||
| 48b63b19d5 | |||
| 184afbb4ee | |||
| f6217810ea | |||
| 46e2de341b | |||
| 9c56fde0b6 | |||
| 2051e5ebf2 | |||
| 5a997e61da | |||
| f27f0deb38 | |||
| 70f437b939 | |||
| 59648a1b25 | |||
| 76482c6c15 | |||
| de23bae8bd | |||
| e07c0616a2 | |||
| 13a7de4956 | |||
| 9ce0aacab0 | |||
| ae502a7dfe | |||
| 947c5970d8 | |||
| 686d163cf6 | |||
| 7c720e66f9 | |||
| 1029fd7aa2 | |||
| 61e59ea315 | |||
| 5047094bd7 | |||
| 28bd9a9d89 | |||
| 4b327eeccc | |||
| d13b5477a5 | |||
| 8cad404098 | |||
| 23de7186d6 | |||
| a26559a07e | |||
| 1bc7ad9b95 | |||
| 1ac844c08d | |||
| d7f7954e59 | |||
| ba16e537e6 | |||
| 60304a23cc | |||
| ce6aa7d167 | |||
| fb55d87876 | |||
| 63374871ac | |||
| 405dcc5ca6 | |||
| 1544405d3a | |||
| 3b547f6925 | |||
| 777f33e212 | |||
| 7c7a8c0dcb | |||
| 6c2722314b | |||
| 7827c24016 | |||
| 043e46128a | |||
| dad30357ac | |||
| 4c6b9cde39 | |||
| ffb210babb | |||
| 145d1c1787 | |||
| 1708526e33 | |||
| f8f9b753a6 | |||
| 7fbb0e0f43 | |||
| 2686670df7 | |||
| 732fb5054a | |||
| 2abfbda2f0 | |||
| cce693174e | |||
| bec7ee40b4 | |||
| 79a6245773 | |||
| 3ae1c3fdff | |||
| eab96b3f84 | |||
| 07b8db317b | |||
| 9debec8daa | |||
| b129b99fd9 | |||
| a397bcf190 | |||
| 13c80fe68f | |||
| 438ab0015e | |||
| 93f5145937 | |||
| 36fcc349ec | |||
| 63a1919872 | |||
| 5b6d18bdbc | |||
| 868d2fb434 | |||
| 6ad66a35e7 | |||
| cd750e7267 | |||
| 40be07cb07 | |||
| e794a902dd | |||
| 94576e98fc | |||
| b7dcb2e875 | |||
| aa9a243894 | |||
| 1911367aeb | |||
| 93bb4a27b9 | |||
| 0456efeed4 | |||
| 3ac2fa290f | |||
| e7feb73f6f | |||
| 5ddb4452ff | |||
| 760f90762d | |||
| 51154044cc | |||
| 06c5cb6cbf | |||
| 0dc1f2cebe | |||
| 0dec7aaf0e | |||
| 6fa8d1856a | |||
| 95a0279c68 | |||
| 80d23204fe | |||
| f45123d6d9 | |||
| 503913c54a | |||
| c4627a13b6 | |||
| e4427fe725 | |||
| 78f5f00225 | |||
| c6fc34136a | |||
| 1a270997c8 | |||
| 390fbcceac | |||
| d7214f4f29 | |||
| b9aaf87dc2 | |||
| 5ee9d754ba | |||
| dc04d54455 | |||
| 9f730e937d | |||
| 13eaf33b1a | |||
| e36f4f97f9 | |||
| 092d5781ca | |||
| 0697a5ea41 | |||
| 607e9e2251 | |||
| c547170efb | |||
| 0222985f4d | |||
| 94c03a9c7c | |||
| 4f4e474e66 | |||
| 7a1dec03a3 | |||
| f49bc071c2 | |||
| 8551f0c756 | |||
| ac4aaeb0f7 | |||
| 4ad963c3be | |||
| 7c943afc2b | |||
| 39ea5c5458 | |||
| 6d8b2de608 | |||
| 05cdcec244 | |||
| a0eb8dcba6 | |||
| 9fbfa378bb | |||
| 872771b02a | |||
| 416d82042f | |||
| a0eb291371 | |||
| 4c88ee18d3 | |||
| 410e582b44 | |||
| a3f720a51e | |||
| 962b3542ce | |||
| a6f0971f0f | |||
| 21789df60a | |||
| 584ff1504d | |||
| caff1a1ed3 | |||
| d7b4411017 | |||
| 66ada655fc | |||
| 8dea1f1bd6 | |||
| e7a865204d | |||
| 3138379e7d | |||
| 7828fa0ac8 | |||
| b770bb8986 | |||
| 07c0150d3e | |||
| f678338822 | |||
| 6e15e69254 | |||
| 2671a3b787 | |||
| 93073c9602 | |||
| 88f8a9d537 | |||
| b75b298a9d | |||
| 031b8ce80e | |||
| b0ceba3bcf | |||
| e5f5b8ff3c | |||
| afb1d291ec | |||
| 55b46ff929 | |||
| 58acd8018a | |||
| e0d0ede2ce | |||
| ac46b0e4d0 | |||
| e12ea2d7e4 | |||
| 5f052facdf | |||
| 4476749203 | |||
| 0fa860bc71 | |||
| b858b23584 | |||
| 6500e60c40 | |||
| efc991923d | |||
| 0b5e057fe6 | |||
| 822e1b0a9c | |||
| 4f21814be0 | |||
| 17da489229 | |||
| 5b8639b80f | |||
| 6c9ef912e6 | |||
| da636ca1f3 | |||
| 7880eddccd | |||
| 3ec1741f10 | |||
| f36d1e0c29 | |||
| ebf32a9905 | |||
| 005a457348 | |||
| a89a279764 | |||
| fbc426f218 | |||
| 27b480e118 | |||
| dee6ff9ba0 | |||
| 73bdcd5441 | |||
| 64a38e024d | |||
| 441b40532f | |||
| bfb6a6226d | |||
| f464585fad | |||
| 3fe61f8b09 | |||
| 43b3625656 | |||
| 6505c90f32 | |||
| 104eb189fe | |||
| b70e0018d7 | |||
| d962d515f5 | |||
| 3c8d7d4f81 | |||
| d1604f8e70 | |||
| 6f07817c0e | |||
| 0ac959ab76 |
@@ -2,3 +2,8 @@
|
||||
[build]
|
||||
rustflags = [ "--cfg=web_sys_unstable_apis" ]
|
||||
|
||||
[registry]
|
||||
global-credential-providers = ["cargo:token"]
|
||||
|
||||
[registries.xinu]
|
||||
index = "sparse+https://git.z.xinu.tv/api/packages/wathiede/cargo/"
|
||||
|
||||
67
.gitea/workflows/rust.yml
Normal file
67
.gitea/workflows/rust.yml
Normal file
@@ -0,0 +1,67 @@
|
||||
on: [push]
|
||||
|
||||
name: Continuous integration
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- run: cargo check
|
||||
|
||||
test:
|
||||
name: Test Suite
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- run: cargo test
|
||||
|
||||
trunk:
|
||||
name: Trunk
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
target: wasm32-unknown-unknown
|
||||
- run: cargo install trunk
|
||||
- run: cd web; trunk build
|
||||
|
||||
fmt:
|
||||
name: Rustfmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
components: rustfmt
|
||||
- name: Rustfmt Check
|
||||
uses: actions-rust-lang/rustfmt@v1
|
||||
|
||||
build:
|
||||
name: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- run: cargo build
|
||||
|
||||
udeps:
|
||||
name: Disallow unused dependencies
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
|
||||
- name: Run cargo-udeps
|
||||
uses: aig787/cargo-udeps-action@v1
|
||||
with:
|
||||
version: 'latest'
|
||||
args: '--all-targets'
|
||||
|
||||
3867
Cargo.lock
generated
3867
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
23
Cargo.toml
23
Cargo.toml
@@ -1,15 +1,18 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
default-members = [
|
||||
"server"
|
||||
]
|
||||
members = [
|
||||
"web",
|
||||
"server",
|
||||
"notmuch",
|
||||
"procmail2notmuch",
|
||||
"shared"
|
||||
]
|
||||
default-members = ["server"]
|
||||
members = ["web", "server", "notmuch", "procmail2notmuch", "shared"]
|
||||
|
||||
[workspace.package]
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
edition = "2021"
|
||||
license = "UNLICENSED"
|
||||
publish = ["xinu"]
|
||||
version = "0.10.10"
|
||||
repository = "https://git.z.xinu.tv/wathiede/letterbox"
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
19
Justfile
Normal file
19
Justfile
Normal file
@@ -0,0 +1,19 @@
|
||||
export CARGO_INCREMENTAL := "0"
|
||||
export RUSTFLAGS := "-D warnings"
|
||||
|
||||
default:
|
||||
@echo "Run: just patch|minor|major"
|
||||
|
||||
major: (_release "major")
|
||||
minor: (_release "minor")
|
||||
patch: (_release "patch")
|
||||
|
||||
sqlx-prepare:
|
||||
cd server; cargo sqlx prepare && git add .sqlx; git commit -m "cargo sqlx prepare" .sqlx || true
|
||||
|
||||
pull:
|
||||
git pull
|
||||
|
||||
|
||||
_release level: pull sqlx-prepare
|
||||
cargo-release release -x {{ level }} --workspace --no-confirm --registry=xinu
|
||||
1
Makefile
1
Makefile
@@ -1,5 +1,6 @@
|
||||
.PHONEY: release
|
||||
release:
|
||||
(cd server; cargo sqlx prepare && git add .sqlx; git commit -m "cargo sqlx prepare" .sqlx || true)
|
||||
bash scripts/update-crate-version.sh
|
||||
git push
|
||||
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
[package]
|
||||
name = "notmuch"
|
||||
version = "0.0.29"
|
||||
edition = "2021"
|
||||
name = "letterbox-notmuch"
|
||||
exclude = ["/testdata"]
|
||||
description = "Wrapper for calling notmuch cli"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.14"
|
||||
mailparse = "0.16.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = { version = "1.0", features = ["unbounded_depth"] }
|
||||
thiserror = "1.0.30"
|
||||
thiserror = "2.0.0"
|
||||
tracing = "0.1.41"
|
||||
|
||||
[dev-dependencies]
|
||||
itertools = "0.10.1"
|
||||
itertools = "0.14.0"
|
||||
pretty_assertions = "1"
|
||||
rayon = "1.5"
|
||||
|
||||
@@ -207,14 +207,16 @@
|
||||
//! ```
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
ffi::OsStr,
|
||||
io::{self},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use log::info;
|
||||
use log::{error, info};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::instrument;
|
||||
|
||||
/// # Number of seconds since the Epoch
|
||||
pub type UnixTime = isize;
|
||||
@@ -269,6 +271,12 @@ pub struct Headers {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bcc: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(alias = "Delivered-To")]
|
||||
pub delivered_to: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(alias = "X-Original-To")]
|
||||
pub x_original_to: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reply_to: Option<String>,
|
||||
pub date: String,
|
||||
}
|
||||
@@ -458,6 +466,8 @@ pub enum NotmuchError {
|
||||
StringUtf8Error(#[from] std::string::FromUtf8Error),
|
||||
#[error("failed to parse str as int")]
|
||||
ParseIntError(#[from] std::num::ParseIntError),
|
||||
#[error("failed to parse mail: {0}")]
|
||||
MailParseError(#[from] mailparse::MailParseError),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -465,6 +475,8 @@ pub struct Notmuch {
|
||||
config_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
// TODO: rewrite to use tokio::process::Command and make everything async to see if that helps with
|
||||
// concurrency being more parallel.
|
||||
impl Notmuch {
|
||||
pub fn with_config<P: AsRef<Path>>(config_path: P) -> Notmuch {
|
||||
Notmuch {
|
||||
@@ -472,6 +484,7 @@ impl Notmuch {
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip_all)]
|
||||
pub fn new(&self) -> Result<Vec<u8>, NotmuchError> {
|
||||
self.run_notmuch(["new"])
|
||||
}
|
||||
@@ -480,6 +493,7 @@ impl Notmuch {
|
||||
self.run_notmuch(std::iter::empty::<&str>())
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
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)?)
|
||||
@@ -489,16 +503,19 @@ impl Notmuch {
|
||||
self.tags_for_query("*")
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(tag=tag,search_term=search_term))]
|
||||
pub fn tag_add(&self, tag: &str, search_term: &str) -> Result<(), NotmuchError> {
|
||||
self.run_notmuch(["tag", &format!("+{tag}"), search_term])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(tag=tag,search_term=search_term))]
|
||||
pub fn tag_remove(&self, tag: &str, search_term: &str) -> Result<(), NotmuchError> {
|
||||
self.run_notmuch(["tag", &format!("-{tag}"), search_term])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query,offset=offset,limit=limit))]
|
||||
pub fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
@@ -507,24 +524,35 @@ impl Notmuch {
|
||||
) -> Result<SearchSummary, NotmuchError> {
|
||||
let query = if query.is_empty() { "*" } else { query };
|
||||
|
||||
let res = self.run_notmuch([
|
||||
"search",
|
||||
"--format=json",
|
||||
&format!("--offset={offset}"),
|
||||
&format!("--limit={limit}"),
|
||||
query,
|
||||
])?;
|
||||
Ok(serde_json::from_slice(&res)?)
|
||||
let res = self
|
||||
.run_notmuch([
|
||||
"search",
|
||||
"--format=json",
|
||||
&format!("--offset={offset}"),
|
||||
&format!("--limit={limit}"),
|
||||
query,
|
||||
])
|
||||
.inspect_err(|err| error!("failed to notmuch search for query '{query}': {err}"))?;
|
||||
Ok(serde_json::from_slice(&res).unwrap_or_else(|err| {
|
||||
error!("failed to decode search result for query '{query}': {err}");
|
||||
SearchSummary(Vec::new())
|
||||
}))
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
pub fn count(&self, query: &str) -> Result<usize, NotmuchError> {
|
||||
// TODO: compare speed of notmuch count for * w/ and w/o --output=threads
|
||||
let res = self.run_notmuch(["count", "--output=threads", query])?;
|
||||
// NOTE: --output=threads is technically more correct, but really slow
|
||||
// TODO: find a fast thread count path
|
||||
// let res = self.run_notmuch(["count", "--output=threads", query])?;
|
||||
let res = self.run_notmuch(["count", query])?;
|
||||
// Strip '\n' from res.
|
||||
let s = std::str::from_utf8(&res[..res.len() - 1])?;
|
||||
Ok(s.parse()?)
|
||||
let s = std::str::from_utf8(&res)?.trim();
|
||||
Ok(s.parse()
|
||||
.inspect_err(|err| error!("failed to parse count for query '{query}': {err}"))
|
||||
.unwrap_or(0))
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
pub fn show(&self, query: &str) -> Result<ThreadSet, NotmuchError> {
|
||||
let slice = self.run_notmuch([
|
||||
"show",
|
||||
@@ -543,6 +571,7 @@ impl Notmuch {
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query,part=part))]
|
||||
pub fn show_part(&self, query: &str, part: usize) -> Result<Part, NotmuchError> {
|
||||
let slice = self.run_notmuch([
|
||||
"show",
|
||||
@@ -562,25 +591,103 @@ impl Notmuch {
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(id=id))]
|
||||
pub fn show_original(&self, id: &MessageId) -> Result<Vec<u8>, NotmuchError> {
|
||||
self.show_original_part(id, 0)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(id=id,part=part))]
|
||||
pub fn show_original_part(&self, id: &MessageId, part: usize) -> Result<Vec<u8>, NotmuchError> {
|
||||
let res = self.run_notmuch(["show", "--part", &part.to_string(), id])?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
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)?)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
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)?)
|
||||
}
|
||||
|
||||
#[instrument(skip_all)]
|
||||
pub fn unread_recipients(&self) -> Result<HashMap<String, usize>, NotmuchError> {
|
||||
let slice = self.run_notmuch([
|
||||
"show",
|
||||
"--include-html=false",
|
||||
"--entire-thread=false",
|
||||
"--body=false",
|
||||
"--format=json",
|
||||
// Arbitrary limit to prevent too much work
|
||||
"--limit=1000",
|
||||
"is:unread",
|
||||
])?;
|
||||
// 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);
|
||||
deserializer.disable_recursion_limit();
|
||||
let ts: ThreadSet = serde::de::Deserialize::deserialize(&mut deserializer)?;
|
||||
deserializer.end()?;
|
||||
let mut r = HashMap::new();
|
||||
fn collect_from_thread_node(
|
||||
r: &mut HashMap<String, usize>,
|
||||
tn: &ThreadNode,
|
||||
) -> Result<(), NotmuchError> {
|
||||
let Some(msg) = &tn.0 else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut addrs = vec![];
|
||||
let hdr = &msg.headers.to;
|
||||
if let Some(to) = hdr {
|
||||
addrs.push(to);
|
||||
} else {
|
||||
let hdr = &msg.headers.x_original_to;
|
||||
if let Some(to) = hdr {
|
||||
addrs.push(to);
|
||||
} else {
|
||||
let hdr = &msg.headers.delivered_to;
|
||||
if let Some(to) = hdr {
|
||||
addrs.push(to);
|
||||
};
|
||||
};
|
||||
};
|
||||
let hdr = &msg.headers.cc;
|
||||
if let Some(cc) = hdr {
|
||||
addrs.push(cc);
|
||||
};
|
||||
for recipient in addrs {
|
||||
mailparse::addrparse(&recipient)?
|
||||
.into_inner()
|
||||
.iter()
|
||||
.for_each(|a| {
|
||||
let mailparse::MailAddr::Single(si) = a else {
|
||||
return;
|
||||
};
|
||||
let addr = &si.addr;
|
||||
|
||||
if addr == "couchmoney@gmail.com" || addr.ends_with("@xinu.tv") {
|
||||
*r.entry(addr.to_lowercase()).or_default() += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
for t in ts.0 {
|
||||
for tn in t.0 {
|
||||
collect_from_thread_node(&mut r, &tn)?;
|
||||
for sub_tn in tn.1 {
|
||||
collect_from_thread_node(&mut r, &sub_tn)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn run_notmuch<I, S>(&self, args: I) -> Result<Vec<u8>, NotmuchError>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::{
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use notmuch::Notmuch;
|
||||
use letterbox_notmuch::Notmuch;
|
||||
use rayon::iter::{ParallelBridge, ParallelIterator};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
[package]
|
||||
name = "procmail2notmuch"
|
||||
version = "0.0.29"
|
||||
edition = "2021"
|
||||
name = "letterbox-procmail2notmuch"
|
||||
description = "Tool for generating notmuch rules from procmail"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
|
||||
6
renovate.json
Normal file
6
renovate.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
]
|
||||
}
|
||||
22
server/.sqlx/query-126e16a4675e8d79f330b235f9e1b8614ab1e1526e4e69691c5ebc70d54a42ef.json
generated
Normal file
22
server/.sqlx/query-126e16a4675e8d79f330b235f9e1b8614ab1e1526e4e69691c5ebc70d54a42ef.json
generated
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\nSELECT\n url\nFROM email_photo ep\nJOIN email_address ea\nON ep.id = ea.email_photo_id\nWHERE\n address = $1\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "url",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "126e16a4675e8d79f330b235f9e1b8614ab1e1526e4e69691c5ebc70d54a42ef"
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT\n site,\n title,\n summary,\n link,\n date,\n is_read,\n uid,\n id\nFROM post\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "site",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "title",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "summary",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "link",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "date",
|
||||
"type_info": "Timestamp"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "is_read",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"name": "uid",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "id",
|
||||
"type_info": "Int4"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "1b2244c9b9b64a1395d8d266f5df5352242bbe5efe481b0852e1c1d4b40584a7"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT\n date,\n is_read,\n link,\n site,\n summary,\n title,\n name,\n homepage\nFROM\n post p\n JOIN feed f ON p.site = f.slug\nWHERE\n uid = $1\n",
|
||||
"query": "SELECT\n date,\n is_read,\n link,\n site,\n summary,\n clean_summary,\n title,\n name,\n homepage\nFROM\n post AS p\nINNER JOIN feed AS f ON p.site = f.slug\nWHERE\n uid = $1\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -30,16 +30,21 @@
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "title",
|
||||
"name": "clean_summary",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"name": "name",
|
||||
"name": "title",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "name",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 8,
|
||||
"name": "homepage",
|
||||
"type_info": "Text"
|
||||
}
|
||||
@@ -52,6 +57,7 @@
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
@@ -60,5 +66,5 @@
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "113694cd5bf0d2582ff3a635776daa608fe88abe1185958c4215646c92335afb"
|
||||
"hash": "383221a94bc3746322ba78e41cde37994440ee67dc32e88d2394c51211bde6cd"
|
||||
}
|
||||
32
server/.sqlx/query-3d271b404f06497a5dcde68cf6bf07291d70fa56058ea736ac24e91d33050c04.json
generated
Normal file
32
server/.sqlx/query-3d271b404f06497a5dcde68cf6bf07291d70fa56058ea736ac24e91d33050c04.json
generated
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT\n p.id,\n link,\n clean_summary\nFROM\n post AS p\nINNER JOIN feed AS f ON p.site = f.slug -- necessary to weed out nzb posts\nWHERE\n search_summary IS NULL\n -- TODO remove AND link ~ '^<'\nORDER BY\n ROW_NUMBER() OVER (PARTITION BY site ORDER BY date DESC)\nLIMIT 100;\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "link",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "clean_summary",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "3d271b404f06497a5dcde68cf6bf07291d70fa56058ea736ac24e91d33050c04"
|
||||
}
|
||||
24
server/.sqlx/query-8c1b3c78649135e98b89092237750088433f7ff1b7c2ddeedec553406ea9f203.json
generated
Normal file
24
server/.sqlx/query-8c1b3c78649135e98b89092237750088433f7ff1b7c2ddeedec553406ea9f203.json
generated
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT COUNT(*) AS count\nFROM\n post\nWHERE\n (\n $1::text IS NULL\n OR site = $1\n )\n AND (\n NOT $2\n OR NOT is_read\n )\n AND (\n $3::text IS NULL\n OR TO_TSVECTOR('english', search_summary)\n @@ WEBSEARCH_TO_TSQUERY('english', $3)\n )\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "count",
|
||||
"type_info": "Int8"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Bool",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "8c1b3c78649135e98b89092237750088433f7ff1b7c2ddeedec553406ea9f203"
|
||||
}
|
||||
22
server/.sqlx/query-dabd12987369cb273c0191d46645c376439d246d5a697340574c6afdac93d2cc.json
generated
Normal file
22
server/.sqlx/query-dabd12987369cb273c0191d46645c376439d246d5a697340574c6afdac93d2cc.json
generated
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\nSELECT id\nFROM feed\nWHERE slug = $1\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Int4"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "dabd12987369cb273c0191d46645c376439d246d5a697340574c6afdac93d2cc"
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT\n COUNT(*) count\nFROM\n post\nWHERE\n ($1::text IS NULL OR site = $1)\n AND (\n NOT $2\n OR NOT is_read\n )\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "count",
|
||||
"type_info": "Int8"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Bool"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "e28b890e308f483aa6bd08617548ae66294ae1e99b1cab49f5f4211e0fd7d419"
|
||||
}
|
||||
24
server/.sqlx/query-e2a448aaf4fe92fc1deda10bf844f6b9225d35758cba7c9f337c1a730aee41bd.json
generated
Normal file
24
server/.sqlx/query-e2a448aaf4fe92fc1deda10bf844f6b9225d35758cba7c9f337c1a730aee41bd.json
generated
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\nINSERT INTO feed ( name, slug, url, homepage, selector )\nVALUES ( $1, $2, $3, '', '' )\nRETURNING id\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Int4"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "e2a448aaf4fe92fc1deda10bf844f6b9225d35758cba7c9f337c1a730aee41bd"
|
||||
}
|
||||
15
server/.sqlx/query-ef8327f039dbfa8f4e59b7a77a6411252a346bf51cf940024a17d9fbb2df173c.json
generated
Normal file
15
server/.sqlx/query-ef8327f039dbfa8f4e59b7a77a6411252a346bf51cf940024a17d9fbb2df173c.json
generated
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE post SET search_summary = $1 WHERE id = $2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Int4"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ef8327f039dbfa8f4e59b7a77a6411252a346bf51cf940024a17d9fbb2df173c"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT\n site,\n date,\n is_read,\n title,\n uid,\n name\nFROM\n post p\n JOIN feed f ON p.site = f.slug\nWHERE\n ($1::text IS NULL OR site = $1)\n AND (\n NOT $2\n OR NOT is_read\n )\nORDER BY\n date DESC,\n title OFFSET $3\nLIMIT\n $4\n",
|
||||
"query": "SELECT\n site,\n date,\n is_read,\n title,\n uid,\n name\nFROM\n post p\n JOIN feed f ON p.site = f.slug\nWHERE\n ($1::text IS NULL OR site = $1)\n AND (\n NOT $2\n OR NOT is_read\n )\n AND (\n $5 :: text IS NULL\n OR to_tsvector('english', search_summary) @@ websearch_to_tsquery('english', $5)\n )\nORDER BY\n date DESC,\n title OFFSET $3\nLIMIT\n $4\n",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -39,7 +39,8 @@
|
||||
"Text",
|
||||
"Bool",
|
||||
"Int8",
|
||||
"Int8"
|
||||
"Int8",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
@@ -51,5 +52,5 @@
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "2c1954b6db3cbcabf9b878cd1c8ea01c607f46dc43a85b58e19217e7633cf337"
|
||||
"hash": "fc4607f02cc76a5f3a6629cce4507c74f52ae44820897b47365da3f339d1da06"
|
||||
}
|
||||
@@ -1,42 +1,58 @@
|
||||
[package]
|
||||
name = "server"
|
||||
version = "0.0.29"
|
||||
edition = "2021"
|
||||
default-run = "server"
|
||||
name = "letterbox-server"
|
||||
default-run = "letterbox-server"
|
||||
description = "Backend for letterbox"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
ammonia = "3.3.0"
|
||||
ammonia = "4.0.0"
|
||||
anyhow = "1.0.79"
|
||||
async-graphql = { version = "6.0.11", features = ["log"] }
|
||||
async-graphql-rocket = "6.0.11"
|
||||
async-graphql = { version = "7", features = ["log"] }
|
||||
async-graphql-rocket = "7"
|
||||
async-trait = "0.1.81"
|
||||
build-info = "0.0.38"
|
||||
cacher = {git = "http://git-private.h.xinu.tv/wathiede/cacher.git"}
|
||||
css-inline = "0.13.0"
|
||||
glog = "0.1.0"
|
||||
build-info = "0.0.40"
|
||||
cacher = { version = "0.2.0", registry = "xinu" }
|
||||
chrono = "0.4.39"
|
||||
clap = { version = "4.5.23", features = ["derive"] }
|
||||
css-inline = "0.14.0"
|
||||
futures = "0.3.31"
|
||||
html-escape = "0.2.13"
|
||||
linkify = "0.10.0"
|
||||
log = "0.4.17"
|
||||
lol_html = "1.2.0"
|
||||
mailparse = "0.15.0"
|
||||
lol_html = "2.0.0"
|
||||
mailparse = "0.16.0"
|
||||
maplit = "1.0.2"
|
||||
memmap = "0.7.0"
|
||||
notmuch = { path = "../notmuch" }
|
||||
regex = "1.11.1"
|
||||
reqwest = { version = "0.12.7", features = ["blocking"] }
|
||||
rocket = { version = "0.5.0-rc.2", features = [ "json" ] }
|
||||
rocket = { version = "0.5.0-rc.2", features = ["json"] }
|
||||
rocket_cors = "0.6.0"
|
||||
scraper = "0.20.0"
|
||||
scraper = "0.23.0"
|
||||
serde = { version = "1.0.147", features = ["derive"] }
|
||||
serde_json = "1.0.87"
|
||||
shared = { path = "../shared" }
|
||||
sqlx = { version = "0.7.4", features = ["postgres", "runtime-tokio", "time"] }
|
||||
tantivy = "0.22.0"
|
||||
thiserror = "1.0.37"
|
||||
sqlx = { version = "0.8.2", features = ["postgres", "runtime-tokio", "time"] }
|
||||
tantivy = { version = "0.24.0", optional = true }
|
||||
thiserror = "2.0.0"
|
||||
tokio = "1.26.0"
|
||||
tracing = "0.1.41"
|
||||
url = "2.5.2"
|
||||
urlencoding = "2.1.3"
|
||||
#xtracing = { path = "../../xtracing" }
|
||||
#xtracing = { git = "http://git-private.h.xinu.tv/wathiede/xtracing.git" }
|
||||
xtracing = { version = "0.3.0", registry = "xinu" }
|
||||
letterbox-notmuch = { version = "0.10.10", path = "../notmuch", registry = "xinu" }
|
||||
letterbox-shared = { version = "0.10.10", path = "../shared", registry = "xinu" }
|
||||
|
||||
[build-dependencies]
|
||||
build-info-build = "0.0.38"
|
||||
build-info-build = "0.0.40"
|
||||
|
||||
[features]
|
||||
#default = [ "tantivy" ]
|
||||
tantivy = ["dep:tantivy"]
|
||||
|
||||
@@ -11,44 +11,4 @@ port = 9345
|
||||
#log_level = "critical"
|
||||
newsreader_database_url = "postgres://newsreader@nixos-07.h.xinu.tv/newsreader"
|
||||
newsreader_tantivy_db_path = "../target/database/newsreader"
|
||||
slurp_cache_path = "/net/nasx/x/letterbox/slurp"
|
||||
|
||||
[debug.slurp_site_selectors]
|
||||
"atmeta.com" = [
|
||||
"div.entry-content"
|
||||
]
|
||||
"blog.prusa3d.com" = [
|
||||
"article.content .post-block"
|
||||
]
|
||||
"blog.cloudflare.com" = [
|
||||
".author-lists .author-name-tooltip",
|
||||
".post-full-content"
|
||||
]
|
||||
"blog.zsa.io" = [
|
||||
"section.blog-article"
|
||||
]
|
||||
"engineering.fb.com" = [
|
||||
"article"
|
||||
]
|
||||
"hackaday.com" = [
|
||||
"div.entry-featured-image",
|
||||
"div.entry-content"
|
||||
]
|
||||
"mitchellh.com" = [
|
||||
"div.w-full"
|
||||
]
|
||||
"natwelch.com" = [
|
||||
"article div.prose"
|
||||
]
|
||||
"slashdot.org" = [
|
||||
"span.story-byline",
|
||||
"div.p"
|
||||
]
|
||||
"www.redox-os.org" = [
|
||||
"div.content"
|
||||
]
|
||||
"www.smbc-comics.com" = [
|
||||
"img#cc-comic",
|
||||
"div#aftercomic img"
|
||||
]
|
||||
|
||||
slurp_cache_path = "/tmp/letterbox/slurp"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
fn main() {
|
||||
// Calling `build_info_build::build_script` collects all data and makes it available to `build_info::build_info!`
|
||||
// and `build_info::format!` in the main program.
|
||||
build_info_build::build_script();
|
||||
// Calling `build_info_build::build_script` collects all data and makes it available to `build_info::build_info!`
|
||||
// and `build_info::format!` in the main program.
|
||||
build_info_build::build_script();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP INDEX IF EXISTS post_summary_idx;
|
||||
DROP INDEX IF EXISTS post_site_idx;
|
||||
DROP INDEX IF EXISTS post_title_idx;
|
||||
@@ -0,0 +1,3 @@
|
||||
CREATE INDEX post_summary_idx ON post USING GIN (to_tsvector('english', summary));
|
||||
CREATE INDEX post_site_idx ON post USING GIN (to_tsvector('english', site));
|
||||
CREATE INDEX post_title_idx ON post USING GIN (to_tsvector('english', title));
|
||||
@@ -0,0 +1,24 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE IF EXISTS public."Email" DROP CONSTRAINT IF EXISTS email_avatar_fkey;
|
||||
ALTER TABLE IF EXISTS public."EmailDisplayName" DROP CONSTRAINT IF EXISTS email_id_fk;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_to_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_cc_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_from_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_header_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_file_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_body_id_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_thread_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_tag_fkey;
|
||||
|
||||
DROP TABLE IF EXISTS public."Email";
|
||||
DROP TABLE IF EXISTS public."EmailDisplayName";
|
||||
DROP TABLE IF EXISTS public."Message";
|
||||
DROP TABLE IF EXISTS public."Header";
|
||||
DROP TABLE IF EXISTS public."File";
|
||||
DROP TABLE IF EXISTS public."Avatar";
|
||||
DROP TABLE IF EXISTS public."Body";
|
||||
DROP TABLE IF EXISTS public."Thread";
|
||||
DROP TABLE IF EXISTS public."Tag";
|
||||
|
||||
END;
|
||||
174
server/migrations/20241218010438_create-email-tables.up.sql
Normal file
174
server/migrations/20241218010438_create-email-tables.up.sql
Normal file
@@ -0,0 +1,174 @@
|
||||
-- This script was generated by the ERD tool in pgAdmin 4.
|
||||
-- Please log an issue at https://github.com/pgadmin-org/pgadmin4/issues/new/choose if you find any bugs, including reproduction steps.
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE IF EXISTS public."Email" DROP CONSTRAINT IF EXISTS email_avatar_fkey;
|
||||
ALTER TABLE IF EXISTS public."EmailDisplayName" DROP CONSTRAINT IF EXISTS email_id_fk;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_to_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_cc_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_from_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_header_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_file_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_body_id_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_thread_fkey;
|
||||
ALTER TABLE IF EXISTS public."Message" DROP CONSTRAINT IF EXISTS message_tag_fkey;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Email"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
address text NOT NULL,
|
||||
avatar_id integer,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT avatar_id UNIQUE (avatar_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."EmailDisplayName"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
email_id integer NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Message"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
subject text,
|
||||
"from" integer,
|
||||
"to" integer,
|
||||
cc integer,
|
||||
header_id integer,
|
||||
hash text NOT NULL,
|
||||
file_id integer NOT NULL,
|
||||
date timestamp with time zone NOT NULL,
|
||||
unread boolean NOT NULL,
|
||||
body_id integer NOT NULL,
|
||||
thread_id integer NOT NULL,
|
||||
tag_id integer,
|
||||
CONSTRAINT body_id UNIQUE (body_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Header"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
key text NOT NULL,
|
||||
value text NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."File"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
path text NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Avatar"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
url text NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Body"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
text text NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Thread"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public."Tag"
|
||||
(
|
||||
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||
name text NOT NULL,
|
||||
display text,
|
||||
fg_color integer,
|
||||
bg_color integer,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
ALTER TABLE IF EXISTS public."Email"
|
||||
ADD CONSTRAINT email_avatar_fkey FOREIGN KEY (avatar_id)
|
||||
REFERENCES public."Avatar" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."EmailDisplayName"
|
||||
ADD CONSTRAINT email_id_fk FOREIGN KEY (email_id)
|
||||
REFERENCES public."Email" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_to_fkey FOREIGN KEY ("to")
|
||||
REFERENCES public."Email" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_cc_fkey FOREIGN KEY (cc)
|
||||
REFERENCES public."Email" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_from_fkey FOREIGN KEY ("from")
|
||||
REFERENCES public."Email" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_header_fkey FOREIGN KEY (header_id)
|
||||
REFERENCES public."Header" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_file_fkey FOREIGN KEY (file_id)
|
||||
REFERENCES public."File" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_body_id_fkey FOREIGN KEY (body_id)
|
||||
REFERENCES public."Body" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_thread_fkey FOREIGN KEY (thread_id)
|
||||
REFERENCES public."Thread" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
|
||||
ALTER TABLE IF EXISTS public."Message"
|
||||
ADD CONSTRAINT message_tag_fkey FOREIGN KEY (tag_id)
|
||||
REFERENCES public."Tag" (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE NO ACTION
|
||||
NOT VALID;
|
||||
|
||||
END;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Add down migration script here
|
||||
ALTER TABLE
|
||||
post DROP CONSTRAINT post_link_key;
|
||||
28
server/migrations/20241225054216_post-link-unique.up.sql
Normal file
28
server/migrations/20241225054216_post-link-unique.up.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
WITH dupes AS (
|
||||
SELECT
|
||||
uid,
|
||||
link,
|
||||
Row_number() over(
|
||||
PARTITION by link
|
||||
ORDER BY
|
||||
link
|
||||
) AS RowNumber
|
||||
FROM
|
||||
post
|
||||
)
|
||||
DELETE FROM
|
||||
post
|
||||
WHERE
|
||||
uid IN (
|
||||
SELECT
|
||||
uid
|
||||
FROM
|
||||
dupes
|
||||
WHERE
|
||||
RowNumber > 1
|
||||
);
|
||||
|
||||
ALTER TABLE
|
||||
post
|
||||
ADD
|
||||
UNIQUE (link);
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE
|
||||
post
|
||||
ALTER COLUMN
|
||||
link DROP NOT NULL;
|
||||
|
||||
ALTER TABLE
|
||||
post DROP CONSTRAINT link;
|
||||
17
server/migrations/20241225180250_post-link-non-empty.up.sql
Normal file
17
server/migrations/20241225180250_post-link-non-empty.up.sql
Normal file
@@ -0,0 +1,17 @@
|
||||
DELETE FROM
|
||||
post
|
||||
WHERE
|
||||
link IS NULL
|
||||
OR link = '';
|
||||
|
||||
ALTER TABLE
|
||||
post
|
||||
ALTER COLUMN
|
||||
link
|
||||
SET
|
||||
NOT NULL;
|
||||
|
||||
ALTER TABLE
|
||||
post
|
||||
ADD
|
||||
CONSTRAINT link CHECK (link <> '');
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP TABLE IF EXISTS email_address;
|
||||
DROP TABLE IF EXISTS photo;
|
||||
DROP TABLE IF EXISTS google_person;
|
||||
19
server/migrations/20250114045217_create-email-photos.up.sql
Normal file
19
server/migrations/20250114045217_create-email-photos.up.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Add up migration script here
|
||||
CREATE TABLE IF NOT EXISTS google_person (
|
||||
id SERIAL PRIMARY KEY,
|
||||
resource_name TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS email_photo (
|
||||
id SERIAL PRIMARY KEY,
|
||||
google_person_id INTEGER REFERENCES google_person (id) UNIQUE,
|
||||
url TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS email_address (
|
||||
id SERIAL PRIMARY KEY,
|
||||
address TEXT NOT NULL UNIQUE,
|
||||
email_photo_id INTEGER REFERENCES email_photo (id),
|
||||
google_person_id INTEGER REFERENCES google_person (id)
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Add down migration script here
|
||||
DROP INDEX post_summary_idx;
|
||||
CREATE INDEX post_summary_idx ON post USING gin (
|
||||
to_tsvector('english', summary)
|
||||
);
|
||||
11
server/migrations/20250117225159_strip-html-index.up.sql
Normal file
11
server/migrations/20250117225159_strip-html-index.up.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
-- Something like this around summary in the idx w/ tsvector
|
||||
DROP INDEX post_summary_idx;
|
||||
CREATE INDEX post_summary_idx ON post USING gin (to_tsvector(
|
||||
'english',
|
||||
regexp_replace(
|
||||
regexp_replace(summary, '<[^>]+>', ' ', 'g'),
|
||||
'\s+',
|
||||
' ',
|
||||
'g'
|
||||
)
|
||||
));
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Add down migration script here
|
||||
DROP INDEX nzb_posts_created_at_idx;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Add up migration script here
|
||||
CREATE INDEX nzb_posts_created_at_idx ON nzb_posts USING btree (created_at);
|
||||
15
server/migrations/20250128234348_add-search-summary.down.sql
Normal file
15
server/migrations/20250128234348_add-search-summary.down.sql
Normal file
@@ -0,0 +1,15 @@
|
||||
-- Add down migration script here
|
||||
BEGIN;
|
||||
DROP INDEX IF EXISTS post_search_summary_idx;
|
||||
ALTER TABLE post DROP search_summary;
|
||||
|
||||
-- CREATE INDEX post_summary_idx ON post USING gin (to_tsvector(
|
||||
-- 'english',
|
||||
-- regexp_replace(
|
||||
-- regexp_replace(summary, '<[^>]+>', ' ', 'g'),
|
||||
-- '\s+',
|
||||
-- ' ',
|
||||
-- 'g'
|
||||
-- )
|
||||
-- ));
|
||||
COMMIT;
|
||||
14
server/migrations/20250128234348_add-search-summary.up.sql
Normal file
14
server/migrations/20250128234348_add-search-summary.up.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
-- Add up migration script here
|
||||
BEGIN;
|
||||
DROP INDEX IF EXISTS post_summary_idx;
|
||||
ALTER TABLE post ADD search_summary TEXT;
|
||||
CREATE INDEX post_search_summary_idx ON post USING gin (
|
||||
to_tsvector('english', search_summary)
|
||||
);
|
||||
UPDATE post SET search_summary = regexp_replace(
|
||||
regexp_replace(summary, '<[^>]+>', ' ', 'g'),
|
||||
'\s+',
|
||||
' ',
|
||||
'g'
|
||||
);
|
||||
COMMIT;
|
||||
20
server/migrations/20250330175930_update-nzfinder-link.sql
Normal file
20
server/migrations/20250330175930_update-nzfinder-link.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
-- Bad examples:
|
||||
-- https://nzbfinder.ws/getnzb/d2c3e5a08abadd985dccc6a574122892030b6a9a.nzb&i=95972&r=b55082d289937c050dedc203c9653850
|
||||
-- https://nzbfinder.ws/getnzb?id=45add174-7da4-4445-bf2b-a67dbbfc07fe.nzb&r=b55082d289937c050dedc203c9653850
|
||||
-- https://nzbfinder.ws/api/v1/getnzb?id=82486020-c192-4fa0-a7e7-798d7d72e973.nzb&r=b55082d289937c050dedc203c9653850
|
||||
UPDATE nzb_posts
|
||||
SET link =
|
||||
regexp_replace(
|
||||
regexp_replace(
|
||||
regexp_replace(
|
||||
link,
|
||||
'https://nzbfinder.ws/getnzb/',
|
||||
'https://nzbfinder.ws/api/v1/getnzb?id='
|
||||
),
|
||||
'https://nzbfinder.ws/getnzb',
|
||||
'https://nzbfinder.ws/api/v1/getnzb'
|
||||
),
|
||||
'&r=',
|
||||
'&apikey='
|
||||
)
|
||||
;
|
||||
@@ -6,5 +6,9 @@ SELECT
|
||||
date,
|
||||
is_read,
|
||||
uid,
|
||||
id
|
||||
FROM post
|
||||
p.id id
|
||||
FROM
|
||||
post AS p
|
||||
JOIN feed AS f ON p.site = f.slug -- necessary to weed out nzb posts
|
||||
ORDER BY
|
||||
date DESC;
|
||||
|
||||
6
server/sql/all-uids.sql
Normal file
6
server/sql/all-uids.sql
Normal file
@@ -0,0 +1,6 @@
|
||||
SELECT
|
||||
uid
|
||||
FROM
|
||||
post AS p
|
||||
JOIN feed AS f ON p.site = f.slug -- necessary to weed out nzb posts
|
||||
;
|
||||
@@ -1,10 +1,17 @@
|
||||
SELECT
|
||||
COUNT(*) count
|
||||
SELECT COUNT(*) AS count
|
||||
FROM
|
||||
post
|
||||
WHERE
|
||||
($1::text IS NULL OR site = $1)
|
||||
(
|
||||
$1::text IS NULL
|
||||
OR site = $1
|
||||
)
|
||||
AND (
|
||||
NOT $2
|
||||
OR NOT is_read
|
||||
)
|
||||
AND (
|
||||
$3::text IS NULL
|
||||
OR TO_TSVECTOR('english', search_summary)
|
||||
@@ WEBSEARCH_TO_TSQUERY('english', $3)
|
||||
)
|
||||
|
||||
13
server/sql/need-search-summary.sql
Normal file
13
server/sql/need-search-summary.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
SELECT
|
||||
p.id,
|
||||
link,
|
||||
clean_summary
|
||||
FROM
|
||||
post AS p
|
||||
INNER JOIN feed AS f ON p.site = f.slug -- necessary to weed out nzb posts
|
||||
WHERE
|
||||
search_summary IS NULL
|
||||
-- TODO remove AND link ~ '^<'
|
||||
ORDER BY
|
||||
ROW_NUMBER() OVER (PARTITION BY site ORDER BY date DESC)
|
||||
LIMIT 100;
|
||||
14
server/sql/posts-from-uids.sql
Normal file
14
server/sql/posts-from-uids.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
SELECT
|
||||
site AS "site!",
|
||||
title AS "title!",
|
||||
summary AS "summary!",
|
||||
link AS "link!",
|
||||
date AS "date!",
|
||||
is_read AS "is_read!",
|
||||
uid AS "uid!",
|
||||
p.id id
|
||||
FROM
|
||||
post p
|
||||
JOIN feed f ON p.site = f.slug
|
||||
WHERE
|
||||
uid = ANY ($1);
|
||||
@@ -4,11 +4,12 @@ SELECT
|
||||
link,
|
||||
site,
|
||||
summary,
|
||||
clean_summary,
|
||||
title,
|
||||
name,
|
||||
homepage
|
||||
FROM
|
||||
post p
|
||||
JOIN feed f ON p.site = f.slug
|
||||
post AS p
|
||||
INNER JOIN feed AS f ON p.site = f.slug
|
||||
WHERE
|
||||
uid = $1
|
||||
|
||||
14
server/sql/threads-from-uid.sql
Normal file
14
server/sql/threads-from-uid.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
SELECT
|
||||
site,
|
||||
date,
|
||||
is_read,
|
||||
title,
|
||||
uid,
|
||||
name
|
||||
FROM
|
||||
post p
|
||||
JOIN feed f ON p.site = f.slug
|
||||
WHERE
|
||||
uid = ANY ($1)
|
||||
ORDER BY
|
||||
date DESC;
|
||||
@@ -14,6 +14,10 @@ WHERE
|
||||
NOT $2
|
||||
OR NOT is_read
|
||||
)
|
||||
AND (
|
||||
$5 :: text IS NULL
|
||||
OR to_tsvector('english', search_summary) @@ websearch_to_tsquery('english', $5)
|
||||
)
|
||||
ORDER BY
|
||||
date DESC,
|
||||
title OFFSET $3
|
||||
|
||||
13
server/sql/too-long-for-search.sql
Normal file
13
server/sql/too-long-for-search.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
select t.id, tt.tokid, tt.alias, length(t.token), t.token from (
|
||||
select id, (ts_parse('default',
|
||||
-- regexp_replace(
|
||||
-- regexp_replace(summary, '<[^>]+>', ' ', 'g'),
|
||||
-- '\s+',
|
||||
-- ' ',
|
||||
-- 'g'
|
||||
-- )
|
||||
summary
|
||||
)).* from post) t
|
||||
inner join ts_token_type('default') tt
|
||||
on t.tokid = tt.tokid
|
||||
where length(token) >= 2*1024;
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::fs;
|
||||
|
||||
use server::sanitize_html;
|
||||
use letterbox_server::sanitize_html;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
|
||||
22
server/src/bin/email2db.rs
Normal file
22
server/src/bin/email2db.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use clap::Parser;
|
||||
use letterbox_server::mail::read_mail_to_db;
|
||||
use sqlx::postgres::PgPool;
|
||||
|
||||
/// Add certain emails as posts in newsfeed app.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
struct Args {
|
||||
/// DB URL, something like postgres://newsreader@nixos-07.h.xinu.tv/newsreader
|
||||
#[arg(short, long)]
|
||||
db_url: String,
|
||||
/// path to parse
|
||||
path: String,
|
||||
}
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let _guard = xtracing::init(env!("CARGO_BIN_NAME"))?;
|
||||
let args = Args::parse();
|
||||
let pool = PgPool::connect(&args.db_url).await?;
|
||||
read_mail_to_db(&pool, &args.path).await?;
|
||||
Ok(())
|
||||
}
|
||||
21
server/src/bin/inline_html.rs
Normal file
21
server/src/bin/inline_html.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use std::fs;
|
||||
|
||||
use url::Url;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
println!("PWD: {}", std::env::current_dir()?.display());
|
||||
let _url = "https://slashdot.org/story/25/01/24/1813201/walgreens-replaced-fridge-doors-with-smart-screens-its-now-a-200-million-fiasco?utm_source=rss1.0mainlinkanon&utm_medium=feed";
|
||||
let _url = "https://hackaday.com/2025/01/24/hackaday-podcast-episode-305-caustic-clocks-practice-bones-and-brick-layers/";
|
||||
let _url = "https://theonion.com/monster-devastated-to-see-film-depicting-things-he-told-guillermo-del-toro-in-confidence/";
|
||||
let _url = "https://trofi.github.io/posts/330-another-nix-language-nondeterminism-example.html";
|
||||
let _url = "https://blog.cloudflare.com/ddos-threat-report-for-2024-q4/";
|
||||
let url = "https://trofi.github.io/posts/330-another-nix-language-nondeterminism-example.html";
|
||||
let body = reqwest::blocking::get(url)?.text()?;
|
||||
let output = "/tmp/h2md/output.html";
|
||||
let inliner = css_inline::CSSInliner::options()
|
||||
.base_url(Url::parse(url).ok())
|
||||
.build();
|
||||
let inlined = inliner.inline(&body)?;
|
||||
fs::write(output, inlined)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,10 +5,18 @@
|
||||
extern crate rocket;
|
||||
use std::{error::Error, io::Cursor, str::FromStr};
|
||||
|
||||
use async_graphql::{http::GraphiQLSource, EmptySubscription, Schema};
|
||||
use async_graphql::{extensions, http::GraphiQLSource, EmptySubscription, Schema};
|
||||
use async_graphql_rocket::{GraphQLQuery, GraphQLRequest, GraphQLResponse};
|
||||
use glog::Flags;
|
||||
use notmuch::{Notmuch, NotmuchError, ThreadSet};
|
||||
use cacher::FilesystemCacher;
|
||||
use letterbox_notmuch::{Notmuch, NotmuchError, ThreadSet};
|
||||
#[cfg(feature = "tantivy")]
|
||||
use letterbox_server::tantivy::TantivyConnection;
|
||||
use letterbox_server::{
|
||||
config::Config,
|
||||
error::ServerError,
|
||||
graphql::{Attachment, GraphqlSchema, Mutation, QueryRoot},
|
||||
nm::{attachment_bytes, cid_attachment_bytes},
|
||||
};
|
||||
use rocket::{
|
||||
fairing::AdHoc,
|
||||
http::{ContentType, Header},
|
||||
@@ -18,19 +26,7 @@ use rocket::{
|
||||
Response, State,
|
||||
};
|
||||
use rocket_cors::{AllowedHeaders, AllowedOrigins};
|
||||
use server::{
|
||||
config::Config,
|
||||
error::ServerError,
|
||||
graphql::{Attachment, GraphqlSchema, Mutation, QueryRoot},
|
||||
nm::{attachment_bytes, cid_attachment_bytes},
|
||||
};
|
||||
use sqlx::postgres::PgPool;
|
||||
use tantivy::{Index, IndexWriter};
|
||||
|
||||
#[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(
|
||||
@@ -166,126 +162,6 @@ fn graphiql() -> content::RawHtml<String> {
|
||||
content::RawHtml(GraphiQLSource::build().endpoint("/api/graphql").finish())
|
||||
}
|
||||
|
||||
#[rocket::post("/create-news-db")]
|
||||
fn create_news_db(config: &State<Config>) -> Result<String, Debug<ServerError>> {
|
||||
create_news_db_impl(config)?;
|
||||
Ok(format!(
|
||||
"DB created in {}\n",
|
||||
config.newsreader_tantivy_db_path
|
||||
))
|
||||
}
|
||||
fn create_news_db_impl(config: &Config) -> Result<(), ServerError> {
|
||||
std::fs::remove_dir_all(&config.newsreader_tantivy_db_path).map_err(ServerError::from)?;
|
||||
std::fs::create_dir_all(&config.newsreader_tantivy_db_path).map_err(ServerError::from)?;
|
||||
use tantivy::schema::*;
|
||||
let mut schema_builder = Schema::builder();
|
||||
schema_builder.add_text_field("site", STRING | STORED);
|
||||
schema_builder.add_text_field("title", TEXT | STORED);
|
||||
schema_builder.add_text_field("summary", TEXT);
|
||||
schema_builder.add_text_field("link", STRING | STORED);
|
||||
schema_builder.add_date_field("date", FAST);
|
||||
schema_builder.add_bool_field("is_read", FAST);
|
||||
schema_builder.add_text_field("uid", STRING | STORED);
|
||||
schema_builder.add_i64_field("id", FAST);
|
||||
|
||||
let schema = schema_builder.build();
|
||||
Index::create_in_dir(&config.newsreader_tantivy_db_path, schema).map_err(ServerError::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[rocket::post("/reindex-news-db")]
|
||||
async fn reindex_news_db(
|
||||
pool: &State<PgPool>,
|
||||
config: &State<Config>,
|
||||
) -> Result<String, Debug<ServerError>> {
|
||||
use tantivy::{doc, Term};
|
||||
|
||||
let start_time = std::time::Instant::now();
|
||||
let pool: &PgPool = pool;
|
||||
|
||||
let index =
|
||||
Index::open_in_dir(&config.newsreader_tantivy_db_path).map_err(ServerError::from)?;
|
||||
let mut index_writer = index.writer(50_000_000).map_err(ServerError::from)?;
|
||||
let schema = index.schema();
|
||||
let site = schema.get_field("site").map_err(ServerError::from)?;
|
||||
let title = schema.get_field("title").map_err(ServerError::from)?;
|
||||
let summary = schema.get_field("summary").map_err(ServerError::from)?;
|
||||
let link = schema.get_field("link").map_err(ServerError::from)?;
|
||||
let date = schema.get_field("date").map_err(ServerError::from)?;
|
||||
let is_read = schema.get_field("is_read").map_err(ServerError::from)?;
|
||||
let uid = schema.get_field("uid").map_err(ServerError::from)?;
|
||||
let id = schema.get_field("id").map_err(ServerError::from)?;
|
||||
|
||||
let rows = sqlx::query_file!("sql/all-posts.sql")
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(ServerError::from)?;
|
||||
|
||||
let total = rows.len();
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
if i % 10_000 == 0 {
|
||||
info!(
|
||||
"{i}/{total} processed, elapsed {:.2}s",
|
||||
start_time.elapsed().as_secs_f32()
|
||||
);
|
||||
}
|
||||
let id_term = Term::from_field_text(uid, &r.uid);
|
||||
index_writer.delete_term(id_term);
|
||||
index_writer
|
||||
.add_document(doc!(
|
||||
site => r.site.expect("UNKOWN_SITE"),
|
||||
title => r.title.expect("UNKOWN_TITLE"),
|
||||
// TODO: clean and extract text from HTML
|
||||
summary => r.summary.expect("UNKNOWN_SUMMARY"),
|
||||
link => r.link.expect("link"),
|
||||
date => tantivy::DateTime::from_primitive(r.date.expect("date")),
|
||||
is_read => r.is_read.expect("is_read"),
|
||||
uid => r.uid,
|
||||
id => r.id as i64,
|
||||
))
|
||||
.map_err(ServerError::from)?;
|
||||
}
|
||||
|
||||
index_writer.commit().map_err(ServerError::from)?;
|
||||
|
||||
info!("took {:.2}s to reindex", start_time.elapsed().as_secs_f32());
|
||||
Ok(format!(
|
||||
"DB openned in {}\n",
|
||||
config.newsreader_tantivy_db_path
|
||||
))
|
||||
}
|
||||
|
||||
#[rocket::get("/search-news-db")]
|
||||
fn search_news_db(
|
||||
index: &State<tantivy::Index>,
|
||||
reader: &State<tantivy::IndexReader>,
|
||||
) -> Result<String, Debug<ServerError>> {
|
||||
use tantivy::{collector::TopDocs, query::QueryParser, Document, TantivyDocument};
|
||||
|
||||
let searcher = reader.searcher();
|
||||
let schema = index.schema();
|
||||
let site = schema.get_field("site").map_err(ServerError::from)?;
|
||||
let title = schema.get_field("title").map_err(ServerError::from)?;
|
||||
let summary = schema.get_field("summary").map_err(ServerError::from)?;
|
||||
let query_parser = QueryParser::for_index(&index, vec![site, title, summary]);
|
||||
|
||||
let query = query_parser
|
||||
.parse_query("grapheme")
|
||||
.map_err(ServerError::from)?;
|
||||
let top_docs = searcher
|
||||
.search(&query, &TopDocs::with_limit(10))
|
||||
.map_err(ServerError::from)?;
|
||||
let mut results = vec![];
|
||||
info!("search found {} docs", top_docs.len());
|
||||
for (_score, doc_address) in top_docs {
|
||||
let retrieved_doc: TantivyDocument =
|
||||
searcher.doc(doc_address).map_err(ServerError::from)?;
|
||||
results.push(format!("{}", retrieved_doc.to_json(&schema)));
|
||||
}
|
||||
|
||||
Ok(format!("{}", results.join(" ")))
|
||||
}
|
||||
|
||||
#[rocket::get("/graphql?<query..>")]
|
||||
async fn graphql_query(schema: &State<GraphqlSchema>, query: GraphQLQuery) -> GraphQLResponse {
|
||||
query.execute(schema.inner()).await
|
||||
@@ -301,16 +177,9 @@ async fn graphql_request(
|
||||
|
||||
#[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 _guard = xtracing::init(env!("CARGO_BIN_NAME"))?;
|
||||
build_info::build_info!(fn bi);
|
||||
info!("Build Info: {}", shared::build_version(bi));
|
||||
info!("Build Info: {}", letterbox_shared::build_version(bi));
|
||||
let allowed_origins = AllowedOrigins::all();
|
||||
let cors = rocket_cors::CorsOptions {
|
||||
allowed_origins,
|
||||
@@ -326,13 +195,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
let rkt = rocket::build()
|
||||
.mount(
|
||||
shared::urls::MOUNT_POINT,
|
||||
letterbox_shared::urls::MOUNT_POINT,
|
||||
routes![
|
||||
create_news_db,
|
||||
reindex_news_db,
|
||||
search_news_db,
|
||||
original,
|
||||
refresh,
|
||||
show_pretty,
|
||||
show,
|
||||
graphql_query,
|
||||
@@ -347,33 +212,27 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
.attach(AdHoc::config::<Config>());
|
||||
|
||||
let config: Config = rkt.figment().extract()?;
|
||||
info!("Config:\n{config:#?}");
|
||||
if !std::fs::exists(&config.slurp_cache_path)? {
|
||||
info!("Creating slurp cache @ '{}'", &config.slurp_cache_path);
|
||||
std::fs::create_dir_all(&config.slurp_cache_path)?;
|
||||
}
|
||||
let pool = PgPool::connect(&config.newsreader_database_url).await?;
|
||||
let tantivy_newsreader_index = match Index::open_in_dir(&config.newsreader_tantivy_db_path) {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => {
|
||||
create_news_db_impl(&config)?;
|
||||
Index::open_in_dir(&config.newsreader_tantivy_db_path)?
|
||||
}
|
||||
};
|
||||
let tantivy_newsreader_reader = tantivy_newsreader_index.reader()?;
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_conn = TantivyConnection::new(&config.newsreader_tantivy_db_path)?;
|
||||
|
||||
let cacher = FilesystemCacher::new(&config.slurp_cache_path)?;
|
||||
let schema = Schema::build(QueryRoot, Mutation, EmptySubscription)
|
||||
.data(Notmuch::default())
|
||||
.data(config)
|
||||
.data(pool.clone())
|
||||
.extension(async_graphql::extensions::Logger)
|
||||
.finish();
|
||||
.data(cacher)
|
||||
.data(pool.clone());
|
||||
|
||||
let rkt = rkt
|
||||
.manage(schema)
|
||||
.manage(pool)
|
||||
.manage(Notmuch::default())
|
||||
.manage(tantivy_newsreader_index)
|
||||
.manage(tantivy_newsreader_reader);
|
||||
#[cfg(feature = "tantivy")]
|
||||
let schema = schema.data(tantivy_conn);
|
||||
|
||||
let schema = schema.extension(extensions::Logger).finish();
|
||||
|
||||
let rkt = rkt.manage(schema).manage(pool).manage(Notmuch::default());
|
||||
//.manage(Notmuch::with_config("../notmuch/testdata/notmuch.config"))
|
||||
|
||||
rkt.launch().await?;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,7 @@
|
||||
use std::{collections::HashMap, fmt::Display, str::FromStr};
|
||||
|
||||
use scraper::Selector;
|
||||
use serde::{de, Deserialize, Deserializer};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DeSelector(pub Selector);
|
||||
impl<'de> Deserialize<'de> for DeSelector {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(DeSelector(Selector::parse(&s).map_err(de::Error::custom)?))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
pub struct Config {
|
||||
pub newsreader_database_url: String,
|
||||
pub newsreader_tantivy_db_path: String,
|
||||
pub slurp_cache_path: String,
|
||||
pub slurp_site_selectors: HashMap<String, Vec<DeSelector>>,
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
pre {
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
code {
|
||||
background-color: var(--color-bg-secondary);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::{convert::Infallible, str::Utf8Error, string::FromUtf8Error};
|
||||
|
||||
use mailparse::MailParseError;
|
||||
use tantivy::TantivyError;
|
||||
use tantivy::query::QueryParserError;
|
||||
#[cfg(feature = "tantivy")]
|
||||
use tantivy::{query::QueryParserError, TantivyError};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::TransformError;
|
||||
@@ -10,7 +10,7 @@ use crate::TransformError;
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ServerError {
|
||||
#[error("notmuch: {0}")]
|
||||
NotmuchError(#[from] notmuch::NotmuchError),
|
||||
NotmuchError(#[from] letterbox_notmuch::NotmuchError),
|
||||
#[error("flatten")]
|
||||
FlattenError,
|
||||
#[error("mail parse error: {0}")]
|
||||
@@ -31,8 +31,10 @@ pub enum ServerError {
|
||||
StringError(String),
|
||||
#[error("invalid url: {0}")]
|
||||
UrlParseError(#[from] url::ParseError),
|
||||
#[cfg(feature = "tantivy")]
|
||||
#[error("tantivy error: {0}")]
|
||||
TantivyError(#[from] TantivyError),
|
||||
#[cfg(feature = "tantivy")]
|
||||
#[error("tantivy query parse error: {0}")]
|
||||
QueryParseError(#[from] QueryParserError),
|
||||
#[error("impossible: {0}")]
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
use std::{fmt, str::FromStr};
|
||||
|
||||
use async_graphql::{
|
||||
connection::{self, Connection, Edge, OpaqueCursor},
|
||||
Context, EmptySubscription, Enum, Error, FieldResult, InputObject, Object, Schema,
|
||||
SimpleObject, Union,
|
||||
};
|
||||
use cacher::FilesystemCacher;
|
||||
use letterbox_notmuch::Notmuch;
|
||||
use log::info;
|
||||
use notmuch::Notmuch;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::postgres::PgPool;
|
||||
use tokio::join;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{config::Config, newsreader, nm, Query};
|
||||
#[cfg(feature = "tantivy")]
|
||||
use crate::tantivy::TantivyConnection;
|
||||
use crate::{newsreader, nm, Query};
|
||||
|
||||
/// # Number of seconds since the Epoch
|
||||
pub type UnixTime = isize;
|
||||
@@ -16,6 +23,26 @@ pub type UnixTime = isize;
|
||||
/// # Thread ID, sans "thread:"
|
||||
pub type ThreadId = String;
|
||||
|
||||
#[derive(Debug, Enum, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum Corpus {
|
||||
Notmuch,
|
||||
Newsreader,
|
||||
Tantivy,
|
||||
}
|
||||
|
||||
impl FromStr for Corpus {
|
||||
type Err = String;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(match s {
|
||||
"notmuch" => Corpus::Notmuch,
|
||||
"newsreader" => Corpus::Newsreader,
|
||||
"tantivy" => Corpus::Tantivy,
|
||||
s => return Err(format!("unknown corpus: '{s}'")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: add is_read field and remove all use of 'tag:unread'
|
||||
#[derive(Debug, SimpleObject)]
|
||||
pub struct ThreadSummary {
|
||||
pub thread: ThreadId,
|
||||
@@ -30,6 +57,7 @@ pub struct ThreadSummary {
|
||||
pub authors: String,
|
||||
pub subject: String,
|
||||
pub tags: Vec<String>,
|
||||
pub corpus: Corpus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Union)]
|
||||
@@ -67,6 +95,10 @@ pub struct Message {
|
||||
pub to: Vec<Email>,
|
||||
// All CC headers found in email
|
||||
pub cc: Vec<Email>,
|
||||
// X-Original-To header found in email
|
||||
pub x_original_to: Option<Email>,
|
||||
// Delivered-To header found in email
|
||||
pub delivered_to: Option<Email>,
|
||||
// First Subject header found in email
|
||||
pub subject: Option<String>,
|
||||
// Parsed Date header, if found and valid
|
||||
@@ -210,6 +242,19 @@ impl Body {
|
||||
pub struct Email {
|
||||
pub name: Option<String>,
|
||||
pub addr: Option<String>,
|
||||
pub photo_url: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Display for Email {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
match (&self.name, &self.addr) {
|
||||
(Some(name), Some(addr)) => write!(f, "{name} <{addr}>")?,
|
||||
(Some(name), None) => write!(f, "{name}")?,
|
||||
(None, Some(addr)) => write!(f, "{addr}")?,
|
||||
(None, None) => write!(f, "<UNKNOWN>")?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(SimpleObject)]
|
||||
@@ -224,6 +269,17 @@ pub struct Tag {
|
||||
struct SearchCursor {
|
||||
newsreader_offset: i32,
|
||||
notmuch_offset: i32,
|
||||
#[cfg(feature = "tantivy")]
|
||||
tantivy_offset: i32,
|
||||
}
|
||||
|
||||
fn request_id() -> String {
|
||||
let now = std::time::SystemTime::now();
|
||||
let nanos = now
|
||||
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
format!("{nanos:x}")
|
||||
}
|
||||
|
||||
pub struct QueryRoot;
|
||||
@@ -231,20 +287,72 @@ pub struct QueryRoot;
|
||||
impl QueryRoot {
|
||||
async fn version<'ctx>(&self, _ctx: &Context<'ctx>) -> Result<String, Error> {
|
||||
build_info::build_info!(fn bi);
|
||||
Ok(shared::build_version(bi))
|
||||
Ok(letterbox_shared::build_version(bi))
|
||||
}
|
||||
#[instrument(skip_all, fields(query=query))]
|
||||
#[instrument(skip_all, fields(query=query, rid=request_id()))]
|
||||
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>();
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy = ctx.data_unchecked::<TantivyConnection>();
|
||||
|
||||
let newsreader_query: Query = query.parse()?;
|
||||
|
||||
let newsreader_count = newsreader::count(pool, &newsreader_query).await?;
|
||||
let notmuch_count = nm::count(nm, &newsreader_query.to_notmuch()).await?;
|
||||
info!("count {newsreader_query:?} newsreader count {newsreader_count} notmuch count {notmuch_count}");
|
||||
Ok(newsreader_count + notmuch_count)
|
||||
let notmuch_count = nm::count(nm, &newsreader_query).await?;
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_count = tantivy.count(&newsreader_query).await?;
|
||||
#[cfg(not(feature = "tantivy"))]
|
||||
let tantivy_count = 0;
|
||||
|
||||
let total = newsreader_count + notmuch_count + tantivy_count;
|
||||
info!("count {newsreader_query:?} newsreader count {newsreader_count} notmuch count {notmuch_count} tantivy count {tantivy_count} total {total}");
|
||||
Ok(total)
|
||||
}
|
||||
async fn catchup<'ctx>(
|
||||
&self,
|
||||
ctx: &Context<'ctx>,
|
||||
query: String,
|
||||
) -> Result<Vec<String>, Error> {
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
let query: Query = query.parse()?;
|
||||
// TODO: implement optimized versions of fetching just IDs
|
||||
let newsreader_fut = newsreader_search(pool, None, None, None, None, &query);
|
||||
let notmuch_fut = notmuch_search(nm, None, None, None, None, &query);
|
||||
let (newsreader_results, notmuch_results) = join!(newsreader_fut, notmuch_fut);
|
||||
|
||||
let newsreader_results = newsreader_results?;
|
||||
let notmuch_results = notmuch_results?;
|
||||
info!(
|
||||
"newsreader_results ({}) notmuch_results ({})",
|
||||
newsreader_results.len(),
|
||||
notmuch_results.len(),
|
||||
);
|
||||
|
||||
let mut results: Vec<_> = newsreader_results
|
||||
.into_iter()
|
||||
.chain(notmuch_results)
|
||||
.collect();
|
||||
// The leading '-' is to reverse sort
|
||||
results.sort_by_key(|item| match item {
|
||||
ThreadSummaryCursor::Newsreader(_, ts) => -ts.timestamp,
|
||||
ThreadSummaryCursor::Notmuch(_, ts) => -ts.timestamp,
|
||||
});
|
||||
let ids = results
|
||||
.into_iter()
|
||||
.map(|r| match r {
|
||||
ThreadSummaryCursor::Newsreader(_, ts) => ts.thread,
|
||||
ThreadSummaryCursor::Notmuch(_, ts) => ts.thread,
|
||||
})
|
||||
.collect();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
// TODO: this function doesn't get parallelism, possibly because notmuch is sync and blocks,
|
||||
// rewrite that with tokio::process:Command
|
||||
#[instrument(skip_all, fields(query=query, rid=request_id()))]
|
||||
async fn search<'ctx>(
|
||||
&self,
|
||||
ctx: &Context<'ctx>,
|
||||
@@ -254,15 +362,12 @@ impl QueryRoot {
|
||||
last: Option<i32>,
|
||||
query: String,
|
||||
) -> Result<Connection<OpaqueCursor<SearchCursor>, ThreadSummary>, Error> {
|
||||
// TODO: add keywords to limit search to one corpus, i.e. is:news or is:mail
|
||||
info!("search({after:?} {before:?} {first:?} {last:?} {query:?})",);
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy = ctx.data_unchecked::<TantivyConnection>();
|
||||
|
||||
enum ThreadSummaryCursor {
|
||||
Newsreader(i32, ThreadSummary),
|
||||
Notmuch(i32, ThreadSummary),
|
||||
}
|
||||
Ok(connection::query(
|
||||
after,
|
||||
before,
|
||||
@@ -273,64 +378,79 @@ impl QueryRoot {
|
||||
first: Option<usize>,
|
||||
last: Option<usize>| async move {
|
||||
info!(
|
||||
"search({:?} {:?} {first:?} {last:?} {query:?})",
|
||||
"search(after {:?} before {:?} first {first:?} last {last:?} query: {query:?})",
|
||||
after.as_ref().map(|v| &v.0),
|
||||
before.as_ref().map(|v| &v.0)
|
||||
);
|
||||
let newsreader_after = after.as_ref().map(|sc| sc.newsreader_offset);
|
||||
let notmuch_after = after.as_ref().map(|sc| sc.notmuch_offset);
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_after = after.as_ref().map(|sc| sc.tantivy_offset);
|
||||
|
||||
let newsreader_before = before.as_ref().map(|sc| sc.newsreader_offset);
|
||||
let notmuch_before = before.as_ref().map(|sc| sc.notmuch_offset);
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_before = before.as_ref().map(|sc| sc.tantivy_offset);
|
||||
let first = first.map(|v| v as i32);
|
||||
let last = last.map(|v| v as i32);
|
||||
|
||||
let newsreader_query: Query = query.parse()?;
|
||||
info!("newsreader_query {newsreader_query:?}");
|
||||
let newsreader_results = if newsreader_query.is_newsreader {
|
||||
newsreader::search(
|
||||
pool,
|
||||
newsreader_after,
|
||||
newsreader_before,
|
||||
first.map(|v| v as i32),
|
||||
last.map(|v| v as i32),
|
||||
&newsreader_query,
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(cur, ts)| ThreadSummaryCursor::Newsreader(cur, ts))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let query: Query = query.parse()?;
|
||||
info!("newsreader_query {query:?}");
|
||||
|
||||
let notmuch_results = if newsreader_query.is_notmuch {
|
||||
nm::search(
|
||||
nm,
|
||||
notmuch_after,
|
||||
notmuch_before,
|
||||
first.map(|v| v as i32),
|
||||
last.map(|v| v as i32),
|
||||
newsreader_query.to_notmuch(),
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(cur, ts)| ThreadSummaryCursor::Notmuch(cur, ts))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let newsreader_fut = newsreader_search(
|
||||
pool,
|
||||
newsreader_after,
|
||||
newsreader_before,
|
||||
first,
|
||||
last,
|
||||
&query,
|
||||
);
|
||||
let notmuch_fut =
|
||||
notmuch_search(nm, notmuch_after, notmuch_before, first, last, &query);
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_fut = tantivy_search(
|
||||
tantivy,
|
||||
pool,
|
||||
tantivy_after,
|
||||
tantivy_before,
|
||||
first,
|
||||
last,
|
||||
&query,
|
||||
);
|
||||
#[cfg(not(feature = "tantivy"))]
|
||||
let tantivy_fut =
|
||||
async { Ok::<Vec<ThreadSummaryCursor>, async_graphql::Error>(Vec::new()) };
|
||||
|
||||
let (newsreader_results, notmuch_results, tantivy_results) =
|
||||
join!(newsreader_fut, notmuch_fut, tantivy_fut);
|
||||
|
||||
let newsreader_results = newsreader_results?;
|
||||
let notmuch_results = notmuch_results?;
|
||||
let tantivy_results = tantivy_results?;
|
||||
info!(
|
||||
"newsreader_results ({}) notmuch_results ({}) tantivy_results ({})",
|
||||
newsreader_results.len(),
|
||||
notmuch_results.len(),
|
||||
tantivy_results.len()
|
||||
);
|
||||
|
||||
let mut results: Vec<_> = newsreader_results
|
||||
.into_iter()
|
||||
.chain(notmuch_results)
|
||||
.chain(tantivy_results)
|
||||
.collect();
|
||||
|
||||
// The leading '-' is to reverse sort
|
||||
results.sort_by_key(|item| match item {
|
||||
ThreadSummaryCursor::Newsreader(_, ts) => -ts.timestamp,
|
||||
ThreadSummaryCursor::Notmuch(_, ts) => -ts.timestamp,
|
||||
#[cfg(feature = "tantivy")]
|
||||
ThreadSummaryCursor::Tantivy(_, ts) => -ts.timestamp,
|
||||
});
|
||||
|
||||
let mut has_next_page = before.is_some();
|
||||
if let Some(first) = first {
|
||||
let first = first as usize;
|
||||
if results.len() > first {
|
||||
has_next_page = true;
|
||||
results.truncate(first);
|
||||
@@ -339,6 +459,7 @@ impl QueryRoot {
|
||||
|
||||
let mut has_previous_page = after.is_some();
|
||||
if let Some(last) = last {
|
||||
let last = last as usize;
|
||||
if results.len() > last {
|
||||
has_previous_page = true;
|
||||
results.truncate(last);
|
||||
@@ -346,8 +467,17 @@ impl QueryRoot {
|
||||
}
|
||||
|
||||
let mut connection = Connection::new(has_previous_page, has_next_page);
|
||||
let mut newsreader_offset = 0;
|
||||
let mut notmuch_offset = 0;
|
||||
// Set starting offset as the value from cursor to preserve state if no results from a corpus survived the truncation
|
||||
let mut newsreader_offset =
|
||||
after.as_ref().map(|sc| sc.newsreader_offset).unwrap_or(0);
|
||||
let mut notmuch_offset = after.as_ref().map(|sc| sc.notmuch_offset).unwrap_or(0);
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy_offset = after.as_ref().map(|sc| sc.tantivy_offset).unwrap_or(0);
|
||||
|
||||
info!(
|
||||
"newsreader_offset ({}) notmuch_offset ({})",
|
||||
newsreader_offset, notmuch_offset,
|
||||
);
|
||||
|
||||
connection.edges.extend(results.into_iter().map(|item| {
|
||||
let thread_summary;
|
||||
@@ -360,10 +490,17 @@ impl QueryRoot {
|
||||
thread_summary = ts;
|
||||
notmuch_offset = offset;
|
||||
}
|
||||
#[cfg(feature = "tantivy")]
|
||||
ThreadSummaryCursor::Tantivy(offset, ts) => {
|
||||
thread_summary = ts;
|
||||
tantivy_offset = offset;
|
||||
}
|
||||
}
|
||||
let cur = OpaqueCursor(SearchCursor {
|
||||
newsreader_offset,
|
||||
notmuch_offset,
|
||||
#[cfg(feature = "tantivy")]
|
||||
tantivy_offset,
|
||||
});
|
||||
Edge::new(cur, thread_summary)
|
||||
}));
|
||||
@@ -373,6 +510,7 @@ impl QueryRoot {
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[instrument(skip_all, fields(rid=request_id()))]
|
||||
async fn tags<'ctx>(&self, ctx: &Context<'ctx>) -> FieldResult<Vec<Tag>> {
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
@@ -381,28 +519,84 @@ impl QueryRoot {
|
||||
tags.append(&mut nm::tags(nm, needs_unread)?);
|
||||
Ok(tags)
|
||||
}
|
||||
#[instrument(skip_all, fields(thread_id=thread_id, rid=request_id()))]
|
||||
async fn thread<'ctx>(&self, ctx: &Context<'ctx>, thread_id: String) -> Result<Thread, Error> {
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let cacher = ctx.data_unchecked::<FilesystemCacher>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
let config = ctx.data_unchecked::<Config>();
|
||||
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(config, pool, thread_id).await?)
|
||||
Ok(newsreader::thread(cacher, pool, thread_id).await?)
|
||||
} else {
|
||||
Ok(nm::thread(nm, thread_id, debug_content_tree).await?)
|
||||
Ok(nm::thread(nm, pool, thread_id, debug_content_tree).await?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ThreadSummaryCursor {
|
||||
Newsreader(i32, ThreadSummary),
|
||||
Notmuch(i32, ThreadSummary),
|
||||
#[cfg(feature = "tantivy")]
|
||||
Tantivy(i32, ThreadSummary),
|
||||
}
|
||||
async fn newsreader_search(
|
||||
pool: &PgPool,
|
||||
after: Option<i32>,
|
||||
before: Option<i32>,
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
query: &Query,
|
||||
) -> Result<Vec<ThreadSummaryCursor>, async_graphql::Error> {
|
||||
Ok(newsreader::search(pool, after, before, first, last, &query)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(cur, ts)| ThreadSummaryCursor::Newsreader(cur, ts))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn notmuch_search(
|
||||
nm: &Notmuch,
|
||||
after: Option<i32>,
|
||||
before: Option<i32>,
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
query: &Query,
|
||||
) -> Result<Vec<ThreadSummaryCursor>, async_graphql::Error> {
|
||||
Ok(nm::search(nm, after, before, first, last, &query)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(cur, ts)| ThreadSummaryCursor::Notmuch(cur, ts))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(feature = "tantivy")]
|
||||
async fn tantivy_search(
|
||||
tantivy: &TantivyConnection,
|
||||
pool: &PgPool,
|
||||
after: Option<i32>,
|
||||
before: Option<i32>,
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
query: &Query,
|
||||
) -> Result<Vec<ThreadSummaryCursor>, async_graphql::Error> {
|
||||
Ok(tantivy
|
||||
.search(pool, after, before, first, last, &query)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(cur, ts)| ThreadSummaryCursor::Tantivy(cur, ts))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub struct Mutation;
|
||||
#[Object]
|
||||
impl Mutation {
|
||||
#[instrument(skip_all, fields(query=query, unread=unread, rid=request_id()))]
|
||||
async fn set_read_status<'ctx>(
|
||||
&self,
|
||||
ctx: &Context<'ctx>,
|
||||
@@ -411,16 +605,17 @@ impl Mutation {
|
||||
) -> Result<bool, Error> {
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
#[cfg(feature = "tantivy")]
|
||||
let tantivy = ctx.data_unchecked::<TantivyConnection>();
|
||||
|
||||
for q in query.split_whitespace() {
|
||||
if newsreader::is_newsreader_thread(&q) {
|
||||
newsreader::set_read_status(pool, &q, unread).await?;
|
||||
} else {
|
||||
nm::set_read_status(nm, q, unread).await?;
|
||||
}
|
||||
}
|
||||
let query: Query = query.parse()?;
|
||||
newsreader::set_read_status(pool, &query, unread).await?;
|
||||
#[cfg(feature = "tantivy")]
|
||||
tantivy.reindex_thread(pool, &query).await?;
|
||||
nm::set_read_status(nm, &query, unread).await?;
|
||||
Ok(true)
|
||||
}
|
||||
#[instrument(skip_all, fields(query=query, tag=tag, rid=request_id()))]
|
||||
async fn tag_add<'ctx>(
|
||||
&self,
|
||||
ctx: &Context<'ctx>,
|
||||
@@ -432,6 +627,7 @@ impl Mutation {
|
||||
nm.tag_add(&tag, &query)?;
|
||||
Ok(true)
|
||||
}
|
||||
#[instrument(skip_all, fields(query=query, tag=tag, rid=request_id()))]
|
||||
async fn tag_remove<'ctx>(
|
||||
&self,
|
||||
ctx: &Context<'ctx>,
|
||||
@@ -443,6 +639,32 @@ impl Mutation {
|
||||
nm.tag_remove(&tag, &query)?;
|
||||
Ok(true)
|
||||
}
|
||||
/// Drop and recreate tantivy index. Warning this is slow
|
||||
#[cfg(feature = "tantivy")]
|
||||
async fn drop_and_load_index<'ctx>(&self, ctx: &Context<'ctx>) -> Result<bool, Error> {
|
||||
let tantivy = ctx.data_unchecked::<TantivyConnection>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
|
||||
tantivy.drop_and_load_index()?;
|
||||
tantivy.reindex_all(pool).await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
#[instrument(skip_all, fields(rid=request_id()))]
|
||||
async fn refresh<'ctx>(&self, ctx: &Context<'ctx>) -> Result<bool, Error> {
|
||||
let nm = ctx.data_unchecked::<Notmuch>();
|
||||
let cacher = ctx.data_unchecked::<FilesystemCacher>();
|
||||
let pool = ctx.data_unchecked::<PgPool>();
|
||||
info!("{}", String::from_utf8_lossy(&nm.new()?));
|
||||
newsreader::refresh(pool, cacher).await?;
|
||||
#[cfg(feature = "tantivy")]
|
||||
{
|
||||
let tantivy = ctx.data_unchecked::<TantivyConnection>();
|
||||
// TODO: parallelize
|
||||
tantivy.refresh(pool).await?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub type GraphqlSchema = Schema<QueryRoot, Mutation, EmptySubscription>;
|
||||
|
||||
@@ -1,31 +1,47 @@
|
||||
pub mod config;
|
||||
pub mod error;
|
||||
pub mod graphql;
|
||||
pub mod mail;
|
||||
pub mod newsreader;
|
||||
pub mod nm;
|
||||
#[cfg(feature = "tantivy")]
|
||||
pub mod tantivy;
|
||||
|
||||
use std::{collections::HashMap, convert::Infallible, str::FromStr, sync::Arc};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
convert::Infallible,
|
||||
fmt,
|
||||
str::FromStr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cacher::{Cacher, FilesystemCacher};
|
||||
use css_inline::{CSSInliner, InlineError, InlineOptions};
|
||||
use linkify::{LinkFinder, LinkKind};
|
||||
use log::{error, info, warn};
|
||||
use log::{debug, error, info, warn};
|
||||
use lol_html::{
|
||||
element, errors::RewritingError, html_content::ContentType, rewrite_str, text,
|
||||
RewriteStrSettings,
|
||||
};
|
||||
use maplit::{hashmap, hashset};
|
||||
use regex::Regex;
|
||||
use reqwest::StatusCode;
|
||||
use scraper::{Html, Selector};
|
||||
use sqlx::types::time::PrimitiveDateTime;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
config::DeSelector,
|
||||
newsreader::{extract_thread_id, is_newsreader_thread},
|
||||
error::ServerError,
|
||||
graphql::{Corpus, ThreadSummary},
|
||||
newsreader::is_newsreader_thread,
|
||||
nm::is_notmuch_thread_or_id,
|
||||
};
|
||||
|
||||
const NEWSREADER_TAG_PREFIX: &'static str = "News/";
|
||||
const NEWSREADER_THREAD_PREFIX: &'static str = "news:";
|
||||
|
||||
// TODO: figure out how to use Cow
|
||||
#[async_trait]
|
||||
trait Transformer: Send + Sync {
|
||||
@@ -49,6 +65,8 @@ pub enum TransformError {
|
||||
ReqwestError(#[from] reqwest::Error),
|
||||
#[error("failed to parse HTML: {0}")]
|
||||
HtmlParsingError(String),
|
||||
#[error("got a retryable error code {0} for {1}")]
|
||||
RetryableHttpStatusError(StatusCode, String),
|
||||
}
|
||||
|
||||
struct SanitizeHtml<'a> {
|
||||
@@ -79,23 +97,44 @@ struct StripHtml;
|
||||
|
||||
#[async_trait]
|
||||
impl Transformer for StripHtml {
|
||||
fn should_run(&self, _: &Option<Url>, html: &str) -> bool {
|
||||
fn should_run(&self, link: &Option<Url>, html: &str) -> bool {
|
||||
debug!("StripHtml should_run {link:?} {}", html.contains("<"));
|
||||
// Lame test
|
||||
html.contains("<")
|
||||
}
|
||||
async fn transform(&self, _: &Option<Url>, html: &str) -> Result<String, TransformError> {
|
||||
async fn transform(&self, link: &Option<Url>, html: &str) -> Result<String, TransformError> {
|
||||
debug!("StripHtml {link:?}");
|
||||
let mut text = String::new();
|
||||
let element_content_handlers = vec![text!("*", |t| {
|
||||
text += t.as_str();
|
||||
Ok(())
|
||||
})];
|
||||
let _ = rewrite_str(
|
||||
let element_content_handlers = vec![
|
||||
element!("style", |el| {
|
||||
el.remove();
|
||||
Ok(())
|
||||
}),
|
||||
element!("script", |el| {
|
||||
el.remove();
|
||||
Ok(())
|
||||
}),
|
||||
];
|
||||
let html = rewrite_str(
|
||||
html,
|
||||
RewriteStrSettings {
|
||||
element_content_handlers,
|
||||
..RewriteStrSettings::default()
|
||||
},
|
||||
)?;
|
||||
let element_content_handlers = vec![text!("*", |t| {
|
||||
text += t.as_str();
|
||||
Ok(())
|
||||
})];
|
||||
let _ = rewrite_str(
|
||||
&html,
|
||||
RewriteStrSettings {
|
||||
element_content_handlers,
|
||||
..RewriteStrSettings::default()
|
||||
},
|
||||
)?;
|
||||
let re = Regex::new(r"\s+").expect("failed to parse regex");
|
||||
let text = re.replace_all(&text, " ").to_string();
|
||||
|
||||
Ok(text)
|
||||
}
|
||||
@@ -109,10 +148,10 @@ impl Transformer for InlineStyle {
|
||||
let css = concat!(
|
||||
"/* chrome-default.css */\n",
|
||||
include_str!("chrome-default.css"),
|
||||
"\n/* mvp.css */\n",
|
||||
include_str!("mvp.css"),
|
||||
"\n/* Xinu Specific overrides */\n",
|
||||
include_str!("custom.css"),
|
||||
//"\n/* mvp.css */\n",
|
||||
//include_str!("mvp.css"),
|
||||
//"\n/* Xinu Specific overrides */\n",
|
||||
//include_str!("custom.css"),
|
||||
);
|
||||
let inline_opts = InlineOptions {
|
||||
inline_style_tags: true,
|
||||
@@ -218,13 +257,14 @@ impl Transformer for AddOutlink {
|
||||
}
|
||||
}
|
||||
|
||||
struct SlurpContents<'h> {
|
||||
cacher: Arc<Mutex<FilesystemCacher>>,
|
||||
site_selectors: &'h HashMap<String, Vec<DeSelector>>,
|
||||
struct SlurpContents<'c> {
|
||||
cacher: &'c FilesystemCacher,
|
||||
inline_css: bool,
|
||||
site_selectors: HashMap<String, Vec<Selector>>,
|
||||
}
|
||||
|
||||
impl<'h> SlurpContents<'h> {
|
||||
fn get_selectors(&self, link: &Url) -> Option<&[DeSelector]> {
|
||||
impl<'c> SlurpContents<'c> {
|
||||
fn get_selectors(&self, link: &Url) -> Option<&[Selector]> {
|
||||
for (host, selector) in self.site_selectors.iter() {
|
||||
if link.host_str().map(|h| h.contains(host)).unwrap_or(false) {
|
||||
return Some(&selector);
|
||||
@@ -235,40 +275,117 @@ impl<'h> SlurpContents<'h> {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<'h> Transformer for SlurpContents<'h> {
|
||||
fn should_run(&self, link: &Option<Url>, _: &str) -> bool {
|
||||
impl<'c> Transformer for SlurpContents<'c> {
|
||||
fn should_run(&self, link: &Option<Url>, html: &str) -> bool {
|
||||
debug!("SlurpContents should_run {link:?}");
|
||||
let mut will_slurp = false;
|
||||
if let Some(link) = link {
|
||||
return self.get_selectors(link).is_some();
|
||||
will_slurp = self.get_selectors(link).is_some();
|
||||
}
|
||||
false
|
||||
if !will_slurp && self.inline_css {
|
||||
return InlineStyle {}.should_run(link, html);
|
||||
}
|
||||
will_slurp
|
||||
}
|
||||
async fn transform(&self, link: &Option<Url>, html: &str) -> Result<String, TransformError> {
|
||||
debug!("SlurpContents {link:?}");
|
||||
let retryable_status: HashSet<StatusCode> = vec![
|
||||
StatusCode::UNAUTHORIZED,
|
||||
StatusCode::FORBIDDEN,
|
||||
StatusCode::REQUEST_TIMEOUT,
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
if let Some(test_link) = link {
|
||||
// If SlurpContents is configured for inline CSS, but no
|
||||
// configuration found for this site, use the local InlineStyle
|
||||
// transform.
|
||||
if self.inline_css && self.get_selectors(test_link).is_none() {
|
||||
debug!("local inline CSS for {link:?}");
|
||||
return InlineStyle {}.transform(link, html).await;
|
||||
}
|
||||
}
|
||||
let Some(link) = link else {
|
||||
return Ok(html.to_string());
|
||||
};
|
||||
let Some(selectors) = self.get_selectors(&link) else {
|
||||
return Ok(html.to_string());
|
||||
};
|
||||
let mut cacher = self.cacher.lock().await;
|
||||
let cacher = self.cacher;
|
||||
let body = if let Some(body) = cacher.get(link.as_str()) {
|
||||
info!("cache hit for {link}");
|
||||
String::from_utf8_lossy(&body).to_string()
|
||||
} else {
|
||||
let body = reqwest::get(link.as_str()).await?.text().await?;
|
||||
let resp = reqwest::get(link.as_str()).await?;
|
||||
let status = resp.status();
|
||||
if status.is_server_error() {
|
||||
error!("status error for {link}: {status}");
|
||||
return Ok(html.to_string());
|
||||
}
|
||||
if retryable_status.contains(&status) {
|
||||
error!("retryable error for {link}: {status}");
|
||||
return Ok(html.to_string());
|
||||
}
|
||||
if !status.is_success() {
|
||||
error!("unsuccessful for {link}: {status}");
|
||||
return Ok(html.to_string());
|
||||
}
|
||||
let body = resp.text().await?;
|
||||
cacher.set(link.as_str(), body.as_bytes());
|
||||
body
|
||||
};
|
||||
let body = Arc::new(body);
|
||||
let base_url = Some(link.clone());
|
||||
let body = if self.inline_css {
|
||||
debug!("inlining CSS for {link}");
|
||||
let inner_body = Arc::clone(&body);
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let css = concat!(
|
||||
"/* chrome-default.css */\n",
|
||||
include_str!("chrome-default.css"),
|
||||
"\n/* vars.css */\n",
|
||||
include_str!("../static/vars.css"),
|
||||
//"\n/* Xinu Specific overrides */\n",
|
||||
//include_str!("custom.css"),
|
||||
);
|
||||
let res = CSSInliner::options()
|
||||
.base_url(base_url)
|
||||
.extra_css(Some(std::borrow::Cow::Borrowed(css)))
|
||||
.build()
|
||||
.inline(&inner_body);
|
||||
|
||||
match res {
|
||||
Ok(inlined_html) => inlined_html,
|
||||
Err(err) => {
|
||||
error!("failed to inline remote CSS: {err}");
|
||||
Arc::into_inner(inner_body).expect("failed to take body out of Arc")
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match res {
|
||||
Ok(inlined_html) => inlined_html,
|
||||
Err(err) => {
|
||||
error!("failed to spawn inline remote CSS: {err}");
|
||||
Arc::into_inner(body).expect("failed to take body out of Arc")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
debug!("using body as-is for {link:?}");
|
||||
Arc::into_inner(body).expect("failed to take body out of Arc")
|
||||
};
|
||||
|
||||
let doc = Html::parse_document(&body);
|
||||
|
||||
let mut results = Vec::new();
|
||||
for selector in selectors {
|
||||
for frag in doc.select(&selector.0) {
|
||||
for frag in doc.select(&selector) {
|
||||
results.push(frag.html())
|
||||
// TODO: figure out how to warn if there were no hits
|
||||
//warn!("couldn't find '{:?}' in {}", selector, link);
|
||||
}
|
||||
}
|
||||
Ok(results.join(""))
|
||||
Ok(results.join("<br>"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,6 +441,38 @@ pub fn sanitize_html(
|
||||
}
|
||||
};
|
||||
let mut element_content_handlers = vec![
|
||||
// Remove width and height attributes on elements
|
||||
element!("[width],[height]", |el| {
|
||||
println!("width or height {el:?}");
|
||||
el.remove_attribute("width");
|
||||
el.remove_attribute("height");
|
||||
Ok(())
|
||||
}),
|
||||
// Remove width and height values from inline styles
|
||||
element!("[style]", |el| {
|
||||
println!("style {el:?}");
|
||||
let style = el.get_attribute("style").unwrap();
|
||||
let style = style
|
||||
.split(";")
|
||||
.filter(|s| {
|
||||
println!("s {s}");
|
||||
let Some((k, _)) = s.split_once(':') else {
|
||||
return true;
|
||||
};
|
||||
match k {
|
||||
"width" | "max-width" | "min-width" | "height" | "max-height"
|
||||
| "min-height" => false,
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(";");
|
||||
println!("style: {style}");
|
||||
if let Err(e) = el.set_attribute("style", &style) {
|
||||
error!("Failed to set style attribute: {e}");
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
// Open links in new tab
|
||||
element!("a[href]", |el| {
|
||||
el.set_attribute("target", "_blank").unwrap();
|
||||
@@ -568,7 +717,7 @@ fn compute_offset_limit(
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
) -> (i32, i32) {
|
||||
let default_page_size = 100;
|
||||
let default_page_size = 10000;
|
||||
match (after, before, first, last) {
|
||||
// Reasonable defaults
|
||||
(None, None, None, None) => (0, default_page_size),
|
||||
@@ -598,14 +747,47 @@ fn compute_offset_limit(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Query {
|
||||
pub unread_only: bool,
|
||||
pub tag: Option<String>,
|
||||
pub uid: Option<String>,
|
||||
pub tags: Vec<String>,
|
||||
pub uids: Vec<String>,
|
||||
pub remainder: Vec<String>,
|
||||
pub is_notmuch: bool,
|
||||
pub is_newsreader: bool,
|
||||
pub is_tantivy: bool,
|
||||
pub corpus: Option<Corpus>,
|
||||
}
|
||||
|
||||
impl fmt::Display for Query {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
if self.unread_only {
|
||||
write!(f, "is:unread ")?;
|
||||
}
|
||||
for tag in &self.tags {
|
||||
write!(f, "tag:{tag} ")?;
|
||||
}
|
||||
for uid in &self.uids {
|
||||
write!(f, "id:{uid} ")?;
|
||||
}
|
||||
if self.is_notmuch {
|
||||
write!(f, "is:mail ")?;
|
||||
}
|
||||
if self.is_newsreader {
|
||||
write!(f, "is:newsreader ")?;
|
||||
}
|
||||
if self.is_newsreader {
|
||||
write!(f, "is:news ")?;
|
||||
}
|
||||
match self.corpus {
|
||||
Some(c) => write!(f, "corpus:{c:?}")?,
|
||||
_ => (),
|
||||
}
|
||||
for rem in &self.remainder {
|
||||
write!(f, "{rem} ")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Query {
|
||||
@@ -620,13 +802,25 @@ impl Query {
|
||||
if self.unread_only {
|
||||
parts.push("is:unread".to_string());
|
||||
}
|
||||
if let Some(site) = &self.tag {
|
||||
parts.push(format!("tag:{site}"));
|
||||
for tag in &self.tags {
|
||||
parts.push(format!("tag:{tag}"));
|
||||
}
|
||||
if let Some(uid) = &self.uid {
|
||||
for uid in &self.uids {
|
||||
parts.push(uid.clone());
|
||||
}
|
||||
parts.extend(self.remainder.clone());
|
||||
for r in &self.remainder {
|
||||
// Rewrite "to:" to include ExtraTo:. ExtraTo: is configured in
|
||||
// notmuch-config to index Delivered-To and X-Original-To headers.
|
||||
if r.starts_with("to:") {
|
||||
parts.push("(".to_string());
|
||||
parts.push(r.to_string());
|
||||
parts.push("OR".to_string());
|
||||
parts.push(r.replace("to:", "ExtraTo:"));
|
||||
parts.push(")".to_string());
|
||||
} else {
|
||||
parts.push(r.to_string());
|
||||
}
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
}
|
||||
@@ -635,44 +829,137 @@ impl FromStr for Query {
|
||||
type Err = Infallible;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let mut unread_only = false;
|
||||
let mut tag = None;
|
||||
let mut uid = None;
|
||||
let mut tags = Vec::new();
|
||||
let mut uids = Vec::new();
|
||||
let mut remainder = Vec::new();
|
||||
let mut is_notmuch = false;
|
||||
let mut is_newsreader = false;
|
||||
let mut is_tantivy = false;
|
||||
let mut corpus = None;
|
||||
for word in s.split_whitespace() {
|
||||
if word == "is:unread" {
|
||||
unread_only = true
|
||||
} else if word.starts_with("tag:") {
|
||||
tag = Some(word["tag:".len()..].to_string())
|
||||
let t = &word["tag:".len()..];
|
||||
// Per-address emails are faked as `tag:@<domain>/<username>`, rewrite to `to:` form
|
||||
if t.starts_with('@') && t.contains('.') {
|
||||
let t = match t.split_once('/') {
|
||||
None => format!("to:{t}"),
|
||||
Some((domain, user)) => format!("to:{user}{domain}"),
|
||||
};
|
||||
remainder.push(t);
|
||||
} else {
|
||||
tags.push(t.to_string());
|
||||
};
|
||||
|
||||
/*
|
||||
} else if word.starts_with("tag:") {
|
||||
// Any tag that doesn't match site_prefix should explicitly set the site to something not in the
|
||||
// database
|
||||
site = Some(NON_EXISTENT_SITE_NAME.to_string());
|
||||
*/
|
||||
} else if word.starts_with("corpus:") {
|
||||
let c = word["corpus:".len()..].to_string();
|
||||
corpus = c.parse::<Corpus>().map(|c| Some(c)).unwrap_or_else(|e| {
|
||||
warn!("Error parsing corpus '{c}': {e:?}");
|
||||
None
|
||||
});
|
||||
} else if is_newsreader_thread(word) {
|
||||
uid = Some(extract_thread_id(word).to_string())
|
||||
uids.push(word.to_string());
|
||||
} else if is_notmuch_thread_or_id(word) {
|
||||
uids.push(word.to_string());
|
||||
} else if word == "is:mail" || word == "is:email" || word == "is:notmuch" {
|
||||
is_notmuch = true;
|
||||
} else if word == "is:news" || word == "is:newsreader" {
|
||||
} else if word == "is:news" {
|
||||
is_newsreader = true;
|
||||
} else if word == "is:newsreader" {
|
||||
is_newsreader = true;
|
||||
} else {
|
||||
remainder.push(word.to_string());
|
||||
}
|
||||
}
|
||||
// If we don't see any explicit filters for a corpus, flip them all on
|
||||
if !(is_notmuch || is_newsreader) {
|
||||
is_newsreader = true;
|
||||
if corpus.is_none() && !(is_notmuch || is_tantivy || is_newsreader) {
|
||||
is_notmuch = true;
|
||||
is_newsreader = true;
|
||||
is_tantivy = true;
|
||||
}
|
||||
Ok(Query {
|
||||
unread_only,
|
||||
tag,
|
||||
uid,
|
||||
tags,
|
||||
uids,
|
||||
remainder,
|
||||
is_notmuch,
|
||||
is_newsreader,
|
||||
is_tantivy,
|
||||
corpus,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub struct ThreadSummaryRecord {
|
||||
pub site: Option<String>,
|
||||
pub date: Option<PrimitiveDateTime>,
|
||||
pub is_read: Option<bool>,
|
||||
pub title: Option<String>,
|
||||
pub uid: String,
|
||||
pub name: Option<String>,
|
||||
pub corpus: Corpus,
|
||||
}
|
||||
|
||||
async fn thread_summary_from_row(r: ThreadSummaryRecord) -> ThreadSummary {
|
||||
let site = r.site.unwrap_or("UNKOWN TAG".to_string());
|
||||
let mut tags = vec![format!("{NEWSREADER_TAG_PREFIX}{site}")];
|
||||
if !r.is_read.unwrap_or(true) {
|
||||
tags.push("unread".to_string());
|
||||
};
|
||||
let mut title = r.title.unwrap_or("NO TITLE".to_string());
|
||||
title = clean_title(&title).await.expect("failed to clean title");
|
||||
ThreadSummary {
|
||||
thread: format!("{NEWSREADER_THREAD_PREFIX}{}", r.uid),
|
||||
timestamp: r
|
||||
.date
|
||||
.expect("post missing date")
|
||||
.assume_utc()
|
||||
.unix_timestamp() as isize,
|
||||
date_relative: format!("{:?}", r.date),
|
||||
//date_relative: "TODO date_relative".to_string(),
|
||||
matched: 0,
|
||||
total: 1,
|
||||
authors: r.name.unwrap_or_else(|| site.clone()),
|
||||
subject: title,
|
||||
tags,
|
||||
corpus: r.corpus,
|
||||
}
|
||||
}
|
||||
async fn clean_title(title: &str) -> Result<String, ServerError> {
|
||||
// Make title HTML so html parsers work
|
||||
let mut title = format!("<html>{title}</html>");
|
||||
let title_tranformers: Vec<Box<dyn Transformer>> =
|
||||
vec![Box::new(EscapeHtml), Box::new(StripHtml)];
|
||||
// Make title HTML so html parsers work
|
||||
title = format!("<html>{title}</html>");
|
||||
for t in title_tranformers.iter() {
|
||||
if t.should_run(&None, &title) {
|
||||
title = t.transform(&None, &title).await?;
|
||||
}
|
||||
}
|
||||
Ok(title)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{SanitizeHtml, Transformer};
|
||||
|
||||
#[tokio::test]
|
||||
async fn strip_sizes() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let ss = SanitizeHtml {
|
||||
cid_prefix: "",
|
||||
base_url: &None,
|
||||
};
|
||||
let input = r#"<p width=16 height=16 style="color:blue;width:16px;height:16px;">This el has width and height attributes and inline styles</p>"#;
|
||||
let want = r#"<p style="color:blue;">This el has width and height attributes and inline styles</p>"#;
|
||||
let got = ss.transform(&None, input).await?;
|
||||
assert_eq!(got, want);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
113
server/src/mail.rs
Normal file
113
server/src/mail.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use std::{fs::File, io::Read};
|
||||
|
||||
use mailparse::{
|
||||
addrparse_header, dateparse, parse_mail, MailHeaderMap, MailParseError, ParsedMail,
|
||||
};
|
||||
use sqlx::postgres::PgPool;
|
||||
use thiserror::Error;
|
||||
use tracing::info;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum MailError {
|
||||
#[error("missing from header")]
|
||||
MissingFrom,
|
||||
#[error("missing from header display name")]
|
||||
MissingFromDisplayName,
|
||||
#[error("missing subject header")]
|
||||
MissingSubject,
|
||||
#[error("missing html part")]
|
||||
MissingHtmlPart,
|
||||
#[error("missing message ID")]
|
||||
MissingMessageId,
|
||||
#[error("missing date")]
|
||||
MissingDate,
|
||||
#[error("DB error {0}")]
|
||||
SqlxError(#[from] sqlx::Error),
|
||||
#[error("IO error {0}")]
|
||||
IOError(#[from] std::io::Error),
|
||||
#[error("mail parse error {0}")]
|
||||
MailParseError(#[from] MailParseError),
|
||||
}
|
||||
|
||||
pub async fn read_mail_to_db(pool: &PgPool, path: &str) -> Result<(), MailError> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut buffer = Vec::new();
|
||||
file.read_to_end(&mut buffer)?;
|
||||
let m = parse_mail(&buffer)?;
|
||||
|
||||
let subject = m
|
||||
.headers
|
||||
.get_first_value("subject")
|
||||
.ok_or(MailError::MissingSubject)?;
|
||||
|
||||
let from = addrparse_header(
|
||||
m.headers
|
||||
.get_first_header("from")
|
||||
.ok_or(MailError::MissingFrom)?,
|
||||
)?;
|
||||
let from = from.extract_single_info().ok_or(MailError::MissingFrom)?;
|
||||
let name = from.display_name.ok_or(MailError::MissingFromDisplayName)?;
|
||||
let slug = name.to_lowercase().replace(' ', "-");
|
||||
let url = from.addr;
|
||||
let message_id = m
|
||||
.headers
|
||||
.get_first_value("Message-ID")
|
||||
.ok_or(MailError::MissingMessageId)?;
|
||||
let uid = &message_id;
|
||||
let feed_id = find_feed(&pool, &name, &slug, &url).await?;
|
||||
let date = dateparse(
|
||||
&m.headers
|
||||
.get_first_value("Date")
|
||||
.ok_or(MailError::MissingDate)?,
|
||||
)?;
|
||||
|
||||
println!("Feed: {feed_id} Subject: {}", subject);
|
||||
|
||||
if let Some(_m) = first_html(&m) {
|
||||
info!("add email {slug} {subject} {message_id} {date} {uid} {url}");
|
||||
} else {
|
||||
return Err(MailError::MissingHtmlPart.into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
fn first_html<'m>(m: &'m ParsedMail<'m>) -> Option<&'m ParsedMail<'m>> {
|
||||
for ele in m.parts() {
|
||||
if ele.ctype.mimetype == "text/html" {
|
||||
return Some(ele);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
async fn find_feed(pool: &PgPool, name: &str, slug: &str, url: &str) -> Result<i32, MailError> {
|
||||
match sqlx::query!(
|
||||
r#"
|
||||
SELECT id
|
||||
FROM feed
|
||||
WHERE slug = $1
|
||||
"#,
|
||||
slug
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
{
|
||||
Err(sqlx::Error::RowNotFound) => {
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO feed ( name, slug, url, homepage, selector )
|
||||
VALUES ( $1, $2, $3, '', '' )
|
||||
RETURNING id
|
||||
"#,
|
||||
name,
|
||||
slug,
|
||||
url
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
|
||||
return Ok(rec.id);
|
||||
}
|
||||
Ok(rec) => return Ok(rec.id),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
}
|
||||
@@ -1,59 +1,83 @@
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cacher::FilesystemCacher;
|
||||
use log::info;
|
||||
use futures::{stream::FuturesUnordered, StreamExt};
|
||||
use letterbox_shared::compute_color;
|
||||
use log::{error, info};
|
||||
use maplit::hashmap;
|
||||
use scraper::Selector;
|
||||
use shared::compute_color;
|
||||
use sqlx::postgres::PgPool;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::instrument;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
compute_offset_limit,
|
||||
config::Config,
|
||||
clean_title, compute_offset_limit,
|
||||
error::ServerError,
|
||||
graphql::{NewsPost, Tag, Thread, ThreadSummary},
|
||||
AddOutlink, EscapeHtml, FrameImages, InlineStyle, Query, SanitizeHtml, SlurpContents,
|
||||
StripHtml, Transformer,
|
||||
graphql::{Corpus, NewsPost, Tag, Thread, ThreadSummary},
|
||||
thread_summary_from_row, AddOutlink, FrameImages, Query, SanitizeHtml, SlurpContents,
|
||||
StripHtml, ThreadSummaryRecord, Transformer, NEWSREADER_TAG_PREFIX, NEWSREADER_THREAD_PREFIX,
|
||||
};
|
||||
|
||||
const TAG_PREFIX: &'static str = "News/";
|
||||
const THREAD_PREFIX: &'static str = "news:";
|
||||
|
||||
pub fn is_newsreader_search(query: &str) -> bool {
|
||||
query.contains(TAG_PREFIX)
|
||||
pub fn is_newsreader_query(query: &Query) -> bool {
|
||||
query.is_newsreader || query.corpus == Some(Corpus::Newsreader)
|
||||
}
|
||||
|
||||
pub fn is_newsreader_thread(query: &str) -> bool {
|
||||
query.starts_with(THREAD_PREFIX)
|
||||
query.starts_with(NEWSREADER_THREAD_PREFIX)
|
||||
}
|
||||
|
||||
pub fn extract_thread_id(query: &str) -> &str {
|
||||
&query[THREAD_PREFIX.len()..]
|
||||
if query.starts_with(NEWSREADER_THREAD_PREFIX) {
|
||||
&query[NEWSREADER_THREAD_PREFIX.len()..]
|
||||
} else {
|
||||
query
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_site(tag: &str) -> &str {
|
||||
&tag[TAG_PREFIX.len()..]
|
||||
&tag[NEWSREADER_TAG_PREFIX.len()..]
|
||||
}
|
||||
|
||||
pub fn make_news_tag(tag: &str) -> String {
|
||||
format!("tag:{TAG_PREFIX}{tag}")
|
||||
format!("tag:{NEWSREADER_TAG_PREFIX}{tag}")
|
||||
}
|
||||
|
||||
fn site_from_tags(tags: &[String]) -> Option<String> {
|
||||
for t in tags {
|
||||
if t.starts_with(NEWSREADER_TAG_PREFIX) {
|
||||
return Some(extract_site(t).to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[instrument(name = "newsreader::count", skip_all, fields(query=%query))]
|
||||
pub async fn count(pool: &PgPool, query: &Query) -> Result<usize, ServerError> {
|
||||
if !query.remainder.is_empty() {
|
||||
// TODO: handle full text search against all sites, for now, early return if search words
|
||||
// are specified.
|
||||
if !is_newsreader_query(query) {
|
||||
return Ok(0);
|
||||
}
|
||||
let site = site_from_tags(&query.tags);
|
||||
if !query.tags.is_empty() && site.is_none() {
|
||||
// Newsreader can only handle all sites read/unread queries, anything with a non-site tag
|
||||
// isn't supported
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let row = sqlx::query_file!("sql/count.sql", query.tag, query.unread_only)
|
||||
let search_term = query.remainder.join(" ");
|
||||
let search_term = search_term.trim();
|
||||
let search_term = if search_term.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(search_term)
|
||||
};
|
||||
// TODO: add support for looking for search_term in title and site
|
||||
let row = sqlx::query_file!("sql/count.sql", site, query.unread_only, search_term)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row.count.unwrap_or(0).try_into().unwrap_or(0))
|
||||
}
|
||||
|
||||
#[instrument(name = "newsreader::search", skip_all, fields(query=%query))]
|
||||
pub async fn search(
|
||||
pool: &PgPool,
|
||||
after: Option<i32>,
|
||||
@@ -63,9 +87,13 @@ pub async fn search(
|
||||
query: &Query,
|
||||
) -> Result<Vec<(i32, ThreadSummary)>, async_graphql::Error> {
|
||||
info!("search({after:?} {before:?} {first:?} {last:?} {query:?}");
|
||||
if !query.remainder.is_empty() {
|
||||
// TODO: handle full text search against all sites, for now, early return if search words
|
||||
// are specified.
|
||||
if !is_newsreader_query(query) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let site = site_from_tags(&query.tags);
|
||||
if !query.tags.is_empty() && site.is_none() {
|
||||
// Newsreader can only handle all sites read/unread queries, anything with a non-site tag
|
||||
// isn't supported
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
@@ -77,53 +105,48 @@ pub async fn search(
|
||||
limit = limit + 1;
|
||||
}
|
||||
|
||||
let site = query.tag.as_ref().map(|t| extract_site(&t).to_string());
|
||||
info!(
|
||||
"search offset {offset} limit {limit} site {site:?} unread_only {}",
|
||||
query.unread_only
|
||||
);
|
||||
let search_term = query.remainder.join(" ");
|
||||
let search_term = search_term.trim();
|
||||
let search_term = if search_term.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(search_term)
|
||||
};
|
||||
|
||||
// TODO: further limit results to include query.remainder if set
|
||||
// TODO: add support for looking for search_term in title and site
|
||||
let rows = sqlx::query_file!(
|
||||
"sql/threads.sql",
|
||||
site,
|
||||
query.unread_only,
|
||||
offset as i64,
|
||||
limit as i64
|
||||
limit as i64,
|
||||
search_term
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let mut res = Vec::new();
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
let site = r.site.unwrap_or("UNKOWN TAG".to_string());
|
||||
let mut tags = vec![format!("{TAG_PREFIX}{site}")];
|
||||
if !r.is_read.unwrap_or(true) {
|
||||
tags.push("unread".to_string());
|
||||
};
|
||||
let mut title = r.title.unwrap_or("NO TITLE".to_string());
|
||||
title = clean_title(&title).await.expect("failed to clean title");
|
||||
res.push((
|
||||
i as i32 + offset,
|
||||
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: title,
|
||||
tags,
|
||||
},
|
||||
thread_summary_from_row(ThreadSummaryRecord {
|
||||
site: r.site,
|
||||
date: r.date,
|
||||
is_read: r.is_read,
|
||||
title: r.title,
|
||||
uid: r.uid,
|
||||
name: r.name,
|
||||
corpus: Corpus::Newsreader,
|
||||
})
|
||||
.await,
|
||||
));
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
#[instrument(name = "newsreader::tags", skip_all, fields(needs_unread=%_needs_unread))]
|
||||
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?;
|
||||
@@ -131,7 +154,10 @@ pub async fn tags(pool: &PgPool, _needs_unread: bool) -> Result<Vec<Tag>, Server
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let unread = tag.unread.unwrap_or(0).try_into().unwrap_or(0);
|
||||
let name = format!("{TAG_PREFIX}{}", tag.site.expect("tag must have site"));
|
||||
let name = format!(
|
||||
"{NEWSREADER_TAG_PREFIX}{}",
|
||||
tag.site.expect("tag must have site")
|
||||
);
|
||||
let hex = compute_color(&name);
|
||||
Tag {
|
||||
name,
|
||||
@@ -144,14 +170,15 @@ pub async fn tags(pool: &PgPool, _needs_unread: bool) -> Result<Vec<Tag>, Server
|
||||
Ok(tags)
|
||||
}
|
||||
|
||||
#[instrument(name = "newsreader::thread", skip_all, fields(thread_id=%thread_id))]
|
||||
pub async fn thread(
|
||||
config: &Config,
|
||||
cacher: &FilesystemCacher,
|
||||
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}'")
|
||||
.strip_prefix(NEWSREADER_THREAD_PREFIX)
|
||||
.expect("news thread doesn't start with '{NEWSREADER_THREAD_PREFIX}'")
|
||||
.to_string();
|
||||
|
||||
let r = sqlx::query_file!("sql/thread.sql", id)
|
||||
@@ -160,39 +187,25 @@ pub async fn thread(
|
||||
|
||||
let slug = r.site.unwrap_or("no-slug".to_string());
|
||||
let site = r.name.unwrap_or("NO SITE".to_string());
|
||||
let default_homepage = "http://no-homepage";
|
||||
let link = &r
|
||||
.link
|
||||
.as_ref()
|
||||
.map(|h| {
|
||||
if h.is_empty() {
|
||||
default_homepage.to_string()
|
||||
} else {
|
||||
h.to_string()
|
||||
}
|
||||
})
|
||||
.map(|h| Url::parse(&h).ok())
|
||||
.flatten();
|
||||
let mut body = 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. imperialviolent
|
||||
let cacher = Arc::new(Mutex::new(FilesystemCacher::new(&config.slurp_cache_path)?));
|
||||
let body_tranformers: Vec<Box<dyn Transformer>> = vec![
|
||||
// TODO: remove the various places that have this as an Option
|
||||
let link = Some(Url::parse(&r.link)?);
|
||||
let mut body = r.clean_summary.unwrap_or("NO SUMMARY".to_string());
|
||||
let body_transformers: Vec<Box<dyn Transformer>> = vec![
|
||||
Box::new(SlurpContents {
|
||||
cacher,
|
||||
site_selectors: &config.slurp_site_selectors,
|
||||
inline_css: true,
|
||||
site_selectors: slurp_contents_selectors(),
|
||||
}),
|
||||
Box::new(FrameImages),
|
||||
Box::new(AddOutlink),
|
||||
Box::new(EscapeHtml),
|
||||
// TODO: causes doubling of images in cloudflare blogs
|
||||
//Box::new(EscapeHtml),
|
||||
Box::new(SanitizeHtml {
|
||||
cid_prefix: "",
|
||||
base_url: &link,
|
||||
}),
|
||||
Box::new(InlineStyle),
|
||||
];
|
||||
for t in body_tranformers.iter() {
|
||||
for t in body_transformers.iter() {
|
||||
if t.should_run(&link, &body) {
|
||||
body = t.transform(&link, &body).await?;
|
||||
}
|
||||
@@ -218,28 +231,154 @@ pub async fn thread(
|
||||
timestamp,
|
||||
}))
|
||||
}
|
||||
#[instrument(name = "newsreader::set_read_status", skip_all, fields(query=%query,unread=%unread))]
|
||||
pub async fn set_read_status<'ctx>(
|
||||
pool: &PgPool,
|
||||
query: &str,
|
||||
query: &Query,
|
||||
unread: bool,
|
||||
) -> Result<bool, ServerError> {
|
||||
let query: Query = query.parse()?;
|
||||
sqlx::query_file!("sql/set_unread.sql", !unread, query.uid)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
// TODO: make single query when query.uids.len() > 1
|
||||
let uids: Vec<_> = query
|
||||
.uids
|
||||
.iter()
|
||||
.filter(|uid| is_newsreader_thread(uid))
|
||||
.map(
|
||||
|uid| extract_thread_id(uid), // TODO strip prefix
|
||||
)
|
||||
.collect();
|
||||
for uid in uids {
|
||||
sqlx::query_file!("sql/set_unread.sql", !unread, uid)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
async fn clean_title(title: &str) -> Result<String, ServerError> {
|
||||
// Make title HTML so html parsers work
|
||||
let mut title = format!("<html>{title}</html>");
|
||||
let title_tranformers: Vec<Box<dyn Transformer>> =
|
||||
vec![Box::new(EscapeHtml), Box::new(StripHtml)];
|
||||
// Make title HTML so html parsers work
|
||||
title = format!("<html>{title}</html>");
|
||||
for t in title_tranformers.iter() {
|
||||
if t.should_run(&None, &title) {
|
||||
title = t.transform(&None, &title).await?;
|
||||
#[instrument(name = "newsreader::refresh", skip_all)]
|
||||
pub async fn refresh<'ctx>(pool: &PgPool, cacher: &FilesystemCacher) -> Result<bool, ServerError> {
|
||||
async fn update_search_summary(
|
||||
pool: &PgPool,
|
||||
cacher: &FilesystemCacher,
|
||||
link: String,
|
||||
body: String,
|
||||
id: i32,
|
||||
) -> Result<(), ServerError> {
|
||||
let slurp_contents = SlurpContents {
|
||||
cacher,
|
||||
inline_css: true,
|
||||
site_selectors: slurp_contents_selectors(),
|
||||
};
|
||||
let strip_html = StripHtml;
|
||||
|
||||
info!("adding {link} to search index");
|
||||
let mut body = body;
|
||||
if let Ok(link) = Url::parse(&link) {
|
||||
let link = Some(link);
|
||||
if slurp_contents.should_run(&link, &body) {
|
||||
body = slurp_contents.transform(&link, &body).await?;
|
||||
}
|
||||
} else {
|
||||
error!("failed to parse link: {}", link);
|
||||
}
|
||||
body = strip_html.transform(&None, &body).await?;
|
||||
sqlx::query!(
|
||||
"UPDATE post SET search_summary = $1 WHERE id = $2",
|
||||
body,
|
||||
id
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
Ok(title)
|
||||
|
||||
let mut unordered: FuturesUnordered<_> = sqlx::query_file!("sql/need-search-summary.sql",)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let Some(body) = r.clean_summary else {
|
||||
error!("clean_summary missing for {}", r.link);
|
||||
return None;
|
||||
};
|
||||
let id = r.id;
|
||||
Some(update_search_summary(pool, cacher, r.link, body, id))
|
||||
})
|
||||
.collect();
|
||||
|
||||
while let Some(res) = unordered.next().await {
|
||||
//let res = res;
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
info!("failed refresh {err:?}");
|
||||
// TODO:
|
||||
//fd.error = Some(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn slurp_contents_selectors() -> HashMap<String, Vec<Selector>> {
|
||||
hashmap![
|
||||
"atmeta.com".to_string() => vec![
|
||||
Selector::parse("div.entry-content").unwrap(),
|
||||
],
|
||||
"blog.prusa3d.com".to_string() => vec![
|
||||
Selector::parse("article.content .post-block").unwrap(),
|
||||
],
|
||||
"blog.cloudflare.com".to_string() => vec![
|
||||
Selector::parse(".author-lists .author-name-tooltip").unwrap(),
|
||||
Selector::parse(".post-full-content").unwrap()
|
||||
],
|
||||
"blog.zsa.io".to_string() => vec![
|
||||
Selector::parse("section.blog-article").unwrap(),
|
||||
],
|
||||
"engineering.fb.com".to_string() => vec![
|
||||
Selector::parse("article").unwrap(),
|
||||
],
|
||||
"grafana.com".to_string() => vec![
|
||||
Selector::parse(".blog-content").unwrap(),
|
||||
],
|
||||
"hackaday.com".to_string() => vec![
|
||||
Selector::parse("div.entry-featured-image").unwrap(),
|
||||
Selector::parse("div.entry-content").unwrap()
|
||||
],
|
||||
"ingowald.blog".to_string() => vec![
|
||||
Selector::parse("article").unwrap(),
|
||||
],
|
||||
"jvns.ca".to_string() => vec![
|
||||
Selector::parse("article").unwrap(),
|
||||
],
|
||||
"mitchellh.com".to_string() => vec![Selector::parse("div.w-full").unwrap()],
|
||||
"natwelch.com".to_string() => vec![
|
||||
Selector::parse("article div.prose").unwrap(),
|
||||
],
|
||||
"rustacean-station.org".to_string() => vec![
|
||||
Selector::parse("article").unwrap(),
|
||||
],
|
||||
"slashdot.org".to_string() => vec![
|
||||
Selector::parse("span.story-byline").unwrap(),
|
||||
Selector::parse("div.p").unwrap(),
|
||||
],
|
||||
"theonion.com".to_string() => vec![
|
||||
// Single image joke w/ title
|
||||
Selector::parse("article > section > div > figure").unwrap(),
|
||||
// Single cartoon
|
||||
Selector::parse("article > div > div > figure").unwrap(),
|
||||
// Image at top of article
|
||||
Selector::parse("article > header > div > div > figure").unwrap(),
|
||||
// Article body
|
||||
Selector::parse("article .entry-content > *").unwrap(),
|
||||
],
|
||||
"trofi.github.io".to_string() => vec![
|
||||
Selector::parse("#content").unwrap(),
|
||||
],
|
||||
"www.redox-os.org".to_string() => vec![
|
||||
Selector::parse("div.content").unwrap(),
|
||||
],
|
||||
"www.smbc-comics.com".to_string() => vec![
|
||||
Selector::parse("img#cc-comic").unwrap(),
|
||||
Selector::parse("div#aftercomic img").unwrap(),
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
257
server/src/nm.rs
257
server/src/nm.rs
@@ -1,55 +1,75 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
time::Instant,
|
||||
};
|
||||
use std::{collections::HashMap, fs::File};
|
||||
|
||||
use letterbox_notmuch::Notmuch;
|
||||
use letterbox_shared::compute_color;
|
||||
use log::{error, info, warn};
|
||||
use mailparse::{parse_mail, MailHeader, MailHeaderMap, ParsedMail};
|
||||
use mailparse::{parse_content_type, parse_mail, MailHeader, MailHeaderMap, ParsedMail};
|
||||
use memmap::MmapOptions;
|
||||
use notmuch::Notmuch;
|
||||
use sqlx::PgPool;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::{
|
||||
compute_offset_limit,
|
||||
error::ServerError,
|
||||
graphql::{
|
||||
Attachment, Body, DispositionType, Email, EmailThread, Header, Html, Message, PlainText,
|
||||
Tag, Thread, ThreadSummary, UnhandledContentType,
|
||||
Attachment, Body, Corpus, DispositionType, Email, EmailThread, Header, Html, Message,
|
||||
PlainText, Tag, Thread, ThreadSummary, UnhandledContentType,
|
||||
},
|
||||
linkify_html, InlineStyle, SanitizeHtml, Transformer,
|
||||
linkify_html, InlineStyle, Query, SanitizeHtml, Transformer,
|
||||
};
|
||||
|
||||
const TEXT_PLAIN: &'static str = "text/plain";
|
||||
const TEXT_HTML: &'static str = "text/html";
|
||||
const IMAGE_JPEG: &'static str = "image/jpeg";
|
||||
const IMAGE_PJPEG: &'static str = "image/pjpeg";
|
||||
const IMAGE_PNG: &'static str = "image/png";
|
||||
const MESSAGE_RFC822: &'static str = "message/rfc822";
|
||||
const MULTIPART_ALTERNATIVE: &'static str = "multipart/alternative";
|
||||
const MULTIPART_MIXED: &'static str = "multipart/mixed";
|
||||
const MULTIPART_RELATED: &'static str = "multipart/related";
|
||||
const TEXT_HTML: &'static str = "text/html";
|
||||
const TEXT_PLAIN: &'static str = "text/plain";
|
||||
|
||||
const MAX_RAW_MESSAGE_SIZE: usize = 100_000;
|
||||
|
||||
fn is_notmuch_query(query: &Query) -> bool {
|
||||
query.is_notmuch || query.corpus == Some(Corpus::Notmuch)
|
||||
}
|
||||
|
||||
pub fn is_notmuch_thread_or_id(id: &str) -> bool {
|
||||
id.starts_with("id:") || id.starts_with("thread:")
|
||||
}
|
||||
|
||||
// TODO(wathiede): decide good error type
|
||||
pub fn threadset_to_messages(thread_set: notmuch::ThreadSet) -> Result<Vec<Message>, ServerError> {
|
||||
pub fn threadset_to_messages(
|
||||
thread_set: letterbox_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)?)
|
||||
#[instrument(name="nm::count", skip_all, fields(query=%query))]
|
||||
pub async fn count(nm: &Notmuch, query: &Query) -> Result<usize, ServerError> {
|
||||
if !is_notmuch_query(query) {
|
||||
return Ok(0);
|
||||
}
|
||||
let query = query.to_notmuch();
|
||||
Ok(nm.count(&query)?)
|
||||
}
|
||||
|
||||
#[instrument(name="nm::search", skip_all, fields(query=%query))]
|
||||
pub async fn search(
|
||||
nm: &Notmuch,
|
||||
after: Option<i32>,
|
||||
before: Option<i32>,
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
query: String,
|
||||
query: &Query,
|
||||
) -> Result<Vec<(i32, ThreadSummary)>, async_graphql::Error> {
|
||||
if !is_notmuch_query(query) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let query = query.to_notmuch();
|
||||
let (offset, mut limit) = compute_offset_limit(after, before, first, last);
|
||||
if before.is_none() {
|
||||
// When searching forward, the +1 is to see if there are more pages of data available.
|
||||
@@ -74,14 +94,15 @@ pub async fn search(
|
||||
authors: ts.authors,
|
||||
subject: ts.subject,
|
||||
tags: ts.tags,
|
||||
corpus: Corpus::Notmuch,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[instrument(name="nm::tags", skip_all, fields(needs_unread=needs_unread))]
|
||||
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.
|
||||
@@ -97,13 +118,11 @@ pub fn tags(nm: &Notmuch, needs_unread: bool) -> Result<Vec<Tag>, ServerError> {
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let tags = nm
|
||||
let tags: Vec<_> = nm
|
||||
.tags()?
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
tag.hash(&mut hasher);
|
||||
let hex = format!("#{:06x}", hasher.finish() % (1 << 24));
|
||||
let hex = compute_color(&tag);
|
||||
let unread = if needs_unread {
|
||||
*unread_msg_cnt.get(&tag).unwrap_or(&0)
|
||||
} else {
|
||||
@@ -116,13 +135,31 @@ pub fn tags(nm: &Notmuch, needs_unread: bool) -> Result<Vec<Tag>, ServerError> {
|
||||
unread,
|
||||
}
|
||||
})
|
||||
.chain(
|
||||
nm.unread_recipients()?
|
||||
.into_iter()
|
||||
.filter_map(|(name, unread)| {
|
||||
let Some(idx) = name.find('@') else {
|
||||
return None;
|
||||
};
|
||||
let name = format!("{}/{}", &name[idx..], &name[..idx]);
|
||||
let bg_color = compute_color(&name);
|
||||
Some(Tag {
|
||||
name,
|
||||
fg_color: "white".to_string(),
|
||||
bg_color,
|
||||
unread,
|
||||
})
|
||||
}),
|
||||
)
|
||||
.collect();
|
||||
info!("Fetching tags took {} seconds", now.elapsed().as_secs_f32());
|
||||
Ok(tags)
|
||||
}
|
||||
|
||||
#[instrument(name="nm::thread", skip_all, fields(thread_id=thread_id))]
|
||||
pub async fn thread(
|
||||
nm: &Notmuch,
|
||||
pool: &PgPool,
|
||||
thread_id: String,
|
||||
debug_content_tree: bool,
|
||||
) -> Result<Thread, ServerError> {
|
||||
@@ -135,7 +172,7 @@ pub async fn thread(
|
||||
let mmap = unsafe { MmapOptions::new().map(&file)? };
|
||||
let m = parse_mail(&mmap)?;
|
||||
let from = email_addresses(&path, &m, "from")?;
|
||||
let from = match from.len() {
|
||||
let mut from = match from.len() {
|
||||
0 => None,
|
||||
1 => from.into_iter().next(),
|
||||
_ => {
|
||||
@@ -147,16 +184,30 @@ pub async fn thread(
|
||||
from.into_iter().next()
|
||||
}
|
||||
};
|
||||
match from.as_mut() {
|
||||
Some(from) => {
|
||||
if let Some(addr) = from.addr.as_mut() {
|
||||
let photo_url = photo_url_for_email_address(&pool, &addr).await?;
|
||||
from.photo_url = photo_url;
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
let to = email_addresses(&path, &m, "to")?;
|
||||
let cc = email_addresses(&path, &m, "cc")?;
|
||||
let delivered_to = email_addresses(&path, &m, "delivered-to")?.pop();
|
||||
let x_original_to = email_addresses(&path, &m, "x-original-to")?.pop();
|
||||
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 cid_prefix = letterbox_shared::urls::cid_prefix(None, &id);
|
||||
let base_url = None;
|
||||
let body = match extract_body(&m, &id)? {
|
||||
let mut part_addr = Vec::new();
|
||||
part_addr.push(id.to_string());
|
||||
let body = match extract_body(&m, &mut part_addr)? {
|
||||
Body::PlainText(PlainText { text, content_tree }) => {
|
||||
let text = if text.len() > MAX_RAW_MESSAGE_SIZE {
|
||||
format!(
|
||||
@@ -185,7 +236,7 @@ pub async fn thread(
|
||||
}
|
||||
|
||||
format!(
|
||||
r#"<p class="view-part-text-plain">{}</p>"#,
|
||||
r#"<p class="view-part-text-plain font-mono whitespace-pre-line">{}</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.
|
||||
@@ -266,6 +317,8 @@ pub async fn thread(
|
||||
body,
|
||||
path,
|
||||
attachments,
|
||||
delivered_to,
|
||||
x_original_to,
|
||||
});
|
||||
}
|
||||
messages.reverse();
|
||||
@@ -303,6 +356,7 @@ fn email_addresses(
|
||||
mailparse::MailAddr::Single(s) => addrs.push(Email {
|
||||
name: s.display_name,
|
||||
addr: Some(s.addr),
|
||||
photo_url: None,
|
||||
}), //println!("Single: {s}"),
|
||||
}
|
||||
}
|
||||
@@ -317,12 +371,14 @@ fn email_addresses(
|
||||
addrs.push(Email {
|
||||
name: Some(name.to_string()),
|
||||
addr: Some(addr.to_string()),
|
||||
photo_url: None,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
addrs.push(Email {
|
||||
name: Some(v),
|
||||
addr: None,
|
||||
photo_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -383,16 +439,14 @@ pub fn attachment_bytes(nm: &Notmuch, id: &str, idx: &[usize]) -> Result<Attachm
|
||||
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());
|
||||
fn extract_body(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, ServerError> {
|
||||
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),
|
||||
MULTIPART_MIXED => extract_mixed(m, part_addr),
|
||||
MULTIPART_ALTERNATIVE => extract_alternative(m, part_addr),
|
||||
MULTIPART_RELATED => extract_related(m, part_addr),
|
||||
_ => extract_unhandled(m),
|
||||
};
|
||||
if let Err(err) = ret {
|
||||
@@ -432,7 +486,7 @@ fn extract_alternative(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Bo
|
||||
}
|
||||
for sp in &m.subparts {
|
||||
if sp.ctype.mimetype.as_str() == MULTIPART_MIXED {
|
||||
return extract_related(sp, part_addr);
|
||||
return extract_mixed(sp, part_addr);
|
||||
}
|
||||
}
|
||||
for sp in &m.subparts {
|
||||
@@ -461,13 +515,16 @@ fn extract_alternative(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Bo
|
||||
// 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> {
|
||||
//todo!("add some sort of visual indicator there are unhandled types, i.e. .ics files");
|
||||
let handled_types = vec![
|
||||
IMAGE_JPEG,
|
||||
IMAGE_PJPEG,
|
||||
IMAGE_PNG,
|
||||
MESSAGE_RFC822,
|
||||
MULTIPART_ALTERNATIVE,
|
||||
MULTIPART_RELATED,
|
||||
TEXT_HTML,
|
||||
TEXT_PLAIN,
|
||||
IMAGE_JPEG,
|
||||
IMAGE_PNG,
|
||||
];
|
||||
let mut unhandled_types: Vec<_> = m
|
||||
.subparts
|
||||
@@ -483,11 +540,12 @@ fn extract_mixed(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, Se
|
||||
for (idx, sp) in m.subparts.iter().enumerate() {
|
||||
part_addr.push(idx.to_string());
|
||||
match sp.ctype.mimetype.as_str() {
|
||||
MESSAGE_RFC822 => parts.push(extract_rfc822(&sp, part_addr)?),
|
||||
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 => {
|
||||
IMAGE_PJPEG | IMAGE_JPEG | IMAGE_PNG => {
|
||||
let pcd = sp.get_content_disposition();
|
||||
let filename = pcd
|
||||
.params
|
||||
@@ -510,24 +568,36 @@ fn extract_mixed(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, Se
|
||||
)));
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
mt => parts.push(unhandled_html(MULTIPART_MIXED, mt)),
|
||||
}
|
||||
part_addr.pop();
|
||||
}
|
||||
Ok(flatten_body_parts(&parts))
|
||||
}
|
||||
|
||||
fn unhandled_html(parent_type: &str, child_type: &str) -> Body {
|
||||
Body::Html(Html {
|
||||
html: format!(
|
||||
r#"
|
||||
<div class="p-4 error">
|
||||
Unhandled mimetype {child_type} in a {parent_type} message
|
||||
</div>
|
||||
"#
|
||||
),
|
||||
content_tree: String::new(),
|
||||
})
|
||||
}
|
||||
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>"#,
|
||||
r#"<p class="view-part-text-plain font-mono whitespace-pre-line">{}</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'))
|
||||
linkify_html(&html_escape::encode_text(text).trim_matches('\n'))
|
||||
)
|
||||
}
|
||||
Body::Html(Html { html, .. }) => html.clone(),
|
||||
@@ -538,14 +608,14 @@ fn flatten_body_parts(parts: &[Body]) -> Body {
|
||||
// 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'))
|
||||
linkify_html(&html_escape::encode_text(text).trim_matches('\n'))
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
info!("flatten_body_parts {} {html}", parts.len());
|
||||
info!("flatten_body_parts {}", parts.len());
|
||||
Body::html(html)
|
||||
}
|
||||
|
||||
@@ -556,6 +626,7 @@ fn extract_related(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body,
|
||||
TEXT_HTML,
|
||||
TEXT_PLAIN,
|
||||
IMAGE_JPEG,
|
||||
IMAGE_PJPEG,
|
||||
IMAGE_PNG,
|
||||
];
|
||||
let mut unhandled_types: Vec<_> = m
|
||||
@@ -570,7 +641,10 @@ fn extract_related(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body,
|
||||
}
|
||||
|
||||
for (i, sp) in m.subparts.iter().enumerate() {
|
||||
if sp.ctype.mimetype == IMAGE_PNG || sp.ctype.mimetype == IMAGE_JPEG {
|
||||
if sp.ctype.mimetype == IMAGE_PNG
|
||||
|| sp.ctype.mimetype == IMAGE_JPEG
|
||||
|| sp.ctype.mimetype == IMAGE_PJPEG
|
||||
{
|
||||
info!("sp.ctype {:#?}", sp.ctype);
|
||||
//info!("sp.headers {:#?}", sp.headers);
|
||||
if let Some(cid) = sp.headers.get_first_value("Content-Id") {
|
||||
@@ -649,11 +723,22 @@ fn extract_attachments(m: &ParsedMail, id: &str) -> Result<Vec<Attachment>, Serv
|
||||
|
||||
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;
|
||||
let pct = m
|
||||
.get_headers()
|
||||
.get_first_value("Content-Type")
|
||||
.map(|s| parse_content_type(&s));
|
||||
let filename = match (
|
||||
pcd.params.get("filename").map(|f| f.clone()),
|
||||
pct.map(|pct| pct.params.get("name").map(|f| f.clone())),
|
||||
) {
|
||||
// Use filename from Content-Disposition
|
||||
(Some(filename), _) => filename,
|
||||
// Use filename from Content-Type
|
||||
(_, Some(Some(name))) => name,
|
||||
// No known filename, assume it's not an attachment
|
||||
_ => return None,
|
||||
};
|
||||
info!("filename {filename}");
|
||||
|
||||
// TODO: grab this from somewhere
|
||||
let content_id = None;
|
||||
@@ -681,6 +766,44 @@ fn extract_attachment(m: &ParsedMail, id: &str, idx: &[usize]) -> Option<Attachm
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
fn email_address_strings(emails: &[Email]) -> Vec<String> {
|
||||
emails
|
||||
.iter()
|
||||
.map(|e| e.to_string())
|
||||
.inspect(|e| info!("e {e}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extract_rfc822(m: &ParsedMail, part_addr: &mut Vec<String>) -> Result<Body, ServerError> {
|
||||
fn extract_headers(m: &ParsedMail) -> Result<Body, ServerError> {
|
||||
let path = "<in-memory>";
|
||||
let from = email_address_strings(&email_addresses(path, &m, "from")?).join(", ");
|
||||
let to = email_address_strings(&email_addresses(path, &m, "to")?).join(", ");
|
||||
let cc = email_address_strings(&email_addresses(path, &m, "cc")?).join(", ");
|
||||
let date = m.headers.get_first_value("date").unwrap_or(String::new());
|
||||
let subject = m
|
||||
.headers
|
||||
.get_first_value("subject")
|
||||
.unwrap_or(String::new());
|
||||
let text = format!(
|
||||
r#"
|
||||
---------- Forwarded message ----------
|
||||
From: {from}
|
||||
To: {to}
|
||||
CC: {cc}
|
||||
Date: {date}
|
||||
Subject: {subject}
|
||||
"#
|
||||
);
|
||||
Ok(Body::text(text))
|
||||
}
|
||||
let inner_body = m.get_body()?;
|
||||
let inner_m = parse_mail(inner_body.as_bytes())?;
|
||||
let headers = extract_headers(&inner_m)?;
|
||||
let body = extract_body(&inner_m, part_addr)?;
|
||||
|
||||
Ok(flatten_body_parts(&[headers, body]))
|
||||
}
|
||||
|
||||
pub fn get_attachment_filename(header_value: &str) -> &str {
|
||||
info!("get_attachment_filename {header_value}");
|
||||
@@ -762,15 +885,45 @@ fn render_content_type_tree(m: &ParsedMail) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
#[instrument(name="nm::set_read_status", skip_all, fields(query=%query, unread=unread))]
|
||||
pub async fn set_read_status<'ctx>(
|
||||
nm: &Notmuch,
|
||||
query: &str,
|
||||
query: &Query,
|
||||
unread: bool,
|
||||
) -> Result<bool, ServerError> {
|
||||
if unread {
|
||||
nm.tag_add("unread", &format!("{query}"))?;
|
||||
} else {
|
||||
nm.tag_remove("unread", &format!("{query}"))?;
|
||||
let uids: Vec<_> = query
|
||||
.uids
|
||||
.iter()
|
||||
.filter(|uid| is_notmuch_thread_or_id(uid))
|
||||
.collect();
|
||||
info!("set_read_status({unread} {uids:?})");
|
||||
for uid in uids {
|
||||
if unread {
|
||||
nm.tag_add("unread", uid)?;
|
||||
} else {
|
||||
nm.tag_remove("unread", uid)?;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn photo_url_for_email_address(
|
||||
pool: &PgPool,
|
||||
addr: &str,
|
||||
) -> Result<Option<String>, ServerError> {
|
||||
let row = sqlx::query!(
|
||||
r#"
|
||||
SELECT
|
||||
url
|
||||
FROM email_photo ep
|
||||
JOIN email_address ea
|
||||
ON ep.id = ea.email_photo_id
|
||||
WHERE
|
||||
address = $1
|
||||
"#,
|
||||
addr
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.map(|r| r.url))
|
||||
}
|
||||
|
||||
353
server/src/tantivy.rs
Normal file
353
server/src/tantivy.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use log::{debug, error, info, warn};
|
||||
use sqlx::{postgres::PgPool, types::time::PrimitiveDateTime};
|
||||
use tantivy::{
|
||||
collector::{DocSetCollector, TopDocs},
|
||||
doc, query,
|
||||
query::{AllQuery, BooleanQuery, Occur, QueryParser, TermQuery},
|
||||
schema::{Facet, IndexRecordOption, Value},
|
||||
DocAddress, Index, IndexReader, Searcher, TantivyDocument, TantivyError, Term,
|
||||
};
|
||||
use tracing::{info_span, instrument, Instrument};
|
||||
|
||||
use crate::{
|
||||
compute_offset_limit,
|
||||
error::ServerError,
|
||||
graphql::{Corpus, ThreadSummary},
|
||||
newsreader::{extract_thread_id, is_newsreader_thread},
|
||||
thread_summary_from_row, Query, ThreadSummaryRecord,
|
||||
};
|
||||
|
||||
pub fn is_tantivy_query(query: &Query) -> bool {
|
||||
query.is_tantivy || query.corpus == Some(Corpus::Tantivy)
|
||||
}
|
||||
pub struct TantivyConnection {
|
||||
db_path: String,
|
||||
index: Index,
|
||||
reader: IndexReader,
|
||||
}
|
||||
|
||||
fn get_index(db_path: &str) -> Result<Index, TantivyError> {
|
||||
Ok(match Index::open_in_dir(db_path) {
|
||||
Ok(idx) => idx,
|
||||
Err(err) => {
|
||||
warn!("Failed to open {db_path}: {err}");
|
||||
create_news_db(db_path)?;
|
||||
Index::open_in_dir(db_path)?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
impl TantivyConnection {
|
||||
pub fn new(tantivy_db_path: &str) -> Result<TantivyConnection, TantivyError> {
|
||||
let index = get_index(tantivy_db_path)?;
|
||||
let reader = index.reader()?;
|
||||
|
||||
Ok(TantivyConnection {
|
||||
db_path: tantivy_db_path.to_string(),
|
||||
index,
|
||||
reader,
|
||||
})
|
||||
}
|
||||
#[instrument(name = "tantivy::refresh", skip_all)]
|
||||
pub async fn refresh(&self, pool: &PgPool) -> Result<(), ServerError> {
|
||||
let start_time = std::time::Instant::now();
|
||||
let p_uids: Vec<_> = sqlx::query_file!("sql/all-uids.sql")
|
||||
.fetch_all(pool)
|
||||
.instrument(info_span!("postgres query"))
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| r.uid)
|
||||
.collect();
|
||||
info!(
|
||||
"refresh from postgres got {} uids in {}",
|
||||
p_uids.len(),
|
||||
start_time.elapsed().as_secs_f32()
|
||||
);
|
||||
|
||||
let t_span = info_span!("tantivy query");
|
||||
let _enter = t_span.enter();
|
||||
let start_time = std::time::Instant::now();
|
||||
let (searcher, _query) = self.searcher_and_query(&Query::default())?;
|
||||
let docs = searcher.search(&AllQuery, &DocSetCollector)?;
|
||||
let uid = self.index.schema().get_field("uid")?;
|
||||
let t_uids: Vec<_> = docs
|
||||
.into_iter()
|
||||
.map(|doc_address| {
|
||||
searcher
|
||||
.doc(doc_address)
|
||||
.map(|doc: TantivyDocument| {
|
||||
debug!("doc: {doc:#?}");
|
||||
doc.get_first(uid)
|
||||
.expect("uid")
|
||||
.as_str()
|
||||
.expect("as_str")
|
||||
.to_string()
|
||||
})
|
||||
.expect("searcher.doc")
|
||||
})
|
||||
.collect();
|
||||
drop(_enter);
|
||||
|
||||
info!(
|
||||
"refresh tantivy got {} uids in {}",
|
||||
t_uids.len(),
|
||||
start_time.elapsed().as_secs_f32()
|
||||
);
|
||||
let t_set: HashSet<_> = t_uids.into_iter().collect();
|
||||
let need: Vec<_> = p_uids
|
||||
.into_iter()
|
||||
.filter(|uid| !t_set.contains(uid.as_str()))
|
||||
.collect();
|
||||
if !need.is_empty() {
|
||||
info!(
|
||||
"need to reindex {} uids: {:?}...",
|
||||
need.len(),
|
||||
&need[..need.len().min(10)]
|
||||
);
|
||||
}
|
||||
let batch_size = 1000;
|
||||
let uids: Vec<_> = need[..need.len().min(batch_size)]
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
self.reindex_uids(pool, &uids).await
|
||||
}
|
||||
#[instrument(skip(self, pool))]
|
||||
async fn reindex_uids(&self, pool: &PgPool, uids: &[String]) -> Result<(), ServerError> {
|
||||
if uids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// TODO: add SlurpContents and convert HTML to text
|
||||
|
||||
let pool: &PgPool = pool;
|
||||
|
||||
let mut index_writer = self.index.writer(50_000_000)?;
|
||||
let schema = self.index.schema();
|
||||
let site = schema.get_field("site")?;
|
||||
let title = schema.get_field("title")?;
|
||||
let summary = schema.get_field("summary")?;
|
||||
let link = schema.get_field("link")?;
|
||||
let date = schema.get_field("date")?;
|
||||
let is_read = schema.get_field("is_read")?;
|
||||
let uid = schema.get_field("uid")?;
|
||||
let id = schema.get_field("id")?;
|
||||
let tag = schema.get_field("tag")?;
|
||||
|
||||
info!("reindexing {} posts", uids.len());
|
||||
let rows = sqlx::query_file_as!(PostgresDoc, "sql/posts-from-uids.sql", uids)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if uids.len() != rows.len() {
|
||||
error!(
|
||||
"Had {} uids and only got {} rows: uids {uids:?}",
|
||||
uids.len(),
|
||||
rows.len()
|
||||
);
|
||||
}
|
||||
for r in rows {
|
||||
let id_term = Term::from_field_text(uid, &r.uid);
|
||||
index_writer.delete_term(id_term);
|
||||
let slug = r.site;
|
||||
let tag_facet = Facet::from(&format!("/News/{slug}"));
|
||||
index_writer.add_document(doc!(
|
||||
site => slug.clone(),
|
||||
title => r.title,
|
||||
// TODO: clean and extract text from HTML
|
||||
summary => r.summary,
|
||||
link => r.link,
|
||||
date => tantivy::DateTime::from_primitive(r.date),
|
||||
is_read => r.is_read,
|
||||
uid => r.uid,
|
||||
id => r.id as u64,
|
||||
tag => tag_facet,
|
||||
))?;
|
||||
}
|
||||
|
||||
info_span!("IndexWriter.commit").in_scope(|| index_writer.commit())?;
|
||||
info_span!("IndexReader.reload").in_scope(|| self.reader.reload())?;
|
||||
Ok(())
|
||||
}
|
||||
#[instrument(name = "tantivy::reindex_thread", skip_all, fields(query=%query))]
|
||||
pub async fn reindex_thread(&self, pool: &PgPool, query: &Query) -> Result<(), ServerError> {
|
||||
let uids: Vec<_> = query
|
||||
.uids
|
||||
.iter()
|
||||
.filter(|uid| is_newsreader_thread(uid))
|
||||
.map(|uid| extract_thread_id(uid).to_string())
|
||||
.collect();
|
||||
Ok(self.reindex_uids(pool, &uids).await?)
|
||||
}
|
||||
#[instrument(name = "tantivy::reindex_all", skip_all)]
|
||||
pub async fn reindex_all(&self, pool: &PgPool) -> Result<(), ServerError> {
|
||||
let rows = sqlx::query_file!("sql/all-posts.sql")
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let uids: Vec<String> = rows.into_iter().map(|r| r.uid).collect();
|
||||
self.reindex_uids(pool, &uids).await?;
|
||||
Ok(())
|
||||
}
|
||||
fn searcher_and_query(
|
||||
&self,
|
||||
query: &Query,
|
||||
) -> Result<(Searcher, Box<dyn query::Query>), ServerError> {
|
||||
// TODO: only create one reader
|
||||
// From https://tantivy-search.github.io/examples/basic_search.html
|
||||
// "For a search server you will typically create one reader for the entire lifetime of
|
||||
// your program, and acquire a new searcher for every single request."
|
||||
//
|
||||
// I think there's some challenge in making the reader work if we reindex, so reader my
|
||||
// need to be stored indirectly, and be recreated on reindex
|
||||
// I think creating a reader takes 200-300 ms.
|
||||
let schema = self.index.schema();
|
||||
let searcher = self.reader.searcher();
|
||||
let title = schema.get_field("title")?;
|
||||
let summary = schema.get_field("summary")?;
|
||||
let query_parser = QueryParser::for_index(&self.index, vec![title, summary]);
|
||||
// Tantivy uses '*' to match all docs, not empty string
|
||||
let term = &query.remainder.join(" ");
|
||||
let term = if term.is_empty() { "*" } else { term };
|
||||
info!("query_parser('{term}')");
|
||||
|
||||
let tantivy_query = query_parser.parse_query(&term)?;
|
||||
|
||||
let tag = schema.get_field("tag")?;
|
||||
let is_read = schema.get_field("is_read")?;
|
||||
let mut terms = vec![(Occur::Must, tantivy_query)];
|
||||
for t in &query.tags {
|
||||
let facet = Facet::from(&format!("/{t}"));
|
||||
let facet_term = Term::from_facet(tag, &facet);
|
||||
let facet_term_query = Box::new(TermQuery::new(facet_term, IndexRecordOption::Basic));
|
||||
terms.push((Occur::Must, facet_term_query));
|
||||
}
|
||||
if query.unread_only {
|
||||
info!("searching for unread only");
|
||||
let term = Term::from_field_bool(is_read, false);
|
||||
terms.push((
|
||||
Occur::Must,
|
||||
Box::new(TermQuery::new(term, IndexRecordOption::Basic)),
|
||||
));
|
||||
}
|
||||
let search_query = BooleanQuery::new(terms);
|
||||
Ok((searcher, Box::new(search_query)))
|
||||
}
|
||||
|
||||
#[instrument(name="tantivy::count", skip_all, fields(query=%query))]
|
||||
pub async fn count(&self, query: &Query) -> Result<usize, ServerError> {
|
||||
if !is_tantivy_query(query) {
|
||||
return Ok(0);
|
||||
}
|
||||
info!("tantivy::count {query:?}");
|
||||
use tantivy::collector::Count;
|
||||
let (searcher, query) = self.searcher_and_query(&query)?;
|
||||
Ok(searcher.search(&query, &Count)?)
|
||||
}
|
||||
#[instrument(name="tantivy::search", skip_all, fields(query=%query))]
|
||||
pub async fn search(
|
||||
&self,
|
||||
pool: &PgPool,
|
||||
after: Option<i32>,
|
||||
before: Option<i32>,
|
||||
first: Option<i32>,
|
||||
last: Option<i32>,
|
||||
query: &Query,
|
||||
) -> Result<Vec<(i32, ThreadSummary)>, async_graphql::Error> {
|
||||
if !is_tantivy_query(query) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (offset, mut limit) = compute_offset_limit(after, before, first, last);
|
||||
if before.is_none() {
|
||||
// When searching forward, the +1 is to see if there are more pages of data available.
|
||||
// Searching backwards implies there's more pages forward, because the value represented by
|
||||
// `before` is on the next page.
|
||||
limit = limit + 1;
|
||||
}
|
||||
|
||||
let (searcher, search_query) = self.searcher_and_query(&query)?;
|
||||
info!("Tantivy::search(query '{query:?}', off {offset}, lim {limit}, search_query {search_query:?})");
|
||||
let top_docs = searcher.search(
|
||||
&search_query,
|
||||
&TopDocs::with_limit(limit as usize)
|
||||
.and_offset(offset as usize)
|
||||
.order_by_u64_field("date", tantivy::index::Order::Desc),
|
||||
)?;
|
||||
info!("search found {} docs", top_docs.len());
|
||||
let uid = self.index.schema().get_field("uid")?;
|
||||
let uids = top_docs
|
||||
.into_iter()
|
||||
.map(|(_, doc_address): (u64, DocAddress)| {
|
||||
searcher.doc(doc_address).map(|doc: TantivyDocument| {
|
||||
debug!("doc: {doc:#?}");
|
||||
doc.get_first(uid)
|
||||
.expect("doc missing uid")
|
||||
.as_str()
|
||||
.expect("doc str missing")
|
||||
.to_string()
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<String>, TantivyError>>()?;
|
||||
|
||||
//let uids = format!("'{}'", uids.join("','"));
|
||||
info!("uids {uids:?}");
|
||||
let rows = sqlx::query_file!("sql/threads-from-uid.sql", &uids as &[String])
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
let mut res = Vec::new();
|
||||
info!("found {} hits joining w/ tantivy", rows.len());
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
res.push((
|
||||
i as i32 + offset,
|
||||
thread_summary_from_row(ThreadSummaryRecord {
|
||||
site: r.site,
|
||||
date: r.date,
|
||||
is_read: r.is_read,
|
||||
title: r.title,
|
||||
uid: r.uid,
|
||||
name: r.name,
|
||||
corpus: Corpus::Tantivy,
|
||||
})
|
||||
.await,
|
||||
));
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
pub fn drop_and_load_index(&self) -> Result<(), TantivyError> {
|
||||
create_news_db(&self.db_path)
|
||||
}
|
||||
}
|
||||
|
||||
fn create_news_db(tantivy_db_path: &str) -> Result<(), TantivyError> {
|
||||
info!("create_news_db");
|
||||
// Don't care if directory didn't exist
|
||||
let _ = std::fs::remove_dir_all(tantivy_db_path);
|
||||
std::fs::create_dir_all(tantivy_db_path)?;
|
||||
use tantivy::schema::*;
|
||||
let mut schema_builder = Schema::builder();
|
||||
schema_builder.add_text_field("site", STRING | STORED);
|
||||
schema_builder.add_text_field("title", TEXT | STORED);
|
||||
schema_builder.add_text_field("summary", TEXT);
|
||||
schema_builder.add_text_field("link", STRING | STORED);
|
||||
schema_builder.add_date_field("date", FAST | INDEXED | STORED);
|
||||
schema_builder.add_bool_field("is_read", FAST | INDEXED | STORED);
|
||||
schema_builder.add_text_field("uid", STRING | STORED);
|
||||
schema_builder.add_u64_field("id", FAST);
|
||||
schema_builder.add_facet_field("tag", FacetOptions::default());
|
||||
|
||||
let schema = schema_builder.build();
|
||||
Index::create_in_dir(tantivy_db_path, schema)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct PostgresDoc {
|
||||
site: String,
|
||||
title: String,
|
||||
summary: String,
|
||||
link: String,
|
||||
date: PrimitiveDateTime,
|
||||
is_read: bool,
|
||||
uid: String,
|
||||
id: i32,
|
||||
}
|
||||
59
server/static/graphql-playground.html
Normal file
59
server/static/graphql-playground.html
Normal file
@@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset=utf-8 />
|
||||
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
|
||||
<title>GraphQL Playground</title>
|
||||
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/css/index.css" />
|
||||
<link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/favicon.png" />
|
||||
<script src="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/js/middleware.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root">
|
||||
<style>
|
||||
body {
|
||||
background-color: rgb(23, 42, 58);
|
||||
font-family: Open Sans, sans-serif;
|
||||
height: 90vh;
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.loading {
|
||||
font-size: 32px;
|
||||
font-weight: 200;
|
||||
color: rgba(255, 255, 255, .6);
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
img {
|
||||
width: 78px;
|
||||
height: 78px;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-weight: 400;
|
||||
}
|
||||
</style>
|
||||
<img src='//cdn.jsdelivr.net/npm/graphql-playground-react/build/logo.png' alt=''>
|
||||
<div class="loading"> Loading
|
||||
<span class="title">GraphQL Playground</span>
|
||||
</div>
|
||||
</div>
|
||||
<script>window.addEventListener('load', function (event) {
|
||||
GraphQLPlayground.init(document.getElementById('root'), {
|
||||
// options as 'endpoint' belong here
|
||||
endpoint: "/api/graphql",
|
||||
})
|
||||
})</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
42
server/static/vars.css
Normal file
42
server/static/vars.css
Normal file
@@ -0,0 +1,42 @@
|
||||
:root {
|
||||
--active-brightness: 0.85;
|
||||
--border-radius: 5px;
|
||||
--box-shadow: 2px 2px 10px;
|
||||
--color-accent: #118bee15;
|
||||
--color-bg: #fff;
|
||||
--color-bg-secondary: #e9e9e9;
|
||||
--color-link: #118bee;
|
||||
--color-secondary: #920de9;
|
||||
--color-secondary-accent: #920de90b;
|
||||
--color-shadow: #f4f4f4;
|
||||
--color-table: #118bee;
|
||||
--color-text: #000;
|
||||
--color-text-secondary: #999;
|
||||
--color-scrollbar: #cacae8;
|
||||
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
--hover-brightness: 1.2;
|
||||
--justify-important: center;
|
||||
--justify-normal: left;
|
||||
--line-height: 1.5;
|
||||
/*
|
||||
--width-card: 285px;
|
||||
--width-card-medium: 460px;
|
||||
--width-card-wide: 800px;
|
||||
*/
|
||||
--width-content: 1080px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root[color-mode="user"] {
|
||||
--color-accent: #0097fc4f;
|
||||
--color-bg: #333;
|
||||
--color-bg-secondary: #555;
|
||||
--color-link: #0097fc;
|
||||
--color-secondary: #e20de9;
|
||||
--color-secondary-accent: #e20de94f;
|
||||
--color-shadow: #bbbbbb20;
|
||||
--color-table: #0097fc;
|
||||
--color-text: #f7f7f7;
|
||||
--color-text-secondary: #aaa;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,16 @@
|
||||
[package]
|
||||
name = "shared"
|
||||
version = "0.0.29"
|
||||
edition = "2021"
|
||||
name = "letterbox-shared"
|
||||
description = "Shared module for letterbox"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
build-info = "0.0.38"
|
||||
notmuch = { path = "../notmuch" }
|
||||
build-info = "0.0.40"
|
||||
letterbox-notmuch = { version = "0.10.10", path = "../notmuch", registry = "xinu" }
|
||||
serde = { version = "1.0.147", features = ["derive"] }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use build_info::{BuildInfo, VersionControl};
|
||||
use notmuch::SearchSummary;
|
||||
use letterbox_notmuch::SearchSummary;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
[package]
|
||||
version = "0.0.29"
|
||||
name = "letterbox"
|
||||
repository = "https://github.com/seed-rs/seed-quickstart"
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
description = "App Description"
|
||||
categories = ["category"]
|
||||
license = "MIT"
|
||||
readme = "./README.md"
|
||||
edition = "2018"
|
||||
name = "letterbox-web"
|
||||
description = "Web frontend for letterbox"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
build-info-build = "0.0.38"
|
||||
build-info-build = "0.0.40"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3.33"
|
||||
@@ -20,19 +19,24 @@ console_error_panic_hook = "0.1.7"
|
||||
log = "0.4.17"
|
||||
seed = { version = "0.10.0", features = ["routing"] }
|
||||
#seed = "0.9.2"
|
||||
console_log = {git = "http://git-private.h.xinu.tv/wathiede/console_log.git"}
|
||||
console_log = { version = "0.1.0", registry = "xinu" }
|
||||
serde = { version = "1.0.147", features = ["derive"] }
|
||||
notmuch = {path = "../notmuch"}
|
||||
shared = {path = "../shared"}
|
||||
itertools = "0.10.5"
|
||||
itertools = "0.14.0"
|
||||
serde_json = { version = "1.0.93", features = ["unbounded_depth"] }
|
||||
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"] }
|
||||
graphql_client = "0.14.0"
|
||||
thiserror = "2.0.0"
|
||||
gloo-net = { version = "0.6.0", features = ["json", "serde_json"] }
|
||||
human_format = "1.1.0"
|
||||
build-info = "0.0.38"
|
||||
build-info = "0.0.40"
|
||||
wasm-bindgen = "=0.2.100"
|
||||
uuid = { version = "1.13.1", features = [
|
||||
"js",
|
||||
] } # direct dep to set js feature, prevents Rng issues
|
||||
letterbox-shared = { version = "0.10.10", path = "../shared", registry = "xinu" }
|
||||
letterbox-notmuch = { version = "0.10.10", path = "../notmuch", registry = "xinu" }
|
||||
seed_hooks = { version = "0.4.0", registry = "xinu" }
|
||||
strum_macros = "0.27.1"
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ['-Os']
|
||||
@@ -46,4 +50,6 @@ features = [
|
||||
"MediaQueryList",
|
||||
"Navigator",
|
||||
"Window",
|
||||
"History",
|
||||
"ScrollRestoration",
|
||||
]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[build]
|
||||
release = true
|
||||
release = false
|
||||
|
||||
[serve]
|
||||
# The address to serve on.
|
||||
@@ -9,6 +9,11 @@ port = 6758
|
||||
[[proxy]]
|
||||
backend = "http://localhost:9345/api/"
|
||||
|
||||
[[hooks]]
|
||||
stage = "pre_build"
|
||||
command = "printf"
|
||||
command_arguments = ["\\033c"]
|
||||
|
||||
#[[hooks]]
|
||||
#stage = "pre_build"
|
||||
#command = "cargo"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
fn main() {
|
||||
// Calling `build_info_build::build_script` collects all data and makes it available to `build_info::build_info!`
|
||||
// and `build_info::format!` in the main program.
|
||||
build_info_build::build_script();
|
||||
// Calling `build_info_build::build_script` collects all data and makes it available to `build_info::build_info!`
|
||||
// and `build_info::format!` in the main program.
|
||||
build_info_build::build_script();
|
||||
}
|
||||
|
||||
3
web/graphql/catchup.graphql
Normal file
3
web/graphql/catchup.graphql
Normal file
@@ -0,0 +1,3 @@
|
||||
query CatchupQuery($query: String!) {
|
||||
catchup(query: $query)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ query FrontPageQuery($query: String!, $after: String $before: String, $first: In
|
||||
subject
|
||||
authors
|
||||
tags
|
||||
corpus
|
||||
}
|
||||
}
|
||||
tags {
|
||||
|
||||
3
web/graphql/refresh.graphql
Normal file
3
web/graphql/refresh.graphql
Normal file
@@ -0,0 +1,3 @@
|
||||
mutation RefreshMutation {
|
||||
refresh
|
||||
}
|
||||
@@ -2,6 +2,28 @@
|
||||
"data": {
|
||||
"__schema": {
|
||||
"directives": [
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": "\"No longer supported\"",
|
||||
"description": "A reason for why it is deprecated, formatted using Markdown syntax",
|
||||
"name": "reason",
|
||||
"type": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"description": "Marks an element of a GraphQL schema as no longer supported.",
|
||||
"locations": [
|
||||
"FIELD_DEFINITION",
|
||||
"ARGUMENT_DEFINITION",
|
||||
"INPUT_FIELD_DEFINITION",
|
||||
"ENUM_VALUE"
|
||||
],
|
||||
"name": "deprecated"
|
||||
},
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
@@ -27,6 +49,14 @@
|
||||
],
|
||||
"name": "include"
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"description": "Indicates that an Input Object is a OneOf Input Object (and thus requires\n exactly one of its field be provided)",
|
||||
"locations": [
|
||||
"INPUT_OBJECT"
|
||||
],
|
||||
"name": "oneOf"
|
||||
},
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
@@ -51,6 +81,29 @@
|
||||
"INLINE_FRAGMENT"
|
||||
],
|
||||
"name": "skip"
|
||||
},
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": null,
|
||||
"description": "URL that specifies the behavior of this scalar.",
|
||||
"name": "url",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"description": "Provides a scalar specification URL for specifying the behavior of custom scalar types.",
|
||||
"locations": [
|
||||
"SCALAR"
|
||||
],
|
||||
"name": "specifiedBy"
|
||||
}
|
||||
],
|
||||
"mutationType": {
|
||||
@@ -232,6 +285,35 @@
|
||||
"name": "Boolean",
|
||||
"possibleTypes": null
|
||||
},
|
||||
{
|
||||
"description": null,
|
||||
"enumValues": [
|
||||
{
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "NOTMUCH"
|
||||
},
|
||||
{
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "NEWSREADER"
|
||||
},
|
||||
{
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "TANTIVY"
|
||||
}
|
||||
],
|
||||
"fields": null,
|
||||
"inputFields": null,
|
||||
"interfaces": null,
|
||||
"kind": "ENUM",
|
||||
"name": "Corpus",
|
||||
"possibleTypes": null
|
||||
},
|
||||
{
|
||||
"description": null,
|
||||
"enumValues": [
|
||||
@@ -282,6 +364,18 @@
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "photoUrl",
|
||||
"type": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"inputFields": null,
|
||||
@@ -577,6 +671,30 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "xOriginalTo",
|
||||
"type": {
|
||||
"kind": "OBJECT",
|
||||
"name": "Email",
|
||||
"ofType": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "deliveredTo",
|
||||
"type": {
|
||||
"kind": "OBJECT",
|
||||
"name": "Email",
|
||||
"ofType": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
@@ -850,6 +968,22 @@
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "refresh",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "Boolean",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"inputFields": null,
|
||||
@@ -1158,6 +1292,45 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": null,
|
||||
"description": null,
|
||||
"name": "query",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "catchup",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "LIST",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [
|
||||
{
|
||||
@@ -1536,6 +1709,22 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "corpus",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "ENUM",
|
||||
"name": "Corpus",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"inputFields": null,
|
||||
@@ -1762,7 +1951,22 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": "false",
|
||||
"description": null,
|
||||
"name": "includeDeprecated",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "Boolean",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
@@ -2033,7 +2237,22 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": "false",
|
||||
"description": null,
|
||||
"name": "includeDeprecated",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "Boolean",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
@@ -2166,6 +2385,34 @@
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "isDeprecated",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "Boolean",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
"name": "deprecationReason",
|
||||
"type": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"inputFields": null,
|
||||
@@ -2178,6 +2425,22 @@
|
||||
"description": "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes\nall available types and directives on the server, as well as the entry\npoints for query, mutation, and subscription operations.",
|
||||
"enumValues": null,
|
||||
"fields": [
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
"description": "description of __Schema for newer graphiql introspection schema\nrequirements",
|
||||
"isDeprecated": false,
|
||||
"name": "description",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "String",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"deprecationReason": null,
|
||||
@@ -2428,7 +2691,22 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"args": [],
|
||||
"args": [
|
||||
{
|
||||
"defaultValue": "false",
|
||||
"description": null,
|
||||
"name": "includeDeprecated",
|
||||
"type": {
|
||||
"kind": "NON_NULL",
|
||||
"name": null,
|
||||
"ofType": {
|
||||
"kind": "SCALAR",
|
||||
"name": "Boolean",
|
||||
"ofType": null
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"deprecationReason": null,
|
||||
"description": null,
|
||||
"isDeprecated": false,
|
||||
|
||||
@@ -21,6 +21,7 @@ query ShowThreadQuery($threadId: String!) {
|
||||
from {
|
||||
name
|
||||
addr
|
||||
photoUrl
|
||||
}
|
||||
to {
|
||||
name
|
||||
@@ -30,6 +31,14 @@ query ShowThreadQuery($threadId: String!) {
|
||||
name
|
||||
addr
|
||||
}
|
||||
xOriginalTo {
|
||||
name
|
||||
addr
|
||||
}
|
||||
deliveredTo {
|
||||
name
|
||||
addr
|
||||
}
|
||||
timestamp
|
||||
body {
|
||||
__typename
|
||||
|
||||
@@ -4,29 +4,22 @@
|
||||
<head>
|
||||
<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=="
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
|
||||
integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg=="
|
||||
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">
|
||||
<link data-trunk rel="css" href="static/site-specific.css" />
|
||||
<!-- <link data-trunk rel="css" href="static/site-specific.css" /> -->
|
||||
<link data-trunk rel="css" href="static/vars.css" />
|
||||
<link data-trunk rel="tailwind-css" href="./src/tailwind.css" />
|
||||
<link data-trunk rel="css" href="static/overrides.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<section id="app"></section>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
</html>
|
||||
@@ -1,10 +1,3 @@
|
||||
use gloo_net::{http::Request, Error};
|
||||
use log::info;
|
||||
|
||||
const BASE_URL: &str = "/api";
|
||||
pub fn refresh() -> String {
|
||||
format!("{BASE_URL}/refresh")
|
||||
}
|
||||
pub mod urls {
|
||||
use seed::Url;
|
||||
pub fn search(query: &str, page: usize) -> Url {
|
||||
@@ -19,9 +12,3 @@ pub mod urls {
|
||||
Url::new().set_hash_path(["t", tid])
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn refresh_request() -> Result<(), Error> {
|
||||
let t = Request::get(&refresh()).send().await?.text().await?;
|
||||
info!("refresh {t}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -12,6 +12,14 @@ use serde::{de::DeserializeOwned, Serialize};
|
||||
)]
|
||||
pub struct FrontPageQuery;
|
||||
|
||||
#[derive(GraphQLQuery)]
|
||||
#[graphql(
|
||||
schema_path = "graphql/schema.json",
|
||||
query_path = "graphql/catchup.graphql",
|
||||
response_derives = "Debug"
|
||||
)]
|
||||
pub struct CatchupQuery;
|
||||
|
||||
#[derive(GraphQLQuery)]
|
||||
#[graphql(
|
||||
schema_path = "graphql/schema.json",
|
||||
@@ -44,6 +52,14 @@ pub struct AddTagMutation;
|
||||
)]
|
||||
pub struct RemoveTagMutation;
|
||||
|
||||
#[derive(GraphQLQuery)]
|
||||
#[graphql(
|
||||
schema_path = "graphql/schema.json",
|
||||
query_path = "graphql/refresh.graphql",
|
||||
response_derives = "Debug"
|
||||
)]
|
||||
pub struct RefreshMutation;
|
||||
|
||||
pub async fn send_graphql<Body, Resp>(body: Body) -> Result<graphql_client::Response<Resp>, Error>
|
||||
where
|
||||
Body: Serialize,
|
||||
|
||||
@@ -18,6 +18,9 @@ fn main() {
|
||||
#[cfg(debug_assertions)]
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
let lvl = Level::Debug;
|
||||
#[cfg(not(debug_assertions))]
|
||||
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".
|
||||
|
||||
229
web/src/state.rs
229
web/src/state.rs
@@ -7,7 +7,6 @@ use thiserror::Error;
|
||||
use web_sys::HtmlElement;
|
||||
|
||||
use crate::{
|
||||
api,
|
||||
api::urls,
|
||||
consts::SEARCH_RESULTS_PER_PAGE,
|
||||
graphql,
|
||||
@@ -28,18 +27,23 @@ pub fn unread_query() -> &'static str {
|
||||
|
||||
// `init` describes what should happen when your app started.
|
||||
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
||||
let version = shared::build_version(bi);
|
||||
let version = letterbox_shared::build_version(bi);
|
||||
info!("Build Info: {}", version);
|
||||
// Disable restoring to scroll position when navigating
|
||||
window()
|
||||
.history()
|
||||
.expect("couldn't get history")
|
||||
.set_scroll_restoration(web_sys::ScrollRestoration::Manual)
|
||||
.expect("failed to set scroll restoration to manual");
|
||||
if url.hash().is_none() {
|
||||
orders.request_url(urls::search(unread_query(), 0));
|
||||
} else {
|
||||
orders.notify(subs::UrlRequested::new(url));
|
||||
orders.request_url(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);
|
||||
orders.subscribe(Msg::OnUrlChanged);
|
||||
orders.stream(streams::window_event(Ev::Scroll, |_| Msg::WindowScrolled));
|
||||
|
||||
build_info::build_info!(fn bi);
|
||||
@@ -54,18 +58,23 @@ pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
||||
client: version,
|
||||
server: None,
|
||||
},
|
||||
catchup: None,
|
||||
last_url: Url::current(),
|
||||
}
|
||||
}
|
||||
|
||||
fn on_url_changed(uc: subs::UrlChanged) -> Msg {
|
||||
let mut url = uc.0;
|
||||
fn on_url_changed(old: &Url, mut new: Url) -> Msg {
|
||||
let did_change = *old != new;
|
||||
let mut messages = Vec::new();
|
||||
if did_change {
|
||||
messages.push(Msg::ScrollToTop)
|
||||
}
|
||||
info!(
|
||||
"url changed '{}', history {}",
|
||||
url,
|
||||
"url changed\nold '{old}'\nnew '{new}', history {}",
|
||||
history().length().unwrap_or(0)
|
||||
);
|
||||
let hpp = url.remaining_hash_path_parts();
|
||||
match hpp.as_slice() {
|
||||
let hpp = new.remaining_hash_path_parts();
|
||||
let msg = match hpp.as_slice() {
|
||||
["t", tid] => Msg::ShowThreadRequest {
|
||||
thread_id: tid.to_string(),
|
||||
},
|
||||
@@ -102,16 +111,29 @@ fn on_url_changed(uc: subs::UrlChanged) -> Msg {
|
||||
last: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
messages.push(msg);
|
||||
Msg::MultiMsg(messages)
|
||||
}
|
||||
|
||||
// `update` describes how to handle each `Msg`.
|
||||
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
info!("update({})", msg);
|
||||
match msg {
|
||||
Msg::Noop => {}
|
||||
Msg::RefreshStart => {
|
||||
model.refreshing_state = RefreshingState::Loading;
|
||||
orders.perform_cmd(async move { Msg::RefreshDone(api::refresh_request().await.err()) });
|
||||
orders.perform_cmd(async move {
|
||||
Msg::RefreshDone(
|
||||
send_graphql::<_, graphql::refresh_mutation::ResponseData>(
|
||||
graphql::RefreshMutation::build_query(
|
||||
graphql::refresh_mutation::Variables {},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.err(),
|
||||
)
|
||||
});
|
||||
}
|
||||
Msg::RefreshDone(err) => {
|
||||
model.refreshing_state = if let Some(err) = err {
|
||||
@@ -122,7 +144,7 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
orders.perform_cmd(async move { Msg::Refresh });
|
||||
}
|
||||
Msg::Refresh => {
|
||||
orders.perform_cmd(async move { on_url_changed(subs::UrlChanged(Url::current())) });
|
||||
orders.request_url(Url::current());
|
||||
}
|
||||
Msg::Reload => {
|
||||
window()
|
||||
@@ -130,7 +152,10 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
.reload()
|
||||
.expect("failed to reload window");
|
||||
}
|
||||
Msg::OnResize => (),
|
||||
Msg::OnUrlChanged(new_url) => {
|
||||
orders.send_msg(on_url_changed(&model.last_url, new_url.0.clone()));
|
||||
model.last_url = new_url.0;
|
||||
}
|
||||
|
||||
Msg::NextPage => {
|
||||
match &model.context {
|
||||
@@ -171,6 +196,9 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
Context::None => (), // do nothing (yet?)
|
||||
};
|
||||
}
|
||||
Msg::GoToSearchResults => {
|
||||
orders.send_msg(Msg::SearchQuery(model.query.clone()));
|
||||
}
|
||||
|
||||
Msg::UpdateQuery(query) => model.query = query,
|
||||
Msg::SearchQuery(query) => {
|
||||
@@ -178,7 +206,6 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
}
|
||||
|
||||
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>,
|
||||
@@ -193,15 +220,10 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
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::Refresh
|
||||
});
|
||||
}
|
||||
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>,
|
||||
@@ -216,15 +238,10 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
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::GoToSearchResults
|
||||
});
|
||||
}
|
||||
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>,
|
||||
@@ -240,11 +257,7 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
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::GoToSearchResults
|
||||
});
|
||||
}
|
||||
|
||||
@@ -279,7 +292,9 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
)
|
||||
});
|
||||
}
|
||||
Msg::FrontPageResult(Err(e)) => error!("error FrontPageResult: {e:?}"),
|
||||
Msg::FrontPageResult(Err(e)) => {
|
||||
error!("error FrontPageResult: {e:?}");
|
||||
}
|
||||
Msg::FrontPageResult(Ok(graphql_client::Response {
|
||||
data: None,
|
||||
errors: None,
|
||||
@@ -307,7 +322,6 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
info!("pager {:#?}", data.search.page_info);
|
||||
let selected_threads = 'context: {
|
||||
if let Context::SearchResult {
|
||||
results,
|
||||
@@ -390,6 +404,38 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
Msg::ShowThreadResult(bad) => {
|
||||
error!("show_thread_query error: {bad:#?}");
|
||||
}
|
||||
Msg::CatchupRequest { query } => {
|
||||
orders.perform_cmd(async move {
|
||||
Msg::CatchupResult(
|
||||
send_graphql::<_, graphql::catchup_query::ResponseData>(
|
||||
graphql::CatchupQuery::build_query(graphql::catchup_query::Variables {
|
||||
query,
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
});
|
||||
}
|
||||
Msg::CatchupResult(Ok(graphql_client::Response {
|
||||
data: Some(data), ..
|
||||
})) => {
|
||||
let items = data.catchup;
|
||||
if items.is_empty() {
|
||||
orders.send_msg(Msg::GoToSearchResults);
|
||||
model.catchup = None;
|
||||
} else {
|
||||
orders.request_url(urls::thread(&items[0]));
|
||||
model.catchup = Some(Catchup {
|
||||
items: items
|
||||
.into_iter()
|
||||
.map(|id| CatchupItem { id, seen: false })
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Msg::CatchupResult(bad) => {
|
||||
error!("catchup_query error: {bad:#?}");
|
||||
}
|
||||
Msg::SelectionSetNone => {
|
||||
if let Context::SearchResult {
|
||||
selected_threads, ..
|
||||
@@ -496,17 +542,19 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
}
|
||||
Msg::MultiMsg(msgs) => msgs.into_iter().for_each(|msg| update(msg, model, orders)),
|
||||
Msg::CopyToClipboard(text) => {
|
||||
let clipboard = seed::window()
|
||||
.navigator()
|
||||
.clipboard()
|
||||
.expect("couldn't get clipboard");
|
||||
let clipboard = seed::window().navigator().clipboard();
|
||||
orders.perform_cmd(async move {
|
||||
wasm_bindgen_futures::JsFuture::from(clipboard.write_text(&text))
|
||||
.await
|
||||
.expect("failed to copy to clipboard");
|
||||
});
|
||||
}
|
||||
Msg::ScrollToTop => {
|
||||
info!("scrolling to the top");
|
||||
web_sys::window().unwrap().scroll_to_with_x_and_y(0., 0.);
|
||||
}
|
||||
Msg::WindowScrolled => {
|
||||
// TODO: model.content_el doesn't go to None like it should when a DOM is recreated and the refrenced element goes away
|
||||
if let Some(el) = model.content_el.get() {
|
||||
let ih = window()
|
||||
.inner_height()
|
||||
@@ -546,7 +594,8 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
model.read_completion_ratio = ratio;
|
||||
}
|
||||
Msg::UpdateServerVersion(version) => {
|
||||
if version != model.versions.client {
|
||||
// Only git versions contain dash, don't autoreload there
|
||||
if !version.contains('-') && version != model.versions.client {
|
||||
warn!(
|
||||
"Server ({}) and client ({}) version mismatch, reloading",
|
||||
version, model.versions.client
|
||||
@@ -555,8 +604,77 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
}
|
||||
model.versions.server = Some(version);
|
||||
}
|
||||
|
||||
Msg::CatchupStart => {
|
||||
let query = if model.query.contains("is:unread") {
|
||||
model.query.to_string()
|
||||
} else {
|
||||
format!("{} is:unread", model.query)
|
||||
};
|
||||
info!("starting catchup mode w/ {}", query);
|
||||
orders.send_msg(Msg::ScrollToTop);
|
||||
orders.send_msg(Msg::CatchupRequest { query });
|
||||
}
|
||||
Msg::CatchupKeepUnread => {
|
||||
if let Some(thread_id) = current_thread_id(&model.context) {
|
||||
orders.send_msg(Msg::SetUnread(thread_id, true));
|
||||
};
|
||||
orders.send_msg(Msg::CatchupNext);
|
||||
}
|
||||
Msg::CatchupMarkAsRead => {
|
||||
if let Some(thread_id) = current_thread_id(&model.context) {
|
||||
orders.send_msg(Msg::SetUnread(thread_id, false));
|
||||
};
|
||||
orders.send_msg(Msg::CatchupNext);
|
||||
}
|
||||
Msg::CatchupNext => {
|
||||
orders.send_msg(Msg::ScrollToTop);
|
||||
let Some(catchup) = &mut model.catchup else {
|
||||
orders.send_msg(Msg::GoToSearchResults);
|
||||
return;
|
||||
};
|
||||
let Some(idx) = catchup.items.iter().position(|i| !i.seen) else {
|
||||
// All items have been seen
|
||||
orders.send_msg(Msg::CatchupExit);
|
||||
orders.send_msg(Msg::GoToSearchResults);
|
||||
return;
|
||||
};
|
||||
catchup.items[idx].seen = true;
|
||||
if idx < catchup.items.len() - 1 {
|
||||
// Reached last item
|
||||
orders.request_url(urls::thread(&catchup.items[idx + 1].id));
|
||||
return;
|
||||
} else {
|
||||
orders.send_msg(Msg::CatchupExit);
|
||||
orders.send_msg(Msg::GoToSearchResults);
|
||||
return;
|
||||
};
|
||||
}
|
||||
Msg::CatchupExit => {
|
||||
orders.send_msg(Msg::ScrollToTop);
|
||||
model.catchup = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn current_thread_id(context: &Context) -> Option<String> {
|
||||
match context {
|
||||
Context::ThreadResult {
|
||||
thread:
|
||||
ShowThreadQueryThread::EmailThread(ShowThreadQueryThreadOnEmailThread {
|
||||
thread_id, ..
|
||||
}),
|
||||
..
|
||||
} => Some(thread_id.clone()),
|
||||
Context::ThreadResult {
|
||||
thread:
|
||||
ShowThreadQueryThread::NewsPost(ShowThreadQueryThreadOnNewsPost { thread_id, .. }),
|
||||
..
|
||||
} => Some(thread_id.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// `Model` describes our app state.
|
||||
pub struct Model {
|
||||
pub query: String,
|
||||
@@ -566,6 +684,8 @@ pub struct Model {
|
||||
pub read_completion_ratio: f64,
|
||||
pub content_el: ElRef<HtmlElement>,
|
||||
pub versions: Version,
|
||||
pub catchup: Option<Catchup>,
|
||||
pub last_url: Url,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -602,6 +722,15 @@ pub enum Context {
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Catchup {
|
||||
pub items: Vec<CatchupItem>,
|
||||
}
|
||||
|
||||
pub struct CatchupItem {
|
||||
pub id: String,
|
||||
pub seen: bool,
|
||||
}
|
||||
|
||||
pub struct Tag {
|
||||
pub name: String,
|
||||
pub bg_color: String,
|
||||
@@ -615,19 +744,21 @@ pub enum RefreshingState {
|
||||
Error(String),
|
||||
}
|
||||
// `Msg` describes the different events you can modify state with.
|
||||
#[derive(strum_macros::Display)]
|
||||
pub enum Msg {
|
||||
Noop,
|
||||
// Tell the client to refresh its state
|
||||
Refresh,
|
||||
// Tell the client to reload whole page from server
|
||||
Reload,
|
||||
// Window has changed size
|
||||
OnResize,
|
||||
// TODO: add GoToUrl
|
||||
OnUrlChanged(subs::UrlChanged),
|
||||
// Tell the server to update state
|
||||
RefreshStart,
|
||||
RefreshDone(Option<gloo_net::Error>),
|
||||
NextPage,
|
||||
PreviousPage,
|
||||
GoToSearchResults,
|
||||
UpdateQuery(String),
|
||||
SearchQuery(String),
|
||||
|
||||
@@ -651,12 +782,17 @@ pub enum Msg {
|
||||
ShowThreadResult(
|
||||
Result<graphql_client::Response<graphql::show_thread_query::ResponseData>, gloo_net::Error>,
|
||||
),
|
||||
CatchupRequest {
|
||||
query: String,
|
||||
},
|
||||
CatchupResult(
|
||||
Result<graphql_client::Response<graphql::catchup_query::ResponseData>, gloo_net::Error>,
|
||||
),
|
||||
|
||||
SelectionSetNone,
|
||||
SelectionSetAll,
|
||||
SelectionAddTag(String),
|
||||
#[allow(dead_code)]
|
||||
// TODO
|
||||
SelectionRemoveTag(String),
|
||||
SelectionMarkAsRead,
|
||||
SelectionMarkAsUnread,
|
||||
@@ -669,7 +805,14 @@ pub enum Msg {
|
||||
|
||||
CopyToClipboard(String),
|
||||
|
||||
ScrollToTop,
|
||||
WindowScrolled,
|
||||
SetProgress(f64),
|
||||
UpdateServerVersion(String),
|
||||
|
||||
CatchupStart,
|
||||
CatchupKeepUnread,
|
||||
CatchupMarkAsRead,
|
||||
CatchupNext,
|
||||
CatchupExit,
|
||||
}
|
||||
|
||||
3
web/src/tailwind.css
Normal file
3
web/src/tailwind.css
Normal file
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -1,49 +0,0 @@
|
||||
use seed::{prelude::*, *};
|
||||
use seed_hooks::topo;
|
||||
|
||||
use crate::{
|
||||
graphql::show_thread_query::*,
|
||||
state::{Context, Model, Msg},
|
||||
view::{self, reading_progress, view_header, view_search_results},
|
||||
};
|
||||
|
||||
#[topo::nested]
|
||||
pub(super) fn view(model: &Model) -> Node<Msg> {
|
||||
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: ShowThreadQueryThread::EmailThread(thread),
|
||||
open_messages,
|
||||
} => view::thread(thread, open_messages, show_icon_text, &model.content_el),
|
||||
Context::ThreadResult {
|
||||
thread: ShowThreadQueryThread::NewsPost(post),
|
||||
..
|
||||
} => view::news_post(post, show_icon_text, &model.content_el),
|
||||
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"],
|
||||
reading_progress(model.read_completion_ratio),
|
||||
div![view::tags(model), view::versions(&model.versions)],
|
||||
div![
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
content,
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use seed::{prelude::*, *};
|
||||
|
||||
use crate::{
|
||||
api::urls,
|
||||
graphql::{front_page_query::*, show_thread_query::*},
|
||||
state::{Context, Model, Msg},
|
||||
view::{
|
||||
self, human_age, pretty_authors, reading_progress, search_toolbar, set_title, tags_chiclet,
|
||||
view_header,
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) fn view(model: &Model) -> Node<Msg> {
|
||||
let show_icon_text = false;
|
||||
let content = match &model.context {
|
||||
Context::None => div![h1!["Loading"]],
|
||||
Context::ThreadResult {
|
||||
thread: ShowThreadQueryThread::EmailThread(thread),
|
||||
open_messages,
|
||||
} => view::thread(thread, open_messages, show_icon_text, &model.content_el),
|
||||
Context::ThreadResult {
|
||||
thread: ShowThreadQueryThread::NewsPost(post),
|
||||
..
|
||||
} => view::news_post(post, show_icon_text, &model.content_el),
|
||||
Context::SearchResult {
|
||||
query,
|
||||
results,
|
||||
count,
|
||||
pager,
|
||||
selected_threads,
|
||||
} => search_results(
|
||||
&query,
|
||||
results.as_slice(),
|
||||
*count,
|
||||
pager,
|
||||
selected_threads,
|
||||
show_icon_text,
|
||||
),
|
||||
};
|
||||
div![
|
||||
reading_progress(model.read_completion_ratio),
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
content,
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
div![view::tags(model), view::versions(&model.versions)]
|
||||
]
|
||||
}
|
||||
|
||||
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),
|
||||
]
|
||||
}
|
||||
1984
web/src/view/mod.rs
1984
web/src/view/mod.rs
File diff suppressed because it is too large
Load Diff
@@ -1,48 +0,0 @@
|
||||
use seed::{prelude::*, *};
|
||||
|
||||
use crate::{
|
||||
graphql::show_thread_query::*,
|
||||
state::{Context, Model, Msg},
|
||||
view::{self, reading_progress, view_header, view_search_results},
|
||||
};
|
||||
|
||||
pub(super) fn view(model: &Model) -> Node<Msg> {
|
||||
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: ShowThreadQueryThread::EmailThread(thread),
|
||||
open_messages,
|
||||
} => view::thread(thread, open_messages, show_icon_text, &model.content_el),
|
||||
Context::ThreadResult {
|
||||
thread: ShowThreadQueryThread::NewsPost(post),
|
||||
..
|
||||
} => view::news_post(post, show_icon_text, &model.content_el),
|
||||
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![
|
||||
reading_progress(model.read_completion_ratio),
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
content,
|
||||
view_header(&model.query, &model.refreshing_state),
|
||||
view::tags(model),
|
||||
view::versions(&model.versions)
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
83
web/static/overrides.css
Normal file
83
web/static/overrides.css
Normal file
@@ -0,0 +1,83 @@
|
||||
html {
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
.mail-thread a,
|
||||
.news-post a {
|
||||
color: var(--color-link) !important;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.mail-thread br,
|
||||
.news-post br {
|
||||
display: block;
|
||||
margin-top: 1em;
|
||||
content: " ";
|
||||
}
|
||||
|
||||
.mail-thread h1,
|
||||
.mail-thread h2,
|
||||
.mail-thread h3,
|
||||
.mail-thread h4,
|
||||
.news-post h1,
|
||||
.news-post h2,
|
||||
.news-post h3,
|
||||
.news-post h4 {
|
||||
margin-top: 1em !important;
|
||||
margin-bottom: 1em !important;
|
||||
}
|
||||
|
||||
.mail-thread p,
|
||||
.news-post p {
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.mail-thread pre,
|
||||
.news-post pre {
|
||||
font-family: monospace;
|
||||
background-color: #eee !important;
|
||||
padding: 0.5em;
|
||||
white-space: break-spaces;
|
||||
}
|
||||
|
||||
.mail-thread code,
|
||||
.news-post code {
|
||||
font-family: monospace;
|
||||
white-space: break-spaces;
|
||||
}
|
||||
|
||||
.mail-thread blockquote {
|
||||
padding-left: 1em;
|
||||
border-left: 2px solid #ddd;
|
||||
}
|
||||
|
||||
.mail-thread ol,
|
||||
.mail-thread ul {
|
||||
margin-left: 2em;
|
||||
}
|
||||
|
||||
.mail-thread .noreply-news-bloomberg-com a {
|
||||
background-color: initial !important;
|
||||
}
|
||||
|
||||
.mail-thread .noreply-news-bloomberg-com h2 {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
/* Hackaday figures have unreadable black on dark grey */
|
||||
.news-post figcaption.wp-caption-text {
|
||||
background-color: initial !important;
|
||||
}
|
||||
|
||||
.news-post.site-nautilus .article-ad,
|
||||
.news-post.site-nautilus .primis-ad {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.news-post.site-slashdot .story-byline {
|
||||
display: block !important;
|
||||
height: initial !important;
|
||||
overflow: auto !important;
|
||||
position: static !important;
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
padding: inherit !important;
|
||||
}
|
||||
|
||||
.body.news-post hr {
|
||||
background-color: #aaa !important;
|
||||
margin: .25rem 0 !important;
|
||||
}
|
||||
|
||||
.body.news-post .number {
|
||||
align-items: inherit;
|
||||
background-color: inherit;
|
||||
|
||||
@@ -41,38 +41,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.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;
|
||||
|
||||
42
web/static/vars.css
Normal file
42
web/static/vars.css
Normal file
@@ -0,0 +1,42 @@
|
||||
:root {
|
||||
--active-brightness: 0.85;
|
||||
--border-radius: 5px;
|
||||
--box-shadow: 2px 2px 10px;
|
||||
--color-accent: #118bee15;
|
||||
--color-bg: #fff;
|
||||
--color-bg-secondary: #e9e9e9;
|
||||
--color-link: #118bee;
|
||||
--color-secondary: #920de9;
|
||||
--color-secondary-accent: #920de90b;
|
||||
--color-shadow: #f4f4f4;
|
||||
--color-table: #118bee;
|
||||
--color-text: #000;
|
||||
--color-text-secondary: #999;
|
||||
--color-scrollbar: #cacae8;
|
||||
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
--hover-brightness: 1.2;
|
||||
--justify-important: center;
|
||||
--justify-normal: left;
|
||||
--line-height: 1.5;
|
||||
/*
|
||||
--width-card: 285px;
|
||||
--width-card-medium: 460px;
|
||||
--width-card-wide: 800px;
|
||||
*/
|
||||
--width-content: 1080px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root[color-mode="user"] {
|
||||
--color-accent: #0097fc4f;
|
||||
--color-bg: #333;
|
||||
--color-bg-secondary: #555;
|
||||
--color-link: #0097fc;
|
||||
--color-secondary: #e20de9;
|
||||
--color-secondary-accent: #e20de94f;
|
||||
--color-shadow: #bbbbbb20;
|
||||
--color-table: #0097fc;
|
||||
--color-text: #f7f7f7;
|
||||
--color-text-secondary: #aaa;
|
||||
}
|
||||
}
|
||||
9
web/tailwind.config.js
Normal file
9
web/tailwind.config.js
Normal file
@@ -0,0 +1,9 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: ['./src/**/*.rs'],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user