S001: workspace, store, settings and strings

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-24 23:29:30 -06:00
commit 79bc90057f
27 changed files with 3068 additions and 10 deletions

View file

@ -22,7 +22,7 @@ After ticking a box: `ArtifactData` `update` with `url` = the tracker, `collecti
Root: the folder holding this file
```
Planned (the Foundation plans create it; keep this list true):
Keep this list true (tools/, assets/ and docs/CONNECTOR come with their plans):
crates/core/ engine, limits, queues, store, connector server; no UI code
crates/app/ egui app: theme, motion, widgets, views, dialogs, tray
crates/cli/ command line and headless mode, a library used by the `medlar` binary

981
Cargo.lock generated Normal file
View file

@ -0,0 +1,981 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
dependencies = [
"libc",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"num-traits",
"windows-link",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
]
[[package]]
name = "hashlink"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"
[[package]]
name = "icu_properties"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"
dependencies = [
"displaydoc",
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"
[[package]]
name = "icu_provider"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "js-sys"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
dependencies = [
"cfg-if",
"futures-util",
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libredox"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
dependencies = [
"libc",
]
[[package]]
name = "libsqlite3-sys"
version = "0.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "medlar"
version = "0.1.0"
dependencies = [
"medlar-cli",
]
[[package]]
name = "medlar-cli"
version = "0.1.0"
dependencies = [
"medlar-core",
]
[[package]]
name = "medlar-core"
version = "0.1.0"
dependencies = [
"chrono",
"dirs",
"log",
"regex",
"rusqlite",
"serde",
"serde_json",
"tempfile",
"url",
]
[[package]]
name = "medlar-testserver"
version = "0.1.0"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "potential_utf"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
dependencies = [
"zerovec",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "redox_users"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
dependencies = [
"libredox",
"thiserror",
]
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rsqlite-vfs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror",
]
[[package]]
name = "rusqlite"
version = "0.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "tinystr"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "url"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0"
dependencies = [
"utf_types",
]
[[package]]
name = "utf_types"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "wasm-bindgen"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
dependencies = [
"cfg-if",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 3.0.10",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
dependencies = [
"unicode-ident",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "yoke"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"synstructure",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"synstructure",
]
[[package]]
name = "zerotrie"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

25
Cargo.toml Normal file
View file

@ -0,0 +1,25 @@
[workspace]
members = ["crates/*"]
resolver = "3"
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
[workspace.dependencies]
medlar-core = { path = "crates/core" }
medlar-cli = { path = "crates/cli" }
medlar-testserver = { path = "crates/testserver" }
log = "0.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 4
strip = true
[profile.dev.package."*"]
opt-level = 2

View file

@ -12,14 +12,14 @@ The Cargo workspace with four crates, and in `core`: task model, SQLite store, s
- ~/Projects/Damson/src/config.rs
## Steps
- [ ] Workspace: `medlar-core`, `medlar` (app), `medlar-cli` (library), `medlar-testserver`; release profile like Damson's; version 0.1.0, MIT
- [ ] Paths: XDG dirs, plus portable mode when a `portable` file sits beside the binary; a `MEDLAR_HOME` override for tests
- [ ] Task model: task, part, queue, tag, host profile, error kind (empty enum list to fill in S007), states and the legal moves between them, with a test that refuses illegal moves
- [ ] Store: rusqlite (bundled), numbered migrations, WAL, one writer thread; survives a kill mid-write (test)
- [ ] Settings: serde with defaults, unknown keys kept, a damaged file is moved aside and reported, never fatal
- [ ] String catalogue: key to text with plurals and arguments, English built in, user files dropped in a folder; a test fails on a missing key
- [ ] Logging to a rotating file; a redaction helper for cookies, tokens, passwords and URL query strings, with tests
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S001: …`, push
- [x] Workspace: `medlar-core`, `medlar` (app), `medlar-cli` (library), `medlar-testserver`; release profile like Damson's; version 0.1.0, MIT
- [x] Paths: XDG dirs, plus portable mode when a `portable` file sits beside the binary; a `MEDLAR_HOME` override for tests
- [x] Task model: task, part, queue, tag, host profile, error kind (empty enum list to fill in S007), states and the legal moves between them, with a test that refuses illegal moves
- [x] Store: rusqlite (bundled), numbered migrations, WAL, one writer thread; survives a kill mid-write (test)
- [x] Settings: serde with defaults, unknown keys kept, a damaged file is moved aside and reported, never fatal
- [x] String catalogue: key to text with plurals and arguments, English built in, user files dropped in a folder; a test fails on a missing key
- [x] Logging to a rotating file; a redaction helper for cookies, tokens, passwords and URL query strings, with tests
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S001: …`, push
## End criteria
- `nice cargo test -j 2` green

View file

@ -6,7 +6,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
## 01 Foundation
- [ ] [S001](01%20Foundation/S001-workspace-store-settings.md) Workspace, store, settings and strings
- [x] [S001](01%20Foundation/S001-workspace-store-settings.md) Workspace, store, settings and strings
- [ ] [S002](01%20Foundation/S002-test-server.md) Test server with faults
- [ ] [S003](01%20Foundation/S003-shell-motion-tools.md) App shell, theme, motion and screenshot tools

9
crates/app/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "medlar"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "A download manager for Linux"
[dependencies]
medlar-cli.workspace = true

5
crates/app/src/main.rs Normal file
View file

@ -0,0 +1,5 @@
use std::process::ExitCode;
fn main() -> ExitCode {
medlar_cli::run(std::env::args().skip(1))
}

9
crates/cli/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "medlar-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Medlar's command line"
[dependencies]
medlar-core.workspace = true

17
crates/cli/src/lib.rs Normal file
View file

@ -0,0 +1,17 @@
//! Command line of the `medlar` binary.
use medlar_core::tr;
use std::process::ExitCode;
/// Runs the command line and returns the exit code of the process.
pub fn run(mut args: impl Iterator<Item = String>) -> ExitCode {
match args.next().as_deref() {
Some("--version" | "-V") => println!("medlar {}", medlar_core::VERSION),
None | Some("--help" | "-h") => println!("{}", tr!("cli.usage")),
Some(other) => {
eprintln!("{}", tr!("cli.unknown", arg = other));
return ExitCode::from(2);
}
}
ExitCode::SUCCESS
}

19
crates/core/Cargo.toml Normal file
View file

@ -0,0 +1,19 @@
[package]
name = "medlar-core"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Medlar's engine, store and settings"
[dependencies]
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
dirs = "6"
log = { workspace = true, features = ["std"] }
regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] }
rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] }
serde.workspace = true
serde_json.workspace = true
url = "2"
[dev-dependencies]
tempfile = "3"

36
crates/core/lang/en.json Normal file
View file

@ -0,0 +1,36 @@
{
"cli.usage": "Usage: medlar [--version | --help]",
"cli.unknown": "Unknown argument: {arg}. Try medlar --help.",
"queue.main": "Main",
"tasks.count": {"one": "{n} download", "other": "{n} downloads"},
"state.queued": "Queued",
"state.waiting": "Waiting",
"state.running": "Downloading",
"state.paused": "Paused",
"state.checking": "Checking",
"state.finishing": "Finishing",
"state.done": "Done",
"state.failed": "Failed",
"state.gone": "File is gone",
"priority.lowest": "Lowest",
"priority.low": "Low",
"priority.normal": "Normal",
"priority.high": "High",
"priority.highest": "Highest",
"priority.only": "Only this one",
"settings.damaged": "Some settings could not be read and are back to their defaults: {keys}. The old file is kept.",
"settings.damaged_all": "The settings file could not be read, so every setting is back to its default. The old file is kept.",
"store.db": "The download list could not be read or saved: {why}",
"store.newer": "The download list was made by a newer Medlar (format {found}, this one knows {known}). Update Medlar to open it.",
"store.illegal_move": "A download can't go from “{from}” to “{to}”.",
"store.not_found": "That download, queue or tag is no longer in the list.",
"store.secret": "A login or cookie would have been saved outside the keyring, so nothing was saved.",
"store.main_queue": "The main queue can't be removed.",
"store.bad_value": "The download list holds a value this version doesn't know: {value}",
"store.closed": "The download list stopped working. Start Medlar again."
}

11
crates/core/src/lib.rs Normal file
View file

@ -0,0 +1,11 @@
//! Medlar's engine, limits, queues, store and settings. No UI code.
pub mod logging;
pub mod model;
pub mod paths;
pub mod redact;
pub mod settings;
pub mod store;
pub mod strings;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

111
crates/core/src/logging.rs Normal file
View file

@ -0,0 +1,111 @@
//! Log file: rotated by size, every line redacted.
use crate::redact;
use log::{Level, LevelFilter, Log, Metadata, Record};
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
const MAX_BYTES: u64 = 1024 * 1024;
/// Old files kept beside the current one: `medlar.log.1`, `.2`, `.3`.
const KEEP: u32 = 3;
struct Rotating {
path: PathBuf,
max: u64,
file: File,
size: u64,
}
impl Rotating {
fn open(path: &Path, max: u64) -> io::Result<Rotating> {
let file = OpenOptions::new().create(true).append(true).mode(0o600).open(path)?;
let size = file.metadata()?.len();
Ok(Rotating { path: path.into(), max, file, size })
}
fn write(&mut self, line: &str) -> io::Result<()> {
if self.size > 0 && self.size + line.len() as u64 > self.max {
let old = |n: u32| PathBuf::from(format!("{}.{n}", self.path.display()));
for n in (1..KEEP).rev() {
let _ = std::fs::rename(old(n), old(n + 1));
}
std::fs::rename(&self.path, old(1))?;
*self = Rotating::open(&self.path, self.max)?;
}
self.size += line.len() as u64;
self.file.write_all(line.as_bytes())
}
}
struct Logger(Mutex<Rotating>);
impl Log for Logger {
fn enabled(&self, m: &Metadata) -> bool {
// Libraries speak up only when something is wrong.
m.level() <= Level::Warn || m.target().starts_with("medlar")
}
fn log(&self, r: &Record) {
if self.enabled(r.metadata()) {
let line = line(r.level(), r.target(), &r.args().to_string());
// A log that can't be written must not stop the app.
let _ = self.0.lock().unwrap_or_else(|e| e.into_inner()).write(&line);
}
}
fn flush(&self) {}
}
/// One entry is one line, whatever a server put into the message.
fn line(level: Level, target: &str, message: &str) -> String {
let message = redact::text(message).replace(|c: char| c.is_control(), " ");
format!("{} {level:5} {target}: {message}\n", chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"))
}
/// Starts logging to `path`. Call once; a second call changes nothing.
pub fn init(path: &Path, level: LevelFilter) -> io::Result<()> {
let logger = Logger(Mutex::new(Rotating::open(path, MAX_BYTES)?));
if log::set_boxed_logger(Box::new(logger)).is_ok() {
log::set_max_level(level);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rotates_and_keeps_three() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("medlar.log");
let mut log = Rotating::open(&path, 25).unwrap();
for n in 0..12 {
log.write(&format!("line {n:04}\n")).unwrap();
}
assert_eq!(std::fs::read_to_string(&path).unwrap(), "line 0010\nline 0011\n");
assert_eq!(std::fs::read_to_string(dir.path().join("medlar.log.1")).unwrap(), "line 0008\nline 0009\n");
assert!(dir.path().join("medlar.log.3").exists());
assert!(!dir.path().join("medlar.log.4").exists());
assert!(std::fs::metadata(&path).unwrap().len() <= 25);
}
#[test]
fn continues_an_existing_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("medlar.log");
Rotating::open(&path, 25).unwrap().write("first\n").unwrap();
Rotating::open(&path, 25).unwrap().write("second\n").unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), "first\nsecond\n");
}
#[test]
fn entries_are_one_redacted_line() {
let l = line(Level::Info, "medlar_core", "name evil\n2026 ERROR fake https://h/f?key=abc");
assert_eq!(l.matches('\n').count(), 1);
assert!(l.ends_with("name evil 2026 ERROR fake https://h/f?…\n"), "{l}");
}
}

284
crates/core/src/model.rs Normal file
View file

@ -0,0 +1,284 @@
//! What Medlar remembers: tasks, parts, queues, tags and hosts.
//!
//! Secrets (cookies, logins, tokens) never appear here. `secret` fields hold the name of a keyring item.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
pub type TaskId = i64;
pub type QueueId = i64;
pub type TagId = i64;
/// Milliseconds since 1970.
pub type Time = i64;
/// The queue that always exists.
pub const MAIN_QUEUE: QueueId = 1;
/// An enum stored by name.
macro_rules! named_enum {
($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $variant:ident = $text:literal),* $(,)? }) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum $name { $($(#[$vmeta])* #[serde(rename = $text)] $variant),* }
impl $name {
pub const ALL: &'static [$name] = &[$($name::$variant),*];
pub fn name(self) -> &'static str {
match self { $($name::$variant => $text),* }
}
pub fn from_name(name: &str) -> Option<$name> {
$name::ALL.iter().copied().find(|v| v.name() == name)
}
}
};
}
named_enum!(
/// What a task is doing. The catalogue holds its label under `state.<name>`.
State {
/// Ready, until its queue has room.
Queued = "queued",
/// Held back by a time, another task, a retry or the network.
Waiting = "waiting",
Running = "running",
Paused = "paused",
/// Comparing the checksum.
Checking = "checking",
/// Naming, unpacking or converting the finished file.
Finishing = "finishing",
Done = "done",
Failed = "failed",
/// Was done, but the file is no longer there.
Gone = "gone",
}
);
impl State {
/// The states this one may move to.
pub fn moves(self) -> &'static [State] {
use State::*;
match self {
Queued => &[Running, Waiting, Paused, Failed],
Waiting => &[Queued, Running, Paused, Failed],
// Queued again: the app was killed, or the task gave up its place.
Running => &[Queued, Waiting, Paused, Checking, Finishing, Failed],
Paused => &[Queued, Waiting, Failed],
Checking => &[Queued, Paused, Finishing, Failed],
Finishing => &[Queued, Done, Failed],
// Queued: download again. Checking: check the file again.
Done => &[Queued, Checking, Gone],
Failed => &[Queued, Waiting, Paused],
Gone => &[Queued, Done],
}
}
pub fn can_become(self, to: State) -> bool {
self.moves().contains(&to)
}
}
named_enum!(
/// Share of bandwidth and connections.
Priority {
Lowest = "lowest",
Low = "low",
Normal = "normal",
High = "high",
Highest = "highest",
/// Everything else waits.
Only = "only",
}
);
named_enum!(
/// Why a task failed. Filled by S007; each kind has a label under `error.<name>`.
ErrorKind {}
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskError {
/// None for a kind this version doesn't know.
pub kind: Option<ErrorKind>,
/// Plain words, already free of secrets.
pub detail: String,
}
/// A file to download. `id` is 0 until the store adds it.
#[derive(Debug, Clone, PartialEq)]
pub struct Task {
pub id: TaskId,
pub url: String,
pub mirrors: Vec<String>,
/// The page the link came from, opened to get a new link.
pub source_page: Option<String>,
pub name: String,
pub folder: PathBuf,
/// Changed through `Store::set_state` only.
pub state: State,
/// Changed through `Store::set_state` only.
pub error: Option<TaskError>,
pub queue: QueueId,
/// Order inside the queue.
pub position: f64,
pub priority: Priority,
pub size: Option<u64>,
pub downloaded: u64,
pub mime: Option<String>,
pub etag: Option<String>,
pub last_modified: Option<String>,
/// `sha256:…`.
pub checksum: Option<String>,
pub max_parts: Option<u32>,
/// Bytes per second.
pub speed_limit: Option<u64>,
/// Cookies and authorization are refused here; they go to the keyring.
pub headers: Vec<(String, String)>,
pub proxy: Option<String>,
/// Keyring item with the cookies and login.
pub secret: Option<String>,
pub after: Option<TaskId>,
pub start_at: Option<Time>,
pub added_at: Time,
pub finished_at: Option<Time>,
/// Set while the removal can still be undone.
pub removed_at: Option<Time>,
pub tags: Vec<TagId>,
pub notes: String,
}
impl Default for Task {
fn default() -> Task {
Task {
id: 0,
url: String::new(),
mirrors: vec![],
source_page: None,
name: String::new(),
folder: PathBuf::new(),
state: State::Queued,
error: None,
queue: MAIN_QUEUE,
position: 0.0,
priority: Priority::Normal,
size: None,
downloaded: 0,
mime: None,
etag: None,
last_modified: None,
checksum: None,
max_parts: None,
speed_limit: None,
headers: vec![],
proxy: None,
secret: None,
after: None,
start_at: None,
added_at: now(),
finished_at: None,
removed_at: None,
tags: vec![],
notes: String::new(),
}
}
}
/// A range of the file: bytes `start..end`, of which the first `done` are on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Part {
pub start: u64,
/// None when the length is unknown.
pub end: Option<u64>,
pub done: u64,
}
/// Weekdays and times a queue may run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule {
/// Bit 0 is Monday.
pub days: u8,
/// Minutes after midnight.
pub from: u16,
/// Smaller than `from` when it ends the next day.
pub to: u16,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Queue {
pub id: QueueId,
/// Empty for the main queue, which the catalogue names (`queue.main`).
pub name: String,
pub folder: Option<PathBuf>,
pub speed_limit: Option<u64>,
pub max_active: Option<u32>,
pub position: f64,
pub paused: bool,
pub schedule: Vec<Schedule>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Tag {
pub id: TagId,
pub name: String,
/// `#rrggbb`.
pub color: Option<String>,
}
/// What Medlar learned, or was told, about a host.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HostProfile {
pub host: String,
/// Connections the host tolerated.
pub good_connections: Option<u32>,
/// Cap set by the user.
pub max_connections: Option<u32>,
pub ranges: Option<bool>,
pub speed_limit: Option<u64>,
pub user_agent: Option<String>,
pub proxy: Option<String>,
/// Keyring item with the login.
pub secret: Option<String>,
pub seen_at: Time,
}
pub fn now() -> Time {
chrono::Utc::now().timestamp_millis()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn illegal_moves_are_refused() {
use State::*;
for (from, to) in [(Queued, Done), (Paused, Done), (Running, Done), (Done, Running), (Gone, Running), (Failed, Done), (Done, Paused)] {
assert!(!from.can_become(to), "{from:?} to {to:?}");
}
for &s in State::ALL {
assert!(!s.can_become(s), "{s:?} to itself");
}
}
#[test]
fn every_state_can_reach_done() {
for &start in State::ALL {
let mut seen = vec![start];
let mut i = 0;
while i < seen.len() {
seen.extend(seen[i].moves().iter().filter(|s| !seen.contains(s)).copied().collect::<Vec<_>>());
i += 1;
}
assert!(seen.contains(&State::Done), "{start:?}");
}
}
#[test]
fn names_round_trip() {
for &s in State::ALL {
assert_eq!(State::from_name(s.name()), Some(s));
}
assert_eq!(Priority::from_name("nope"), None);
}
}

127
crates/core/src/paths.rs Normal file
View file

@ -0,0 +1,127 @@
//! Where Medlar keeps its files.
use std::ffi::OsString;
use std::io;
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
/// A file with this name beside the binary turns portable mode on.
pub const PORTABLE_MARK: &str = "portable";
/// The folder beside the binary that holds everything in portable mode.
pub const PORTABLE_DIR: &str = "medlar-data";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paths {
pub config: PathBuf,
pub data: PathBuf,
/// Logs.
pub state: PathBuf,
pub cache: PathBuf,
pub portable: bool,
}
impl Paths {
/// `MEDLAR_HOME` wins, then portable mode, then the XDG folders.
pub fn detect() -> Paths {
Paths::choose(std::env::var_os("MEDLAR_HOME"), binary())
}
fn choose(home: Option<OsString>, binary: Option<PathBuf>) -> Paths {
if let Some(home) = home.filter(|h| !h.is_empty()) {
return Paths::under(Path::new(&home), false);
}
if let Some(dir) = binary.as_deref().and_then(Path::parent)
&& dir.join(PORTABLE_MARK).exists()
{
return Paths::under(&dir.join(PORTABLE_DIR), true);
}
// Every XDG folder is missing only when there is no home at all.
let base = |dir: Option<PathBuf>, name: &str| match dir {
Some(dir) => dir.join("medlar"),
None => std::env::temp_dir().join("medlar").join(name),
};
Paths {
config: base(dirs::config_dir(), "config"),
data: base(dirs::data_dir(), "data"),
state: base(dirs::state_dir(), "state"),
cache: base(dirs::cache_dir(), "cache"),
portable: false,
}
}
fn under(root: &Path, portable: bool) -> Paths {
Paths {
config: root.join("config"),
data: root.join("data"),
state: root.join("state"),
cache: root.join("cache"),
portable,
}
}
/// Makes the folders, readable by this user only.
pub fn create(&self) -> io::Result<()> {
for dir in [&self.config, &self.data, &self.state, &self.cache] {
std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?;
}
Ok(())
}
pub fn settings(&self) -> PathBuf {
self.config.join("settings.json")
}
pub fn database(&self) -> PathBuf {
self.data.join("medlar.db")
}
pub fn log(&self) -> PathBuf {
self.state.join("medlar.log")
}
/// Where the user drops language files.
pub fn languages(&self) -> PathBuf {
self.config.join("languages")
}
}
/// The running binary, or the AppImage it was mounted from.
fn binary() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
// Another AppImage that started us leaves its own variables behind.
let ours = std::env::var_os("APPDIR").is_some_and(|dir| !dir.is_empty() && exe.starts_with(dir));
match std::env::var_os("APPIMAGE") {
Some(image) if ours => Some(image.into()),
_ => Some(exe),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn home_override_wins_over_portable() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(PORTABLE_MARK), "").unwrap();
let exe = Some(dir.path().join("medlar"));
let p = Paths::choose(Some("/x".into()), exe);
assert_eq!(p.database(), Path::new("/x/data/medlar.db"));
assert!(!p.portable);
}
#[test]
fn portable_file_keeps_everything_beside_the_binary() {
let dir = tempfile::tempdir().unwrap();
let exe = Some(dir.path().join("medlar"));
assert!(!Paths::choose(None, exe.clone()).portable);
std::fs::write(dir.path().join(PORTABLE_MARK), "").unwrap();
let p = Paths::choose(Some("".into()), exe);
assert!(p.portable);
for path in [&p.config, &p.data, &p.state, &p.cache] {
assert!(path.starts_with(dir.path().join(PORTABLE_DIR)));
}
p.create().unwrap();
assert!(p.state.is_dir());
}
}

92
crates/core/src/redact.rs Normal file
View file

@ -0,0 +1,92 @@
//! Takes secrets out of text before it is logged or shown.
use regex::{Captures, Regex};
use std::borrow::Cow;
use std::sync::LazyLock;
const HIDDEN: &str = "[hidden]";
/// Headers that carry secrets: kept in the keyring only, never stored or logged.
pub fn is_secret_header(name: &str) -> bool {
let name = name.trim().to_ascii_lowercase();
["cookie", "authorization", "token", "api-key", "apikey", "secret", "password", "x-auth"].iter().any(|s| name.contains(s))
}
/// A URL without login, query string or fragment.
pub fn url(url: &str) -> Cow<'_, str> {
static URL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"(?i)\b([a-z][a-z0-9+.-]*)://(?:[^\s/?#]*@)?([^\s?#"<>]*)([?#][^\s"<>]*)?"#).unwrap());
URL.replace_all(url, |c: &Captures| {
let tail = c.get(3).map_or("", |m| if m.as_str().starts_with('?') { "?…" } else { "" });
format!("{}://{}{tail}", &c[1], &c[2])
})
}
/// Any text, with the secrets in its URLs, headers and `name=value` pairs hidden.
pub fn text(text: &str) -> String {
static HEADER: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?i)\b((?:proxy-)?authorization|set-cookie2?|cookies?|x-[a-z-]*(?:token|key|auth|secret)[a-z-]*)(["']?\s*[:=,]\s*)[^\r\n]+"#)
.unwrap()
});
static PAIR: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r#"(?i)\b([\w-]*(?:token|password|passwd|passphrase|pwd|secret|api[_-]?key|session[_-]?id|signature))(["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s&;,"']+)"#,
)
.unwrap()
});
static SCHEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\b(bearer|basic)\s+[a-z0-9+/=._~-]{8,}").unwrap());
let out = url(text);
let out = HEADER.replace_all(&out, format!("${{1}}${{2}}{HIDDEN}"));
let out = PAIR.replace_all(&out, format!("${{1}}${{2}}{HIDDEN}"));
SCHEME.replace_all(&out, format!("${{1}} {HIDDEN}")).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn urls_lose_login_query_and_fragment() {
assert_eq!(url("https://me:p@[email protected]:8080/a/b.zip?token=abc&x=1#frag"), "https://h.org:8080/a/b.zip?…");
assert_eq!(url("ftp://me@h/f"), "ftp://h/f");
assert_eq!(url("http://h/f#access_token=1"), "http://h/f");
assert_eq!(url("https://h/[email protected]"), "https://h/[email protected]");
}
#[test]
fn text_hides_every_kind_of_secret() {
for line in [
"GET https://u:S3CRET@h/f failed",
"GET https://h/f?sig=S3CRET failed",
"Cookie: a=1; sid=S3CRET",
"set-cookie: sid=S3CRET; Path=/",
r#"headers [("cookie", "sid=S3CRET")]"#,
r#"{"cookies": "a=b; c=S3CRET"}"#,
"Authorization: Digest username=\"u\", response=\"S3CRET\"",
"proxy-authorization: Basic S3CRETS3CRET",
"sent bearer S3CRET.S3CRET",
"X-Auth-Token: S3CRET",
"access_token=S3CRET&b=2",
r#"password: "my S3CRET""#,
"api-key='S3CRET'",
] {
assert!(!text(line).contains("S3CRET"), "{}", text(line));
}
}
#[test]
fn plain_text_stays() {
let line = "Part 3 of disk.iso: the server closed the connection (attempt 2 of 5)";
assert_eq!(text(line), line);
}
#[test]
fn secret_headers_are_known() {
for h in ["Cookie", "Set-Cookie", "AUTHORIZATION", "X-Api-Key", "X-Auth-Token", "proxy-authorization"] {
assert!(is_secret_header(h), "{h}");
}
for h in ["Referer", "User-Agent", "Accept"] {
assert!(!is_secret_header(h), "{h}");
}
}
}

235
crates/core/src/settings.rs Normal file
View file

@ -0,0 +1,235 @@
//! Settings, stored as JSON. Unknown keys are kept, damage is reported and never fatal.
//!
//! No secrets: logins and tokens are keyring items, named here at most.
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// Language code, or empty to follow the desktop.
pub language: String,
/// Empty for the desktop's download folder.
pub download_folder: String,
/// The speed mode in use.
pub mode: Mode,
pub low: Limits,
pub medium: Limits,
pub high: Limits,
pub snail: Limits,
pub connector: bool,
pub connector_port: u16,
/// Add links from the browser without showing the Add dialog.
pub add_without_asking: bool,
/// Follow the desktop's colours; None until the first run decides (D-012).
pub desktop_colors: Option<bool>,
pub own_color: String,
pub appearance: Appearance,
pub motion: Motion,
/// Keys of newer versions.
#[serde(flatten)]
pub unknown: Map<String, Value>,
}
/// What a speed mode allows. 0 means no limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Limits {
/// Bytes per second.
pub speed: u64,
pub max_active: u32,
pub max_connections: u32,
pub parts_per_download: u32,
pub connections_per_host: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
Low,
Medium,
High,
Snail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Appearance {
Auto,
Light,
Dark,
Amoled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Motion {
Off,
Reduced,
Normal,
Expressive,
}
impl Limits {
const fn new(speed: u64, max_active: u32, max_connections: u32, parts_per_download: u32, connections_per_host: u32) -> Limits {
Limits { speed, max_active, max_connections, parts_per_download, connections_per_host }
}
}
impl Default for Limits {
fn default() -> Limits {
Limits::new(0, 4, 64, 16, 16)
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
language: String::new(),
download_folder: String::new(),
mode: Mode::High,
low: Limits::new(256 * 1024, 2, 8, 4, 4),
medium: Limits::new(1024 * 1024, 3, 24, 8, 8),
high: Limits::default(),
snail: Limits::new(32 * 1024, 1, 1, 1, 1),
connector: true,
connector_port: 17616,
add_without_asking: false,
desktop_colors: None,
own_color: "#8a5a2b".into(),
appearance: Appearance::Auto,
motion: Motion::Expressive,
unknown: Map::new(),
}
}
}
/// What was wrong with the settings file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Damage {
/// The untouched file, moved (or copied) here.
pub kept_at: Option<PathBuf>,
/// Settings that went back to their default; empty when all of them did.
pub keys: Vec<String>,
pub reason: String,
}
impl Settings {
/// Never fails: whatever can't be read keeps its default and is reported.
pub fn load(path: &Path) -> (Settings, Option<Damage>) {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(e) if e.kind() == io::ErrorKind::NotFound => return (Settings::default(), None),
Err(e) => return (Settings::default(), Some(Damage { kept_at: set_aside(path), keys: vec![], reason: e.to_string() })),
};
let mut map: Map<String, Value> = match serde_json::from_slice(&bytes) {
Ok(map) => map,
Err(e) => return (Settings::default(), Some(Damage { kept_at: set_aside(path), keys: vec![], reason: e.to_string() })),
};
let mut keys = vec![];
let mut reason = String::new();
// One bad value must not cost the others.
map.retain(|key, value| {
let alone = Value::Object(Map::from_iter([(key.clone(), value.clone())]));
match serde_json::from_value::<Settings>(alone) {
Ok(_) => true,
Err(e) => {
keys.push(key.clone());
reason = e.to_string();
false
}
}
});
let settings = serde_json::from_value(Value::Object(map)).expect("every key was checked");
if keys.is_empty() {
return (settings, None);
}
(settings, Some(Damage { kept_at: set_aside(path), keys, reason }))
}
/// Replaces the file in one step, so a crash leaves the old or the new one.
pub fn save(&self, path: &Path) -> io::Result<()> {
// A link made by the user stays a link.
let path = fs::canonicalize(path).unwrap_or_else(|_| path.into());
let tmp = path.with_extension("json.tmp");
let mut file = fs::File::create(&tmp)?;
file.write_all(&serde_json::to_vec_pretty(self)?)?;
file.sync_all()?;
fs::rename(tmp, path)
}
pub fn limits(&self) -> Limits {
match self.mode {
Mode::Low => self.low,
Mode::Medium => self.medium,
Mode::High => self.high,
Mode::Snail => self.snail,
}
}
}
fn set_aside(path: &Path) -> Option<PathBuf> {
let to = path.with_extension(format!("damaged-{}.json", chrono::Local::now().format("%Y%m%d-%H%M%S%3f")));
fs::rename(path, &to).ok().map(|_| to)
}
#[cfg(test)]
mod tests {
use super::*;
fn file(text: &str) -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(&path, text).unwrap();
(dir, path)
}
#[test]
fn missing_file_gives_defaults() {
assert_eq!(Settings::load(Path::new("/nonexistent/settings.json")), (Settings::default(), None));
}
#[test]
fn missing_keys_get_defaults_and_unknown_keys_are_kept() {
let (_dir, path) = file(r#"{"mode": "snail", "low": {"speed": 5}, "from_the_future": {"a": [1]}}"#);
let (s, damage) = Settings::load(&path);
assert_eq!(damage, None);
assert_eq!((s.mode, s.low.speed, s.low.max_active, s.connector_port), (Mode::Snail, 5, 4, 17616));
s.save(&path).unwrap();
assert!(fs::read_to_string(&path).unwrap().contains("from_the_future"));
assert_eq!(Settings::load(&path), (s, None));
}
#[test]
fn damaged_file_is_moved_aside() {
for text in ["{\"mode\": ", "", "[1]"] {
let (_dir, path) = file(text);
let (s, damage) = Settings::load(&path);
assert_eq!(s, Settings::default());
assert_eq!(fs::read_to_string(damage.unwrap().kept_at.unwrap()).unwrap(), text);
assert!(!path.exists());
}
}
#[test]
fn one_bad_value_costs_only_itself() {
let (_dir, path) = file(r#"{"mode": "warp", "connector_port": 70000, "language": "de"}"#);
let (s, damage) = Settings::load(&path);
let damage = damage.unwrap();
assert_eq!(damage.keys, ["connector_port", "mode"]);
assert!(damage.kept_at.unwrap().exists());
assert_eq!((s.mode, s.connector_port, s.language.as_str()), (Mode::High, 17616, "de"));
}
#[test]
fn an_unreadable_path_is_reported() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::create_dir(&path).unwrap();
assert!(Settings::load(&path).1.is_some());
}
}

View file

@ -0,0 +1,77 @@
CREATE TABLE queues (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
folder BLOB,
speed_limit INTEGER,
max_active INTEGER,
position REAL NOT NULL,
paused INTEGER NOT NULL DEFAULT 0,
schedule TEXT NOT NULL DEFAULT '[]'
);
INSERT INTO queues (id, name, position) VALUES (1, '', 0);
CREATE TABLE tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
mirrors TEXT NOT NULL,
source_page TEXT,
name TEXT NOT NULL,
folder BLOB NOT NULL,
state TEXT NOT NULL,
error_kind TEXT,
error_detail TEXT,
queue INTEGER NOT NULL REFERENCES queues(id),
position REAL NOT NULL,
priority TEXT NOT NULL,
size INTEGER,
downloaded INTEGER NOT NULL,
mime TEXT,
etag TEXT,
last_modified TEXT,
checksum TEXT,
max_parts INTEGER,
speed_limit INTEGER,
headers TEXT NOT NULL,
proxy TEXT,
secret TEXT,
after INTEGER REFERENCES tasks(id) ON DELETE SET NULL,
start_at INTEGER,
added_at INTEGER NOT NULL,
finished_at INTEGER,
removed_at INTEGER,
notes TEXT NOT NULL
);
CREATE INDEX tasks_queue ON tasks(queue, position);
CREATE INDEX tasks_url ON tasks(url);
CREATE TABLE parts (
task INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
start INTEGER NOT NULL,
end INTEGER,
done INTEGER NOT NULL,
PRIMARY KEY (task, start)
) WITHOUT ROWID;
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
color TEXT
);
CREATE TABLE task_tags (
task INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
tag INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (task, tag)
) WITHOUT ROWID;
CREATE TABLE hosts (
host TEXT PRIMARY KEY,
good_connections INTEGER,
max_connections INTEGER,
ranges INTEGER,
speed_limit INTEGER,
user_agent TEXT,
proxy TEXT,
secret TEXT,
seen_at INTEGER NOT NULL
) WITHOUT ROWID;

View file

@ -0,0 +1,271 @@
//! The download list, in SQLite.
//!
//! One thread writes; reads go through a second connection and never wait for it. `write` methods return after the commit, so
//! a read that follows sees the change. They block for a moment: call them from a blocking context.
mod rows;
use crate::model::*;
use crate::{redact, strings, tr};
use rusqlite::{Connection, OptionalExtension, Transaction, params};
use std::fmt;
use std::path::Path;
use std::sync::{Mutex, mpsc};
use std::thread::JoinHandle;
use std::time::Duration;
/// Never edit one that shipped; add the next number.
const MIGRATIONS: &[&str] = &[include_str!("001.sql")];
#[derive(Debug)]
pub enum Error {
Db(rusqlite::Error),
Newer { found: usize },
IllegalMove { from: State, to: State },
NotFound,
/// A secret was about to be stored outside the keyring.
Secret,
MainQueue,
BadValue(String),
Closed,
}
pub type Result<T> = std::result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let label = |s: &State| strings::text(&format!("state.{}", s.name()), &[]);
f.write_str(&match self {
Error::Db(e) => tr!("store.db", why = redact::text(&e.to_string())),
Error::Newer { found } => tr!("store.newer", found = found, known = MIGRATIONS.len()),
Error::IllegalMove { from, to } => tr!("store.illegal_move", from = label(from), to = label(to)),
Error::NotFound => tr!("store.not_found"),
Error::Secret => tr!("store.secret"),
Error::MainQueue => tr!("store.main_queue"),
Error::BadValue(value) => tr!("store.bad_value", value = value),
Error::Closed => tr!("store.closed"),
})
}
}
impl std::error::Error for Error {}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Error {
Error::Db(e)
}
}
type Job = Box<dyn FnOnce(&mut Connection) + Send>;
/// Share it in an `Arc`. Dropping it finishes the writes that wait.
pub struct Store {
jobs: Option<mpsc::Sender<Job>>,
writer: Option<JoinHandle<()>>,
reader: Mutex<Connection>,
}
impl Store {
pub fn open(path: &Path) -> Result<Store> {
let mut conn = connect(path)?;
migrate(&mut conn)?;
let reader = connect(path)?;
reader.pragma_update(None, "query_only", true)?;
let (jobs, queue) = mpsc::channel::<Job>();
let writer = std::thread::Builder::new()
.name("store".into())
.spawn(move || queue.into_iter().for_each(|job| job(&mut conn)))
.map_err(|e| Error::Db(rusqlite::Error::ToSqlConversionFailure(Box::new(e))))?;
Ok(Store { jobs: Some(jobs), writer: Some(writer), reader: Mutex::new(reader) })
}
/// Runs `f` in one transaction on the writer thread and waits for the commit.
fn write<T: Send + 'static>(&self, f: impl FnOnce(&Transaction) -> Result<T> + Send + 'static) -> Result<T> {
let (reply, answer) = mpsc::sync_channel(1);
self.send(Box::new(move |conn| {
let _ = reply.send(transact(conn, f));
}))?;
answer.recv().map_err(|_| Error::Closed)?
}
fn send(&self, job: Job) -> Result<()> {
self.jobs.as_ref().ok_or(Error::Closed)?.send(job).map_err(|_| Error::Closed)
}
fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
f(&self.reader.lock().unwrap_or_else(|e| e.into_inner()))
}
/// Adds a task and returns its id; `task.id` is ignored.
pub fn add_task(&self, task: Task) -> Result<TaskId> {
refuse_secrets(&task)?;
self.write(move |tx| {
let id = rows::insert_task(tx, &task)?;
rows::set_tags(tx, id, &task.tags)?;
Ok(id)
})
}
/// Saves everything but the state and error, which belong to `set_state`.
pub fn save_task(&self, task: Task) -> Result<()> {
refuse_secrets(&task)?;
self.write(move |tx| {
found(rows::update_task(tx, &task)?)?;
rows::set_tags(tx, task.id, &task.tags)
})
}
/// Moves a task to another state, if the model allows it. The error is replaced; None clears it.
pub fn set_state(&self, id: TaskId, to: State, error: Option<TaskError>) -> Result<()> {
self.write(move |tx| {
let name: String =
tx.query_row("SELECT state FROM tasks WHERE id = ?", [id], |r| r.get(0)).optional()?.ok_or(Error::NotFound)?;
let from = State::from_name(&name).ok_or(Error::BadValue(name))?;
if !from.can_become(to) {
return Err(Error::IllegalMove { from, to });
}
let finished = (to == State::Done && from == State::Finishing).then(now);
let (kind, detail) = error.map(|e| (e.kind.map(ErrorKind::name), redact::text(&e.detail))).unzip();
tx.execute(
"UPDATE tasks SET state = ?, error_kind = ?, error_detail = ?, finished_at = coalesce(?, finished_at) WHERE id = ?",
params![to.name(), kind.flatten(), detail, finished, id],
)?;
Ok(())
})
}
/// Forgets a task for good. Set `removed_at` instead while it can be undone.
pub fn delete_task(&self, id: TaskId) -> Result<()> {
self.write(move |tx| found(tx.execute("DELETE FROM tasks WHERE id = ?", [id])?))
}
pub fn task(&self, id: TaskId) -> Result<Task> {
self.read(|c| rows::tasks(c, "WHERE id = ?", [id])?.pop().ok_or(Error::NotFound))
}
/// All tasks in queue order, removed ones included.
pub fn tasks(&self) -> Result<Vec<Task>> {
self.read(|c| rows::tasks(c, "ORDER BY queue, position, id", []))
}
/// Replaces the parts of a task and its `downloaded`, without waiting. A failure is logged; the next save repairs it.
pub fn post_parts(&self, task: TaskId, parts: Vec<Part>) -> Result<()> {
self.send(Box::new(move |conn| {
if let Err(e) = transact(conn, |tx| rows::set_parts(tx, task, &parts)) {
log::error!("parts of task {task} not saved: {e}");
}
}))
}
/// The same, but returns after the commit.
pub fn save_parts(&self, task: TaskId, parts: Vec<Part>) -> Result<()> {
self.write(move |tx| rows::set_parts(tx, task, &parts))
}
pub fn parts(&self, task: TaskId) -> Result<Vec<Part>> {
self.read(|c| rows::parts(c, task))
}
/// Adds a queue (id 0) or saves one. Returns its id.
pub fn save_queue(&self, queue: Queue) -> Result<QueueId> {
self.write(move |tx| rows::save_queue(tx, &queue))
}
/// Removes a queue; its tasks go to the main one.
pub fn delete_queue(&self, id: QueueId) -> Result<()> {
if id == MAIN_QUEUE {
return Err(Error::MainQueue);
}
self.write(move |tx| {
tx.execute("UPDATE tasks SET queue = ? WHERE queue = ?", [MAIN_QUEUE, id])?;
found(tx.execute("DELETE FROM queues WHERE id = ?", [id])?)
})
}
pub fn queues(&self) -> Result<Vec<Queue>> {
self.read(rows::queues)
}
/// Adds a tag (id 0) or saves one. Returns its id.
pub fn save_tag(&self, tag: Tag) -> Result<TagId> {
self.write(move |tx| rows::save_tag(tx, &tag))
}
pub fn delete_tag(&self, id: TagId) -> Result<()> {
self.write(move |tx| found(tx.execute("DELETE FROM tags WHERE id = ?", [id])?))
}
pub fn tags(&self) -> Result<Vec<Tag>> {
self.read(rows::tags)
}
pub fn save_host(&self, host: HostProfile) -> Result<()> {
refuse_login(host.proxy.as_deref().unwrap_or_default())?;
self.write(move |tx| rows::save_host(tx, &host))
}
pub fn host(&self, host: &str) -> Result<Option<HostProfile>> {
self.read(|c| rows::host(c, host))
}
}
impl Drop for Store {
fn drop(&mut self) {
self.jobs = None;
if let Some(writer) = self.writer.take() {
let _ = writer.join();
}
}
}
fn connect(path: &Path) -> Result<Connection> {
let conn = Connection::open(path)?;
conn.busy_timeout(Duration::from_secs(5))?;
conn.pragma_update(None, "journal_mode", "wal")?;
// WAL stays whole without a sync per commit; a power cut may lose the last moments.
conn.pragma_update(None, "synchronous", "normal")?;
conn.pragma_update(None, "foreign_keys", true)?;
Ok(conn)
}
fn migrate(conn: &mut Connection) -> Result<()> {
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let found: usize = tx.pragma_query_value(None, "user_version", |r| r.get(0))?;
if found > MIGRATIONS.len() {
return Err(Error::Newer { found });
}
for sql in &MIGRATIONS[found..] {
tx.execute_batch(sql)?;
}
tx.pragma_update(None, "user_version", MIGRATIONS.len())?;
Ok(tx.commit()?)
}
fn transact<T>(conn: &mut Connection, f: impl FnOnce(&Transaction) -> Result<T>) -> Result<T> {
let tx = conn.transaction()?;
let value = f(&tx)?;
tx.commit()?;
Ok(value)
}
fn found(changed: usize) -> Result<()> {
if changed == 0 { Err(Error::NotFound) } else { Ok(()) }
}
fn refuse_secrets(task: &Task) -> Result<()> {
if task.headers.iter().any(|(name, _)| redact::is_secret_header(name)) {
return Err(Error::Secret);
}
[&task.url].into_iter().chain(&task.mirrors).chain(&task.source_page).chain(&task.proxy).try_for_each(|u| refuse_login(u))
}
/// The login in `scheme://user:password@host` belongs to the keyring.
fn refuse_login(url: &str) -> Result<()> {
match url::Url::parse(url) {
Ok(u) if u.password().is_some() => Err(Error::Secret),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,230 @@
//! Rows to model and back.
use super::{Error, Result};
use crate::model::*;
use rusqlite::{Connection, OptionalExtension, Params, Row, ToSql, named_params, params};
use std::ffi::OsString;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
/// File names needn't be UTF-8.
fn path_bytes(path: &Path) -> &[u8] {
path.as_os_str().as_bytes()
}
fn bytes_path(bytes: Vec<u8>) -> PathBuf {
OsString::from_vec(bytes).into()
}
fn json<T: serde::Serialize>(value: &T) -> String {
serde_json::to_string(value).expect("plain data always serializes")
}
fn from_json<T: serde::de::DeserializeOwned>(text: String) -> Result<T> {
serde_json::from_str(&text).map_err(|_| Error::BadValue(text))
}
/// Runs an insert or update that names all the columns of a task.
fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
let folder = path_bytes(&t.folder);
let (mirrors, headers) = (json(&t.mirrors), json(&t.headers));
let columns: &[(&str, &dyn ToSql)] = named_params! {
":url": t.url, ":mirrors": mirrors, ":source_page": t.source_page, ":name": t.name, ":folder": folder,
":queue": t.queue, ":position": t.position, ":priority": t.priority.name(), ":size": t.size,
":downloaded": t.downloaded, ":mime": t.mime, ":etag": t.etag, ":last_modified": t.last_modified,
":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers,
":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at,
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes,
};
Ok(c.execute(sql, columns)?)
}
pub fn insert_task(c: &Connection, t: &Task) -> Result<TaskId> {
bind_task(
c,
"INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime,
etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at,
finished_at, removed_at, notes)
VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime,
:etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at,
:finished_at, :removed_at, :notes)",
t,
)?;
let id = c.last_insert_rowid();
let (kind, detail) = t.error.as_ref().map(|e| (e.kind.map(ErrorKind::name), &e.detail)).unzip();
c.execute(
"UPDATE tasks SET state = ?, error_kind = ?, error_detail = ? WHERE id = ?",
params![t.state.name(), kind.flatten(), detail, id],
)?;
Ok(id)
}
pub fn update_task(c: &Connection, t: &Task) -> Result<usize> {
let sql = format!(
"UPDATE tasks SET url = :url, mirrors = :mirrors, source_page = :source_page, name = :name, folder = :folder,
queue = :queue, position = :position, priority = :priority, size = :size, downloaded = :downloaded, mime = :mime,
etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts,
speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after,
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes
WHERE id = {}",
t.id
);
bind_task(c, &sql, t)
}
pub fn set_tags(c: &Connection, task: TaskId, tags: &[TagId]) -> Result<()> {
c.execute("DELETE FROM task_tags WHERE task = ?", [task])?;
for tag in tags {
c.execute("INSERT OR IGNORE INTO task_tags (task, tag) VALUES (?, ?)", [task, *tag])?;
}
Ok(())
}
pub fn tasks(c: &Connection, tail: &str, args: impl Params) -> Result<Vec<Task>> {
let sql = format!(
"SELECT *, (SELECT json_group_array(tag) FROM (SELECT tag FROM task_tags WHERE task = tasks.id ORDER BY tag)) AS tags
FROM tasks {tail}"
);
let mut stmt = c.prepare_cached(&sql)?;
let mut rows = stmt.query(args)?;
let mut out = vec![];
while let Some(row) = rows.next()? {
out.push(task(row)?);
}
Ok(out)
}
fn task(r: &Row) -> Result<Task> {
let state: String = r.get("state")?;
let priority: String = r.get("priority")?;
let detail: Option<String> = r.get("error_detail")?;
let kind: Option<String> = r.get("error_kind")?;
Ok(Task {
id: r.get("id")?,
url: r.get("url")?,
mirrors: from_json(r.get("mirrors")?)?,
source_page: r.get("source_page")?,
name: r.get("name")?,
folder: bytes_path(r.get("folder")?),
state: State::from_name(&state).ok_or(Error::BadValue(state))?,
error: detail.map(|detail| TaskError { kind: kind.as_deref().and_then(ErrorKind::from_name), detail }),
queue: r.get("queue")?,
position: r.get("position")?,
priority: Priority::from_name(&priority).ok_or(Error::BadValue(priority))?,
size: r.get("size")?,
downloaded: r.get("downloaded")?,
mime: r.get("mime")?,
etag: r.get("etag")?,
last_modified: r.get("last_modified")?,
checksum: r.get("checksum")?,
max_parts: r.get("max_parts")?,
speed_limit: r.get("speed_limit")?,
headers: from_json(r.get("headers")?)?,
proxy: r.get("proxy")?,
secret: r.get("secret")?,
after: r.get("after")?,
start_at: r.get("start_at")?,
added_at: r.get("added_at")?,
finished_at: r.get("finished_at")?,
removed_at: r.get("removed_at")?,
tags: from_json(r.get("tags")?)?,
notes: r.get("notes")?,
})
}
pub fn set_parts(c: &Connection, task: TaskId, parts: &[Part]) -> Result<()> {
c.execute("DELETE FROM parts WHERE task = ?", [task])?;
let mut insert = c.prepare_cached("INSERT INTO parts (task, start, end, done) VALUES (?, ?, ?, ?)")?;
for p in parts {
insert.execute(params![task, p.start, p.end, p.done])?;
}
let done: u64 = parts.iter().map(|p| p.done).sum();
super::found(c.execute("UPDATE tasks SET downloaded = ? WHERE id = ?", params![done, task])?)
}
pub fn parts(c: &Connection, task: TaskId) -> Result<Vec<Part>> {
let mut stmt = c.prepare_cached("SELECT start, end, done FROM parts WHERE task = ? ORDER BY start")?;
let rows = stmt.query_map([task], |r| Ok(Part { start: r.get(0)?, end: r.get(1)?, done: r.get(2)? }))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn save_queue(c: &Connection, q: &Queue) -> Result<QueueId> {
let folder = q.folder.as_deref().map(path_bytes);
let schedule = json(&q.schedule);
let columns = params![q.name, folder, q.speed_limit, q.max_active, q.position, q.paused, schedule];
if q.id == 0 {
c.execute(
"INSERT INTO queues (name, folder, speed_limit, max_active, position, paused, schedule) VALUES (?, ?, ?, ?, ?, ?, ?)",
columns,
)?;
return Ok(c.last_insert_rowid());
}
let sql = format!(
"UPDATE queues SET name = ?, folder = ?, speed_limit = ?, max_active = ?, position = ?, paused = ?, schedule = ? WHERE id = {}",
q.id
);
super::found(c.execute(&sql, columns)?)?;
Ok(q.id)
}
pub fn queues(c: &Connection) -> Result<Vec<Queue>> {
let mut stmt = c.prepare_cached("SELECT * FROM queues ORDER BY position, id")?;
let mut rows = stmt.query([])?;
let mut out = vec![];
while let Some(r) = rows.next()? {
out.push(Queue {
id: r.get("id")?,
name: r.get("name")?,
folder: r.get::<_, Option<Vec<u8>>>("folder")?.map(bytes_path),
speed_limit: r.get("speed_limit")?,
max_active: r.get("max_active")?,
position: r.get("position")?,
paused: r.get("paused")?,
schedule: from_json(r.get("schedule")?)?,
});
}
Ok(out)
}
pub fn save_tag(c: &Connection, t: &Tag) -> Result<TagId> {
if t.id == 0 {
c.execute("INSERT INTO tags (name, color) VALUES (?, ?)", params![t.name, t.color])?;
return Ok(c.last_insert_rowid());
}
super::found(c.execute("UPDATE tags SET name = ?, color = ? WHERE id = ?", params![t.name, t.color, t.id])?)?;
Ok(t.id)
}
pub fn tags(c: &Connection) -> Result<Vec<Tag>> {
let mut stmt = c.prepare_cached("SELECT id, name, color FROM tags ORDER BY name")?;
let rows = stmt.query_map([], |r| Ok(Tag { id: r.get(0)?, name: r.get(1)?, color: r.get(2)? }))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn save_host(c: &Connection, h: &HostProfile) -> Result<()> {
c.execute(
"INSERT OR REPLACE INTO hosts (host, good_connections, max_connections, ranges, speed_limit, user_agent, proxy, secret, seen_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
h.host, h.good_connections, h.max_connections, h.ranges, h.speed_limit, h.user_agent, h.proxy, h.secret, h.seen_at
],
)?;
Ok(())
}
pub fn host(c: &Connection, host: &str) -> Result<Option<HostProfile>> {
let row = c.query_row("SELECT * FROM hosts WHERE host = ?", [host], |r| {
Ok(HostProfile {
host: r.get("host")?,
good_connections: r.get("good_connections")?,
max_connections: r.get("max_connections")?,
ranges: r.get("ranges")?,
speed_limit: r.get("speed_limit")?,
user_agent: r.get("user_agent")?,
proxy: r.get("proxy")?,
secret: r.get("secret")?,
seen_at: r.get("seen_at")?,
})
});
Ok(row.optional()?)
}

Some files were not shown because too many files have changed in this diff Show more