commit 37660d826a241aab369f35d4d7ade7f0780745f7 Author: husky Date: Wed Mar 12 12:32:15 2025 -0700 move everything to mono repo diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d2be69 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +/target \ No newline at end of file diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..0a55afb --- /dev/null +++ b/Caddyfile @@ -0,0 +1,21 @@ +http://127.0.0.1:8001 { + route /static/* { + uri strip_prefix /static + file_server { + root ./asklyphe-auth-frontend/static + } + } + + reverse_proxy 127.0.0.1:5843 +} + +http://127.0.0.1:8002 { + route /static/* { + uri strip_prefix /static + file_server { + root ./asklyphe-frontend/static + } + } + + reverse_proxy 127.0.0.1:5842 +} diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..324f355 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5638 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom 0.2.15", + "once_cell", + "version_check", +] + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "getrandom 0.2.15", + "once_cell", + "version_check", + "zerocopy 0.7.35", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" + +[[package]] +name = "anstyle-parse" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" +dependencies = [ + "anstyle", + "once_cell", + "windows-sys 0.59.0", +] + +[[package]] +name = "anyhow" +version = "1.0.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "askama" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28" +dependencies = [ + "askama_derive", + "askama_escape", + "humansize", + "num-traits", + "percent-encoding", +] + +[[package]] +name = "askama_axum" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a41603f7cdbf5ac4af60760f17253eb6adf6ec5b6f14a7ed830cf687d375f163" +dependencies = [ + "askama", + "axum-core", + "http 1.2.0", +] + +[[package]] +name = "askama_derive" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83" +dependencies = [ + "askama_parser", + "basic-toml", + "mime", + "mime_guess", + "proc-macro2", + "quote", + "serde", + "syn 2.0.99", +] + +[[package]] +name = "askama_escape" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341" + +[[package]] +name = "askama_parser" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "asklyphe-auth-frontend" +version = "0.1.0" +dependencies = [ + "argon2", + "askama", + "askama_axum", + "asklyphe-common", + "async-nats", + "axum", + "env_logger 0.11.6", + "futures", + "rmp-serde", + "serde", + "tokio", + "tracing", + "tracing-loki", + "tracing-subscriber", + "ulid", +] + +[[package]] +name = "asklyphe-common" +version = "0.1.0" +dependencies = [ + "async-nats", + "chrono", + "foundationdb", + "futures", + "log", + "rand 0.8.5", + "rmp-serde", + "serde", + "tokio", + "ulid", +] + +[[package]] +name = "asklyphe-frontend" +version = "0.1.0" +dependencies = [ + "askama", + "askama_axum", + "asklyphe-common", + "async-nats", + "axum", + "axum-extra", + "chrono", + "env_logger 0.11.6", + "futures", + "html-escape", + "isahc", + "once_cell", + "rand 0.8.5", + "rmp-serde", + "serde", + "serde_json", + "time", + "tokio", + "tower-http", + "tracing", + "tracing-loki", + "tracing-subscriber", + "ulid", + "unit_converter", + "url_encoded_data", +] + +[[package]] +name = "astro-float" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffbd469c925b479358981be1e1f1207ab20fecd8ed72734edcbcfc8e9374312" +dependencies = [ + "astro-float-macro", + "astro-float-num", +] + +[[package]] +name = "astro-float-macro" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac843ce8123b98c0da2667e1db6db6531d4dee133101a486afc6d8b1db34279" +dependencies = [ + "astro-float-num", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "astro-float-num" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bf9647991ed5c8432085c326d70badf4d2480778434e657fb32a4fd353e441f" +dependencies = [ + "itertools 0.10.5", + "lazy_static", + "rand 0.8.5", + "serde", +] + +[[package]] +name = "async-attributes" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand 2.3.0", + "futures-lite 2.6.0", + "slab", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.3.1", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite 2.6.0", + "once_cell", + "tokio", +] + +[[package]] +name = "async-io" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" +dependencies = [ + "async-lock", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.6.0", + "parking", + "polling 3.7.4", + "rustix 0.38.44", + "slab", + "tracing", + "windows-sys 0.59.0", +] + +[[package]] +name = "async-lock" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +dependencies = [ + "event-listener 5.4.0", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-nats" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76433c4de73442daedb3a59e991d94e85c14ebfc33db53dfcd347a21cd6ef4f8" +dependencies = [ + "base64", + "bytes", + "futures", + "memchr", + "nkeys", + "nuid", + "once_cell", + "pin-project", + "portable-atomic", + "rand 0.8.5", + "regex", + "ring", + "rustls-native-certs 0.7.3", + "rustls-pemfile", + "rustls-webpki", + "serde", + "serde_json", + "serde_nanos", + "serde_repr", + "thiserror 1.0.69", + "time", + "tokio", + "tokio-rustls", + "tokio-util", + "tokio-websockets", + "tracing", + "tryhard", + "url", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "async-std" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" +dependencies = [ + "async-attributes", + "async-channel 1.9.0", + "async-global-executor", + "async-io", + "async-lock", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 2.6.0", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "authservice" +version = "0.1.0" +dependencies = [ + "argon2", + "asklyphe-common", + "async-nats", + "chrono", + "entity", + "env_logger 0.10.2", + "futures", + "lettre", + "log", + "once_cell", + "rand 0.8.5", + "regex", + "rmp-serde", + "sea-orm", + "serde", + "tokio", + "ulid", +] + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core", + "bytes", + "futures-util", + "http 1.2.0", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http 1.2.0", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-extra" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04" +dependencies = [ + "axum", + "axum-core", + "bytes", + "cookie", + "fastrand 2.3.0", + "futures-util", + "http 1.2.0", + "http-body", + "http-body-util", + "mime", + "multer", + "pin-project-lite", + "serde", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "backtrace" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-targets 0.52.6", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bigdecimal" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f31f3af01c5c65a07985c804d3366560e6fa7883d640a122819b14ec327482c" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "bindgen" +version = "0.65.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfdf7b466f9a4903edc73f95d6d2bcd5baf8ae620638762244d3f60143643cc5" +dependencies = [ + "bitflags 1.3.2", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.99", + "which", +] + +[[package]] +name = "bingservice" +version = "0.1.0" +dependencies = [ + "asklyphe-common", + "async-nats", + "chrono", + "env_logger 0.10.2", + "isahc", + "log", + "once_cell", + "scraper", + "serde", + "tokio", + "url_encoded_data", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +dependencies = [ + "serde", +] + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" +dependencies = [ + "async-channel 2.3.1", + "async-task", + "futures-io", + "futures-lite 2.6.0", + "piper", +] + +[[package]] +name = "borsh" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5430e3be710b68d984d1391c854eb431a9d548640711faa54eecb1df93db91cc" +dependencies = [ + "borsh-derive", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b668d39970baad5356d7c83a86fee3a539e6f93bf6764c97368243e17a0487" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "bumpalo" +version = "3.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" + +[[package]] +name = "bytecheck" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" +dependencies = [ + "bytecheck_derive", + "ptr_meta", + "simdutf8", +] + +[[package]] +name = "bytecheck_derive" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +dependencies = [ + "serde", +] + +[[package]] +name = "castaway" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2698f953def977c68f935bb0dfa959375ad4638570e969e2f1e9f433cbf1af6" + +[[package]] +name = "cc" +version = "1.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" +dependencies = [ + "shlex", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "chumsky" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" +dependencies = [ + "hashbrown 0.14.5", + "stacker", +] + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.5.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "clap_lex" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" + +[[package]] +name = "colorchoice" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.31.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3df4f93e5fbbe73ec01ec8d3f68bba73107993a5b1e7519273c32db9b0d5be" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.11.3", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.99", +] + +[[package]] +name = "curl" +version = "0.4.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9fb4d13a1be2b58f14d60adba57c9834b78c62fd86c3e76a148f732686e9265" +dependencies = [ + "curl-sys", + "libc", + "openssl-probe", + "openssl-sys", + "schannel", + "socket2", + "windows-sys 0.52.0", +] + +[[package]] +name = "curl-sys" +version = "0.4.80+curl-8.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55f7df2eac63200c3ab25bde3b2268ef2ee56af3d238e76d61f01c3c49bff734" +dependencies = [ + "cc", + "libc", + "libnghttp2-sys", + "libz-sys", + "openssl-sys", + "pkg-config", + "vcpkg", + "windows-sys 0.52.0", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "darling" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "darling_macro" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "data-encoding" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "575f75dfd25738df5b91b8e43e14d44bda14637a58fae779fd2b064f8bf3e010" + +[[package]] +name = "der" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + +[[package]] +name = "derive_more" +version = "0.99.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3da29a38df43d6f156149c9b43ded5e018ddff2a855cf2cfd62e8cd7d079c69f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "dtoa" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6add3b8cff394282be81f3fc1a0605db594ed69890078ca6e2cab1c408bcf04" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "signature", + "subtle", +] + +[[package]] +name = "ego-tree" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12a0bb14ac04a9fcf170d0bbbef949b44cc492f4452bd20c095636956f653642" + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] + +[[package]] +name = "email-encoding" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea3d894bbbab314476b265f9b2d46bf24b123a36dd0e96b06a1b49545b9d9dcc" +dependencies = [ + "base64", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "entity" +version = "0.1.0" +dependencies = [ + "sea-orm", +] + +[[package]] +name = "env_filter" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" +dependencies = [ + "humantime", + "is-terminal", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "env_logger" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcaee3d8e3cfc3fd92428d477bc97fc29ec8716d180c0d74c643bb26166660e0" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "humantime", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3492acde4c3fc54c845eaab3eed8bd00c7a7d881f78bfc801e43a93dec1331ae" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3e4e0dd3673c1139bf041f3008816d9cf2946bbfac2945c09e523b8d7b05b2" +dependencies = [ + "event-listener 5.4.0", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "foundationdb" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8696fd1be198f101eb58aeecf0f504fc02b28c7afcc008b4e4a998a91b305108" +dependencies = [ + "async-recursion", + "async-trait", + "foundationdb-gen", + "foundationdb-macros", + "foundationdb-sys", + "futures", + "memchr", + "rand 0.8.5", + "serde", + "serde_bytes", + "serde_json", + "static_assertions", + "uuid", +] + +[[package]] +name = "foundationdb-gen" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62239700f01b041b6372aaeb847c52f960e1a69fd2b1025dc995ea3dd90e3308" +dependencies = [ + "xml-rs", +] + +[[package]] +name = "foundationdb-macros" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83c8d52fe8b46ab822b4decdcc0d6d85aeedfc98f0d52ba2bd4aec4a97807516" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", + "try_map", +] + +[[package]] +name = "foundationdb-sys" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98e49545f5393d276b7b888c77e3f9519fd33727435f8244344be72c3284256f" +dependencies = [ + "bindgen", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-lite" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +dependencies = [ + "fastrand 2.3.0", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getopts" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.13.3+wasi-0.2.2", + "windows-targets 0.52.6", +] + +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" + +[[package]] +name = "glob" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "googleservice" +version = "0.1.0" +dependencies = [ + "asklyphe-common", + "async-nats", + "chrono", + "env_logger 0.10.2", + "isahc", + "log", + "once_cell", + "scraper", + "serde", + "tokio", + "url_encoded_data", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash 0.7.8", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash 0.8.11", + "allocator-api2", +] + +[[package]] +name = "hashbrown" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.2", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + +[[package]] +name = "hermit-abi" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbd780fe5cc30f81464441920d82ac8740e2e46b29a6fad543ddd075229ce37e" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "hostname" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c7c7c8ac16c798734b8a24560c1362120597c40d5e1459f09498f8f6c8f2ba" +dependencies = [ + "cfg-if", + "libc", + "windows", +] + +[[package]] +name = "html-escape" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476" +dependencies = [ + "utf8-width", +] + +[[package]] +name = "html5ever" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4" +dependencies = [ + "log", + "mac", + "markup5ever", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http 1.2.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http 1.2.0", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humansize" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" +dependencies = [ + "libm", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "hyper" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.2.0", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.2.0", + "http-body", + "hyper", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "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 = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +dependencies = [ + "equivalent", + "hashbrown 0.15.2", +] + +[[package]] +name = "inherent" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c38228f24186d9cc68c729accb4d413be9eaed6ad07ff79e0270d9e56f3de13" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ipnet" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" + +[[package]] +name = "is-terminal" +version = "0.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" +dependencies = [ + "hermit-abi 0.5.0", + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "isahc" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "334e04b4d781f436dc315cb1e7515bd96826426345d498149e4bde36b67f8ee9" +dependencies = [ + "async-channel 1.9.0", + "castaway", + "crossbeam-utils", + "curl", + "curl-sys", + "encoding_rs", + "event-listener 2.5.3", + "futures-lite 1.13.0", + "http 0.2.12", + "log", + "mime", + "once_cell", + "polling 2.8.0", + "serde", + "serde_json", + "slab", + "sluice", + "tracing", + "tracing-futures", + "url", + "waker-fn", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "js-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "lettre" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d476fe7a4a798f392ce34947aa7d53d981127e37523c5251da3c927f7fa901f" +dependencies = [ + "base64", + "chumsky", + "email-encoding", + "email_address", + "fastrand 2.3.0", + "futures-util", + "hostname", + "httpdate", + "idna", + "mime", + "native-tls", + "nom 8.0.0", + "percent-encoding", + "quoted_printable", + "socket2", + "tokio", + "url", +] + +[[package]] +name = "libc" +version = "0.2.170" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828" + +[[package]] +name = "libloading" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +dependencies = [ + "cfg-if", + "windows-targets 0.52.6", +] + +[[package]] +name = "libm" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" + +[[package]] +name = "libnghttp2-sys" +version = "0.1.11+1.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b6c24e48a7167cffa7119da39d577fa482e66c688a4aac016bee862e1a713c4" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libz-sys" +version = "1.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9b68e50e6e0b26f672573834882eb57759f6db9b3be2ea3c35c91188bb4eaa" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db9c683daf087dc577b7506e9695b3d556a9f3849903fa28186283afd6809e9" + +[[package]] +name = "litemap" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" +dependencies = [ + "value-bag", +] + +[[package]] +name = "loki-api" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdc38a304f59a03e6efa3876766a48c70a766a93f88341c3fff4212834b8e327" +dependencies = [ + "prost", + "prost-types", +] + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "markup5ever" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45" +dependencies = [ + "log", + "phf 0.11.3", + "phf_codegen 0.11.3", + "string_cache", + "string_cache_codegen", + "tendril", +] + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata 0.1.10", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "migration" +version = "0.1.0" +dependencies = [ + "async-std", + "sea-orm-migration", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +dependencies = [ + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys 0.52.0", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http 1.2.0", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "native-tls" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework 2.11.1", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nkeys" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f49e787f4c61cbd0f9320b31cc26e58719f6aa5068e34697dd3aea361412fe3" +dependencies = [ + "data-encoding", + "ed25519", + "ed25519-dalek", + "getrandom 0.2.15", + "log", + "rand 0.8.5", + "signatory", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "nuid" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc895af95856f929163a0aa20c26a78d26bfdc839f51b9d5aa7a5b79e52b7e83" +dependencies = [ + "rand 0.8.5", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.5", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "object" +version = "0.36.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" + +[[package]] +name = "openssl" +version = "0.10.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd" +dependencies = [ + "bitflags 2.9.0", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb61ea9811cc39e3c2069f40b8b8e2e70d8569b361f879786cc7ed48b777cdd" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "ordered-float" +version = "3.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1e1c390732d15f1d48471625cd92d154e66db2c56645e29a9cd26f4699f72dc" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.6", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pgvector" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0e8871b6d7ca78348c6cd29b911b94851f3429f0cd403130ca17f26c1fb91a6" +dependencies = [ + "serde", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_shared 0.10.0", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_codegen" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.5", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.5", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher 1.0.1", +] + +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "piper" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" +dependencies = [ + "atomic-waker", + "fastrand 2.3.0", + "futures-io", +] + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + +[[package]] +name = "polling" +version = "3.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi 0.4.0", + "pin-project-lite", + "rustix 0.38.44", + "tracing", + "windows-sys 0.59.0", +] + +[[package]] +name = "portable-atomic" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy 0.7.35", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "prettyplease" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1ccf34da56fc294e7d4ccf69a85992b7dfb826b7cf57bac6a70bba3494cc08a" +dependencies = [ + "proc-macro2", + "syn 2.0.99", +] + +[[package]] +name = "proc-macro-crate" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "proc-macro2" +version = "1.0.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", + "version_check", + "yansi", +] + +[[package]] +name = "prost" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "prost-types" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16" +dependencies = [ + "prost", +] + +[[package]] +name = "psm" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58e5423e24c18cc840e1c98370b3993c6649cd1678b4d24318bcf0a083cbe88" +dependencies = [ + "cc", +] + +[[package]] +name = "ptr_meta" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "quote" +version = "1.0.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "quoted_printable" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", + "zerocopy 0.8.23", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.15", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.1", +] + +[[package]] +name = "redox_syscall" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1" +dependencies = [ + "bitflags 2.9.0", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata 0.4.9", + "regex-syntax 0.8.5", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.5", +] + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "rend" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" +dependencies = [ + "bytecheck", +] + +[[package]] +name = "reqwest" +version = "0.12.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43e734407157c3c2034e0258f5e4473ddb361b1e85f95a66690d67264d7cd1da" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http 1.2.0", + "http-body", + "http-body-util", + "hyper", + "hyper-tls", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-registry", +] + +[[package]] +name = "ring" +version = "0.17.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ac5d832aa16abd7d1def883a8545280c20a60f523a370aa3a9617c2b8550ee" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.15", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rkyv" +version = "0.7.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b" +dependencies = [ + "bitvec", + "bytecheck", + "bytes", + "hashbrown 0.12.3", + "ptr_meta", + "rend", + "rkyv_derive", + "seahash", + "tinyvec", + "uuid", +] + +[[package]] +name = "rkyv_derive" +version = "0.7.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "503d1d27590a2b0a3a4ca4c94755aa2875657196ecbf401a42eff41d7de532c0" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "rmp" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "228ed7c16fa39782c3b3468e974aec2795e9089153cd08ee2e9aefb3613334c4" +dependencies = [ + "byteorder", + "num-traits", + "paste", +] + +[[package]] +name = "rmp-serde" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52e599a477cf9840e92f2cde9a7189e67b42c57532749bf90aea6ec10facd4db" +dependencies = [ + "byteorder", + "rmp", + "serde", +] + +[[package]] +name = "rsa" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47c75d7c5c6b673e58bf54d8544a9f432e3a925b0e80f7cd3602ab5c50c55519" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rust_decimal" +version = "1.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b082d80e3e3cc52b2ed634388d436fe1f4de6af5786cc2de9ba9737527bdf555" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.5", + "rkyv", + "serde", + "serde_json", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.9.0", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dade4812df5c384711475be5fcd8c162555352945401aed22a35bffeab61f657" +dependencies = [ + "bitflags 2.9.0", + "errno", + "libc", + "linux-raw-sys 0.9.2", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.23.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework 2.11.1", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework 3.2.0", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "schannel" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scraper" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b90460b31bfe1fc07be8262e42c665ad97118d4585869de9345a84d501a9eaf0" +dependencies = [ + "ahash 0.8.11", + "cssparser", + "ego-tree", + "getopts", + "html5ever", + "once_cell", + "selectors", + "tendril", +] + +[[package]] +name = "sea-bae" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f694a6ab48f14bc063cfadff30ab551d3c7e46d8f81836c51989d548f44a2a25" +dependencies = [ + "heck 0.4.1", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "sea-orm" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3417812d38049e8ec3d588c03570f8c60de811d2453fb48e424045a1600ffd86" +dependencies = [ + "async-stream", + "async-trait", + "bigdecimal", + "chrono", + "futures-util", + "log", + "ouroboros", + "pgvector", + "rust_decimal", + "sea-orm-macros", + "sea-query", + "sea-query-binder", + "serde", + "serde_json", + "sqlx", + "strum", + "thiserror 1.0.69", + "time", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "sea-orm-cli" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf2a390d6528f8e5c9ecd327bbb1a4c6cd7ab8333ef0da97010d5dc8f83f01c4" +dependencies = [ + "chrono", + "clap", + "dotenvy", + "glob", + "regex", + "sea-schema", + "tracing", + "tracing-subscriber", + "url", +] + +[[package]] +name = "sea-orm-macros" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d705ba84e1c74c8ac27784e4ac6f21584058c1dc0cadb9d39b43e109fcf8139c" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "sea-bae", + "syn 2.0.99", + "unicode-ident", +] + +[[package]] +name = "sea-orm-migration" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c38451d5112e3a518a02251b5e6d3bc72e626957a44a79264716808a4c28ee0" +dependencies = [ + "async-trait", + "clap", + "dotenvy", + "sea-orm", + "sea-orm-cli", + "sea-schema", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "sea-query" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b731192738ebf56d20580fc8ba2d23940333befe900b04dd08a26a77cd056f02" +dependencies = [ + "bigdecimal", + "chrono", + "inherent", + "ordered-float", + "rust_decimal", + "sea-query-derive", + "serde_json", + "time", + "uuid", +] + +[[package]] +name = "sea-query-binder" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0019f47430f7995af63deda77e238c17323359af241233ec768aba1faea7608" +dependencies = [ + "bigdecimal", + "chrono", + "rust_decimal", + "sea-query", + "serde_json", + "sqlx", + "time", + "uuid", +] + +[[package]] +name = "sea-query-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9834af2c4bd8c5162f00c89f1701fb6886119a88062cf76fe842ea9e232b9839" +dependencies = [ + "darling", + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 2.0.99", + "thiserror 1.0.69", +] + +[[package]] +name = "sea-schema" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef5dd7848c993f3789d09a2616484c72c9330cae2b048df59d8c9b8c0343e95" +dependencies = [ + "futures", + "sea-query", + "sea-schema-derive", +] + +[[package]] +name = "sea-schema-derive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "debdc8729c37fdbf88472f97fd470393089f997a909e535ff67c544d18cfccf0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "searchservice" +version = "0.1.0" +dependencies = [ + "asklyphe-common", + "async-nats", + "async-recursion", + "chrono", + "env_logger 0.10.2", + "futures", + "log", + "once_cell", + "rand 0.8.5", + "rmp-serde", + "serde", + "tokio", + "ulid", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.9.0", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" +dependencies = [ + "bitflags 2.9.0", + "core-foundation 0.10.0", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4eb30575f3638fc8f6815f448d50cb1a2e255b0897985c8c59f4d37b72a07b06" +dependencies = [ + "bitflags 2.9.0", + "cssparser", + "derive_more", + "fxhash", + "log", + "new_debug_unreachable", + "phf 0.10.1", + "phf_codegen 0.10.0", + "precomputed-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" + +[[package]] +name = "serde" +version = "1.0.218" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "364fec0df39c49a083c9a8a18a23a6bcfd9af130fe9fe321d18520a0d113e09e" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.218" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "serde_json" +version = "1.0.140" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_nanos" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a93142f0367a4cc53ae0fead1bcda39e85beccfad3dcd717656cacab94b12985" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a" +dependencies = [ + "itoa", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "servo_arc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d036d71a959e00c77a63538b90a6c2390969f9772b096ea837205c6bd0491a44" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + +[[package]] +name = "signatory" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1e303f8205714074f6068773f0e29527e0453937fe837c9717d066635b65f31" +dependencies = [ + "pkcs8", + "rand_core 0.6.4", + "signature", + "zeroize", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "sluice" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d7400c0eff44aa2fcb5e31a5f24ba9716ed90138769e4977a2ba6014ae63eb5" +dependencies = [ + "async-channel 1.9.0", + "futures-core", + "futures-io", +] + +[[package]] +name = "smallvec" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" +dependencies = [ + "serde", +] + +[[package]] +name = "snap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" + +[[package]] +name = "socket2" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4410e73b3c0d8442c5f99b425d7a435b5ee0ae4167b3196771dd3f7a01be745f" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a007b6936676aa9ab40207cde35daab0a04b823be8ae004368c0793b96a61e0" +dependencies = [ + "bigdecimal", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener 5.4.0", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.2", + "hashlink", + "indexmap", + "log", + "memchr", + "native-tls", + "once_cell", + "percent-encoding", + "rust_decimal", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror 2.0.12", + "time", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3112e2ad78643fef903618d78cf0aec1cb3134b019730edb039b69eaf531f310" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.99", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e9f90acc5ab146a99bf5061a7eb4976b573f560bc898ef3bf8435448dd5e7ad" +dependencies = [ + "dotenvy", + "either", + "heck 0.5.0", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.99", + "tempfile", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4560278f0e00ce64938540546f59f590d60beee33fffbd3b9cd47851e5fff233" +dependencies = [ + "atoi", + "base64", + "bigdecimal", + "bitflags 2.9.0", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.5", + "rsa", + "rust_decimal", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 2.0.12", + "time", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5b98a57f363ed6764d5b3a12bfedf62f07aa16e1856a7ddc2a0bb190a959613" +dependencies = [ + "atoi", + "base64", + "bigdecimal", + "bitflags 2.9.0", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "num-bigint", + "once_cell", + "rand 0.8.5", + "rust_decimal", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 2.0.12", + "time", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f85ca71d3a5b24e64e1d08dd8fe36c6c95c339a896cc33068148906784620540" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "time", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "stacker" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9156ebd5870ef293bfb43f91c7a74528d363ec0d424afe24160ed5a4343d08a" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.59.0", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "string_cache" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "938d512196766101d333398efde81bc1f37b00cb42c2f8350e5df639f040bbbe" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.11.3", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", +] + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c317e0a526ee6120d8dabad239c8dadca62b24b6f168914bbbc8e2fb1f0e567" +dependencies = [ + "cfg-if", + "fastrand 2.3.0", + "getrandom 0.3.1", + "once_cell", + "rustix 1.0.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" +dependencies = [ + "thiserror-impl 2.0.12", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "time" +version = "0.3.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad298b01a40a23aac4580b67e3dbedb7cc8402f3592d7f49469de2ea4aecdd8" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "765c97a5b985b7c11d7bc27fa927dc4fe6af3a6dfb021d28deb60d3bf51e76ef" + +[[package]] +name = "time-macros" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8093bc3e81c3bc5f7879de09619d06c9a5a5e45ca44dfeeb7225bae38005c5c" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9975ea0f48b5aa3972bf2d888c238182458437cc2a19374b81b25cdf1023fb3a" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.52.0", +] + +[[package]] +name = "tokio-macros" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-websockets" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f591660438b3038dd04d16c938271c79e7e06260ad2ea2885a4861bfb238605d" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-sink", + "http 1.2.0", + "httparse", + "rand 0.8.5", + "ring", + "rustls-native-certs 0.8.1", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tokio-util", +] + +[[package]] +name = "toml_datetime" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" + +[[package]] +name = "toml_edit" +version = "0.22.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" +dependencies = [ + "indexmap", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tower" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" +dependencies = [ + "bitflags 2.9.0", + "bytes", + "http 1.2.0", + "http-body", + "http-body-util", + "pin-project-lite", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "tracing-core" +version = "0.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-futures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" +dependencies = [ + "pin-project", + "tracing", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-loki" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3beec919fbdf99d719de8eda6adae3281f8a5b71ae40431f44dc7423053d34" +dependencies = [ + "loki-api", + "reqwest", + "serde", + "serde_json", + "snap", + "tokio", + "tokio-stream", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", + "tracing-subscriber", + "url", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "try_map" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1626d07cb5c1bb2cf17d94c0be4852e8a7c02b041acec9a8c5bdda99f9d580" + +[[package]] +name = "tryhard" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9f0a709784e86923586cff0d872dba54cd2d2e116b3bc57587d15737cfce9d" +dependencies = [ + "futures", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "typenum" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" + +[[package]] +name = "ulid" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab82fc73182c29b02e2926a6df32f2241dbadb5cfc111fd595515b3598f46bb3" +dependencies = [ + "rand 0.9.0", + "web-time", +] + +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" + +[[package]] +name = "unicode-normalization" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unit_converter" +version = "0.1.0" +dependencies = [ + "astro-float", + "once_cell", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "url_encoded_data" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e1fdf35657b22e2c3b485cfb5ab66d5aa9dd5b0dce9902a314a830e2ea05972" +dependencies = [ + "anyhow", + "url", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8-width" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0f540e3240398cce6128b64ba83fdbdd86129c16a3aa1a3a252efd66eb3d587" +dependencies = [ + "serde", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "value-bag" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasi" +version = "0.13.3+wasi-0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn 2.0.99", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2210b291f7ea53617fbafcc4939f10914214ec15aace5ba62293a668f322c5c9" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "whoami" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372d5b87f58ec45c384ba03563b03544dc5fadc3983e434b286913f5b4a9bb6d" +dependencies = [ + "redox_syscall", + "wasite", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-link" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3" + +[[package]] +name = "windows-registry" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" +dependencies = [ + "windows-result", + "windows-strings", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7f4ea97f6f78012141bcdb6a216b2609f0979ada50b20ca5b52dde2eac2bb1" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +dependencies = [ + "bitflags 2.9.0", +] + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "xml-rs" +version = "0.8.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5b940ebc25896e71dd073bad2dbaa2abfe97b0a391415e22ad1326d9c54e3c4" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd97444d05a4328b90e75e503a34bad781f14e28a823ad3557f0750df1ebcbc6" +dependencies = [ + "zerocopy-derive 0.8.23", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6352c01d0edd5db859a63e2605f4ea3183ddbd15e2c4a9e7d32184df75e4f154" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.99", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..34a8a11 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["asklyphe-common", "asklyphe-frontend", "searchservice", "asklyphe-auth-frontend", "unit_converter", "authservice", "authservice/migration", "authservice/entity", "bingservice", "googleservice"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8f7adf2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,183 @@ +NOTE: Some subdirectories contain a file named ASSET_LICENSE which should be referred to as well when applicable. + +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based on the Program. + + To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + 1. Source Code. + The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + + A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those + subprograms and other parts of the work. + + The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + 2. Basic Permissions. + All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + + When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + 4. Conveying Verbatim Copies. + You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + 5. Conveying Modified Source Versions. + You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + + A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + 6. Conveying Non-Source Forms. + You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + + If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + + The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + 7. Additional Terms. + "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + + All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + 8. Termination. + + You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + + However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + + Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + + If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent + license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + + A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may + not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + + Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + + Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + diff --git a/asklyphe-auth-frontend/.gitignore b/asklyphe-auth-frontend/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/asklyphe-auth-frontend/.gitignore @@ -0,0 +1 @@ +/target diff --git a/asklyphe-auth-frontend/ASSET_LICENSE b/asklyphe-auth-frontend/ASSET_LICENSE new file mode 100644 index 0000000..064d7e9 --- /dev/null +++ b/asklyphe-auth-frontend/ASSET_LICENSE @@ -0,0 +1,454 @@ +AskLyphe data/media assets under /static and /templates are licensed under CC-BY-NC-SA-4.0 except where otherwise specified. + +The AskLyphe Character, "Lyphe", and the design of this character are also licensed under CC-BY-NC-SA-4.0 + +-- INFO FOR FAN ARTISTS -- +Please visit https://creativecommons.org/licenses/by-nc-sa/4.0/ for a simplified version of this license. +You are free to create whatever AskLyphe fan-art you'd like, as long as you +- Give us credit for the character design +- Don't use the art for commercial purposes +- Release the art under the same license (i.e. people must follow the same terms if sharing your art) +- - This is mostly in order to allow for modified AskLyphe art assets to be licensed similarly to our AGPL code +- Don't add additional legal restrictions that would restrict others from doing something that our license allows + +You are encouraged to read the license below in full, the information above should not substitute doing so. + +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + + diff --git a/asklyphe-auth-frontend/Cargo.toml b/asklyphe-auth-frontend/Cargo.toml new file mode 100644 index 0000000..139d97a --- /dev/null +++ b/asklyphe-auth-frontend/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "asklyphe-auth-frontend" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } + +tokio = { version = "1.35.1", features = ["full"] } + +axum = "0.7.4" + +askama = { version = "0.12.1", features = ["default", "with-axum"] } +askama_axum = "0.4.0" + +tracing = "0.1.40" +tracing-subscriber = "0.3.18" +tracing-loki = "0.2.4" + +env_logger = "0.11.5" +serde = { version = "1.0", features = ["derive"] } +async-nats = "0.38.0" +rmp-serde = "1.1.2" +ulid = "1.1.0" +futures = "0.3.30" +argon2 = "0.5.3" \ No newline at end of file diff --git a/asklyphe-auth-frontend/build.rs b/asklyphe-auth-frontend/build.rs new file mode 100644 index 0000000..f3626f5 --- /dev/null +++ b/asklyphe-auth-frontend/build.rs @@ -0,0 +1,36 @@ +/* + * asklyphe-auth-frontend build.rs + * - build script + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::process::Command; +fn main() { + let output = Command::new("git") + .args(["rev-parse", "--short", "HEAD"]) + .output() + .expect("Failed to execute git command"); + let git_commit = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=GIT_COMMIT={}", git_commit); + + let output = Command::new("date") + .args(["-u", "+%Y-%m-%d"]) + .output() + .expect("Failed to execute date command"); + let built_on = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=BUILT_ON={}", built_on); + + let output = Command::new("date") + .args(["-u", "+%Y"]) + .output() + .expect("Failed to execute date command"); + let year = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=YEAR={}", year); +} diff --git a/asklyphe-auth-frontend/src/login.rs b/asklyphe-auth-frontend/src/login.rs new file mode 100644 index 0000000..d3e0b69 --- /dev/null +++ b/asklyphe-auth-frontend/src/login.rs @@ -0,0 +1,186 @@ +/* + * asklyphe-auth-frontend login.rs + * - login page routes + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::ops::Deref; +use std::sync::Arc; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, EmailError, LoginError, LoginRequest, LoginResponse, PasswordError, RegisterError, RegisterRequest, RegisterResponse, UsernameError}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::{Extension, Form}; +use axum::response::Redirect; +use serde::Deserialize; +use tokio::sync::Mutex; +use tracing::error; +use crate::{BUILT_ON, GIT_COMMIT, Opts, VERSION, YEAR}; + +#[derive(Template)] +#[template(path = "login.html")] +struct LoginTemplate { + error: Option, + success: bool, + email: String, + version: String, + git_commit: String, + built_on: String, + year: String, +} + +#[derive(Deserialize, Debug)] +pub struct LoginForm { + email: Option, + password: Option, +} + +pub async fn login_get() -> impl IntoResponse { + LoginTemplate { + error: None, + success: false, + email: "".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } +} + +pub async fn login_post( + Extension(nats): Extension>>, + Extension(opts): Extension, + Form(input): Form, +) -> impl IntoResponse { + fn login_error(error: &str, email: String) -> LoginTemplate { + LoginTemplate { + error: Some(error.to_string()), + success: false, + email, + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } + } + + let email = input.email; + let password = input.password; + if email.is_none() + || password.is_none() { + return login_error( + "one or more fields blank!", + email.unwrap_or_default(), + ).into_response(); + } + let email = email.unwrap(); + let password = password.unwrap(); + + // todo: implement more frontend input checking + + if email.is_empty() + || password.is_empty() { + return login_error( + "one or more fields blank!", + email, + ).into_response(); + } + + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::LoginRequest( + LoginRequest { + email: email.clone(), + password, + } + ), + replyto: "".to_string(), + }), + &*nats.lock().await, + false, + ).await; + + if let Err(e) = response { + error!("internal server error while trying to communicate with auth service! {:?}", e); + return login_error( + "internal server error! try again, or contact an administrator if the issue persists!", + email, + ).into_response(); + } + + let response = response.unwrap(); + + let mut internal_server_error = false; + + match &response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::AuthService(r) => { + match r { + AuthServiceResponse::LoginResponse(_) => {} + x => { + error!("auth service gave {} to our login request!", x); + internal_server_error = true; + } + } + } + } + + if internal_server_error { + return login_error( + "internal server error! try again, or contact an administrator if the issue persists!", + email, + ).into_response(); + } + + match response { + ServiceResponse::AuthService(AuthServiceResponse::LoginResponse(r)) => match r { + LoginResponse::Success(r) => { + Redirect::to(&format!("{}/semaphore?one_time_token={}", opts.asklyphe_url, r.token)).into_response() + } + LoginResponse::Failure(r) => match r { + LoginError::InternalServer(error) => { + error!("internal server error during login attempt! {error}"); + login_error( + "internal server error! try again, or contact an administrator if the issue persists!", + email, + ).into_response() + } + LoginError::InvalidAccount => { + login_error( + "your email or password is incorrect! please try again, or click \"forgot password\" if you continue to have trouble!", + email, + ).into_response() + } + LoginError::SuspendedAccount => { + login_error( + "unfortunately your account has been suspended and you are no longer able to log in, for more help check our support pages or contact our support team!", + email, + ).into_response() + } + LoginError::AccountNotVerified => { + login_error( + "your account has not been verified yet! please check your email for a link from us to verify your account!", + email, + ).into_response() + } + } + } + _ => unreachable!() + } +} diff --git a/asklyphe-auth-frontend/src/main.rs b/asklyphe-auth-frontend/src/main.rs new file mode 100644 index 0000000..cd16d94 --- /dev/null +++ b/asklyphe-auth-frontend/src/main.rs @@ -0,0 +1,124 @@ +/* + * asklyphe-auth-frontend main.rs + * - entrypoint for the asklyphe authentication frontend + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod register; +mod verify; +mod login; + +use std::{env, process}; +use std::collections::HashMap; +use std::net::SocketAddr; +use std::ops::Deref; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use argon2::{Argon2, PasswordHasher}; +use argon2::password_hash::rand_core::OsRng; +use argon2::password_hash::SaltString; +use askama::Template; +use asklyphe_common::nats; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, EmailError, PasswordError, RegisterError, RegisterRequest, RegisterResponse, UsernameError}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::{Extension, Form, Router}; +use axum::extract::Query; +use axum::response::IntoResponse; +use axum::routing::get; +use serde::Deserialize; +use tokio::sync::Mutex; +use tracing::error; +use tracing_loki::url::Url; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use crate::login::{login_get, login_post}; +use crate::register::{register_get, register_post}; +use crate::verify::verify_get; + +const VERSION: &str = env!("CARGO_PKG_VERSION"); +const GIT_COMMIT: &str = env!("GIT_COMMIT"); +const BUILT_ON: &str = env!("BUILT_ON"); +const YEAR: &str = env!("YEAR"); + +#[derive(Clone)] +struct Opts { + bind_addr: SocketAddr, + nats_addr: SocketAddr, + nats_cert: String, + nats_key: String, + asklyphe_url: String, + loki_addr: Option, + datacenter_id: i64, +} + +#[tokio::main] +async fn main() { + env_logger::init(); + let opts = Opts { + bind_addr: env::var("BIND_ADDR").unwrap_or("0.0.0.0:5843".to_string()).parse().expect("Badly formed BIND_ADDR (Needs to be SocketAddr)"), + nats_addr: env::var("NATS_ADDR").unwrap_or("127.0.0.1:4222".to_string()).parse().expect("Badly formed NATS_ADDR (Needs to be SocketAddr)"), + nats_cert: env::var("NATS_CERT").expect("NATS_CERT needs to be set"), + nats_key: env::var("NATS_KEY").expect("NATS_KEY needs to be set"), + asklyphe_url: env::var("ASKLYPHE_URL").unwrap_or("https://asklyphe.com".to_string()), + loki_addr: match env::var("LOKI_ADDR") { + Ok(url) => { + Some(Url::parse(&url).expect("Badly formed LOKI_ADDR (Needs to be Url)")) + } + Err(_) => { + None + } + }, + datacenter_id: env::var("DATACENTER_ID").unwrap_or("1".to_string()).parse().expect("Badly formed DATACENTER_ID (Need to be i64)"), + }; + + //if opts.loki_addr.is_some() { + // let (layer, task) = tracing_loki::builder() + // .label("environment", "dev").unwrap() + // .extra_field("pid", process::id().to_string()).unwrap() + // .extra_field("run_id", snowflake_factory.generate().to_string()).unwrap() + // .build_url(opts.loki_addr.clone().unwrap()).unwrap(); + + // // Register Loki layer + // tracing_subscriber::registry() + // .with(layer) + // .init(); + + // // Spawn Loki background task + // tokio::spawn(task); + //} else { + // tracing_subscriber::fmt::init() + //} + + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(opts.nats_cert.as_str().into(), opts.nats_key.as_str().into()) + .connect(opts.nats_addr.to_string()) + .await; + if let Err(e) = nats { + eprintln!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + let nats = Arc::new(Mutex::new(nats)); + + let app = Router::new() + .route("/register", get(register_get).post(register_post)) + .route("/login", get(login_get).post(login_post)) + .route("/verify", get(verify_get)) + .layer(Extension(nats.clone())) + .layer(Extension(opts.clone())); + + let listener = tokio::net::TcpListener::bind(opts.bind_addr).await.expect("Failed to get listener"); + axum::serve(listener, app).await.expect("Failed to serve"); +} + diff --git a/asklyphe-auth-frontend/src/register.rs b/asklyphe-auth-frontend/src/register.rs new file mode 100644 index 0000000..8dc83f6 --- /dev/null +++ b/asklyphe-auth-frontend/src/register.rs @@ -0,0 +1,321 @@ +/* + * asklyphe-auth-frontend register.rs + * - registration page routes + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::ops::Deref; +use std::sync::Arc; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, EmailError, PasswordError, RegisterError, RegisterRequest, RegisterResponse, UsernameError}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::{Extension, Form}; +use serde::Deserialize; +use tokio::sync::Mutex; +use tracing::error; +use crate::{BUILT_ON, GIT_COMMIT, VERSION, YEAR}; + +#[derive(Template)] +#[template(path = "register.html")] +struct RegisterTemplate { + error: Option, + success: bool, + username: String, + email: String, + invite_code: String, + version: String, + git_commit: String, + built_on: String, + year: String, +} + +#[derive(Deserialize, Debug)] +pub struct RegisterForm { + username: Option, + email: Option, + password: Option, + // todo: rename fields to adhere to snakecase + verifypassword: Option, + invitecode: Option, +} + +pub async fn register_get() -> impl IntoResponse { + RegisterTemplate { + error: None, + success: false, + username: "".to_string(), + email: "".to_string(), + invite_code: "".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } +} + +pub async fn register_post( + Extension(nats): Extension>>, + Form(input): Form, +) -> impl IntoResponse { + fn register_error(error: &str, username: String, email: String, invite_code: String) -> RegisterTemplate { + RegisterTemplate { + error: Some(error.to_string()), + success: false, + username, + email, + invite_code, + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } + } + + let username = input.username; + let email = input.email; + let password = input.password; + let verify_password = input.verifypassword; + let invite_code = input.invitecode; + if username.is_none() + || email.is_none() + || password.is_none() + || verify_password.is_none() + || invite_code.is_none() { + return register_error( + "one or more fields blank!", + username.unwrap_or_default(), + email.unwrap_or_default(), + invite_code.unwrap_or_default(), + ); + } + let username = username.unwrap(); + let email = email.unwrap(); + let password = password.unwrap(); + let verify_password = verify_password.unwrap(); + let invite_code = invite_code.unwrap(); + + // todo: implement more frontend input checking + + if username.is_empty() + || email.is_empty() + || password.is_empty() + || verify_password.is_empty() + || invite_code.is_empty() { + return register_error( + "one or more fields blank!", + username, + email, + invite_code, + ); + } + + if password != verify_password { + return register_error( + "passwords do not match!", + username, + email, + invite_code, + ); + } + + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::RegisterRequest( + RegisterRequest { + username: username.clone(), + email: email.clone(), + password, + invite_code: invite_code.clone(), + } + ), + replyto: "".to_string(), + }), + &*nats.lock().await, + false, + ).await; + + if let Err(e) = response { + error!("internal server error while trying to communicate with auth service! {:?}", e); + return register_error( + "internal server error! try again, or contact an administrator if the issue persists!", + username, + email, + invite_code, + ); + } + + let response = response.unwrap(); + + let mut internal_server_error = false; + + match &response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::AuthService(r) => { + match r { + AuthServiceResponse::RegisterResponse(_) => {} + x => { + error!("auth service gave {} to our login request!", x); + internal_server_error = true; + } + } + } + } + + if internal_server_error { + return register_error( + "internal server error! try again, or contact an administrator if the issue persists!", + username, + email, + invite_code, + ); + } + + match response { + ServiceResponse::AuthService(AuthServiceResponse::RegisterResponse(r)) => match r { + RegisterResponse::Success => { + RegisterTemplate { + error: None, + success: true, + username: "".to_string(), + email: "".to_string(), + invite_code: "".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } + } + RegisterResponse::Failure(e) => { + match e { + RegisterError::InternalServer(e) => { + error!("auth service gave internal server error during our registration query!! {e}"); + register_error( + "internal server error! try again, or contact an administrator if the issue persists!", + username, + email, + invite_code, + ) + } + RegisterError::Password(e) => { + match e { + PasswordError::InvalidCharacters => { + register_error( + "your password contains invalid characters! please only use ascii characters in your password!", + username, + email, + invite_code, + ) + } + PasswordError::TooShort => { + register_error( + "your password is too short! please have a minimum of 14 characters in your password", + username, + email, + invite_code, + ) + } + PasswordError::TooCommon => { + register_error( + "your password is insecure! please avoid using commonly used passwords and try again", + username, + email, + invite_code, + ) + } + } + } + RegisterError::Email(e) => { + match e { + EmailError::InvalidEmail => { + register_error( + "the provided email address is invalid! please check your input and try again!", + username, + email, + invite_code, + ) + } + EmailError::EmailTaken => { + register_error( + "the provided email address is already in use!", + username, + email, + invite_code, + ) + } + EmailError::EmailBlacklisted => { + register_error( + "the provided email address is blocked! your email server may have been blacklisted for large amounts of spam, please try again with a different email!", + username, + email, + invite_code, + ) + } + } + } + RegisterError::BadInviteCode => { + register_error( + "the provided invite code is non-existent, malformed, expired, or already used!", + username, + email, + invite_code, + ) + } + RegisterError::Username(e) => { + match e { + UsernameError::InvalidCharacters => { + register_error( + "the provided username contains invalid characters! please only include dashes, underscores, and alphanumeric characters in your username!", + username, + email, + invite_code, + ) + } + UsernameError::TooShort => { + register_error( + "the provided username is too short! please make sure your username is at least 1 character long!", + username, + email, + invite_code, + ) + } + UsernameError::Taken => { + register_error( + "the provided username is already in use! if you have forgotten the password for your account, please visit the \"forgot password\" link on the login page!", + username, + email, + invite_code, + ) + } + UsernameError::Inappropriate => { + register_error( + "uh oh! we don't use that type of language on asklyphe.com! please choose a different username!", + username, + email, + invite_code, + ) + } + } + } + } + } + } + _ => unreachable!() + } +} diff --git a/asklyphe-auth-frontend/src/verify.rs b/asklyphe-auth-frontend/src/verify.rs new file mode 100644 index 0000000..3e07e92 --- /dev/null +++ b/asklyphe-auth-frontend/src/verify.rs @@ -0,0 +1,137 @@ +/* + * asklyphe-auth-frontend verify.rs + * - email verification page routes + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, VerifyEmailRequest, VerifyEmailResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::Extension; +use axum::extract::Query; +use serde::Deserialize; +use tokio::sync::Mutex; +use tracing::error; +use crate::{BUILT_ON, GIT_COMMIT, VERSION, YEAR}; + +#[derive(Template)] +#[template(path = "verify.html")] +struct VerifyTemplate { + system_message: String, + version: String, + git_commit: String, + built_on: String, + year: String, +} + +#[derive(Deserialize, Debug)] +pub struct VerifyParams { + username: Option, + token: Option, +} + +pub async fn verify_get( + Extension(nats): Extension>>, + Query(params): Query, +) -> impl IntoResponse { + fn verify_error(error: &str) -> impl IntoResponse { + VerifyTemplate { + system_message: format!("error: {error}"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + } + } + + let username = params.username; + let token = params.token; + if username.is_none() || token.is_none() { + return verify_error("one or more fields blank!").into_response(); + } + let username = username.unwrap(); + let token = token.unwrap(); + if username.is_empty() || token.is_empty() { + return verify_error("one or more fields blank!").into_response(); + } + + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::VerifyEmailRequest(VerifyEmailRequest { + username, + token, + }), + replyto: "".to_string(), + }), + &*nats.lock().await, + false, + ).await; + + if let Err(e) = response { + error!("internal server error while trying to communicate with auth service! {:?}", e); + return verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response(); + } + let response = response.unwrap(); + let mut internal_server_error = false; + + match &response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::AuthService(r) => { + match r { + AuthServiceResponse::VerifyEmailResponse(_) => {} + x => { + error!("auth service gave {} to our verify email query!", x); + internal_server_error = true; + } + } + } + } + + if internal_server_error { + return verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response(); + } + + match response { + ServiceResponse::AuthService(AuthServiceResponse::VerifyEmailResponse(response)) => match response { + VerifyEmailResponse::Success => { + VerifyTemplate { + system_message: "email verified! you should be good to log in to your account now! (:".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + }.into_response() + } + VerifyEmailResponse::InvalidToken => { + verify_error("invalid token").into_response() + } + VerifyEmailResponse::ExpiredToken => { + verify_error("token expired, please try signing up again, or resending the request if you're changing emails").into_response() + } + VerifyEmailResponse::InternalServerError(e) => { + error!("experienced internal server error \"{e}\" while attempting to verify email"); + verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response() + } + } + _ => unreachable!() + } + +} diff --git a/asklyphe-auth-frontend/static/auth.css b/asklyphe-auth-frontend/static/auth.css new file mode 100644 index 0000000..695abd1 --- /dev/null +++ b/asklyphe-auth-frontend/static/auth.css @@ -0,0 +1,95 @@ +#lyphebig { + display: grid; + margin: 7% auto; + grid-auto-flow: column; + width: 55%; +} + +#alyphebig { + margin: auto; +} + +@media screen and (max-width: 800px) { + #lyphebig { + grid-auto-flow: row; + } +} + +#lyphetitle { + display: grid; + margin-left: 5px; + padding-top: 20%; +} + +@media screen and (max-width: 800px) { + #lyphetitle { + padding-top: 0; + } +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 90%; + display: grid; + height: auto; +} + +#lypheimg { + width: 90%; + margin: auto; +} + +#lyphetitle > img { + width: 100%; + margin: 0; +} + +#lyphetitle > p { + font-family: NanumGothicCoding, monospace; + font-size: 175%; + color: #9baba4; +} + +@media screen and (max-width: 800px) { + #lyphetitle > h2 { + font-size: 100%; + } +} + +form { + margin-top: 10%; + display: flex; + flex-direction: column; +} + +.form-buttons { + display: flex; + flex-direction: row; + margin-top: 25px; +} + +@media screen and (max-width: 800px) { + .form-buttons { + flex-direction: column; + align-items: center; + } +} + +.pagecontent { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +td { + margin: auto; + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; +} + +td > label { + width: 70px; +} \ No newline at end of file diff --git a/asklyphe-auth-frontend/static/bluestars.gif b/asklyphe-auth-frontend/static/bluestars.gif new file mode 100644 index 0000000..9ddb845 Binary files /dev/null and b/asklyphe-auth-frontend/static/bluestars.gif differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.ttf b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.ttf new file mode 100644 index 0000000..36bd220 Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.ttf differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff new file mode 100644 index 0000000..2f1b9cb Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff2 b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff2 new file mode 100644 index 0000000..b99441f Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Bold.woff2 differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding-Regular.ttf b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Regular.ttf new file mode 100644 index 0000000..990066a Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding-Regular.ttf differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff b/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff new file mode 100644 index 0000000..1f26953 Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff differ diff --git a/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff2 b/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff2 new file mode 100644 index 0000000..3813615 Binary files /dev/null and b/asklyphe-auth-frontend/static/font/NanumGothicCoding.woff2 differ diff --git a/asklyphe-auth-frontend/static/font/OFL.txt b/asklyphe-auth-frontend/static/font/OFL.txt new file mode 100644 index 0000000..9872707 --- /dev/null +++ b/asklyphe-auth-frontend/static/font/OFL.txt @@ -0,0 +1,97 @@ +Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com), +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver +NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver +NanumBrush, NanumPen, Naver NanumPen. + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/asklyphe-auth-frontend/static/home.css b/asklyphe-auth-frontend/static/home.css new file mode 100644 index 0000000..145d8f8 --- /dev/null +++ b/asklyphe-auth-frontend/static/home.css @@ -0,0 +1,7 @@ +.response { + display: flex; + flex-direction: column; + align-items: center; +} + + diff --git a/asklyphe-auth-frontend/static/img/bigbutton.png b/asklyphe-auth-frontend/static/img/bigbutton.png new file mode 100644 index 0000000..2974f36 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/bigbutton.png differ diff --git a/asklyphe-auth-frontend/static/img/borderbent.png b/asklyphe-auth-frontend/static/img/borderbent.png new file mode 100644 index 0000000..bb276e6 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/borderbent.png differ diff --git a/asklyphe-auth-frontend/static/img/button.png b/asklyphe-auth-frontend/static/img/button.png new file mode 100644 index 0000000..ddf11c7 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/button.png differ diff --git a/asklyphe-auth-frontend/static/img/logo.png b/asklyphe-auth-frontend/static/img/logo.png new file mode 100644 index 0000000..1b3ff32 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/logo.png differ diff --git a/asklyphe-auth-frontend/static/img/lyphebent.png b/asklyphe-auth-frontend/static/img/lyphebent.png new file mode 100644 index 0000000..a80a824 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/lyphebent.png differ diff --git a/asklyphe-auth-frontend/static/img/paper.jpg b/asklyphe-auth-frontend/static/img/paper.jpg new file mode 100644 index 0000000..7087b35 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/paper.jpg differ diff --git a/asklyphe-auth-frontend/static/img/textbox.png b/asklyphe-auth-frontend/static/img/textbox.png new file mode 100644 index 0000000..9562d55 Binary files /dev/null and b/asklyphe-auth-frontend/static/img/textbox.png differ diff --git a/asklyphe-auth-frontend/static/lyphe.png b/asklyphe-auth-frontend/static/lyphe.png new file mode 100644 index 0000000..7e89311 Binary files /dev/null and b/asklyphe-auth-frontend/static/lyphe.png differ diff --git a/asklyphe-auth-frontend/static/osd.xml b/asklyphe-auth-frontend/static/osd.xml new file mode 100644 index 0000000..9ef320f --- /dev/null +++ b/asklyphe-auth-frontend/static/osd.xml @@ -0,0 +1,10 @@ + + + AskLyphe + the best search engine! + UTF-8 + https://asklyphe.com/favicon.ico + + https://asklyphe.com/ + + diff --git a/asklyphe-auth-frontend/static/search.css b/asklyphe-auth-frontend/static/search.css new file mode 100644 index 0000000..63b516b --- /dev/null +++ b/asklyphe-auth-frontend/static/search.css @@ -0,0 +1,108 @@ +.lyphe-says { + text-align: left; + min-width: 20%; + max-height: 128px; + border: 3px inset black; + padding: 10px; + background-image: url("/static/snow.gif"); +} + +.lyphe-says > img { + height: 100px; + float: left; + margin-right: 10px; +} + +.lyphe-says > h5, p { + color: black; + word-break: break-word; +} + +.lyphe-says > h5 { + padding: 0; + margin: 0; + line-height: 2em; +} + +.navbar { + width: 85%; + padding-bottom: 10px; + border-bottom: 1px black solid; +} + +.ask { + text-align: left; + width: 85%; +} + +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} + +.response { + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; + margin: 20px; + width: 85%; +} + +.resultstat { + text-align: right; + float: right; +} + +.search-result-list { + width: 100%; + padding-left: 0; + list-style: none; +} + +.search-result-list > li { + list-style-type: none; + padding: 5px; + border-top: 1px black solid; + margin-top: 5px; + white-space: nowrap; + display: flex; +} + +@media screen and (max-width: 800px) { + .search-result-list > li { + flex-direction: column; + } +} + +.search-link { + color: lightblue; + flex-grow: 1; + word-break: break-all; + white-space: initial; +} +.search-link:visited { + color: lightblue; +} \ No newline at end of file diff --git a/asklyphe-auth-frontend/static/shell.css b/asklyphe-auth-frontend/static/shell.css new file mode 100644 index 0000000..ae6766c --- /dev/null +++ b/asklyphe-auth-frontend/static/shell.css @@ -0,0 +1,228 @@ +@font-face { + font-family: NanumGothicCoding; + src: url("/static/font/NanumGothicCoding.woff2") format("woff2"), + url("/static/font/NanumGothicCoding.woff") format("woff"); + font-weight: normal; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: NanumGothicCoding; + src: url("/static/font/NanumGothicCoding-Bold.woff2") format("woff2"), + url("/static/font/NanumGothicCoding-Bold.woff") format("woff"); + font-weight: bold; + font-style: normal; + font-display: swap; +} + +a, a:visited { + text-decoration: none; +} + +body { + text-align: center; + background-color: #4e6e7e; + min-height: 100vh; + margin: 0; + padding: 0; +} + +@media screen and (max-width: 800px) { + body { + padding: 0; + } +} + +.main { + background-image: url("/static/img/paper.jpg"); + min-height: 100vh; + margin: 0 7% 0 7%; + color: #9baba4; + font-family: monospace; + font-weight: bold; + display: flex; + flex-direction: column; + align-items: center; + flex-grow: 1; +} + +@media screen and (max-width: 800px) { + .main { + margin: 0; + } +} + +.main > img { + max-width: 35vw; +} + +.footer { + bottom: 0; + left: 0; + width: 100%; + margin-top: 6%; +} + +.footer-inner { + /*margin: 2vw;*/ + margin: 2vw 0; + background-color: rgba(77,77,77,0.3); + border: 1px solid cadetblue; + color: white; + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; +} + +.footer-inner > ul { + padding: 0; + margin: 0; + list-style: none; + display: flex; + flex-wrap: wrap; +} + +.footer-list { + display: flex; + line-height: 1.5em; + align-items: center; +} + +.footer-item { + padding: 10px 12px; + text-align: center; +} + +.footer-item a { + color: white; + text-decoration: none; +} + +.lyphe-label { + display: block; +} + +input[type=text], input[type=email], input[type=password] { + background: url("/static/img/textbox.png") no-repeat center; + background-size: 256px 64px; + width: 232px; + height: 64px; + border: none; + padding-inline: 10px 10px; + font-family: NanumGothicCoding, monospace; + font-weight: bold; +} + +input[type=text]:focus { + border: none; +} + +button, .button { + display: inline-block; + background: url("/static/img/button.png") no-repeat center; + background-size: 138px 64px; + width: 138px; + height: 64px; + vertical-align: bottom; + padding-top: 6px; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 1.2em; + text-decoration: none; + line-height: 58px; + color: black; +} + +button:hover, .button:hover { + filter: brightness(78%); + cursor: pointer; +} + +.bigbutton { + display: inline-block; + background: url("/static/img/bigbutton.png") no-repeat center; + background-size: 276px 64px; + width: 276px; + height: 64px; + vertical-align: bottom; + padding-top: 6px; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 1.2em; + text-decoration: none; + line-height: 58px; + color: black; +} +.bigbutton:hover { + filter: brightness(78%); + cursor: pointer; +} + +#lyphesmall { + margin-top: 1%; + display: flex; + flex-direction: row; + height: 10%; + text-align: left; +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 85px; + display: grid; + height: 85px; + margin: auto; +} + +#lypheimg { + width: 85px; + margin: auto; +} + +#lyphetitlenav > img { + height: 72px; + padding-top: 20px; + margin: auto; +} + +.navbar { + width: 95%; + margin-bottom: 1%; +} + +.user-bar { + display: flex; + width: 100%; + flex-direction: row; + align-items: center; + justify-content: right; +} + +.user-bar > form { + margin: 0; +} + +.user-bar > span { + margin-top: auto; + margin-bottom: auto; +} + +.user-bar > form > button { + display: inline-block; + background: url("/static/img/button.png") no-repeat center; + background-size: 69px 32px; + width: 69px; + height: 32px; + margin-top: -6px; + vertical-align: bottom; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 0.9em; + text-decoration: none; + line-height: 10px; + color: #586761; +} diff --git a/asklyphe-auth-frontend/static/snow.gif b/asklyphe-auth-frontend/static/snow.gif new file mode 100644 index 0000000..2ad24b8 Binary files /dev/null and b/asklyphe-auth-frontend/static/snow.gif differ diff --git a/asklyphe-auth-frontend/templates/login.html b/asklyphe-auth-frontend/templates/login.html new file mode 100644 index 0000000..4d40273 --- /dev/null +++ b/asklyphe-auth-frontend/templates/login.html @@ -0,0 +1,51 @@ +{% extends "shell.html" %} + +{% block title %}Login{% endblock %} + +{% block head %} + +{% endblock %} + +{% block page %} +
+ +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +

the best search engine!

+
+
+
+

login

+
+ {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% endmatch %} +
+ + + + + + + +
+
+
+ +
+
+
+ +{% include "ui/footer.html" %} +{% endblock %} \ No newline at end of file diff --git a/asklyphe-auth-frontend/templates/register.html b/asklyphe-auth-frontend/templates/register.html new file mode 100644 index 0000000..24c06e2 --- /dev/null +++ b/asklyphe-auth-frontend/templates/register.html @@ -0,0 +1,69 @@ +{% extends "shell.html" %} + +{% block title %}Register{% endblock %} + +{% block head %} + +{% endblock %} + +{% block page %} +
+ +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +

the best search engine!

+
+
+
+

register

+
+ {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% endmatch %} + {% if success %} +
your account has been registered! before attempting to login, please check your email for a + link to verify your account +
+ {% endif %} +
+ + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
+ +{% include "ui/footer.html" %} +{% endblock %} \ No newline at end of file diff --git a/asklyphe-auth-frontend/templates/shell.html b/asklyphe-auth-frontend/templates/shell.html new file mode 100644 index 0000000..7e69818 --- /dev/null +++ b/asklyphe-auth-frontend/templates/shell.html @@ -0,0 +1,21 @@ + + + + + + + AskLyphe - {% block title %}{% endblock %} + + + + + + {% block head %}{% endblock %} + + + {% block page %}{% endblock %} + + \ No newline at end of file diff --git a/asklyphe-auth-frontend/templates/ui/footer.html b/asklyphe-auth-frontend/templates/ui/footer.html new file mode 100644 index 0000000..6598a08 --- /dev/null +++ b/asklyphe-auth-frontend/templates/ui/footer.html @@ -0,0 +1,31 @@ + diff --git a/asklyphe-auth-frontend/templates/ui/navbar.html b/asklyphe-auth-frontend/templates/ui/navbar.html new file mode 100644 index 0000000..5a65f44 --- /dev/null +++ b/asklyphe-auth-frontend/templates/ui/navbar.html @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/asklyphe-auth-frontend/templates/verify.html b/asklyphe-auth-frontend/templates/verify.html new file mode 100644 index 0000000..2956a49 --- /dev/null +++ b/asklyphe-auth-frontend/templates/verify.html @@ -0,0 +1,27 @@ +{% extends "shell.html" %} + +{% block title %}Verify Email{% endblock %} + +{% block head %} + +{% endblock %} + +{% block page %} +
+ +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +

the best search engine!

+
+
+
+

verify email

+ {{ system_message }} +
+ +{% include "ui/footer.html" %} +{% endblock %} \ No newline at end of file diff --git a/asklyphe-common/.gitignore b/asklyphe-common/.gitignore new file mode 100644 index 0000000..3a8cabc --- /dev/null +++ b/asklyphe-common/.gitignore @@ -0,0 +1,2 @@ +/target +.idea diff --git a/asklyphe-common/Cargo.toml b/asklyphe-common/Cargo.toml new file mode 100644 index 0000000..b85d0b1 --- /dev/null +++ b/asklyphe-common/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "asklyphe-common" +version = "0.1.0" +edition = "2021" +license = "AGPL-3" +license-file = "LICENSE" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +tokio = { version = "1.0", features = ["full"] } +chrono = "0.4.31" +serde = { version = "1.0", features = ["derive"] } +foundationdb = { version = "0.8.0", features = ["embedded-fdb-include"] } +log = "0.4.20" +rmp-serde = "1.1.2" +futures = "0.3.30" +async-nats = "0.38.0" +ulid = "1.1.0" +rand = "0.8.5" \ No newline at end of file diff --git a/asklyphe-common/src/db/mod.rs b/asklyphe-common/src/db/mod.rs new file mode 100644 index 0000000..7b05d7a --- /dev/null +++ b/asklyphe-common/src/db/mod.rs @@ -0,0 +1,995 @@ +/* + * asklyphe-common db/mod.rs + * - foundationdb functions for accessing crawled websites + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use chrono::{TimeZone}; +use foundationdb::{Database, RangeOption}; +use foundationdb::options::StreamingMode; +use foundationdb::tuple::{pack, Subspace, unpack}; +use log::{error, warn}; +use rand::Rng; +use crate::db::tables::{DEHOMOGENISE_TABLE, HASH_TABLE, HOST_TABLE, LINK_TABLE, LINKWORD_TABLE, METAWORD_TABLE, WEBSITE_TABLE, WORD_TABLE, INFO_TABLE, REVLINK_TABLE, WEBSITE_TABLE_HOST, WEBSITE_TABLE_DAMPING, WEBSITE_TABLE_LASTPARSEBEGIN, WEBSITE_TABLE_LASTPARSEFINISH, WEBSITE_TABLE_LASTPARSEFINISHTRUE, WEBSITE_TABLE_CACHEDPAGERANK, WEBSITE_TABLE_LASTPAGERANKCACHE, WEBSITE_TABLE_ROBOTSFLAG, INFO_TABLE_TITLE, INFO_TABLE_DESC, INFO_TABLE_FAVICON, METAWURL_TABLE, WURL_TABLE, WEBSITE_TABLE_WORDCOUNT, DERANK_TABLE}; + + +pub mod tables; + +pub type STRHASH = i64; + +pub fn hash(val: &str) -> STRHASH { + let mut hasher = DefaultHasher::new(); + val.hash(&mut hasher); + unsafe { std::mem::transmute(hasher.finish()) } +} + +pub struct DerankEntry { + pub urlmatch: String, + pub and: Option, + pub unless: Option, + pub amount: f64, + pub comment: String, +} + +pub async fn remove_deranked_website(db: &Database, id: i64) { + let trx = db.create_trx(); + if let Err(e) = trx { + eprintln!("DATABASE ERROR remove_deranked_website {e}"); + } else { + let trx = trx.unwrap(); + // info -> url + let subspace = Subspace::from(id); + + trx.clear(&subspace.pack(&id)); + + if let Err(e) = trx.commit().await { + eprintln!("DATABASE ERROR remove_deranked_website {e}"); + } + } +} + +pub async fn add_deranked_website(db: &Database, entry: DerankEntry) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + eprintln!("DATABASE ERROR add_deranked_website {e}"); + None + } else { + let trx = trx.unwrap(); + let id: i64 = { + let mut r = rand::thread_rng(); + r.gen() + }; + // info -> url + let subspace = Subspace::from(DERANK_TABLE); + + trx.set(&subspace.pack(&id), &pack(&( + entry.urlmatch, entry.unless.clone().unwrap_or_default(), entry.and.clone().unwrap_or_default(), + entry.unless.is_some(), entry.and.is_some(), entry.amount, entry.comment + ))); + + if let Err(e) = trx.commit().await { + eprintln!("DATABASE ERROR add_deranked_website {e}"); + } + + Some(id) + } +} + +pub async fn get_deranked_websites(db: &Database) -> Vec<(i64, DerankEntry)> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR get_deranked_websites {e}"); + vec![] + } else { + let trx = trx.unwrap(); + // derank -> * + let subspace = Subspace::from(DERANK_TABLE); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR page_links_entering {e}"); + vec![] + } else { + let kv = kv.unwrap(); + + let mut hashes = vec![]; + + for kv in kv.into_iter() { + let (_, id) = unpack::<(String, i64)>(kv.key()).expect("INVALID K TYPE get_deranked_websites"); + let (urlmatch, unless, and, use_unless, use_and, amount, comment) + = unpack::< + (String, String, String, bool, bool, f64, String) + >(kv.value()).expect("INVALID V TYPE get_deranked_websites"); + + hashes.push((id, DerankEntry { + urlmatch, + and: if use_and { Some(and) } else { None }, + unless: if use_unless { Some(unless) } else { None }, + amount, + comment, + })); + } + + hashes + } + } +} + +pub async fn info_title(db: &Database, url: STRHASH) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_pagerank {e}"); + None + } else { + let trx = trx.unwrap(); + // info -> url -> title + let subspace = Subspace::from((INFO_TABLE, url)); + let v = trx.get(&subspace.pack(&(INFO_TABLE_TITLE)), true).await; + + if let Ok(v) = v { + v.map(|v| unpack::<(String,)>(&v).expect("INVALID K TYPE page_pagerank").0) + } else { + None + } + } +} + +pub async fn info_description(db: &Database, url: STRHASH) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_pagerank {e}"); + None + } else { + let trx = trx.unwrap(); + // info -> url -> title + let subspace = Subspace::from((INFO_TABLE, url)); + let v = trx.get(&subspace.pack(&(INFO_TABLE_DESC)), true).await; + + if let Ok(v) = v { + v.map(|v| unpack::<(String,)>(&v).expect("INVALID K TYPE page_pagerank").0) + } else { + None + } + } +} + +pub async fn set_page_word_count(db: &Database, url: STRHASH, wc: u64) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR set_page_word_count {e}"); + } else { + let trx = trx.unwrap(); + trx.set(&pack(&(WEBSITE_TABLE, url, WEBSITE_TABLE_WORDCOUNT)), &pack(&(wc))); + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR set_page_word_count {e}"); + } + } +} + +pub async fn page_word_count(db: &Database, url: STRHASH) -> u64 { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_word_count {e}"); + 0 + } else { + let trx = trx.unwrap(); + + let wc = trx.get(&pack(&(WEBSITE_TABLE, url, WEBSITE_TABLE_WORDCOUNT)), true).await; + if let Ok(Some(wc)) = wc { + let val = unpack::(&wc).unwrap(); + if val > 0 { + return val; + } + } else if let Err(e) = wc { + warn!("DATABASE ERROR page_word_count {e}"); + } + warn!("recalculating page word count..."); + // link -> from -> * + let subspace = Subspace::from((WURL_TABLE, url)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + + if let Err(e) = kv { + error!("DATABASE ERROR page_word_count {e}"); + 0 + } else { + let kv = kv.unwrap(); + let mut counter = 0; + for kv in kv.into_iter() { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_word_count {e}"); + } else { + let trx = trx.unwrap(); + if let Ok(word) = unpack::(kv.value()) { + let subspace = Subspace::from((WORD_TABLE, word)); + let kv = trx.get(&subspace.pack(&url), true).await; + if let Err(e) = kv { + error!("DATABASE ERROR page_word_count {e}"); + } else { + let kv = kv.unwrap(); + if kv.is_none() { + warn!("WURL HAS NO CORRESPONDING WORD"); + } else { + let kv = kv.unwrap(); + counter += u64::from_be_bytes(kv.split_at(std::mem::size_of::()).0.try_into().unwrap()); + } + } + } + } + } + + let add_wc_trx = db.create_trx(); + if let Err(e) = add_wc_trx { + error!("couldn't add precalced wordcount to db: {e}"); + } else { + let add_wc_trx = add_wc_trx.unwrap(); + add_wc_trx.set(&pack(&(WEBSITE_TABLE, url, WEBSITE_TABLE_WORDCOUNT)), &pack(&(counter))); + if let Err(e) = add_wc_trx.commit().await { + warn!("couldn't add precalced wordcount to db: {e}"); + } + } + counter + } + } +} + +pub async fn page_links_entering(db: &Database, url: STRHASH) -> Vec { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_links_entering {e}"); + vec![] + } else { + let trx = trx.unwrap(); + // revlink -> to -> * + let subspace = Subspace::from((REVLINK_TABLE, url)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR page_links_entering {e}"); + vec![] + } else { + let kv = kv.unwrap(); + + let mut hashes = vec![]; + + for kv in kv.into_iter() { + let (_, _, from) = unpack::<(String, i64, i64)>(kv.key()).expect("INVALID K TYPE page_links_entering"); + + hashes.push(from); + } + + hashes + } + } +} + +pub async fn page_pagerank(db: &Database, url: STRHASH) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_pagerank {e}"); + None + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + let v = trx.get(&subspace.pack(&(WEBSITE_TABLE_CACHEDPAGERANK)), true).await; + + if let Ok(v) = v { + v.map(|v| unpack::<(f64, )>(&v).expect("INVALID K TYPE page_pagerank").0) + } else { + None + } + } +} + +pub async fn page_damping(db: &Database, url: STRHASH) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_damping {e}"); + None + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + let v = trx.get(&subspace.pack(&(WEBSITE_TABLE_DAMPING)), true).await; + + if let Ok(v) = v { + v.map(|v| unpack::<(f64, )>(&v).expect("INVALID K TYPE page_damping").0) + } else { + None + } + } +} + +pub async fn page_links_exiting_count(db: &Database, url: STRHASH) -> u64 { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_links_exiting_count {e}"); + 0 + } else { + let trx = trx.unwrap(); + // link -> from -> * + let subspace = Subspace::from((LINK_TABLE, url)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + + if let Err(e) = kv { + error!("DATABASE ERROR page_links_exiting_count {e}"); + 0 + } else { + let kv = kv.unwrap(); + + kv.len() as u64 + } + } +} + +// todo: precalc statements +// url, occurs +pub async fn word_occurs(db: &Database, word: STRHASH) -> Vec<(STRHASH, Vec)> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR word_occurs {e}"); + vec![] + } else { + let trx = trx.unwrap(); + // word -> word -> * + let subspace = Subspace::from((WORD_TABLE, word)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR word_occurs {e}"); + vec![] + } else { + let kv = kv.unwrap(); + + let mut results = vec![]; + + for kv in kv.into_iter() { + let (_, _, url) = unpack::<(String, STRHASH, STRHASH)>(kv.key()).expect("INVALID K TYPE word_occurs"); + + results.push((url, kv.value().to_vec())); + } + + results + } + } +} + +// todo: precalc statements +// url, property, occurs +pub async fn metaword_occurs(db: &Database, property: STRHASH, word: STRHASH) -> Vec<(STRHASH, Vec)> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR metaword_occurs {e}"); + vec![] + } else { + let trx = trx.unwrap(); + // metaword -> word -> prop -> * + let subspace = Subspace::from((METAWORD_TABLE, word, property)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR metaword_occurs {e}"); + vec![] + } else { + let kv = kv.unwrap(); + + let mut results = vec![]; + + for kv in kv.into_iter() { + let (_, _, _, url) = unpack::<(String, STRHASH, STRHASH, STRHASH)>(kv.key()).expect("INVALID K TYPE metaword_occurs"); + + results.push((url, kv.value().to_vec())); + } + + results + } + } +} + +// todo: precalc statements +// url, occurs +pub async fn linkword_occurs(db: &Database, word: STRHASH) -> Vec<(STRHASH, Vec)> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR linkword_occurs {e}"); + vec![] + } else { + let trx = trx.unwrap(); + // metaword -> word -> prop -> * + let subspace = Subspace::from((LINKWORD_TABLE, word)); + let mut range = RangeOption::from(&subspace); + range.mode = StreamingMode::WantAll; + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR linkword_occurs {e}"); + vec![] + } else { + let kv = kv.unwrap(); + + let mut results = vec![]; + + for kv in kv.into_iter() { + let (_, _, _, url) = unpack::<(String, STRHASH, STRHASH, STRHASH)>(kv.key()).expect("INVALID K TYPE linkword_occurs"); + + results.push((url, kv.value().to_vec())); + } + + results + } + } +} + +pub async fn foa_strhash(db: &Database, value: &str) -> STRHASH { + let trx = db.create_trx(); + if let Err(e) = trx { + panic!("FATAL DATABASE ERROR foa_strhash {e}"); + } else { + let trx = trx.unwrap(); + // hash -> value + let subspace = Subspace::from((HASH_TABLE, )); + + let hash = hash(value); + + trx.set(&subspace.pack(&hash), &pack(&(value.to_string(), ))); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR foa_strhash (HASH MAY NOT HAVE BEEN INSERTED! {e}"); + } + + hash + } +} + +pub async fn fof_strhash(db: &Database, value: &str) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR fof_strhash {e}"); + None + } else { + let trx = trx.unwrap(); + // hash -> value + let subspace = Subspace::from((HASH_TABLE, )); + + let hash = hash(value); + + let v = trx.get(&subspace.pack(&hash), true).await; + + if let Err(e) = v { + error!("DATABASE ERROR fof_strhash {e}"); + None + } else { + let v = v.unwrap(); + v.map(|_| hash) + } + } +} + +pub async fn unhash(db: &Database, value: STRHASH) -> String { + let trx = db.create_trx(); + if let Err(e) = trx { + panic!("FATAL DATABASE ERROR unhash {e}"); + } else { + let trx = trx.unwrap(); + // hash -> value + let subspace = Subspace::from((HASH_TABLE, )); + + let v = trx.get(&subspace.pack(&value), true).await; + + if let Err(e) = v { + panic!("FATAL DATABASE ERROR unhash {e}"); + } else { + let v = v.unwrap(); + if v.is_none() { + panic!("UNHASH CALLED ON NON-EXISTANT HASH {value}") + } + unpack::(&v.unwrap()).expect("INVALID K TYPE unhash") + } + } +} + +pub async fn host_in_database(db: &Database, url: STRHASH) -> bool { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR host_in_database {e}"); + false + } else { + let trx = trx.unwrap(); + // host -> url + let subspace = Subspace::from(HOST_TABLE); + + let v = trx.get(&subspace.pack(&url), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR host_in_database {e}"); + false + } else { + v.unwrap().is_some() + } + } +} + +pub async fn create_host(db: &Database, url: STRHASH) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR create_host {e}"); + } else { + let trx = trx.unwrap(); + // host -> url + let subspace = Subspace::from(HOST_TABLE); + + trx.set(&subspace.pack(&url), &pack(&(0i64))); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR create_host {e}"); + } + } +} + +pub async fn create_empty_document(db: &Database, url: STRHASH, host_url: STRHASH, damping: f32, parse_begin: Option) { + if !document_in_database(db, url).await { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR create_empty_document {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_HOST), &pack(&host_url)); + trx.set(&subspace.pack(&WEBSITE_TABLE_DAMPING), &pack(&(damping as f64))); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEBEGIN), &pack(&parse_begin.unwrap_or(0i64))); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEFINISH), &pack(&0i64)); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEFINISHTRUE), &pack(&0i64)); + trx.set(&subspace.pack(&WEBSITE_TABLE_CACHEDPAGERANK), &pack(&0f64)); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPAGERANKCACHE), &pack(&0i64)); + trx.set(&subspace.pack(&WEBSITE_TABLE_ROBOTSFLAG), &pack(&false)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR create_empty_document {e}"); + } + } + } else {} +} + +pub async fn link_in_database(db: &Database, url: STRHASH, dest: STRHASH) -> bool { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR link_in_database {e}"); + false + } else { + let trx = trx.unwrap(); + // link -> from (url) -> to (dest) + let subspace = Subspace::from((LINK_TABLE, url)); + + let v = trx.get(&subspace.pack(&dest), true).await; + + if let Err(e) = v { + error!("DATABASE ERROR link_in_database {e}"); + false + } else { + v.unwrap().is_some() + } + } +} + +// creates an empty link between two websites, does nothing if it already exists +pub async fn create_empty_link(db: &Database, url: STRHASH, host: STRHASH, dest_url: STRHASH) { + if !document_in_database(db.clone(), dest_url).await { + create_empty_document(db.clone(), dest_url, host, 0.85, None).await; + } + if !link_in_database(db, url, dest_url).await { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR create_empty_link {e}"); + } else { + let trx = trx.unwrap(); + // link -> from -> to && revlink -> to -> from + let subspace = Subspace::from((LINK_TABLE, url)); + let revsubspace = Subspace::from((REVLINK_TABLE, dest_url)); + + trx.set(&subspace.pack(&dest_url), &[0u8]); + trx.set(&revsubspace.pack(&url), &[0u8]); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR create_empty_link {e}"); + } + } + } +} + +pub async fn link_set_flags(db: &Database, url: STRHASH, dest_url: STRHASH, flags: u8) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR link_set_flags {e}"); + } else { + let trx = trx.unwrap(); + // link -> from -> to && revlink -> to -> from + let subspace = Subspace::from((LINK_TABLE, url)); + let revsubspace = Subspace::from((REVLINK_TABLE, dest_url)); + + trx.set(&subspace.pack(&dest_url), &[flags]); + trx.set(&revsubspace.pack(&url), &[flags]); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR link_set_flags {e}"); + } + } +} + +pub async fn document_in_database(db: &Database, url: STRHASH) -> bool { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_in_database {e}"); + false + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + let v = trx.get(&subspace.pack(&WEBSITE_TABLE_HOST), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR document_in_database {e}"); + false + } else { + v.unwrap().is_some() + } + } +} + +pub async fn info_in_database(db: &Database, url: STRHASH) -> bool { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR info_in_database {e}"); + false + } else { + let trx = trx.unwrap(); + // info -> url + let subspace = Subspace::from(INFO_TABLE); + + let v = trx.get(&subspace.pack(&url), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR info_in_database {e}"); + false + } else { + v.unwrap().is_some() + } + } +} + +pub async fn set_info(db: &Database, url: STRHASH, title: String, description: String, favicon: i64) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR set_info {e}"); + } else { + let trx = trx.unwrap(); + // info -> url + let subspace = Subspace::from((INFO_TABLE, url)); + + trx.set(&subspace.pack(&INFO_TABLE_TITLE), &pack(&title)); + trx.set(&subspace.pack(&INFO_TABLE_DESC), &pack(&(description))); + trx.set(&subspace.pack(&INFO_TABLE_FAVICON), &pack(&favicon)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR set_info {e}"); + } + } +} + +pub async fn document_last_parse_begin(db: &Database, url: STRHASH) -> Option> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_last_parse_begin {e}"); + None + } else { + let trx = trx.unwrap(); + // website -> url -> lastparsebegin + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + let v = trx.get(&subspace.pack(&WEBSITE_TABLE_LASTPARSEBEGIN), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR document_last_parse_begin {e}"); + None + } else { + v.unwrap().map(|v| chrono::Utc.timestamp_opt(unpack::(&v).expect("INVALID K TYPE document_last_parse_begin"), 0).unwrap()) + } + } +} + +pub async fn document_last_parse_finish(db: &Database, url: STRHASH) -> Option> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_last_parse_finish {e}"); + None + } else { + let trx = trx.unwrap(); + // website -> url -> lastparsefinish + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + let v = trx.get(&subspace.pack(&WEBSITE_TABLE_LASTPARSEFINISH), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR document_last_parse_finish {e}"); + None + } else { + v.unwrap().map(|v| chrono::Utc.timestamp_opt(unpack::(&v).expect("INVALID K TYPE document_last_parse_finish"), 0).unwrap()) + } + } +} + +pub async fn document_set_damping(db: &Database, url: STRHASH, damping: f32) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_damping {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_DAMPING), &pack(&(damping as f64))); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_damping {e}"); + } + } +} + +pub async fn document_set_pagerank(db: &Database, url: STRHASH, pagerank: f64, now: i64) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_pagerank {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_CACHEDPAGERANK), &pack(&(pagerank))); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPAGERANKCACHE), &pack(&(now))); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_dampingdocument_set_pagerank {e}"); + } + } +} + +pub async fn document_set_last_parse_begin(db: &Database, url: STRHASH, now: i64) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_last_parse_begin {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEBEGIN), &pack(&now)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_last_parse_begin {e}"); + } + } +} + +pub async fn document_set_last_parse_finish(db: &Database, url: STRHASH, now: i64, true_now: i64) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_last_parse_finish {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEFINISH), &pack(&now)); + trx.set(&subspace.pack(&WEBSITE_TABLE_LASTPARSEFINISHTRUE), &pack(&true_now)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_last_parse_finish {e}"); + } + } +} + +pub async fn document_set_robots_flag(db: &Database, url: STRHASH, value: bool) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_robots_flag {e}"); + } else { + let trx = trx.unwrap(); + // website -> url + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + trx.set(&subspace.pack(&WEBSITE_TABLE_ROBOTSFLAG), &pack(&value)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_robots_flag {e}"); + } + } +} + +pub async fn document_set_metaword(db: &Database, url: STRHASH, word_name: STRHASH, property: STRHASH, occurances: &[u8]) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_metaword {e}"); + } else { + let trx = trx.unwrap(); + // metaword -> word -> prop -> url + // metawurl -> url -> prop -> word + let subspace = Subspace::from((METAWORD_TABLE, word_name, property)); + let revsubspace = Subspace::from((METAWURL_TABLE, url, property)); + + trx.set(&subspace.pack(&url), occurances); + trx.set(&revsubspace.pack(&word_name), &pack(&word_name)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_metaword {e}"); + } + } +} + +pub async fn document_set_word(db: &Database, url: STRHASH, word_name: STRHASH, occurances: &[u8]) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_set_word {e}"); + } else { + let trx = trx.unwrap(); + // word -> word -> url + let subspace = Subspace::from((WORD_TABLE, word_name)); + let revsubspace = Subspace::from((WURL_TABLE, url)); + + trx.set(&subspace.pack(&url), occurances); + trx.set(&revsubspace.pack(&word_name), &pack(&word_name)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR document_set_word {e}"); + } + } +} + +pub async fn link_set_linkword(db: &Database, url: STRHASH, dest: STRHASH, word_name: STRHASH, occurances: &[u8]) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR link_set_linkword {e}"); + } else { + let trx = trx.unwrap(); + // linkword -> word -> from -> to + let subspace = Subspace::from((LINKWORD_TABLE, word_name, url)); + let revsubspace = Subspace::from((LINKWORD_TABLE, url, dest)); + + trx.set(&subspace.pack(&dest), occurances); + trx.set(&revsubspace.pack(&word_name), &pack(&word_name)); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR link_set_linkword {e}"); + } + } +} + +pub async fn document_host(db: &Database, url: STRHASH) -> Option { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR document_host {e}"); + None + } else { + let trx = trx.unwrap(); + // website -> url -> host + let subspace = Subspace::from((WEBSITE_TABLE, url)); + + let v = trx.get(&subspace.pack(&WEBSITE_TABLE_HOST), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR document_host {e}"); + None + } else { + v.unwrap().map(|v| unpack::(&v).expect("INVALID K TYPE document_last_parse_finish")) + } + } +} + +pub async fn host_last_fetch(db: &Database, url: STRHASH) -> Option> { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR host_last_fetch {e}"); + None + } else { + let trx = trx.unwrap(); + // host -> url + let subspace = Subspace::from(HOST_TABLE); + + let v = trx.get(&subspace.pack(&url), true).await; + + + if let Err(e) = v { + error!("DATABASE ERROR host_last_fetch {e}"); + None + } else { + v.unwrap().map(|v| chrono::Utc.timestamp_opt(unpack::(&v).expect("INVALID K TYPE host_last_fetch"), 0).unwrap()) + } + } +} + +pub async fn host_set_last_fetch(db: &Database, url: STRHASH, now: chrono::DateTime) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR host_set_last_fetch {e}"); + } else { + let trx = trx.unwrap(); + // host -> url + let subspace = Subspace::from(HOST_TABLE); + + trx.set(&subspace.pack(&url), &pack(&now.timestamp())); + + if let Err(e) = trx.commit().await { + error!("DATABASE ERROR host_set_last_fetch {e}"); + } + } +} + +pub async fn prevented_by_dehomogeniser(db: &Database, url: &str) -> (bool, String, String) { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR prevented_by_dehomogeniser {e}"); + (false, "".to_string(), "".to_string()) + } else { + let trx = trx.unwrap(); + // revlink -> to -> * + let subspace = Subspace::from(DEHOMOGENISE_TABLE); + let range = RangeOption::from(&subspace); + + let kv = trx.get_range(&range, 1024, true).await; + + if let Err(e) = kv { + error!("DATABASE ERROR prevented_by_dehomogeniser {e}"); + (false, "".to_string(), "".to_string()) + } else { + let kv = kv.unwrap(); + + for kv in kv.into_iter() { + let (block, unless) = unpack::<(String, String)>(kv.value()).expect("INVALID V TYPE prevented_by_dehomogeniser"); + + if url.contains(&block) && (unless.is_empty() || !url.contains(&unless)) { + return (true, block.to_string(), unless.to_string()); + } + } + + (false, "".to_string(), "".to_string()) + } + } +} \ No newline at end of file diff --git a/asklyphe-common/src/db/tables.rs b/asklyphe-common/src/db/tables.rs new file mode 100644 index 0000000..bdd3695 --- /dev/null +++ b/asklyphe-common/src/db/tables.rs @@ -0,0 +1,80 @@ +/* + * asklyphe-common db/tables.rs + * - foundationdb key name parts + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use log::info; + +/// str = STRHASH +/// text = u64 len + chars + +/// (derank_) +/// (match text, unless text, and text, use_unless bool, use_and bool, value f64, comment text) +pub const DERANK_TABLE: &str = "derank"; + +/// (info_) +/// (url STRHASH, title text, description text, favicon hash) +pub const INFO_TABLE: &str = "info"; +pub const INFO_TABLE_TITLE: &str = "title"; +pub const INFO_TABLE_DESC: &str = "desc"; +pub const INFO_TABLE_FAVICON: &str = "favicon"; +/// (hash_) +/// (value text) +pub const HASH_TABLE: &str = "hash"; +/// (dehomo_) +/// (block text, unless text) +pub const DEHOMOGENISE_TABLE: &str = "dehomogenise"; +/// (website_) +/// (host text, flags u8, +/// damping f64, lastparsebegin i64, +/// lastparsefinish i64, lastparsefinishtrue i64, +/// cachedpagerank f64, lastpagerankcache i64, +/// robotsflag bool) +pub const WEBSITE_TABLE: &str = "website"; +pub const WEBSITE_TABLE_HOST: &str = "host"; +pub const WEBSITE_TABLE_DAMPING: &str = "damping"; +pub const WEBSITE_TABLE_LASTPARSEBEGIN: &str = "lastparsebegin"; +pub const WEBSITE_TABLE_LASTPARSEFINISH: &str = "lastparsefinish"; +pub const WEBSITE_TABLE_LASTPARSEFINISHTRUE: &str = "lastparsefinishtrue"; +pub const WEBSITE_TABLE_CACHEDPAGERANK: &str = "cachedpagerank"; +pub const WEBSITE_TABLE_LASTPAGERANKCACHE: &str = "lastpagerankcache"; +pub const WEBSITE_TABLE_ROBOTSFLAG: &str = "robotsflag"; +pub const WEBSITE_TABLE_WORDCOUNT: &str = "wordcount"; +/// (host_) +/// (lastcrawl i64) +pub const HOST_TABLE: &str = "hosts"; +/// (word__) +/// see vorebot words encoded format +/// -- +/// (wurl__) +/// (word i64, maybe expand in future) +pub const WORD_TABLE: &str = "word"; +pub const WURL_TABLE: &str = "word"; +/// (metaword___) +/// see vorebot metawords encoded format +/// -- +/// (metawurl___) +/// (mword i64, maybe expand in future) +pub const METAWORD_TABLE: &str = "metaword"; +pub const METAWURL_TABLE: &str = "metawurl"; +/// (link__) +/// (flags u8) +/// -- +/// (revlink__) +/// (flags u8) +pub const LINK_TABLE: &str = "link"; +pub const REVLINK_TABLE: &str = "revlink"; +/// (linkword___) +/// see vorebot linkword encoded format +/// -- +/// (linkwurl___) +/// (word i64, maybe expand in future) +pub const LINKWORD_TABLE: &str = "linkword"; \ No newline at end of file diff --git a/asklyphe-common/src/lib.rs b/asklyphe-common/src/lib.rs new file mode 100644 index 0000000..1684fad --- /dev/null +++ b/asklyphe-common/src/lib.rs @@ -0,0 +1,32 @@ +/* + * asklyphe-common lib.rs + * - main library file for asklyphe-common + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod nats; +pub mod db; + +pub use foundationdb; + +pub fn add(left: usize, right: usize) -> usize { + left + right +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} diff --git a/asklyphe-common/src/nats/authservice/admin.rs b/asklyphe-common/src/nats/authservice/admin.rs new file mode 100644 index 0000000..a6b2aa3 --- /dev/null +++ b/asklyphe-common/src/nats/authservice/admin.rs @@ -0,0 +1,160 @@ +/* + * asklyphe-common nats/authservice/admin.rs + * - nats structs for admin-only queries + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use serde::{Deserialize, Serialize}; +use crate::nats::authservice::UserPrivateToken; + +/// # StatsRequest +/// sent from frontend -> authsrvc, requires token with admin privs, returns data for display +/// on the admin stats summary page +/// expecting an AuthServiceResponse::StatsResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct StatsRequest { + pub token: UserPrivateToken, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Stats { + pub last_ten_users: Vec, + pub user_count: usize, + pub admin_count: usize, + pub active_verification_requests: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum StatsResponse { + Success(Stats), + InternalServerError(String), + Logout, + AccessDenied, +} + +/// # AdminInviteCodeGenerateRequest +/// sent from frontend -> authsrvc, requires token with admin privs +/// adds a valid invite code to the database +/// expecting an AuthServiceResponse::AdminInviteCodeGenerateResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminInviteCodeGenerateRequest { + pub token: UserPrivateToken, + pub invite_code: String, + pub comment: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdminInviteCodeGenerateResponse { + Success, + CodeAlreadyExists, + InternalServerError(String), + Logout, + AccessDenied, +} + +/// # AdminListInviteCodesRequest +/// sent from frontend -> authsrvc, requires token with admin privs +/// lists invite codes that match the criteria +/// expecting an AuthServiceResponse::AdminListInviteCodesResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminListInviteCodesRequest { + pub token: UserPrivateToken, + /// if true, will return invite codes that have been used instead of ones that are not yet used + pub show_used: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InviteCodeSerialized { + pub code: String, + pub comment: String, + pub creator: String, + pub root_creator: String, + pub created_at: String, + pub used_at: Option, + pub used_by: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdminListInviteCodesResponse { + Success(Vec), + InternalServerError(String), + Logout, + AccessDenied, +} + +/// # AdminCreateAnnouncementRequest +/// sent from frontend -> authsrvc, requires token with admin privs +/// creates an announcement, and optionally sends emails to those who want to receive them +/// expecting an AuthServiceResponse::AdminCreateAnnouncementRequest +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminCreateAnnouncementRequest { + pub token: UserPrivateToken, + pub title: String, + pub slug: String, + pub short_text: String, + pub full_markdown_text: String, + pub send_emails: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdminCreateAnnouncementResponse { + Success, + SlugTaken, + InternalServerError(String), + Logout, + AccessDenied, +} + +/// # AdminUpdateAnnouncementRequest +/// sent from frontend -> authsrvc, requires token with admin privs +/// updates the contents of an announcement +/// expecting an AuthServiceResponse::AdminUpdateAnnouncementRequest +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminUpdateAnnouncementRequest { + pub token: UserPrivateToken, + pub slug: String, + pub new_title: String, + pub new_short_text: String, + pub new_full_markdown_text: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdminUpdateAnnouncementResponse { + Success, + OriginalNotFound, + InternalServerError(String), + Logout, + AccessDenied, +} + +/// # AdminListAllUsersRequest +/// sent from frontend -> authsrvc, requires token with admin privs +/// returns a list of all users with accounts +/// expecting an AuthServiceResponse::AdminListAllUsersResponse +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminListAllUsersRequest { + pub token: UserPrivateToken, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct UserSerialized { + pub username: String, + pub email: String, + pub verified: bool, + pub admin: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AdminListAllUsersResponse { + Success(Vec), + InternalServerError(String), + Logout, + AccessDenied, +} \ No newline at end of file diff --git a/asklyphe-common/src/nats/authservice/announcements.rs b/asklyphe-common/src/nats/authservice/announcements.rs new file mode 100644 index 0000000..d6e16c7 --- /dev/null +++ b/asklyphe-common/src/nats/authservice/announcements.rs @@ -0,0 +1,77 @@ +/* + * asklyphe-common nats/authservice/announcements.rs + * - nats structs for reading announcements + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +// announcements are also sometimes referred to as "notes" + +use serde::{Deserialize, Serialize}; + +/// # LatestAnnouncementRequest +/// sent from frontend -> authsrvc, returns the latest announcement in its short form +/// expecting an AuthServiceResponse::LatestAnnouncementResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LatestAnnouncementRequest {} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AnnouncementShortForm { + pub title: String, + pub short_text: String, + pub date: i64, // unix utc + pub slug: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum LatestAnnouncementResponse { + Some(AnnouncementShortForm), + None, + InternalServerError(String), +} + +/// # AnnouncementListRequest +/// sent from frontend -> authsrvc, +/// returns a list of all announcements in order of newest first to oldest last +/// expecting an AuthServiceResponse::AnnouncementListResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AnnouncementListRequest { + pub limit: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AnnouncementListResponse { + Success(Vec), + InternalServerError(String), +} + +/// # AnnouncementFullRequest +/// sent from frontend -> authsrvc, returns the full contents of an announcement +/// expecting an AuthServiceResponse::AnnouncementFullResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AnnouncementFullRequest { + pub slug: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AnnouncementFull { + pub title: String, + pub created_on: i64, + pub updated_on: Option, + pub slug: String, + pub creator: String, // username + pub markdown_text: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AnnouncementFullResponse { + Some(AnnouncementFull), + NotFound, + InternalServerError(String), +} \ No newline at end of file diff --git a/asklyphe-common/src/nats/authservice/mod.rs b/asklyphe-common/src/nats/authservice/mod.rs new file mode 100644 index 0000000..bf654bf --- /dev/null +++ b/asklyphe-common/src/nats/authservice/mod.rs @@ -0,0 +1,363 @@ +/* + * asklyphe-common nats/authservice/mod.rs + * - module file + general structs for the asklyphe authentication service + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod profile; +pub mod admin; +pub mod announcements; + +use std::fmt::{Display, Formatter, Write}; +use serde::{Deserialize, Serialize}; +use crate::nats::authservice::admin::{AdminCreateAnnouncementRequest, AdminCreateAnnouncementResponse, AdminInviteCodeGenerateRequest, AdminInviteCodeGenerateResponse, AdminListAllUsersRequest, AdminListAllUsersResponse, AdminListInviteCodesRequest, AdminListInviteCodesResponse, AdminUpdateAnnouncementRequest, AdminUpdateAnnouncementResponse, StatsRequest, StatsResponse}; +use crate::nats::authservice::announcements::{AnnouncementFullRequest, AnnouncementFullResponse, AnnouncementListRequest, AnnouncementListResponse, LatestAnnouncementRequest, LatestAnnouncementResponse}; +use crate::nats::authservice::profile::{ThemeChangeRequest, ThemeChangeResponse, UserInfoRequest, UserInfoResponse}; + +pub const AUTH_SERVICE: &str = "authsrvc"; +pub const AUTH_REPLY_SERVICE: &str = "authsrvcreply"; + +/// used internally to identify a session +pub type UserPrivateToken = String; + +/// used as a semi-secure way to let the user identify individual sessions +pub type UserDisplayToken = String; +/// internal identifier for accounts, should be unique no matter what as this is what we will pass +/// to trusted services to query account info +pub type AccountId = String; +/// internal identifier for an email verification request, given to an account upon creation or email change +/// should be kept private as it will be in the query string of the url that will automatically verify +/// the new email +pub type EmailVerificationId = String; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AuthServiceQuery { + pub request: AuthServiceRequest, + /// if using comms::query_service, you don't need to set this + pub replyto: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AuthServiceRequest { + RegisterRequest(RegisterRequest), + VerifyEmailRequest(VerifyEmailRequest), + LoginRequest(LoginRequest), + AuthRequest(AuthRequest), + LogoutRequest(LogoutRequest), + UserInfoRequest(UserInfoRequest), + EmailChangeRequest(EmailChangeRequest), + CancelEmailChangeRequest(CancelEmailChangeRequest), + ThemeChangeRequest(ThemeChangeRequest), + StatsRequest(StatsRequest), + AdminInviteCodeGenerateRequest(AdminInviteCodeGenerateRequest), + LatestAnnouncementRequest(LatestAnnouncementRequest), + AnnouncementListRequest(AnnouncementListRequest), + AnnouncementFullRequest(AnnouncementFullRequest), + AdminCreateAnnouncementRequest(AdminCreateAnnouncementRequest), + AdminUpdateAnnouncementRequest(AdminUpdateAnnouncementRequest), + AdminListInviteCodesRequest(AdminListInviteCodesRequest), + AdminListAllUsersRequest(AdminListAllUsersRequest), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AuthServiceResponse { + InvalidRequest, + OtherError(String), + RegisterResponse(RegisterResponse), + VerifyEmailResponse(VerifyEmailResponse), + LoginResponse(LoginResponse), + AuthResponse(AuthResponse), + LogoutResponse(LogoutResponse), + UserInfoResponse(UserInfoResponse), + EmailChangeResponse(EmailChangeResponse), + CancelEmailChangeResponse(CancelEmailChangeResponse), + ThemeChangeResponse(ThemeChangeResponse), + StatsResponse(StatsResponse), + AdminInviteCodeGenerateResponse(AdminInviteCodeGenerateResponse), + LatestAnnouncementResponse(LatestAnnouncementResponse), + AnnouncementListResponse(AnnouncementListResponse), + AnnouncementFullResponse(AnnouncementFullResponse), + AdminCreateAnnouncementResponse(AdminCreateAnnouncementResponse), + AdminUpdateAnnouncementResponse(AdminUpdateAnnouncementResponse), + AdminListInviteCodesResponse(AdminListInviteCodesResponse), + AdminListAllUsersResponse(AdminListAllUsersResponse), +} + +// fixme: this should really be done with a macro +impl Display for AuthServiceResponse { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + AuthServiceResponse::InvalidRequest => { + f.write_str("invalid request") + } + AuthServiceResponse::OtherError(_) => { + f.write_str("other error") + } + AuthServiceResponse::RegisterResponse(_) => { + f.write_str("register response") + } + AuthServiceResponse::VerifyEmailResponse(_) => { + f.write_str("verify email response") + } + AuthServiceResponse::LoginResponse(_) => { + f.write_str("login response") + } + AuthServiceResponse::AuthResponse(_) => { + f.write_str("auth response") + } + AuthServiceResponse::LogoutResponse(_) => { + f.write_str("logout response") + } + AuthServiceResponse::UserInfoResponse(_) => { + f.write_str("user info response") + } + AuthServiceResponse::EmailChangeResponse(_) => { + f.write_str("email change response") + } + AuthServiceResponse::CancelEmailChangeResponse(_) => { + f.write_str("cancel email change response") + } + AuthServiceResponse::ThemeChangeResponse(_) => { + f.write_str("theme change resposne") + } + AuthServiceResponse::StatsResponse(_) => { + f.write_str("stats response") + } + AuthServiceResponse::AdminInviteCodeGenerateResponse(_) => { + f.write_str("admin invite code generate response") + } + AuthServiceResponse::LatestAnnouncementResponse(_) => { + f.write_str("latest announcement response") + } + AuthServiceResponse::AnnouncementListResponse(_) => { + f.write_str("announcement list response") + } + AuthServiceResponse::AnnouncementFullResponse(_) => { + f.write_str("announcement full response") + } + AuthServiceResponse::AdminCreateAnnouncementResponse(_) => { + f.write_str("admin create announcement response") + } + AuthServiceResponse::AdminUpdateAnnouncementResponse(_) => { + f.write_str("admin update announcement response") + } + AuthServiceResponse::AdminListInviteCodesResponse(_) => { + f.write_str("admin list invite codes response") + } + AuthServiceResponse::AdminListAllUsersResponse(_) => { + f.write_str("admin list all users response") + } + } + } +} + +/// # RegisterRequest +/// sent from frontend -> authsrvc to attempt to register a user account +/// expecting a AuthServiceResponse::RegisterResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RegisterRequest { + /// username may be eventually used in settings where users will interact; preventing email addresses being shared + pub username: String, + pub email: String, + /// value is NOT hashed over nats! make sure that tls is enabled! + pub password: String, + /// during private beta, only accept requests with a valid invite code; + /// afterwards, an empty invite code will indicate a free trial + pub invite_code: String, +} + +/// # RegisterResponse +/// sent from authsrvc -> frontend once the RegisterRequest was completed +/// success should give user a message to check their email for verification +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum RegisterResponse { + Success, + Failure(RegisterError), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum RegisterError { + /// probably best to not display the actual error to the user, for security reasons + InternalServer(String), + Password(PasswordError), + Email(EmailError), + Username(UsernameError), + BadInviteCode, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum PasswordError { + /// weird / non-ascii characters in password + InvalidCharacters, + /// password too short + TooShort, + /// commonly used + TooCommon, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum EmailError { + /// doesn't match email format + InvalidEmail, + /// email already in use + EmailTaken, + /// email blacklisted (e.g. if email server is commonly used for spam) + EmailBlacklisted, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum UsernameError { + /// contains invalid characters (i.e. not a-z, 0-9, -, _, ~, maybe some others?) + /// usernames should be case insensitive + InvalidCharacters, + /// usernames should probably be at minimum 3 chars? idk i'm just coming up with a random value + TooShort, + /// no duplicate usernames + Taken, + /// try to avoid people using slurs as usernames + Inappropriate, +} + +/// # VerifyEmailRequest +/// sent from frontend -> authsrvc to attempt to verify an email +/// expecting a AuthServiceResponse::VerifyEmailResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VerifyEmailRequest { + pub username: String, + pub token: EmailVerificationId, +} + +/// # VerifyEmailResponse +/// sent from authsrvc -> frontend once the VerifyEmailRequest completes +/// if successful, it's assumed that a user can now log in to their account without issue +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum VerifyEmailResponse { + Success, + InvalidToken, + ExpiredToken, + InternalServerError(String), +} + +/// # LoginRequest +/// sent from frontend -> authsrvc to attempt to login to a user account +/// expecting a AuthServiceResponse::LoginResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoginRequest { + pub email: String, + /// value is NOT hashed over nats! make sure that tls is enabled! + pub password: String, +} + +/// # LoginResponse +/// sent from authsrvc -> frontend once the LoginRequest was completed +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum LoginResponse { + Success(TokenAssignment), + Failure(LoginError), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum LoginError { + /// probably best to not display the actual error to the user, for security reasons + InternalServer(String), + /// to avoid bruteforce attempts on accounts, don't say what part of the given email/pass + /// combo was invalid + InvalidAccount, + /// best to include a message on the frontend indicating that the user check their email for more info + SuspendedAccount, + /// don't let people login unless they've verified their email + AccountNotVerified, +} + +/// # AuthRequest +/// sent from any service -> authsrvc to check credentials on an internal request +/// expecting a AuthServiceResponse::AuthResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AuthRequest { + pub token: UserPrivateToken, +} + +/// # AuthResponse +/// sent from authsrvc -> requesting service once the AuthRequest was completed +/// errors should ideally be forwarded to the user if necessary +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AuthResponse { + Success(AccountId), + Failure(AuthError), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AuthError { + /// probably best to not display the actual error to the user, for security reasons + InternalServer(String), + /// if the token is expired + TokenExpired, + /// if the account was suspended between now and the last valid request + AccountSuspended, + /// if the token just doesn't exist + TokenInvalid, +} + +/// # TokenAssignment +/// generic struct used in usersrvc -> frontend messages when the user needs to have their session assigned +/// (such as after logging in) +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TokenAssignment { + pub token: UserPrivateToken, + /// unix utc timestamp of death date + pub ttl: i64, +} + +/// # LogoutRequest +/// sent from frontend -> authsrvc to delete a session +/// expecting a AuthServiceResponse::LogoutResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LogoutRequest { + pub token: UserPrivateToken, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum LogoutResponse { + Success, + InternalServerError(String), + /// not that important what happened with the token, the frontend is already discarding it regardless + BadTokenError, +} + +/// # EmailChangeRequest +/// sent from frontend -> authsrvc to start the process of changing a user's associated email address +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EmailChangeRequest { + pub token: UserPrivateToken, + pub new_email: String, +} + +/// # EmailChangeResponse +/// authsrvc -> frontend, response to EmailChangeRequest +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum EmailChangeResponse { + /// verification email has been sent + Success, + /// user token invalid, log out + InvalidToken, + /// new email was not valid + InvalidEmail, + /// internal error + InternalError, +} + +/// # CancelEmailChangeRequest +/// frontend -> authsrvc, cancel an in-progress email change +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CancelEmailChangeRequest { + pub token: UserPrivateToken, +} + +/// # CancelEmailChangeResponse +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum CancelEmailChangeResponse { + Success, + /// user token invalid, log out + InvalidToken, + /// internal error + InternalError, +} \ No newline at end of file diff --git a/asklyphe-common/src/nats/authservice/profile.rs b/asklyphe-common/src/nats/authservice/profile.rs new file mode 100644 index 0000000..e9db754 --- /dev/null +++ b/asklyphe-common/src/nats/authservice/profile.rs @@ -0,0 +1,58 @@ +/* + * asklyphe-common nats/authservice/profile.rs + * - nats structs for user profile queries + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use serde::{Deserialize, Serialize}; +use crate::nats::authservice::UserPrivateToken; + +/// # UserInfoRequest +/// sent from frontend -> authsrvc to receive info for display on the frontend +/// expecting a AuthServiceResponse::UserInfoResponse back +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct UserInfoRequest { + pub token: UserPrivateToken, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct UserInfo { + pub username: String, + pub email: String, + pub new_email: Option, + pub theme: String, + pub administrator: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum UserInfoResponse { + Success(UserInfo), + InternalServerError(String), + TokenExpired, + TokenInvalid, + AccountSuspended, +} + +/// # ThemeChangeRequest +/// sent from frontend -> authsrvc to set the user's preferred theme +/// do note that the backend will not check if the theme is valid, this must be done on the frontend +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ThemeChangeRequest { + pub token: UserPrivateToken, + pub theme: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum ThemeChangeResponse { + Success, + /// sent if the token is invalid, and the account should be logged out + Logout, + InternalServerError, +} diff --git a/asklyphe-common/src/nats/bingservice.rs b/asklyphe-common/src/nats/bingservice.rs new file mode 100644 index 0000000..a3f3594 --- /dev/null +++ b/asklyphe-common/src/nats/bingservice.rs @@ -0,0 +1,63 @@ +/* + * asklyphe-common nats/bingservice.rs + * - nats structs for external search engines + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use serde::{Deserialize, Serialize}; + +pub const BING_SERVICE: &str = "bingservice"; +pub const BING_REPLY_SERVICE: &str = "bingservicereply"; +pub const GOOGLE_SERVICE: &str = "googleservice"; +pub const GOOGLE_REPLY_SERVICE: &str = "googleservicereply"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BingServiceQuery { + pub request: BingServiceRequest, + /// if using comms::query_service, you don't need to set this + pub replyto: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum BingServiceRequest { + SearchRequest(BingSearchRequest), + ImageRequest(BingImageRequest), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum BingServiceResponse { + InvalidRequest, + OtherError(String), + SearchResponse(SearchResponse), + ImageResponse(Vec), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BingSearchRequest { + pub query: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BingSearchResult { + pub url: String, + pub title: Option, + pub description: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SearchResponse { + pub results: Vec, + pub blocked: Vec<(String, String)>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BingImageRequest { + pub query: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BingImageResult { + pub url: String, +} diff --git a/asklyphe-common/src/nats/comms.rs b/asklyphe-common/src/nats/comms.rs new file mode 100644 index 0000000..bf41a95 --- /dev/null +++ b/asklyphe-common/src/nats/comms.rs @@ -0,0 +1,427 @@ +/* + * asklyphe-common nats/comms.rs + * - communication functions for nats + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use crate::nats::authservice::{AUTH_REPLY_SERVICE, AUTH_SERVICE}; +use crate::nats::bingservice::{BingServiceResponse, BING_REPLY_SERVICE, BING_SERVICE, GOOGLE_REPLY_SERVICE, GOOGLE_SERVICE}; +use crate::nats::searchservice::{SearchSrvcResponse, SEARCH_REPLY_SERVICE, SEARCH_SERVICE}; +use crate::nats::{authservice, bingservice, searchservice}; +use async_nats::jetstream; +use async_nats::jetstream::consumer::PullConsumer; +use async_nats::jetstream::stream::RetentionPolicy; +use futures::StreamExt; +use log::{debug, error, warn}; +use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::future::Future; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::RwLock; +use ulid::Ulid; + +#[derive(Serialize, Deserialize, Clone)] +pub enum Query { + SearchService(searchservice::SearchSrvcQuery), + BingService(bingservice::BingServiceQuery), + GoogleService(bingservice::BingServiceQuery), + AuthService(authservice::AuthServiceQuery), +} + +impl PartialEq for Query { + fn eq(&self, other: &Self) -> bool { + let a = rmp_serde::to_vec(self).unwrap(); + let b = rmp_serde::to_vec(other).unwrap(); + a == b + } +} + +impl Eq for Query {} +impl PartialOrd for Query { + fn partial_cmp(&self, other: &Self) -> Option { + let a = rmp_serde::to_vec(self).unwrap(); + let b = rmp_serde::to_vec(other).unwrap(); + let mut hash = DefaultHasher::new(); + a.hash(&mut hash); + let a = hash.finish(); + let mut hash = DefaultHasher::new(); + b.hash(&mut hash); + let b = hash.finish(); + a.partial_cmp(&b) + } +} + +impl Ord for Query { + fn cmp(&self, other: &Self) -> Ordering { + let a = rmp_serde::to_vec(self).unwrap(); + let b = rmp_serde::to_vec(other).unwrap(); + let mut hash = DefaultHasher::new(); + a.hash(&mut hash); + let a = hash.finish(); + let mut hash = DefaultHasher::new(); + b.hash(&mut hash); + let b = hash.finish(); + a.cmp(&b) + } +} + +pub enum Service { + SearchService, + BingService, + GoogleService, // mirror of bingservice but with different name + AuthService, +} + +#[derive(Clone)] +pub enum ServiceResponse { + SearchService(searchservice::SearchSrvcResponse), + BingService(bingservice::BingServiceResponse), + AuthService(authservice::AuthServiceResponse), +} + +#[derive(Copy, Clone, Debug)] +pub enum ServiceError { + /// may indicate that the given nats server is down + NatsSubscriptionFailure, + /// may indicate that the given nats server is out of memory, or overloaded + NatsPublishFailure, + /// could mean multiple things, but treat this as nats being down + NatsRecvMessageFailure, + /// usually this one happens if we try to get a service that doesn't exist, but i haven't + /// experienced it lately in production + NatsGetServiceError, + /// never experienced in production, unsure when/if this could occur + SerialiseError, + /// indicates something wrong with a service / backend, check logs + DeserialiseError, +} + +pub fn ulid() -> String { + Ulid::new().to_string() +} + +static SERVICE_CACHE: RwLock> = RwLock::const_new(BTreeMap::new()); +pub const CACHE_PERIOD_MINUTES: u64 = 120; + +// todo: add timeouts +/// use_cache will enable deterministic caching, where when given the same input, the same output *should* happen +/// only use for search queries and such, not anything authentication related +pub async fn query_service( + mut query: Query, + nats: &jetstream::Context, + use_cache: bool, +) -> Result { + { + if use_cache { + let cache = SERVICE_CACHE.read().await; + let mut query = query.clone(); + match &mut query { + Query::SearchService(s) => s.replyto = "".to_string(), + Query::BingService(s) => s.replyto = "".to_string(), + Query::GoogleService(s) => s.replyto = "".to_string(), + Query::AuthService(s) => s.replyto = "".to_string(), + } + if let Some(r) = cache.get(&query).cloned() { + debug!("cache hit"); + return Ok(r); + } else { + debug!("cache miss"); + } + } + } + + let ulid = ulid(); + let service = match &query { + Query::SearchService(_) => SEARCH_SERVICE, + Query::AuthService(_) => AUTH_SERVICE, + Query::BingService(_) => BING_SERVICE, + Query::GoogleService(_) => GOOGLE_SERVICE, + }; + let replyservice = match &query { + Query::SearchService(_) => SEARCH_REPLY_SERVICE, + Query::AuthService(_) => AUTH_REPLY_SERVICE, + Query::BingService(_) => BING_REPLY_SERVICE, + Query::GoogleService(_) => GOOGLE_REPLY_SERVICE, + }; + + let stream = nats + .get_or_create_stream(jetstream::stream::Config { + name: replyservice.to_string(), + subjects: vec![format!("{}.*", replyservice)], + retention: RetentionPolicy::Limits, + max_messages_per_subject: 1, + max_age: Duration::from_secs(60), + ..Default::default() + }) + .await + .map_err(|_| ServiceError::NatsGetServiceError)?; + + let consumer_name = format!("{}-{}", replyservice, ulid); + + // todo: kinda dumb way to do things, maybe change? + let reply_to = format!("{replyservice}.{}", ulid); + match &mut query { + Query::SearchService(q) => q.replyto = reply_to.clone(), + Query::AuthService(q) => q.replyto = reply_to.clone(), + Query::BingService(q) => q.replyto = reply_to.clone(), + Query::GoogleService(q) => q.replyto = reply_to.clone(), + } + + let consumer: PullConsumer = stream + .get_or_create_consumer( + &consumer_name, + jetstream::consumer::pull::Config { + filter_subject: reply_to.clone(), + inactive_threshold: Duration::from_secs(65), // todo: choose a less arbitrary value? + durable_name: None, + ..Default::default() + }, + ) + .await + .map_err(|_| ServiceError::NatsSubscriptionFailure)?; + + // todo! log these errors if they ever occur + let buf = match &query { + Query::SearchService(q) => { + rmp_serde::encode::to_vec(q).map_err(|_| ServiceError::SerialiseError)? + } + Query::AuthService(q) => { + rmp_serde::encode::to_vec(q).map_err(|_| ServiceError::SerialiseError)? + } + Query::BingService(q) => { + rmp_serde::encode::to_vec(q).map_err(|_| ServiceError::SerialiseError)? + } + Query::GoogleService(q) => { + rmp_serde::encode::to_vec(q).map_err(|_| ServiceError::SerialiseError)? + } + }; + + if let Err(e) = nats.publish(service, buf.into()).await { + error!("error occurred while trying to publish to nats!! {e}"); + return Err(ServiceError::NatsPublishFailure); + } + + // todo: log these errors? + let mut messages = consumer + .messages() + .await + .map_err(|_| ServiceError::NatsSubscriptionFailure)?; + + if let Some(Ok(message)) = messages.next().await { + if let Err(e) = message.ack().await { + warn!("failure while acking message! {e}"); + } + + let result = match &query { + Query::SearchService(_) => ServiceResponse::SearchService( + rmp_serde::from_slice::( + message.payload.as_ref(), + ) + .map_err(|_| ServiceError::DeserialiseError)?, + ), + Query::AuthService(_) => ServiceResponse::AuthService( + rmp_serde::from_slice::(message.payload.as_ref()) + .map_err(|_| ServiceError::DeserialiseError)?, + ), + Query::BingService(_) => ServiceResponse::BingService( + rmp_serde::from_slice::(message.payload.as_ref()) + .map_err(|_| ServiceError::DeserialiseError)?, + ), + Query::GoogleService(_) => ServiceResponse::BingService( + rmp_serde::from_slice::(message.payload.as_ref()) + .map_err(|_| ServiceError::DeserialiseError)?, + ), + }; + + if use_cache { + // only write cache if this isn't an error + let mut error = false; + match &result { + ServiceResponse::SearchService(s) => match s { + SearchSrvcResponse::InvalidRequest => { error = true; } + SearchSrvcResponse::OtherError(_) => { error = true; } + _ => {} + } + ServiceResponse::BingService(s) => match s { + BingServiceResponse::InvalidRequest => { error = true; } + BingServiceResponse::OtherError(_) => { error = true; } + _ => {} + } + ServiceResponse::AuthService(_) => { error = true; } // fallback to make sure we absolutely don't cache authservice stuff + } + if !error { + let mut cache = SERVICE_CACHE.write().await; + let mut query = query.clone(); + match &mut query { + Query::SearchService(s) => s.replyto = "".to_string(), + Query::BingService(s) => s.replyto = "".to_string(), + Query::GoogleService(s) => s.replyto = "".to_string(), + Query::AuthService(s) => s.replyto = "".to_string(), + } + cache.insert(query.clone(), result.clone()); + let query_clone = query.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(60 * CACHE_PERIOD_MINUTES)).await; + let mut cache = SERVICE_CACHE.write().await; + cache.remove(&query_clone); + }); + } + } + + Ok(result) + } else { + error!("couldn't receive message from service {} !!!!", service); + Err(ServiceError::NatsRecvMessageFailure) + } +} + +pub async fn subscribe_service< + F: Fn(Query) -> Fut + Sync + Send + 'static, + Fut: Send + Future, +>( + service: Service, + nats: &jetstream::Context, + process: Arc, +) -> Result<(), ServiceError> { + let service_name = match &service { + Service::SearchService => SEARCH_SERVICE, + Service::AuthService => AUTH_SERVICE, + Service::BingService => BING_SERVICE, + Service::GoogleService => GOOGLE_SERVICE, + }; + + let consumer: PullConsumer = nats + .get_or_create_stream(jetstream::stream::Config { + name: service_name.to_string(), + subjects: vec![service_name.to_string()], + retention: RetentionPolicy::WorkQueue, + ..Default::default() + }) + .await + .map_err(|_| ServiceError::NatsGetServiceError)? + .get_or_create_consumer( + &format!("{}er", service_name), + jetstream::consumer::pull::Config { + durable_name: Some(format!("{}er", service_name)), + filter_subject: service_name.to_string(), + ..Default::default() + }, + ) + .await + .map_err(|_| ServiceError::NatsGetServiceError)?; + + let mut messages = consumer + .messages() + .await + .map_err(|_| ServiceError::NatsSubscriptionFailure)?; + + while let Some(message) = messages.next().await { + if let Err(e) = message { + warn!("error when recv js message! {e}"); + continue; + } + let message = message.unwrap(); + + if let Err(e) = message.ack().await { + warn!("failure while acking message! {e}"); + } + + let message = match &service { + Service::SearchService => { + let res = rmp_serde::from_slice::( + message.payload.as_ref(), + ); + if let Err(e) = res { + warn!("invalid message sent via js!!! {e}"); + continue; + } + Query::SearchService(res.unwrap()) + } + Service::AuthService => { + let res = rmp_serde::from_slice::( + message.payload.as_ref(), + ); + if let Err(e) = res { + warn!("invalid message sent via js!!! {e}"); + continue; + } + Query::AuthService(res.unwrap()) + } + Service::BingService => { + let res = rmp_serde::from_slice::( + message.payload.as_ref(), + ); + if let Err(e) = res { + warn!("invalid message sent via js!!! {e}"); + continue; + } + Query::BingService(res.unwrap()) + } + Service::GoogleService => { + let res = rmp_serde::from_slice::( + message.payload.as_ref(), + ); + if let Err(e) = res { + warn!("invalid message sent via js!!! {e}"); + continue; + } + Query::GoogleService(res.unwrap()) + } + }; + + let replyto = match &message { + Query::SearchService(m) => m.replyto.clone(), + Query::AuthService(m) => m.replyto.clone(), + Query::BingService(m) => m.replyto.clone(), + Query::GoogleService(m) => m.replyto.clone(), + }; + + let nats = nats.clone(); + let process = process.clone(); + tokio::spawn(async move { + let response = process(message).await; + let buf = match &response { + ServiceResponse::SearchService(r) => { + let res = rmp_serde::encode::to_vec(r); + if let Err(e) = res { + warn!("unable to serialise response!!! {e}"); + return; + } + res.unwrap() + } + ServiceResponse::AuthService(r) => { + let res = rmp_serde::encode::to_vec(r); + if let Err(e) = res { + warn!("unable to serialise response!!! {e}"); + return; + } + res.unwrap() + } + ServiceResponse::BingService(r) => { + let res = rmp_serde::encode::to_vec(r); + if let Err(e) = res { + warn!("unable to serialise response!!! {e}"); + return; + } + res.unwrap() + } + }; + + if let Err(e) = nats.publish(replyto, buf.into()).await { + error!("error occurred while trying to publish to nats!! {e}"); + } + }); + } + + Ok(()) +} diff --git a/asklyphe-common/src/nats/injest.rs b/asklyphe-common/src/nats/injest.rs new file mode 100644 index 0000000..0abccbd --- /dev/null +++ b/asklyphe-common/src/nats/injest.rs @@ -0,0 +1,87 @@ +/* + * asklyphe-common nats/injest.rs + * - nats structs for crawler injest service + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use log::error; +use serde::{Deserialize, Serialize}; +pub const INJEST_SERVICE: &str = "injest"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum InjestRequest { + WebsiteCreateRequest(WebsiteCreateRequest), + WebsiteLastParseFinish(WebsiteLastParseFinish), + WebsiteRobotsFlag(WebsiteRobotsFlag), + SetMetawords(SetMetawords), + SetWords(SetWords), + SetLinks(SetLinks), + SetInfo(SetInfo), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WebsiteCreateRequest { + pub url: String, + pub last_parse_begin: i64, + pub damping: f64, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SetInfo { + pub url: String, + pub title: String, + pub description: String, + pub favicon_hash: i64, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WebsiteLastParseFinish { + pub url: String, + pub last_parse_finish: i64, + pub last_parse_finish_true: i64, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WebsiteRobotsFlag { + pub url: String, + pub robots: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Metaword { + pub word: String, + pub property: String, + pub encoded: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SetMetawords { + pub url: String, + pub metawords: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Word { + pub word: String, + pub encoded: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SetWords { + pub url: String, + pub words: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Link { + pub from: String, + pub to: String, + pub flags: u8, + pub words: Vec<(String, Vec)> +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SetLinks { + pub links: Vec, +} \ No newline at end of file diff --git a/asklyphe-common/src/nats/mod.rs b/asklyphe-common/src/nats/mod.rs new file mode 100644 index 0000000..806ce3f --- /dev/null +++ b/asklyphe-common/src/nats/mod.rs @@ -0,0 +1,19 @@ +/* + * asklyphe-common nats/mod.rs + * - module file for nats-related structs and functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod searchservice; +pub mod vorebot; +pub mod injest; +pub mod authservice; +pub mod comms; +pub mod bingservice; \ No newline at end of file diff --git a/asklyphe-common/src/nats/searchservice.rs b/asklyphe-common/src/nats/searchservice.rs new file mode 100644 index 0000000..4564e68 --- /dev/null +++ b/asklyphe-common/src/nats/searchservice.rs @@ -0,0 +1,62 @@ +/* + * asklyphe-common nats/searchservice.rs + * - nats structs for the asklyphe engine + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use serde::{Deserialize, Serialize}; + +pub const SEARCH_SERVICE: &str = "searchbot"; +pub const SEARCH_REPLY_SERVICE: &str = "searchbotreply"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SearchSrvcQuery { + pub request: SearchSrvcRequest, + /// if using comms::query_service, you don't need to set this + pub replyto: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum SearchSrvcRequest { + SearchRequest(SearchRequest), + SiteCountRequest, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum SearchSrvcResponse { + InvalidRequest, + OtherError(String), + SearchResponse(SearchResponse), + SiteCountResponse(SiteCountResponse), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SiteCountResponse { + pub count: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SearchRequest { + pub query: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SearchResult { + pub url: String, + pub relevance: f64, + pub title: Option, + pub description: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SearchResponse { + pub results: Vec, + pub blocked: Vec<(String, String)>, + pub pagerank_time_seconds: f64, + pub total_query_seconds: f64, + pub max_relevance: f64, + pub exact_phrase_found: bool, +} \ No newline at end of file diff --git a/asklyphe-common/src/nats/vorebot.rs b/asklyphe-common/src/nats/vorebot.rs new file mode 100644 index 0000000..4c0e0f6 --- /dev/null +++ b/asklyphe-common/src/nats/vorebot.rs @@ -0,0 +1,24 @@ +/* + * asklyphe-common nats/vorebot.rs + * - nats structs for the asklyphe crawler "vorebot" + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use serde::{Deserialize, Serialize}; + +pub const VOREBOT_SERVICE: &str = "websiteparse"; +pub const VOREBOT_NEWHOSTNAME_SERVICE: &str = "websiteparse_highpriority"; +pub const VOREBOT_SUGGESTED_SERVICE: &str = "websiteparse_highestpriority"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WebParseRequest { + pub url: String, + pub damping_factor: f32, +} \ No newline at end of file diff --git a/asklyphe-frontend/.gitignore b/asklyphe-frontend/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/asklyphe-frontend/.gitignore @@ -0,0 +1 @@ +/target diff --git a/asklyphe-frontend/ASSET_LICENSE b/asklyphe-frontend/ASSET_LICENSE new file mode 100644 index 0000000..064d7e9 --- /dev/null +++ b/asklyphe-frontend/ASSET_LICENSE @@ -0,0 +1,454 @@ +AskLyphe data/media assets under /static and /templates are licensed under CC-BY-NC-SA-4.0 except where otherwise specified. + +The AskLyphe Character, "Lyphe", and the design of this character are also licensed under CC-BY-NC-SA-4.0 + +-- INFO FOR FAN ARTISTS -- +Please visit https://creativecommons.org/licenses/by-nc-sa/4.0/ for a simplified version of this license. +You are free to create whatever AskLyphe fan-art you'd like, as long as you +- Give us credit for the character design +- Don't use the art for commercial purposes +- Release the art under the same license (i.e. people must follow the same terms if sharing your art) +- - This is mostly in order to allow for modified AskLyphe art assets to be licensed similarly to our AGPL code +- Don't add additional legal restrictions that would restrict others from doing something that our license allows + +You are encouraged to read the license below in full, the information above should not substitute doing so. + +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + + diff --git a/asklyphe-frontend/Cargo.toml b/asklyphe-frontend/Cargo.toml new file mode 100644 index 0000000..071dde5 --- /dev/null +++ b/asklyphe-frontend/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "asklyphe-frontend" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } +unit_converter = { path = "../unit_converter" } + +tokio = { version = "1.35.1", features = ["full"] } + +axum = "0.7.4" +axum-extra = { version = "0.9.2", features = [ "cookie" ] } +tower-http = { version = "0.5.2", features = ["cors"] } +time = "0.3.34" + +askama = { version = "0.12.1", features = ["default", "with-axum"] } +askama_axum = "0.4.0" + +tracing = "0.1.40" +tracing-subscriber = "0.3.18" +tracing-loki = "0.2.4" + +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +async-nats = "0.38.0" +rmp-serde = "1.1.2" +ulid = "1.1.0" +futures = "0.3.30" + +html-escape = "0.2.13" +isahc = "1.7.2" +once_cell = "1.19.0" +chrono = "0.4.33" +rand = "0.8.5" +url_encoded_data = "0.6.1" + +env_logger = "*" diff --git a/asklyphe-frontend/build.rs b/asklyphe-frontend/build.rs new file mode 100644 index 0000000..4f9cfda --- /dev/null +++ b/asklyphe-frontend/build.rs @@ -0,0 +1,36 @@ +/* + * asklyphe-frontend build.rs + * - build script + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::process::Command; +fn main() { + let output = Command::new("git") + .args(["rev-parse", "--short", "HEAD"]) + .output() + .expect("Failed to execute git command"); + let git_commit = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=GIT_COMMIT={}", git_commit); + + let output = Command::new("date") + .args(["-u", "+%Y-%m-%d"]) + .output() + .expect("Failed to execute date command"); + let built_on = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=BUILT_ON={}", built_on); + + let output = Command::new("date") + .args(["-u", "+%Y"]) + .output() + .expect("Failed to execute date command"); + let year = String::from_utf8(output.stdout).unwrap(); + println!("cargo:rustc-env=YEAR={}", year); +} \ No newline at end of file diff --git a/asklyphe-frontend/src/main.rs b/asklyphe-frontend/src/main.rs new file mode 100644 index 0000000..2b87121 --- /dev/null +++ b/asklyphe-frontend/src/main.rs @@ -0,0 +1,157 @@ +/* + * asklyphe-frontend main.rs + * - entrypoint for the asklyphe frontend + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod searchbot; +pub mod wikipedia; +pub mod unit_converter; +pub mod routes; + +use std::{env, process}; +use std::collections::HashMap; +use std::net::SocketAddr; +use std::ops::Deref; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use askama::Template; +use asklyphe_common::nats; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::searchservice::{SearchSrvcQuery, SearchSrvcRequest, SearchSrvcResponse}; +use async_nats::jetstream; +use axum::{Extension, Router}; +use axum::extract::Query; +use axum::http::{HeaderValue, Method}; +use axum::response::IntoResponse; +use axum::routing::{get, post}; +use serde::Serialize; +use tokio::sync::Mutex; +use tower_http::cors::{AllowOrigin, CorsLayer}; +use tracing::error; +use tracing_loki::url::Url; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use crate::routes::admin::{admin_announcement, admin_announcement_post, admin_home, admin_invitecode, admin_invitecode_post, admin_user_list}; +use crate::routes::announcement::announcement_full; +use crate::routes::index::{frontpage, index, logout}; +use crate::routes::search::{image_proxy, search, search_json}; +use crate::routes::semaphore::semaphore; +use crate::routes::user_settings::{theme_change_post, user_settings}; +use crate::unit_converter::UnitConversion; +use crate::wikipedia::WikipediaSummary; + +const ALPHA: bool = { + let alpha = option_env!("ALPHA"); + alpha.is_some() +}; +const VERSION: &str = env!("CARGO_PKG_VERSION"); +const GIT_COMMIT: &str = env!("GIT_COMMIT"); +const BUILT_ON: &str = env!("BUILT_ON"); +const YEAR: &str = env!("YEAR"); + +#[derive(Clone)] +pub struct Opts { + pub bind_addr: SocketAddr, + pub nats_addr: SocketAddr, + nats_cert: String, + nats_key: String, + auth_url: String, + pub loki_addr: Option, + pub datacenter_id: i64, + pub emergency: bool, +} + +pub static WEBSITE_COUNT: AtomicU64 = AtomicU64::new(0); + +async fn website_count_update_thread(nats: Arc) { + loop { + searchbot::update_website_counter(nats.clone()).await; + tokio::time::sleep(Duration::from_secs(30)).await; + } +} + +#[tokio::main] +async fn main() { + env_logger::init(); + let opts = Opts { + bind_addr: env::var("BIND_ADDR").unwrap_or("0.0.0.0:5842".to_string()).parse().expect("Badly formed BIND_ADDR (Needs to be SocketAddr)"), + nats_addr: env::var("NATS_ADDR").unwrap_or("127.0.0.1:4222".to_string()).parse().expect("Badly formed NATS_ADDR (Needs to be SocketAddr)"), + nats_cert: env::var("NATS_CERT").expect("NATS_CERT needs to be set"), + nats_key: env::var("NATS_KEY").expect("NATS_KEY needs to be set"), + auth_url: env::var("AUTH_URL").unwrap_or("https://auth.asklyphe.com".to_string()), + loki_addr: match env::var("LOKI_ADDR") { + Ok(url) => { + Some(Url::parse(&url).expect("Badly formed LOKI_ADDR (Needs to be Url)")) + } + Err(_) => { + None + } + }, + datacenter_id: env::var("DATACENTER_ID").unwrap_or("1".to_string()).parse().expect("Badly formed DATACENTER_ID (Need to be i64)"), + emergency: env::var("EMERGENCY").unwrap_or("0".to_string()).eq("1"), + }; + + if opts.loki_addr.is_some() { + //let (layer, task) = tracing_loki::builder() + // .label("environment", "dev").unwrap() + // .extra_field("pid", process::id().to_string()).unwrap() + // .extra_field("run_id", snowflake_factory.generate().to_string()).unwrap() + // .build_url(opts.loki_addr.clone().unwrap()).unwrap(); + + //// Register Loki layer + //tracing_subscriber::registry() + // .with(layer) + // .init(); + + //// Spawn Loki background task + //tokio::spawn(task); + } else { + //tracing_subscriber::fmt::init() + } + + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(opts.nats_cert.as_str().into(), opts.nats_key.as_str().into()) + .connect(opts.nats_addr.to_string()) + .await; + if let Err(e) = nats { + eprintln!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + let nats = Arc::new(nats); + + tokio::spawn(website_count_update_thread(nats.clone())); + + let app = Router::new() + .route("/", get(index)) + .route("/semaphore", get(semaphore)) + .route("/frontpage", get(frontpage)) + .route("/ask", get(search)) + .route("/ask_json", get(search_json)) + .route("/imgproxy", get(image_proxy)) + .route("/logout", post(logout)) + .route("/user_settings", get(user_settings)) + .route("/user_settings/set_theme", post(theme_change_post)) + .route("/admin", get(admin_home)) + .route("/admin/invitecode", get(admin_invitecode).post(admin_invitecode_post)) + .route("/admin/announcement", get(admin_announcement).post(admin_announcement_post)) + .route("/admin/allusers", get(admin_user_list)) + .route("/announcements/:slug", get(announcement_full)) + .layer(CorsLayer::new().allow_methods([Method::GET, Method::POST]).allow_origin(AllowOrigin::exact(HeaderValue::from_str("localhost").unwrap()))) + .layer(Extension(nats.clone())) + .layer(Extension(opts.clone())) + .fallback(routes::not_found); + + let listener = tokio::net::TcpListener::bind(opts.bind_addr).await.expect("Failed to get listener"); + axum::serve(listener, app).await.expect("Failed to serve"); +} diff --git a/asklyphe-frontend/src/routes/admin.rs b/asklyphe-frontend/src/routes/admin.rs new file mode 100644 index 0000000..4e93d30 --- /dev/null +++ b/asklyphe-frontend/src/routes/admin.rs @@ -0,0 +1,629 @@ +/* + * asklyphe-frontend routes/admin.rs + * - http routes for the admin panel + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use askama::Template; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse}; +use asklyphe_common::nats::authservice::admin::{AdminCreateAnnouncementRequest, AdminCreateAnnouncementResponse, AdminInviteCodeGenerateRequest, AdminInviteCodeGenerateResponse, AdminListAllUsersRequest, AdminListAllUsersResponse, AdminListInviteCodesRequest, AdminListInviteCodesResponse, InviteCodeSerialized, Stats, StatsRequest, StatsResponse, UserSerialized}; +use asklyphe_common::nats::authservice::profile::{UserInfoRequest, UserInfoResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::{Extension, Form}; +use axum::response::{IntoResponse, Redirect}; +use axum_extra::extract::CookieJar; +use rand::Rng; +use serde::Deserialize; +use tracing::{debug, error}; +use crate::Opts; +use crate::routes::{authenticate_user, UserInfo}; + +const MOTD: &[&str] = &[ + "be evil :3c", + "pong", + ">:o", + "\" UNION SELECT username, password FROM users; -- ", +]; + +#[derive(Template)] +#[template(path = "admin/error.html")] +pub struct AdminErrorTemplate { + motd: &'static str, + + error: String, +} + +#[derive(Template)] +#[template(path = "admin/home.html")] +pub struct AdminHomeTemplate { + motd: &'static str, + + last_ten_users: Vec, + user_count: usize, + admin_count: usize, + active_verification_requests: usize, +} + +fn motd() -> &'static str { + let mut rng = rand::thread_rng(); + MOTD[rng.gen_range(0..MOTD.len())] +} + +fn adminerror(message: String) -> impl IntoResponse { + AdminErrorTemplate { + motd: motd(), + error: message, + } +} + +async fn stats(nats: Arc, token: String) -> Result { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::StatsRequest(StatsRequest { + token, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + Err(adminerror(format!("nats error: {:?}", e)).into_response()) + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent search service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent bing service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::StatsResponse(stats) => { + match stats { + StatsResponse::Success(stats) => { + Ok(stats) + } + StatsResponse::InternalServerError(e) => { + Err(adminerror(format!("internal server error: {e}")).into_response()) + } + StatsResponse::Logout => { + Err(Redirect::to("/").into_response()) + } + StatsResponse::AccessDenied => { + Err(Redirect::to("/").into_response()) + } + } + } + x => { + error!("auth service gave {} to our user info request!", x); + Err(adminerror(format!("auth service gave {} to our user info request!", x)).into_response()) + } + }, + } + } +} + +async fn list_invite_codes(nats: Arc, token: String, show_used: bool) -> Result, impl IntoResponse> { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::AdminListInviteCodesRequest(AdminListInviteCodesRequest { + token, + show_used, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + Err(adminerror(format!("nats error: {:?}", e)).into_response()) + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent search service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent bing service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::AdminListInviteCodesResponse(v) => { + match v { + AdminListInviteCodesResponse::Success(v) => { + Ok(v) + } + AdminListInviteCodesResponse::InternalServerError(e) => { + Err(adminerror(format!("internal server error: {e}")).into_response()) + } + AdminListInviteCodesResponse::Logout => { + Err(Redirect::to("/").into_response()) + } + AdminListInviteCodesResponse::AccessDenied => { + Err(Redirect::to("/").into_response()) + } + } + } + x => { + error!("auth service gave {} to our list invite codes request!", x); + Err(adminerror(format!("auth service gave {} to our list invite codes request!", x)).into_response()) + } + }, + } + } +} + +async fn list_all_users(nats: Arc, token: String) -> Result, impl IntoResponse> { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::AdminListAllUsersRequest(AdminListAllUsersRequest { + token, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + Err(adminerror(format!("nats error: {:?}", e)).into_response()) + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent search service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent bing service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::AdminListAllUsersResponse(v) => { + match v { + AdminListAllUsersResponse::Success(v) => { + Ok(v) + } + AdminListAllUsersResponse::InternalServerError(e) => { + Err(adminerror(format!("internal server error: {e}")).into_response()) + } + AdminListAllUsersResponse::Logout => { + Err(Redirect::to("/").into_response()) + } + AdminListAllUsersResponse::AccessDenied => { + Err(Redirect::to("/").into_response()) + } + } + } + x => { + error!("auth service gave {} to our list users request!", x); + Err(adminerror(format!("auth service gave {} to our list users request!", x)).into_response()) + } + }, + } + } +} + +async fn gen_invite_code(nats: Arc, token: String, code: String, comment: String) -> Result<(), impl IntoResponse> { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::AdminInviteCodeGenerateRequest(AdminInviteCodeGenerateRequest { + token, + invite_code: code, + comment, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + Err(adminerror(format!("nats error: {:?}", e)).into_response()) + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent search service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + Err(adminerror("sent bing service response when asking auth service!".to_string()).into_response()) + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::AdminInviteCodeGenerateResponse(res) => { + match res { + AdminInviteCodeGenerateResponse::Success => { + Ok(()) + } + AdminInviteCodeGenerateResponse::InternalServerError(e) => { + Err(adminerror(format!("internal server error: {e}")).into_response()) + } + AdminInviteCodeGenerateResponse::Logout => { + Err(Redirect::to("/").into_response()) + } + AdminInviteCodeGenerateResponse::AccessDenied => { + Err(Redirect::to("/").into_response()) + } + AdminInviteCodeGenerateResponse::CodeAlreadyExists => { + Err(adminerror("code already exists".to_string()).into_response()) + } + } + } + x => { + error!("auth service gave {} to our user info request!", x); + Err(adminerror(format!("auth service gave {} to our geninvitecode request!", x)).into_response()) + } + }, + } + } +} + +pub async fn admin_home( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + let stats = match stats(nats.clone(), token).await { + Ok(s) => s, + Err(e) => { + return e.into_response(); + } + }; + + AdminHomeTemplate { + motd: motd(), + last_ten_users: stats.last_ten_users, + user_count: stats.user_count, + admin_count: stats.admin_count, + active_verification_requests: stats.active_verification_requests, + }.into_response() + } else { + Redirect::to("/").into_response() + } +} + + +#[derive(Template)] +#[template(path = "admin/invitecode.html")] +pub struct AdminInviteCodeTemplate { + motd: &'static str, + + username: String, + active_codes: Vec, + used_codes: Vec, +} + +pub async fn admin_invitecode( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + let active_codes = match list_invite_codes(nats.clone(), token.clone(), false).await { + Ok(v) => v, + Err(e) => { + return e.into_response(); + } + }; + + let used_codes = match list_invite_codes(nats.clone(), token.clone(), true).await { + Ok(v) => v.into_iter().map(|mut v| if v.used_at.is_none() { v.used_at = Some(String::from("unset")); v } else { v }).collect(), + Err(e) => { + return e.into_response(); + } + }; + + AdminInviteCodeTemplate { + motd: motd(), + username: info.username, + active_codes, + used_codes, + }.into_response() + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Deserialize, Debug)] +pub struct InviteCodeForm { + code: Option, + comment: Option, +} + +pub async fn admin_invitecode_post( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, + Form(input): Form, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + if input.code.is_none() || input.comment.is_none() { + return adminerror("code and comment required".to_string()).into_response(); + } + if input.code.as_ref().unwrap().is_empty() || input.comment.as_ref().unwrap().is_empty() { + return adminerror("code and comment required".to_string()).into_response(); + } + + match gen_invite_code(nats.clone(), token, input.code.unwrap(), input.comment.unwrap()).await { + Ok(_) => { + Redirect::to("/admin/invitecode").into_response() + } + Err(e) => { + e.into_response() + } + } + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Template)] +#[template(path = "admin/announcement.html")] +pub struct AdminAnnouncementTemplate { + motd: &'static str, + + error: Option, + + username: String, + + slug: String, + title: String, + short_content: String, + full_content: String, +} + +pub async fn admin_announcement( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + AdminAnnouncementTemplate { + motd: motd(), + error: None, + username: info.username, + slug: "the-post-like-this".to_string(), + title: "Changes Happened!".to_string(), + short_content: "we made some changes!".to_string(), + full_content: "we made some changes! here are the details!".to_string(), + }.into_response() + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Deserialize, Debug, Clone)] +pub struct AnnouncementForm { + slug: Option, + title: Option, + short_content: Option, + full_content: Option, + send_emails: Option, +} + +pub async fn admin_announcement_post( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, + Form(input): Form, +) -> impl IntoResponse { + fn announcement_error(error: &str, username: String, form: AnnouncementForm) -> impl IntoResponse { + AdminAnnouncementTemplate { + motd: motd(), + error: Some(error.to_string()), + username, + slug: form.slug.unwrap_or_default(), + title: form.title.unwrap_or_default(), + short_content: form.short_content.unwrap_or_default(), + full_content: form.full_content.unwrap_or_default(), + } + } + + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + if input.slug.is_none() || input.slug.as_ref().unwrap().is_empty() { + return announcement_error("slug required", info.username, input).into_response(); + } + if input.title.is_none() || input.title.as_ref().unwrap().is_empty() { + return announcement_error("title required", info.username, input).into_response(); + } + if input.short_content.is_none() || input.short_content.as_ref().unwrap().is_empty() { + return announcement_error("short content required", info.username, input).into_response(); + } + if input.full_content.is_none() || input.full_content.as_ref().unwrap().is_empty() { + return announcement_error("full content required", info.username, input).into_response(); + } + + debug!("sendemails: {:?}", input.send_emails); + + let input_og = input.clone(); + let response = comms::query_service(comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::AdminCreateAnnouncementRequest(AdminCreateAnnouncementRequest { + token: token.clone(), + title: input.title.unwrap(), + slug: input.slug.unwrap(), + short_text: input.short_content.unwrap(), + full_markdown_text: input.full_content.unwrap(), + send_emails: !input.send_emails.unwrap_or("".to_string()).is_empty(), + }), + replyto: "".to_string(), + }), &nats, false).await; + + if let Err(e) = response { + error!("nats error: {:?}", e); + announcement_error(&format!("nats error: {:?}", e), info.username, input_og).into_response() + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + announcement_error("auth service error", info.username, input_og).into_response() + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + announcement_error("auth service error", info.username, input_og).into_response() + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::AdminCreateAnnouncementResponse(r) => { + match r { + AdminCreateAnnouncementResponse::Success => { + AdminAnnouncementTemplate { + motd: motd(), + error: Some("success!".to_string()), + username: info.username, + slug: "".to_string(), + title: "".to_string(), + short_content: "".to_string(), + full_content: "".to_string(), + }.into_response() + } + AdminCreateAnnouncementResponse::SlugTaken => { + announcement_error("slug taken!", info.username, input_og).into_response() + } + AdminCreateAnnouncementResponse::InternalServerError(e) => { + announcement_error(&format!("internal server error: {}", e), info.username, input_og).into_response() + } + AdminCreateAnnouncementResponse::Logout => { + Redirect::to("/").into_response() + } + AdminCreateAnnouncementResponse::AccessDenied => { + Redirect::to("/").into_response() + } + } + } + x => { + error!("auth survace gave {} to our create announcement request!", x); + announcement_error(&format!("auth service gave {x} to our create announcement request!"), info.username, input_og).into_response() + } + } + } + } + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Template)] +#[template(path = "admin/allusers.html")] +pub struct AdminUserListTemplate { + motd: &'static str, + + users: Vec +} + +pub async fn admin_user_list( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return Redirect::to("/").into_response(); + } + }; + + if !info.administrator { + return Redirect::to("/").into_response(); + } + + match list_all_users(nats.clone(), token).await { + Ok(mut v) => { + for v in &mut v { + if v.username.len() > 32 { + v.username = format!("{}...", &v.username[0..32]); + } + } + AdminUserListTemplate { + motd: motd(), + users: v, + }.into_response() + } + Err(e) => { + e.into_response() + } + } + } else { + Redirect::to("/").into_response() + } +} \ No newline at end of file diff --git a/asklyphe-frontend/src/routes/announcement.rs b/asklyphe-frontend/src/routes/announcement.rs new file mode 100644 index 0000000..37865f6 --- /dev/null +++ b/asklyphe-frontend/src/routes/announcement.rs @@ -0,0 +1,118 @@ +/* + * asklyphe-frontend routes/announcement.rs + * - http routes for announcements + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use askama::Template; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse}; +use asklyphe_common::nats::authservice::announcements::{AnnouncementFullRequest, AnnouncementFullResponse, LatestAnnouncementRequest, LatestAnnouncementResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::Extension; +use axum::extract::Path; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use serde::Serialize; +use tracing::{debug, error}; +use tracing::log::warn; +use crate::{Opts, ALPHA, BUILT_ON, GIT_COMMIT, VERSION, YEAR}; +use crate::routes::index::FrontpageAnnouncement; + +#[derive(Serialize, Debug)] +struct FullAnnouncement { + title: String, + date: String, + creator: String, + full: String +} + +async fn announcement(nats: Arc, slug: String) -> Option { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::AnnouncementFullRequest(AnnouncementFullRequest { slug }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + None + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + None + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + None + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::AnnouncementFullResponse(v) => { + match v { + AnnouncementFullResponse::Some(v) => { + Some(FullAnnouncement { + title: v.title, + date: chrono::DateTime::from_timestamp(v.created_on, 0).unwrap().to_rfc2822(), + creator: v.creator, + full: v.markdown_text.replace("\n", "
"), + }) + } + AnnouncementFullResponse::NotFound => { + None + } + AnnouncementFullResponse::InternalServerError(e) => { + warn!("internal server error while getting announcement: {}", e); + None + } + } + } + x => { + error!("auth service gave {} to our user info request!", x); + None + } + }, + } + } +} + +#[derive(Template)] +#[template(path = "announcement.html")] +pub struct AnnouncementTemplate { + version: String, + git_commit: String, + built_on: String, + year: String, + alpha: bool, + theme: String, + announcement: FullAnnouncement, +} + +pub async fn announcement_full(Extension(nats): Extension>, Extension(opts): Extension, Path(slug): Path) -> impl IntoResponse { + debug!("looking up {slug}"); + if let Some(announcement) = announcement(nats.clone(), slug.clone()).await { + AnnouncementTemplate { + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme: "default".to_string(), + announcement, + }.into_response() + } else { + StatusCode::NOT_FOUND.into_response() + } +} \ No newline at end of file diff --git a/asklyphe-frontend/src/routes/index.rs b/asklyphe-frontend/src/routes/index.rs new file mode 100644 index 0000000..fa7d199 --- /dev/null +++ b/asklyphe-frontend/src/routes/index.rs @@ -0,0 +1,267 @@ +/* + * asklyphe-frontend routes/index.rs + * - http routes for homepages + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthError, AuthRequest, AuthResponse, AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, LogoutRequest, LogoutResponse}; +use asklyphe_common::nats::authservice::admin::{Stats, StatsRequest, StatsResponse}; +use asklyphe_common::nats::authservice::announcements::{LatestAnnouncementRequest, LatestAnnouncementResponse}; +use asklyphe_common::nats::authservice::profile::{UserInfoRequest, UserInfoResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::{ServiceError, ServiceResponse}; +use async_nats::jetstream; +use axum::Extension; +use axum::response::Redirect; +use axum_extra::extract::CookieJar; +use serde::Serialize; +use tokio::sync::Mutex; +use tracing::error; +use tracing::log::warn; +use crate::{BUILT_ON, GIT_COMMIT, Opts, ALPHA, VERSION, WEBSITE_COUNT, YEAR}; +use crate::routes::{authenticate_user, UserInfo}; + +#[derive(Serialize, Debug)] +pub struct FrontpageAnnouncement { + pub url: String, + pub title: String, + pub content: String, + pub date: String, +} + +async fn latest_announcement(nats: Arc) -> Option { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::LatestAnnouncementRequest(LatestAnnouncementRequest {}), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + None + } else { + let response = response.unwrap(); + match response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + None + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + None + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::LatestAnnouncementResponse(v) => { + match v { + LatestAnnouncementResponse::Some(v) => { + Some(FrontpageAnnouncement { + url: format!("/announcements/{}", v.slug), + title: v.title, + content: v.short_text, + date: chrono::DateTime::from_timestamp(v.date, 0).unwrap().to_rfc2822(), + }) + } + LatestAnnouncementResponse::None => { + None + } + LatestAnnouncementResponse::InternalServerError(e) => { + warn!("internal server error during latest announcement request! {e}"); + None + } + } + } + x => { + error!("auth service gave {} to our user info request!", x); + None + } + }, + } + } +} + +pub fn frontpage_error(error: &str, auth_url: String) -> FrontpageTemplate { + FrontpageTemplate { + authurl: auth_url, + error: Some(error.to_string()), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme: "default".to_string(), + announcement: None, + } +} + +pub async fn logout( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::LogoutRequest(LogoutRequest { + token, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + frontpage_error("internal server error", opts.auth_url.clone()).into_response() + } else { + let response = response.unwrap(); + let mut internal_server_error = false; + match &response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::LogoutResponse(_) => {} + x => { + error!("auth service gave {} to our user info request!", x); + internal_server_error = true; + } + } + } + if internal_server_error { + frontpage_error("internal server error", opts.auth_url.clone()).into_response() + } else { + match response { + ServiceResponse::AuthService(AuthServiceResponse::LogoutResponse(r)) => match r { + LogoutResponse::Success => { + (jar.remove("token"), + Redirect::to("/").into_response()).into_response() + } + LogoutResponse::InternalServerError(e) => { + error!("internal server error {e} returned from auth service during logout! investigate ASAP!!!"); + frontpage_error("internal server error", opts.auth_url.clone()).into_response() + } + LogoutResponse::BadTokenError => { + (jar.remove("token"), + Redirect::to("/").into_response()).into_response() + } + } + _ => unreachable!() + } + } + } + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Template)] +#[template(path = "frontpage.html")] +pub struct FrontpageTemplate { + authurl: String, + error: Option, + version: String, + git_commit: String, + built_on: String, + year: String, + alpha: bool, + count: u64, + theme: String, + announcement: Option, +} + +pub async fn frontpage( + Extension(nats): Extension>, + Extension(opts): Extension) -> impl IntoResponse { + let announcement = latest_announcement(nats.clone()).await; + FrontpageTemplate { + authurl: opts.auth_url.clone(), + error: None, + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme: "default".to_string(), + announcement, + } +} + +#[derive(Template)] +#[template(path = "home.html")] +struct IndexTemplate { + info: UserInfo, + version: String, + git_commit: String, + built_on: String, + year: String, + alpha: bool, + count: u64, + theme: String, + announcement: Option, +} + +pub async fn index( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return (jar.remove("token"), frontpage_error(e.as_str(), opts.auth_url.clone())).into_response(); + } + }; + let theme = info.theme.clone(); + + let announcement = latest_announcement(nats.clone()).await; + + IndexTemplate { + info, + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme, + announcement, + }.into_response() + } else { + let announcement = latest_announcement(nats.clone()).await; + FrontpageTemplate { + authurl: opts.auth_url.clone(), + error: None, + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme: "default".to_string(), + announcement, + }.into_response() + } +} diff --git a/asklyphe-frontend/src/routes/mod.rs b/asklyphe-frontend/src/routes/mod.rs new file mode 100644 index 0000000..445859b --- /dev/null +++ b/asklyphe-frontend/src/routes/mod.rs @@ -0,0 +1,117 @@ +/* + * asklyphe-frontend routes/mod.rs + * - module file for http routes + some commonly used functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse}; +use asklyphe_common::nats::authservice::profile::{UserInfoRequest, UserInfoResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::ServiceResponse; +use async_nats::jetstream; +use axum::http::StatusCode; +use serde::Serialize; +use tracing::error; + +pub mod search; +pub mod index; +pub mod semaphore; +pub mod user_settings; +pub mod admin; +pub mod announcement; + +#[derive(Serialize)] +pub struct UserInfo { + pub username: String, + pub email: String, + pub new_email: Option, + pub theme: String, + pub administrator: bool, +} + +pub async fn authenticate_user(nats: Arc, token: String) -> Result { + let response = comms::query_service( + comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::UserInfoRequest(UserInfoRequest { + token, + }), + replyto: "".to_string(), + }), + &nats, + false, + ).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + Err("internal server error".to_string()) + } else { + let response = response.unwrap(); + let mut internal_server_error = false; + match &response { + ServiceResponse::SearchService(_) => { + error!("sent search service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::BingService(_) => { + error!("sent bing service response when asking for auth service!! investigate ASAP!!!"); + internal_server_error = true; + } + ServiceResponse::AuthService(r) => match r { + AuthServiceResponse::UserInfoResponse(_) => {} + x => { + error!("auth service gave {} to our user info request!", x); + internal_server_error = true; + } + }, + } + let info = if internal_server_error { + return Err("internal server error".to_string()); + } else { + match response { + ServiceResponse::AuthService(AuthServiceResponse::UserInfoResponse(r)) => match r { + UserInfoResponse::Success(ui) => { + UserInfo { + username: ui.username, + email: ui.email, + new_email: ui.new_email, + theme: ui.theme, + administrator: ui.administrator, + } + } + UserInfoResponse::InternalServerError(e) => { + error!("internal server error while querying user data! {e}"); + return Err("internal server error".to_string()); + } + UserInfoResponse::TokenExpired => { + return Err("your session has expired! please log in and try again!".to_string()); + } + UserInfoResponse::TokenInvalid => { + return Err("your session has expired! please log in and try again!".to_string()); + } + UserInfoResponse::AccountSuspended => { + return Err("unfortunately your account has been suspended, please check our support pages for more info".to_string()); + } + } + _ => unreachable!() + } + }; + Ok(info) + } +} + +#[derive(Template)] +#[template(path = "404.html")] +pub struct NotFoundTemplate; + +pub async fn not_found() -> impl IntoResponse { + (StatusCode::NOT_FOUND, NotFoundTemplate).into_response() +} \ No newline at end of file diff --git a/asklyphe-frontend/src/routes/search.rs b/asklyphe-frontend/src/routes/search.rs new file mode 100644 index 0000000..0c90393 --- /dev/null +++ b/asklyphe-frontend/src/routes/search.rs @@ -0,0 +1,607 @@ +/* + * asklyphe-frontend routes/search.rs + * - http routes for web searching + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use crate::routes::index::frontpage_error; +use crate::routes::{authenticate_user, UserInfo}; +use crate::searchbot::{gather_image_results, gather_search_results}; +use crate::unit_converter; +use crate::unit_converter::UnitConversion; +use crate::wikipedia::WikipediaSummary; +use crate::{wikipedia, Opts, ALPHA, BUILT_ON, GIT_COMMIT, VERSION, YEAR}; +use askama::Template; +use asklyphe_common::nats; +use asklyphe_common::nats::bingservice::{ + BingServiceQuery, BingServiceRequest, BingServiceResponse, +}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::searchservice::{ + SearchSrvcQuery, SearchSrvcRequest, SearchSrvcResponse, +}; +use async_nats::jetstream; +use axum::extract::Query; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Redirect}; +use axum::Extension; +use axum_extra::extract::CookieJar; +use isahc::config::{IpVersion, RedirectPolicy}; +use isahc::RequestExt; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ops::Deref; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::{Mutex, RwLock}; +use tracing::error; + +#[derive(Serialize)] +pub struct SearchResult { + pub title: Option, + pub description: Option, + pub url: String, + pub percentage: String, + pub value: String, + pub asklyphe: bool, + pub bing: bool, + pub google: bool, +} + +#[derive(Serialize)] +pub struct ImageSearchResult { + pub src: String, + pub url: String, + pub bing: bool, + pub google: bool, +} + +#[derive(Debug, Default)] +pub struct Complications { + disabled: bool, + wikipedia: Option, + unit_converter: Option, +} + +pub async fn search( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + let stype = params + .get("stype") + .unwrap_or(&"web".to_string()) + .to_string(); + if stype == "image" { + return image_search(jar, Query(params), Extension(nats), Extension(opts)) + .await + .into_response(); + } + let use_javascript = params.get("js").unwrap_or(&"0".to_string()).to_string(); + if use_javascript != *"1" { + search_nojs(jar, Query(params), Extension(nats), Extension(opts)) + .await + .into_response() + } else { + search_js(jar, Query(params), Extension(nats), Extension(opts)) + .await + .into_response() + } +} + +#[derive(Template)] +#[template(path = "search_js.html")] +struct SearchTemplateJavascript { + info: UserInfo, + error: Option, + complications: Complications, + search_query: String, + websearch_url: String, + imagesearch_url: String, + version: String, + git_commit: String, + built_on: String, + year: String, + alpha: bool, + theme: String, +} + +pub async fn search_js( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + fn error_response(query: String, info: UserInfo, error: &str) -> SearchTemplateJavascript { + let theme = info.theme.clone(); + let querystr = url_encoded_data::stringify(&[("q", query.as_str())]); + SearchTemplateJavascript { + info, + error: Some(format!( + "internal server error ({})! report to developers (:", + error + )), + complications: Default::default(), + search_query: query, + websearch_url: format!("/ask?{querystr}&js=1"), + imagesearch_url: format!("/ask?{querystr}&js=1&stype=image"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } + } + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return ( + jar.remove("token"), + frontpage_error(e.as_str(), opts.auth_url.clone()), + ) + .into_response(); + } + }; + let mut query = params.get("q").unwrap_or(&"Deez".to_string()).to_string(); + let og_query = query.clone(); + let mut complications = Complications::default(); + // todo: better way of specifying that user doesn't want complications + if !query.contains("-complications") { + let mut wikiquery = query.clone().to_lowercase(); + wikiquery.retain(|c| c.is_alphanumeric() || c.is_ascii_whitespace()); + wikiquery = wikiquery.replace(' ', "%20"); + // todo: proper url escaping + let wikipedia_comp = + tokio::spawn(async move { wikipedia::get_wikipedia_page(&wikiquery, 20).await }); + complications.wikipedia = wikipedia_comp.await.unwrap_or_default(); + + let mut unit_query = query.clone().to_lowercase(); + unit_query = unit_query.replace("metre", "meter"); + let unit_comp = unit_converter::convert_unit(&unit_query); + complications.unit_converter = unit_comp; + } else { + complications.disabled = true; + query = query.replace("-complications", ""); + } + + let theme = info.theme.clone(); + let querystr = url_encoded_data::stringify(&[("q", og_query.as_str())]); + SearchTemplateJavascript { + info, + error: None, + complications, + search_query: og_query, + websearch_url: format!("/ask?{querystr}&js=1"), + imagesearch_url: format!("/ask?{querystr}&js=1&stype=image"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } + .into_response() + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Template)] +#[template(path = "search.html")] +pub struct SearchTemplate { + pub info: UserInfo, + pub error: Option, + pub note: Option, + pub complications: Complications, + pub search_query: String, + pub query_time: f64, + pub page_rank_time: f64, + pub max_relevance: String, + pub search_results: Vec, + pub blocked: Vec<(String, String)>, + pub websearch_url: String, + pub imagesearch_url: String, + pub version: String, + pub git_commit: String, + pub built_on: String, + pub year: String, + pub alpha: bool, + pub theme: String, +} + +pub async fn search_nojs( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + fn error_response(query: String, info: UserInfo, error: &str) -> SearchTemplate { + let theme = info.theme.clone(); + let querystr = url_encoded_data::stringify(&[("q", query.as_str())]); + SearchTemplate { + info, + error: Some(format!( + "internal server error ({})! report to developers (:", + error + )), + note: None, + complications: Default::default(), + search_query: query, + query_time: 0.0, + page_rank_time: 0.0, + max_relevance: "".to_string(), + search_results: vec![], + blocked: vec![], + websearch_url: format!("/ask?{querystr}&js=0"), + imagesearch_url: format!("/ask?{querystr}&js=0&stype=image"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } + } + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return ( + jar.remove("token"), + frontpage_error(e.as_str(), opts.auth_url.clone()), + ) + .into_response(); + } + }; + let mut query = params.get("q").unwrap_or(&"Deez".to_string()).to_string(); + let og_query = query.clone(); + let mut complications = Complications::default(); + // todo: better way of specifying that user doesn't want complications + if !query.contains("-complications") { + let mut wikiquery = query.clone().to_lowercase(); + wikiquery.retain(|c| c.is_alphanumeric() || c.is_ascii_whitespace()); + wikiquery = wikiquery.replace(' ', "%20"); + // todo: proper url escaping + let wikipedia_comp = + tokio::spawn(async move { wikipedia::get_wikipedia_page(&wikiquery, 20).await }); + complications.wikipedia = wikipedia_comp.await.unwrap_or_default(); + + let mut unit_query = query.clone().to_lowercase(); + unit_query = unit_query.replace("metre", "meter"); + let unit_comp = unit_converter::convert_unit(&unit_query); + complications.unit_converter = unit_comp; + } else { + complications.disabled = true; + query = query.replace("-complications", ""); + } + + let engines = params + .get("engines") + .unwrap_or(&"asklyphe,bing,google".to_string()) + .to_string(); + let mut engines = engines + .split(",") + .map(|v| v.to_string()) + .collect::>(); + if opts.emergency { + // disable asklyphe backend + engines.retain(|v| v != "asklyphe"); + } + + gather_search_results(nats, query.as_str(), info, complications, Some(engines)) + .await + .into_response() + } else { + Redirect::to("/").into_response() + } +} + +#[derive(Serialize)] +struct BlockedResult { + url: String, + reason: String, +} + +#[derive(Serialize)] +struct SearchJsonInner { + #[serde(skip_serializing_if = "Option::is_none")] + note: Option, + query_time: f64, + page_rank_time: f64, + max_relevance: String, + search_results: Vec, + blocked: Vec, +} + +#[derive(Serialize)] +struct SearchJson { + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + results: Option, +} + +pub async fn search_json( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> String { + fn json(input: SearchJson) -> String { + serde_json::to_string(&input).expect("failed to serialise!") + } + + fn error_response(error: &str) -> String { + json(SearchJson { + error: Some(error.to_string()), + results: None, + }) + } + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return error_response("not authenticated"); + } + }; + let query = params.get("q").unwrap_or(&"Deez".to_string()).to_string(); + let engines = params + .get("engines") + .unwrap_or(&"asklyphe,bing,google".to_string()) + .to_string(); + let mut engines = engines + .split(",") + .map(|v| v.to_string()) + .collect::>(); + if opts.emergency { + // disable asklyphe backend + engines.retain(|v| v != "asklyphe"); + } + + let result = gather_search_results( + nats, + query.as_str(), + info, + Complications::default(), + Some(engines), + ) + .await; + + json(SearchJson { + error: None, + results: Some(SearchJsonInner { + note: result.note, + query_time: result.query_time, + page_rank_time: result.page_rank_time, + max_relevance: result.max_relevance, + search_results: result.search_results, + blocked: result + .blocked + .into_iter() + .map(|(url, reason)| BlockedResult { url, reason }) + .collect(), + }), + }) + } else { + error_response("not authenticated") + } +} + +#[derive(Template)] +#[template(path = "image_search.html")] +pub struct ImageSearchTemplate { + pub info: UserInfo, + pub error: Option, + pub note: Option, + pub search_query: String, + pub search_results: Vec, + pub blocked: Vec<(String, String)>, + pub websearch_url: String, + pub imagesearch_url: String, + pub version: String, + pub git_commit: String, + pub built_on: String, + pub year: String, + pub alpha: bool, + pub theme: String, +} +pub async fn image_search( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + fn error_response(query: String, info: UserInfo, error: &str) -> ImageSearchTemplate { + let theme = info.theme.clone(); + let querystr = url_encoded_data::stringify(&[("q", query.as_str())]); + ImageSearchTemplate { + info, + error: Some(format!( + "internal server error ({})! report to developers (:", + error + )), + note: None, + search_query: query, + search_results: vec![], + blocked: vec![], + websearch_url: format!("/ask?{querystr}&js=0"), + imagesearch_url: format!("/ask?{querystr}&js=0&stype=image"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } + } + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return ( + jar.remove("token"), + frontpage_error(e.as_str(), opts.auth_url.clone()), + ) + .into_response(); + } + }; + let query = params.get("q").unwrap_or(&"Deez".to_string()).to_string(); + let js = params.get("js").unwrap_or(&"0".to_string()).to_string(); + let engines = params + .get("engines") + .unwrap_or(&"bing,google".to_string()) + .to_string(); + let engines = engines + .split(",") + .map(|v| v.to_string()) + .collect::>(); + + gather_image_results(nats, &query, info, Some(engines), js == "1") + .await + .into_response() + } else { + Redirect::to("/").into_response() + } +} + +pub async fn image_proxy( + jar: CookieJar, + Query(params): Query>, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + static PROXY_TOKEN_CACHE: RwLock> = RwLock::const_new(BTreeSet::new()); + static IMAGE_CACHE: RwLock>> = RwLock::const_new(BTreeMap::new()); + const TOKEN_CACHE_TTL_MINS: u64 = 10; + const IMAGE_CACHE_TTL_MINS: u64 = 10; + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let mut authenticated = false; + { + let cache = PROXY_TOKEN_CACHE.read().await; + authenticated = cache.contains(&token); + } + if !authenticated { + let _info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return StatusCode::UNAUTHORIZED.into_response(); + } + }; + { + let mut cache = PROXY_TOKEN_CACHE.write().await; + cache.insert(token.clone()); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(TOKEN_CACHE_TTL_MINS * 60)).await; + let mut cache = PROXY_TOKEN_CACHE.write().await; + cache.remove(&token); + }); + } + authenticated = true; + } + if !authenticated { + return StatusCode::UNAUTHORIZED.into_response(); + } + use isahc::prelude::*; + let url = params.get("url"); + if url.is_none() { + return StatusCode::BAD_REQUEST.into_response(); + } + let mut url = url.unwrap().to_string(); + + let mut host = url.split("://"); + let host = host.nth(1).unwrap_or(&url); + // fixme: we really need a better solution + const BLOCKED_HOSTS: &[&str] = &[ + "0", + "10", + "100.6", + "100.7", + "100.8", + "100.9", + "100.10", + "100.11", + "100.12", + "127", + "169.254", + "172.1", + "172.2", + "172.30", + "172.31", + "192.168", + "198.18", + "198.19", + "localhost", + ]; + for blocked in BLOCKED_HOSTS { + if host.starts_with(blocked) { + return StatusCode::NO_CONTENT.into_response(); + } + } + + if !(url.starts_with("http://") || url.starts_with("https://")) { + url.insert_str(0, "http://"); + } + // fixme: replace with actual smart encoding system + url = url.replace(" ", "%20"); + + { + let cache = IMAGE_CACHE.read().await; + if let Some(cached_image) = cache.get(&url).cloned() { + return cached_image.into_response(); + } + } + + let response = isahc::Request::get(url.clone()) + .ip_version(IpVersion::V4) + .header("user-agent", "AskLyphe Image Proxy (+https://asklyphe.com)") + .timeout(Duration::from_secs(10)) + .redirect_policy(RedirectPolicy::Limit(6)) + .body(()) + .unwrap() + .send_async() + .await; + if response.is_err() { + return StatusCode::NO_CONTENT.into_response(); + } + let mut response = response.unwrap(); + let data = response.bytes().await; + if data.is_err() { + return StatusCode::NO_CONTENT.into_response(); + } + let data = data.unwrap(); + const MAX_IMAGE_SIZE_IN_CACHE_MB: usize = 512; + if !data.is_empty() && data.len() < MAX_IMAGE_SIZE_IN_CACHE_MB * 1024 * 1024 { + let mut cache = IMAGE_CACHE.write().await; + const MAX_CACHE_SIZE_GB: usize = 10; + const MAX_CACHE_SIZE_MB: usize = MAX_CACHE_SIZE_GB * 1024 * 1024; + const MAX_CACHE_ENTRIES: usize = + MAX_CACHE_SIZE_MB / MAX_IMAGE_SIZE_IN_CACHE_MB; + if cache.len() < MAX_CACHE_ENTRIES { + cache.insert(url.clone(), data.clone()); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(IMAGE_CACHE_TTL_MINS * 60)).await; + let mut cache = IMAGE_CACHE.write().await; + cache.remove(&url); + }); + } + } + data.into_response() + } else { + StatusCode::UNAUTHORIZED.into_response() + } +} diff --git a/asklyphe-frontend/src/routes/semaphore.rs b/asklyphe-frontend/src/routes/semaphore.rs new file mode 100644 index 0000000..b20c3b9 --- /dev/null +++ b/asklyphe-frontend/src/routes/semaphore.rs @@ -0,0 +1,42 @@ +/* + * asklyphe-frontend routes/semaphore.rs + * - communication between asklyphe-frontend and asklyphe-auth-frontend + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use axum::extract::Query; +use axum::response::{IntoResponse, Redirect}; +use axum_extra::extract::cookie::{Cookie, Expiration, SameSite}; +use axum_extra::extract::CookieJar; +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +pub struct SemaphoreQuery { + one_time_token: Option, +} + +pub async fn semaphore( + jar: CookieJar, + Query(params): Query, +) -> impl IntoResponse { + if params.one_time_token.is_none() { + return Redirect::to("/").into_response(); + } + let ott = params.one_time_token.unwrap(); + (jar.add(Cookie::build(("token", ott)) + .permanent() + .max_age(time::Duration::days(30)) + .secure(true) + .http_only(true) + // we can "safely" set lax because anything that could mess up stuff should be behind post requests with tokens + .same_site(SameSite::Lax) + .build() + ), Redirect::to("/")).into_response() +} diff --git a/asklyphe-frontend/src/routes/user_settings.rs b/asklyphe-frontend/src/routes/user_settings.rs new file mode 100644 index 0000000..df53dee --- /dev/null +++ b/asklyphe-frontend/src/routes/user_settings.rs @@ -0,0 +1,203 @@ +/* + * asklyphe-frontend routes/user_settings.rs + * - http routes for the settings page + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use askama::Template; +use askama_axum::IntoResponse; +use asklyphe_common::nats::authservice::{AuthError, AuthRequest, AuthResponse, AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, LogoutRequest, LogoutResponse}; +use asklyphe_common::nats::authservice::profile::{ThemeChangeRequest, ThemeChangeResponse, UserInfoRequest, UserInfoResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::{ServiceError, ServiceResponse}; +use async_nats::jetstream; +use axum::{Extension, Form}; +use axum::response::Redirect; +use axum_extra::extract::CookieJar; +use serde::Deserialize; +use tokio::sync::Mutex; +use tracing::error; +use crate::{BUILT_ON, GIT_COMMIT, Opts, ALPHA, VERSION, WEBSITE_COUNT, YEAR}; +use crate::routes::{authenticate_user, UserInfo}; + +pub struct Theme<'a> { + pub value: &'a str, + pub name: &'a str, +} + +pub static THEMES: &[Theme] = &[ + Theme { + value: "default", + name: "default theme", + }, + Theme { + value: "dark", + name: "dark theme", + }, + Theme { + value: "oled", + name: "lights out", + }, + Theme { + value: "classic", + name: "classic", + }, + Theme { + value: "freaky", + name: "freaky", + }, + Theme { + value: "water", + name: "water", + }, + Theme { + value: "gloss", + name: "gloss", + }, +]; + +#[derive(Template)] +#[template(path = "user_settings.html")] +pub struct SettingsTemplate { + themes: &'static [Theme<'static>], + + error: Option, + + info: UserInfo, + search_query: String, + version: String, + git_commit: String, + built_on: String, + year: String, + alpha: bool, + count: u64, + theme: String, +} + +pub async fn user_settings( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, +) -> impl IntoResponse { + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token).await { + Ok(i) => i, + Err(e) => { + return (jar.remove("token"), crate::routes::index::frontpage_error(e.as_str(), opts.auth_url.clone())).into_response(); + } + }; + let theme = info.theme.clone(); + SettingsTemplate { + themes: THEMES, + error: None, + info, + search_query: "".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme, + }.into_response() + } else { + Redirect::temporary("/").into_response() + } +} + +#[derive(Deserialize, Debug)] +pub struct ThemeChangeForm { + pub theme: Option, +} + +pub async fn theme_change_post( + jar: CookieJar, + Extension(nats): Extension>, + Extension(opts): Extension, + Form(input): Form, +) -> impl IntoResponse { + fn settings_error(info: UserInfo, theme: String, error: String) -> impl IntoResponse { + SettingsTemplate { + themes: THEMES, + error: Some(error), + info, + search_query: "".to_string(), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + count: WEBSITE_COUNT.load(Ordering::Relaxed), + theme, + }.into_response() + } + + if let Some(token) = jar.get("token") { + let token = token.value().to_string(); + let info = match authenticate_user(nats.clone(), token.clone()).await { + Ok(i) => i, + Err(e) => { + return (jar.remove("token"), crate::routes::index::frontpage_error(e.as_str(), opts.auth_url.clone())).into_response(); + } + }; + + let theme = info.theme.clone(); + + if !THEMES.iter().map(|v| v.value.to_string()).collect::>().contains(&input.theme.clone().unwrap_or("default".to_string())) { + return settings_error(info, theme, "invalid input, please try again!".to_string()).into_response(); + } + + let response = comms::query_service(comms::Query::AuthService(AuthServiceQuery { + request: AuthServiceRequest::ThemeChangeRequest(ThemeChangeRequest { + token, + theme: input.theme.unwrap_or("default".to_string()), + }), + replyto: "".to_string(), + }), &nats, false).await; + if let Err(e) = response { + error!("nats error: {:?}", e); + settings_error(info, theme, "internal server error occurred! if the error persists, contact a developer!".to_string()).into_response() + } else { + let response = response.unwrap(); + match response { + ServiceResponse::AuthService(r) => { + match r { + AuthServiceResponse::ThemeChangeResponse(r) => { + match r { + ThemeChangeResponse::Success => { + Redirect::to("/user_settings").into_response() + } + ThemeChangeResponse::Logout => { + (jar.remove("token"), crate::routes::index::frontpage_error("your session token was invalid, please try logging in again", opts.auth_url.clone())).into_response() + } + ThemeChangeResponse::InternalServerError => { + settings_error(info, theme, "internal server error occurred! if the error persists, contact a developer!".to_string()).into_response() + } + } + } + x => { + error!("ERROR! RECV WRONG AUTHSERVICE RESPONSE WHEN ASKING FOR THEME CHANGE! INVESTIGATE ASAP! {x}"); + settings_error(info, theme, "internal server error occurred! if the error persists, contact a developer!".to_string()).into_response() + } + } + } + x => { + error!("ERROR! RECV WRONG SERVICE RESPONSE WHEN ASKING AUTHSERVICE! INVESTIGATE ASAP!"); + settings_error(info, theme, "internal server error occurred! if the error persists, contact a developer!".to_string()).into_response() + } + } + } + } else { + Redirect::to("/").into_response() + } +} \ No newline at end of file diff --git a/asklyphe-frontend/src/searchbot.rs b/asklyphe-frontend/src/searchbot.rs new file mode 100644 index 0000000..ca43ef9 --- /dev/null +++ b/asklyphe-frontend/src/searchbot.rs @@ -0,0 +1,509 @@ +/* + * asklyphe-frontend searchbot.rs + * - commonly used functions for querying the searchservice + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Deref; +use std::sync::Arc; +use std::sync::atomic::Ordering; +use asklyphe_common::nats; +use asklyphe_common::nats::bingservice::{BingServiceQuery, BingServiceRequest, BingServiceResponse}; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::searchservice::{SearchSrvcQuery, SearchSrvcRequest, SearchSrvcResponse}; +use async_nats::jetstream; +use async_nats::jetstream::consumer::PullConsumer; +use async_nats::jetstream::stream::RetentionPolicy; +use futures::StreamExt; +use tokio::sync::Mutex; +use tracing::log::error; +use tracing::warn; +use ulid::Ulid; +use crate::routes::search::{Complications, ImageSearchResult, ImageSearchTemplate, SearchResult, SearchTemplate}; +use crate::routes::UserInfo; +use crate::{BUILT_ON, GIT_COMMIT, ALPHA, VERSION, WEBSITE_COUNT, YEAR}; + +pub async fn update_website_counter(nats: Arc) { + let result = comms::query_service(comms::Query::SearchService(SearchSrvcQuery { + request: SearchSrvcRequest::SiteCountRequest, + replyto: "".to_string(), + }), nats.deref(), false).await; + + if let Ok(comms::ServiceResponse::SearchService(result)) = result { + match result { + SearchSrvcResponse::OtherError(e) => { + warn!("received error while asking for website count {e}"); + } + SearchSrvcResponse::SiteCountResponse(count) => { + WEBSITE_COUNT.store(count.count, Ordering::Relaxed); + } + _ => { + warn!("received invalid response while asking for website count"); + } + } + } +} + +pub async fn gather_search_results(nats: Arc, query: &str, user_info: UserInfo, complications: Complications, engines: Option>) -> SearchTemplate { + let mut search_results = vec![]; + let mut note = None; + + let asklyphe = if let Some(engines) = &engines { engines.contains(&"asklyphe".to_string()) } else { true }; + let bing = if let Some(engines) = &engines { engines.contains(&"bing".to_string()) } else { true }; + let google = if let Some(engines) = &engines { engines.contains(&"google".to_string()) } else { true }; + + // bing + + if bing { + let result = comms::query_service(comms::Query::BingService(BingServiceQuery { + request: BingServiceRequest::SearchRequest(nats::bingservice::BingSearchRequest { + query: query.to_lowercase(), + }), + replyto: "".to_string(), + }), nats.deref(), true).await; + + if let Ok(comms::ServiceResponse::BingService(result)) = result { + match result { + BingServiceResponse::InvalidRequest => { + note = Some("invalid request! report to developers!".to_string()); + } + BingServiceResponse::OtherError(e) => { + error!("bing service gave unknown error {e}!!"); + note = Some("internal server error! report to developers!".to_string()); + } + BingServiceResponse::SearchResponse(results) => { + let result_count = results.results.len(); + + search_results.extend(results.results.into_iter().enumerate().map(|(i, v)| { + const MAX_LENGTH: usize = 800; + const MAX_URL_LENGTH: usize = 100; + SearchResult { + url: v.url, + title: v.title.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_URL_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_URL_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + description: v.description.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + percentage: format!("{:.2}", ((1.0 - (i as f64 / result_count as f64)) * 50.0) + 40.0), + value: format!("{}", i), + asklyphe: false, + bing: true, + google: false, + } + })); + } + BingServiceResponse::ImageResponse(_) => { + error!("bing service gave image response to search request!!"); + note = Some("internal server error! report to developers!".to_string()); + } + } + } + } + + // google + + if google { + let result = comms::query_service(comms::Query::GoogleService(BingServiceQuery { + request: BingServiceRequest::SearchRequest(nats::bingservice::BingSearchRequest { + query: query.to_lowercase(), + }), + replyto: "".to_string(), + }), nats.deref(), true).await; + + if let Ok(comms::ServiceResponse::BingService(result)) = result { + match result { + BingServiceResponse::InvalidRequest => { + note = Some("invalid request! report to developers!".to_string()); + } + BingServiceResponse::OtherError(e) => { + error!("google service gave unknown error {e}!!"); + note = Some("internal server error! report to developers!".to_string()); + } + BingServiceResponse::SearchResponse(results) => { + let result_count = results.results.len(); + + search_results.extend(results.results.into_iter().enumerate().map(|(i, v)| { + const MAX_LENGTH: usize = 800; + const MAX_URL_LENGTH: usize = 100; + SearchResult { + url: v.url, + title: v.title.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_URL_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_URL_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + description: v.description.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + percentage: format!("{:.2}", ((1.0 - (i as f64 / result_count as f64)) * 50.0) + 40.0), + value: format!("{}", i), + asklyphe: false, + bing: false, + google: true, + } + })); + } + BingServiceResponse::ImageResponse(_) => { + error!("google service gave image response to search request!!"); + note = Some("internal server error! report to developers!".to_string()); + } + } + } + } + + // raw lyphe + let mut query_time = 0.0; + let mut page_rank_time = 0.0; + let mut max_relevance = 0.0; + let mut blocked = vec![]; + + if asklyphe { + let result = comms::query_service(comms::Query::SearchService(SearchSrvcQuery { + request: SearchSrvcRequest::SearchRequest(nats::searchservice::SearchRequest { + query: query.to_lowercase(), + }), + replyto: "".to_string(), + }), nats.deref(), true).await; + + + if let Ok(comms::ServiceResponse::SearchService(result)) = result { + match result { + SearchSrvcResponse::InvalidRequest => { + note = Some("invalid request! report to developers!".to_string()); + } + SearchSrvcResponse::OtherError(e) => { + error!("search service gave unknown error {e}!!"); + note = Some("unknown error! report to developers!".to_string()); + } + SearchSrvcResponse::SearchResponse(results) => { + if note.is_none() { + note = if !results.exact_phrase_found { + Some("didn't find exact phrase, returning sites containing requested words".to_string()) + } else { + None + }; + } + + query_time = results.total_query_seconds; + page_rank_time = results.pagerank_time_seconds; + max_relevance = results.max_relevance; + + blocked = results.blocked; + + search_results.extend(results.results.into_iter().map(|v| { + const MAX_LENGTH: usize = 800; + const MAX_URL_LENGTH: usize = 100; + SearchResult { + title: v.title.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_URL_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_URL_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + description: v.description.map(|v| { + let initial = html_escape::decode_html_entities(&v).to_string(); + let mut shortened = String::new(); + if initial.len() > MAX_LENGTH { + for (i, c) in initial.chars().enumerate() { + shortened.push(c); + if i > MAX_LENGTH { + break; + } + } + shortened.push_str("..."); + } else { + shortened = initial; + } + shortened + }), + url: v.url, + percentage: format!("{:.2}", (v.relevance / results.max_relevance) * 100.0), + value: format!("{:.2}", v.relevance), + asklyphe: true, + bing: false, + google: false, + } + })); + } + _ => { + note = Some("bad response! report to developers!".to_string()); + } + } + } else { + note = Some("unknown! report to developers!".to_string()); + } + } + + search_results.sort_by(|a, b| { + b.percentage.parse::().unwrap().total_cmp(&a.percentage.parse::().unwrap()) + }); + + let mut already_included = BTreeMap::new(); + + let mut remove = vec![]; + + let mut add_bing = vec![]; + let mut add_google = vec![]; + + for (i, result) in search_results.iter().enumerate() { + let mut trimmed_url = result.url.clone(); + trimmed_url = trimmed_url.trim_end_matches('/').to_string(); + if already_included.contains_key(&trimmed_url) && !result.asklyphe { + remove.push(i); + let main = already_included.get(&trimmed_url).unwrap(); + if result.bing { + add_bing.push(*main); + } + if result.google { + add_google.push(*main); + } + } + already_included.insert(trimmed_url, i); + } + + for i in add_bing { + search_results[i].bing = true; + } + for i in add_google { + search_results[i].google = true; + } + + for (i, rm) in remove.into_iter().enumerate() { + search_results.remove(rm - i); + } + + let theme = user_info.theme.clone(); + let querystr = url_encoded_data::stringify(&[("q", query)]); + SearchTemplate { + info: user_info, + error: None, + note, + complications, + search_query: query.to_string(), + query_time, + page_rank_time, + max_relevance: format!("{:.2}", max_relevance), + search_results, + blocked, + websearch_url: format!("/ask?{querystr}&js=0"), + imagesearch_url: format!("/ask?{querystr}&js=0&stype=image"), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } +} + +pub async fn gather_image_results(nats: Arc, query: &str, user_info: UserInfo, engines: Option>, js: bool) -> ImageSearchTemplate { + let mut search_results = vec![]; + let mut note = None; + + let bing = if let Some(engines) = &engines { engines.contains(&"bing".to_string()) } else { true }; + let google = if let Some(engines) = &engines { engines.contains(&"google".to_string()) } else { true }; + + // google + + if google { + let result = comms::query_service(comms::Query::GoogleService(BingServiceQuery { + request: BingServiceRequest::ImageRequest(nats::bingservice::BingImageRequest { + query: query.to_lowercase(), + }), + replyto: "".to_string(), + }), nats.deref(), true).await; + + if let Ok(comms::ServiceResponse::BingService(result)) = result { + match result { + BingServiceResponse::InvalidRequest => { + note = Some("invalid request! report to developers!".to_string()); + } + BingServiceResponse::OtherError(e) => { + error!("google service gave unknown error {e}!!"); + note = Some("internal server error! report to developers!".to_string()); + } + BingServiceResponse::ImageResponse(results) => { + search_results.extend(results.into_iter().enumerate().map(|(i, v)| { + const MAX_LENGTH: usize = 800; + const MAX_URL_LENGTH: usize = 100; + ImageSearchResult { + src: v.url.clone(), + url: v.url, + bing: false, + google: true, + } + })); + } + BingServiceResponse::SearchResponse(_) => { + error!("google service gave search response for image response!!"); + note = Some("internal server error! report to developers!".to_string()); + } + } + } + } + + // bing + + if bing { + let result = comms::query_service(comms::Query::BingService(BingServiceQuery { + request: BingServiceRequest::ImageRequest(nats::bingservice::BingImageRequest { + query: query.to_lowercase(), + }), + replyto: "".to_string(), + }), nats.deref(), true).await; + + if let Ok(comms::ServiceResponse::BingService(result)) = result { + match result { + BingServiceResponse::InvalidRequest => { + note = Some("invalid request! report to developers!".to_string()); + } + BingServiceResponse::OtherError(e) => { + error!("bing service gave unknown error {e}!!"); + note = Some("internal server error! report to developers!".to_string()); + } + BingServiceResponse::ImageResponse(results) => { + search_results.extend(results.into_iter().enumerate().map(|(i, v)| { + const MAX_LENGTH: usize = 800; + const MAX_URL_LENGTH: usize = 100; + ImageSearchResult { + src: v.url.clone(), + url: v.url, + bing: true, + google: false, + } + })); + } + BingServiceResponse::SearchResponse(_) => { + error!("bing service gave search response for image response!!"); + note = Some("internal server error! report to developers!".to_string()); + } + } + } + } + + let mut already_included = BTreeMap::new(); + + let mut remove = vec![]; + + let mut add_bing = vec![]; + let mut add_google = vec![]; + + for (i, result) in search_results.iter().enumerate() { + let mut trimmed_url = result.url.clone(); + trimmed_url = trimmed_url.trim_end_matches('/').to_string(); + if already_included.contains_key(&trimmed_url) { + remove.push(i); + let main = already_included.get(&trimmed_url).unwrap(); + if result.bing { + add_bing.push(*main); + } + if result.google { + add_google.push(*main); + } + } + already_included.insert(trimmed_url, i); + } + + for i in add_bing { + search_results[i].bing = true; + } + for i in add_google { + search_results[i].google = true; + } + + for (i, rm) in remove.into_iter().enumerate() { + search_results.remove(rm - i); + } + + for result in &mut search_results { + let url = url_encoded_data::stringify(&[("url", &result.url)]); + result.src = format!("/imgproxy?{}", url); + } + + let theme = user_info.theme.clone(); + ImageSearchTemplate { + info: user_info, + error: None, + note, + search_query: query.to_string(), + search_results, + blocked: vec![], + websearch_url: format!("/ask?q={query}&js={}", if js { 1 } else { 0 }), + imagesearch_url: format!("/ask?q={query}&js={}&stype=image", if js { 1 } else { 0 }), + version: VERSION.to_string(), + git_commit: GIT_COMMIT.to_string(), + built_on: BUILT_ON.to_string(), + year: YEAR.to_string(), + alpha: ALPHA, + theme, + } +} diff --git a/asklyphe-frontend/src/unit_converter.rs b/asklyphe-frontend/src/unit_converter.rs new file mode 100644 index 0000000..68f1a1c --- /dev/null +++ b/asklyphe-frontend/src/unit_converter.rs @@ -0,0 +1,59 @@ +/* + * asklyphe-frontend unit_converter.rs + * - wrapper for the unit converter library + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::str::FromStr; +use unit_converter::length_units::{LengthUnit, LENGTH_NAMES}; +use unit_converter::unit_defs::{BestUnit, ConvertTo, FromUnitName, UnitName}; +use unit_converter::{parse_number, remove_leading_conversion_word}; + +#[derive(Clone, Debug)] +pub struct UnitConversion { + pub value: String, + pub unit_a: String, + pub equals: String, + pub unit_b: String, +} + +pub fn convert_unit(query_text: &str) -> Option { + let (number, remainder) = parse_number(query_text); + if number.is_nan() { + return None; + } + let og_number = number.clone(); + let unit = LengthUnit::parse(remainder); + unit.as_ref()?; + let (unit_a, remainder) = unit.unwrap(); + let remainder = remove_leading_conversion_word(&remainder); + if let Some((unit_b, _)) = LengthUnit::parse(remainder) { + let conversion = unit_a.convert_to(number, unit_b); + let approx = f64::from_str(&format!("{}", conversion)).unwrap(); + let approx_og = f64::from_str(&format!("{}", og_number)).unwrap(); + Some(UnitConversion { + value: format!("{}", approx_og), + unit_a: unit_a.unit_name(og_number), + equals: format!("{}", approx), + unit_b: unit_b.unit_name(conversion), + }) + } else { + let best_unit = LengthUnit::best_unit(unit_a, number.clone()); + let conversion = unit_a.convert_to(number, best_unit); + let approx = f64::from_str(&format!("{}", conversion)).unwrap(); + let approx_og = f64::from_str(&format!("{}", og_number)).unwrap(); + Some(UnitConversion { + value: format!("{}", approx_og), + unit_a: unit_a.unit_name(og_number), + equals: format!("{}", approx), + unit_b: best_unit.unit_name(conversion), + }) + } +} diff --git a/asklyphe-frontend/src/wikipedia.rs b/asklyphe-frontend/src/wikipedia.rs new file mode 100644 index 0000000..f1430af --- /dev/null +++ b/asklyphe-frontend/src/wikipedia.rs @@ -0,0 +1,152 @@ +/* + * asklyphe-frontend wikipedia.rs + * - wikipedia helper functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::Mutex; +use std::time::Duration; +use isahc::auth::Authentication; +use isahc::config::RedirectPolicy; +use isahc::{HttpClient, Request}; +use isahc::prelude::*; +use once_cell::sync::Lazy; +use serde::Deserialize; +use tracing::{error, warn}; + +#[derive(Clone, Debug, Deserialize)] +pub struct WikipediaPage { + pub title: String, + pub description: String, + pub extract: String, + pub thumbnail: Option, + pub content_urls: WikipediaContentUrls, +} +#[derive(Clone, Debug, Deserialize)] +pub struct WikipediaThumbnail { + pub source: Option, +} +#[derive(Clone, Debug, Deserialize)] +pub struct WikipediaContentUrls { + pub desktop: WikipediaUrls, +} +#[derive(Clone, Debug, Deserialize)] +pub struct WikipediaUrls { + pub page: String, +} + + + +pub static USER_AGENT: Lazy = Lazy::new(|| format!("AskLyphe/{} (https://asklyphe.com; nikocs@voremicrocomputers.com)", env!("CARGO_PKG_VERSION"))); + +pub static WIKIPEDIA_CACHE: Lazy>> = Lazy::new(|| Mutex::new(BTreeMap::new())); +pub static WIKIPEDIA_TIMEOUT: AtomicI64 = AtomicI64::new(0); + +#[derive(Clone, Debug)] +pub struct WikipediaSummary { + pub title: String, + pub description: String, + pub extract: String, + pub image: Option, + pub url: String, +} + +pub async fn get_wikipedia_page(query_text: &str, timeout_secs: u64) -> Option { + if let Some(cached) = { + let cache = WIKIPEDIA_CACHE.lock().unwrap(); + cache.get(query_text).cloned() + } { + let compare = "may refer to:"; + if cached.extract.ends_with(compare) { + return None; + } + Some(cached) + } else { + if WIKIPEDIA_TIMEOUT.load(Ordering::Relaxed) > 0 { + if WIKIPEDIA_TIMEOUT.load(Ordering::Relaxed) > chrono::Utc::now().timestamp() { + return None; + } else { + WIKIPEDIA_TIMEOUT.store(0, Ordering::Relaxed); + } + } + + let url = format!( + r#"https://en.wikipedia.org/api/rest_v1/page/summary/{}?redirect=true"#, query_text); + + let client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)) + .timeout(Duration::from_secs(timeout_secs)) + .build(); + if let Err(e) = client { + error!("failed to build client for fetching wikipedia: {e}"); + return None; + } + let client = client.unwrap(); + let request = Request::get(url.clone()) + .header("user-agent", USER_AGENT.as_str()) + .header("accept", "*/*") + .body(()); + if let Err(e) = request { + error!("failed to fetch wikipedia api: {e}"); + return None; + } + let request = request.unwrap(); + let response = client.send_async(request).await; + if let Err(e) = response { + error!("failed to fetch wikipedia api: {e}"); + return None; + } + let mut response = response.unwrap(); + if response.status() != 200 && response.status() != 302 { + return None; + } + let body = response.text().await; + if let Err(e) = body { + error!("failed to fetch wikipedia api: {e}"); + return None; + } + let body = body.unwrap(); + let wikiresult = serde_json::from_str::(&body); + if let Err(e) = wikiresult { + error!("failed to deserialise wikipedia api: {e}"); + return None; + } + let wikiresult = wikiresult.unwrap(); + let mut wiki = WikipediaSummary { + title: wikiresult.title.clone(), + description: wikiresult.description.clone(), + extract: wikiresult.extract.clone(), + image: None, + url: wikiresult.content_urls.desktop.page.clone(), + }; + let compare = "may refer to:"; + if wiki.extract.ends_with(compare) { + WIKIPEDIA_CACHE.lock().unwrap().insert(query_text.to_string(), wiki.clone()); + return None; + } + const MAX_LENGTH: usize = 800; + if wiki.description.len() > MAX_LENGTH { + let mut shortened = String::new(); + for (i, c) in wiki.description.chars().enumerate() { + shortened.push(c); + if i > MAX_LENGTH { + break; + } + } + shortened.push_str("..."); + wiki.description = shortened; + } + wiki.image = wikiresult.thumbnail.as_ref().and_then(|v| v.source.clone()); + WIKIPEDIA_CACHE.lock().unwrap().insert(query_text.to_string(), wiki.clone()); + Some(wiki) + } +} \ No newline at end of file diff --git a/asklyphe-frontend/static/admin/css/shell.css b/asklyphe-frontend/static/admin/css/shell.css new file mode 100644 index 0000000..7257d36 --- /dev/null +++ b/asklyphe-frontend/static/admin/css/shell.css @@ -0,0 +1,166 @@ +* { + transition: inherit; +} + +body { + background-image: url("/static/admin/img/bg.png"); + padding: 0; + margin: 0; +} + +#header { + background-image: url("/static/admin/img/bg.png"); + margin: 0; + padding: 10px; + height: 200px; +} + +#header > img { + float: left; + max-height: 200px; +} + +#content-area { + display: flex; + flex-direction: row; + margin: auto; +} + +#navbar { + box-shadow: inset 6px 6px 6px -6px rgba(0, 0, 0, 0.6); + border-right: 1px solid #6f6f6f; + border-bottom: 1px solid #6f6f6f; + width: 320px; + min-height: 100vh; + background-color: #e5e5e5; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; +} + +#navbar > a { + display: block; + background-image: url("/static/admin/img/column/bg.png"); + color: black; + margin: 0; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); + border-radius: 0; + border: 1px solid #6f6f6f; + border-right: none; + min-height: 20px; + padding: 3px 10px; + font-size: 16px; + transition: all 0.2s linear; + font-weight: normal; +} + +#navbar > a:first-child { + box-shadow: inset 0 6px 6px -6px rgba(0, 0, 0, 0.6); +} + +#navbar > a:hover { + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); +} + +#navbar > a:active { + background: url("/static/admin/img/column/bg_clicked.png"); + color: #474747; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.6); +} + +a, button { + text-decoration: none; + color: inherit; + background-image: url("/static/admin/img/button/bg.png"); + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8); + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.6); + color: white; + min-height: 20px; + border: 1px solid #56929f; + border-radius: 10px; + padding: 3px 10px; + margin: 3px; + font-size: 16px; + transition: all 0.2s linear; + font-family: sans-serif; + font-weight: bold; +} + +a:hover, button:hover { + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); +} + +a:active, button:active { + background-image: url("/static/admin/img/button/bg_clicked.png"); + color: #e0e0e0; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.6); +} + +input[type="text"] { + border-radius: 10px; + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.6); + min-height: 20px; + border: 1px solid #9f9f9f; + padding: 3px 10px; + margin: 3px; + font-size: 16px; + transition: all 0.2s linear; +} + +#panel-content { + background-color: #e5e5e5; + width: 100%; + box-shadow: inset 0 0 6px 0 rgba(0, 0, 0, 0.6); + padding: 10px; +} + +form { + display: flex; + flex-direction: column; + width: 35%; +} + +table { + background-color: white; + border-spacing: 0; +} + +tbody { + margin: 0; + padding: 0; + width: 100%; +} + +th { + background-image: url("/static/admin/img/column/bg.png"); + margin: 0; + border: 1px solid #6f6f6f; + border-right: none; + border-radius: 0; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); + box-shadow: inset 0 6px 6px -6px rgba(0, 0, 0, 0.6); + padding: 3px 10px; +} + +th:last-child { + border-right: 1px solid #6f6f6f; +} + +td { + border: 1px solid #6f6f6f; + border-right: none; + border-top: none; +} + +td:last-child { + border-right: 1px solid #6f6f6f; +} + +tr:nth-child(odd) { + background-color: rgba(150, 212, 212, 0.2); +} + +tr:nth-child(odd),td:nth-child(even) { + background-color: rgba(150, 212, 212, 0.2); +} diff --git a/asklyphe-frontend/static/admin/img/bg.png b/asklyphe-frontend/static/admin/img/bg.png new file mode 100644 index 0000000..1e1a9af Binary files /dev/null and b/asklyphe-frontend/static/admin/img/bg.png differ diff --git a/asklyphe-frontend/static/admin/img/button/bg.png b/asklyphe-frontend/static/admin/img/button/bg.png new file mode 100644 index 0000000..c4dea4e Binary files /dev/null and b/asklyphe-frontend/static/admin/img/button/bg.png differ diff --git a/asklyphe-frontend/static/admin/img/button/bg_clicked.png b/asklyphe-frontend/static/admin/img/button/bg_clicked.png new file mode 100644 index 0000000..73a52a3 Binary files /dev/null and b/asklyphe-frontend/static/admin/img/button/bg_clicked.png differ diff --git a/asklyphe-frontend/static/admin/img/column/bg.png b/asklyphe-frontend/static/admin/img/column/bg.png new file mode 100644 index 0000000..f5a6da3 Binary files /dev/null and b/asklyphe-frontend/static/admin/img/column/bg.png differ diff --git a/asklyphe-frontend/static/admin/img/column/bg_clicked.png b/asklyphe-frontend/static/admin/img/column/bg_clicked.png new file mode 100644 index 0000000..2e8003b Binary files /dev/null and b/asklyphe-frontend/static/admin/img/column/bg_clicked.png differ diff --git a/asklyphe-frontend/static/admin/logo.png b/asklyphe-frontend/static/admin/logo.png new file mode 100644 index 0000000..8469499 Binary files /dev/null and b/asklyphe-frontend/static/admin/logo.png differ diff --git a/asklyphe-frontend/static/bluestars.gif b/asklyphe-frontend/static/bluestars.gif new file mode 100644 index 0000000..9ddb845 Binary files /dev/null and b/asklyphe-frontend/static/bluestars.gif differ diff --git a/asklyphe-frontend/static/creature.css b/asklyphe-frontend/static/creature.css new file mode 100644 index 0000000..823e4c4 --- /dev/null +++ b/asklyphe-frontend/static/creature.css @@ -0,0 +1,4 @@ +.response { + background: url("/static/img/creature.png"); + background-size: 128px 128px; +} diff --git a/asklyphe-frontend/static/docs/about/index.html b/asklyphe-frontend/static/docs/about/index.html new file mode 100644 index 0000000..84a2e10 --- /dev/null +++ b/asklyphe-frontend/static/docs/about/index.html @@ -0,0 +1,66 @@ + + + + + AskLyphe Docs - About + + + + +
+ WARNING! askLyphe is in pre-alpha! user experience is in no way representative of the final product! + +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+ back +

about askLyphe and its creators

+ +

+ askLyphe is a search engine currently being developed by the Vore Microcomputers Team at + Real Microsoft, LLC. (not affiliated with the Microsoft Corporation or its products). + this currently consists of Niko Viau-Chow-Stuart, as well as our volunteers. +

+
+
+

+ our goal is to create a search engine that is fast, accurate, and ad-free; while also being + well-built with features that we find useful, and with leadership that both respects its users and + supports the safety of the people that made it possible. +

+

+ in order to follow these goals, Real Microsoft, LLC will never accept investments, + VC funding, or any income beyond that earned through profit and donations. +

+

+ we will strive to keep these goals and values as the foundation of our company til either the day + that the downfall of capitalism removes the need for us to run a company in order to make the IRS + happy; or when microsoft sues us out of existence. +

+ +

pricing and availability

+

+ currently, askLyphe is only available to those who have been given invite codes. we are planning on + soon allowing our liberapay donators to get free invite codes, and in the future switch to a public + subscription model (with all previous users getting free lifetime access). +

+

+ our plan for pricing in the future is probably around $5USD a month. no particular reason, it just + seems like a good number (: we may change it in the future. +

+
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/docs/complications/index.html b/asklyphe-frontend/static/docs/complications/index.html new file mode 100644 index 0000000..395867e --- /dev/null +++ b/asklyphe-frontend/static/docs/complications/index.html @@ -0,0 +1,60 @@ + + + + + AskLyphe Docs - Complications + + + + +
+ WARNING! askLyphe is in pre-alpha! user experience is in no way representative of the final product! + +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+ back +

complications guide / info

+ +

+ complications are the little panels that show up on certain searches. + some examples are the wikipedia complication, which will show you wikipedia results + for searches that result in wikipedia pages; or the unit converter complication, which will + attempt to convert units when given a query such as "5 km to miles". +

+
+
+

+ we currently have only implemented the wikipedia and unit converter complications, we plan to add + more in the future but for now this is all. furthermore, the unit converter complication only + currently supports length units. +

+
+
+

+ an additional note on the unit converter is that it, if given a single unit such as "5km", will + attempt to automatically find the simplest alternate unit to represent the value as. +

+
+
+

+ you can disable complications by adding "-complications" to your search query. in the future, this + will be a setting in your user settings area. +

+ +
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/docs/index.html b/asklyphe-frontend/static/docs/index.html new file mode 100644 index 0000000..3df33f6 --- /dev/null +++ b/asklyphe-frontend/static/docs/index.html @@ -0,0 +1,52 @@ + + + + + AskLyphe Docs - Index + + + + +
+ WARNING! askLyphe is in pre-alpha! user experience is in no way representative of the final product! + +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+

askLyphe documentation

+ +

+ as askLyphe is currently in alpha, we cannot guarantee that every feature or notable + issue will be properly documented. however, we will try our best to catalog as much + as we can here. +

+
+
+

+ if you find any issues or have any suggestions, please email us at + devnull@voremicrocomputers.com. +

+ + +

table of contents

+ +
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/docs/roadmap/index.html b/asklyphe-frontend/static/docs/roadmap/index.html new file mode 100644 index 0000000..01f4b0f --- /dev/null +++ b/asklyphe-frontend/static/docs/roadmap/index.html @@ -0,0 +1,110 @@ + + + + + AskLyphe Docs - Roadmap + + + + +
+ WARNING! askLyphe is in pre-alpha! user experience is in no way representative of the final product! + +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+ back +

askLyphe development roadmap

+ +

+ this page will be used to list and categorise some present and future goals, + mainly to list features that we want to implement either soon or in the further future. +

+
+
+

+ bugs will not be listed here. for now, bugs should be reported to our email + (devnull@voremicrocomputers.com), + and once we release the source code, on our git. +

+
+
+

+ this page will likely be replaced with an actual issue tracker in the future +

+ +

+ search engine +

+
    +
  • + more backends (currently we have askLyphe and bing) +
  • +
  • + result caching; (not implemented) +
  • +
  • + search suggestions; (not implemented, needs research) +
  • +
+ +

+ complications +

+
    +
  • + calculator; (not implemented, medium priority) +
  • +
  • + stack overflow; (not implemented, low priority) +
  • +
+ +

+ unit converter +

+
    +
  • + weight units; (not implemented, medium priority) +
  • +
  • + currency; (not implemented, low priority) +
  • +
+ +

+ user backend +

+
    +
  • + automated email changes / reverification; (not implemented, high priority) +
  • +
  • + password changes; (not implemented, high priority) +
  • +
+ +

+ general +

+
    +
  • + open source (will be done after git audit for copyrighted content / private information) +
  • +
+
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/font/AtkinsonHyperlegible-Bold.ttf b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Bold.ttf new file mode 100644 index 0000000..c72b488 Binary files /dev/null and b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Bold.ttf differ diff --git a/asklyphe-frontend/static/font/AtkinsonHyperlegible-BoldItalic.ttf b/asklyphe-frontend/static/font/AtkinsonHyperlegible-BoldItalic.ttf new file mode 100644 index 0000000..ff966b1 Binary files /dev/null and b/asklyphe-frontend/static/font/AtkinsonHyperlegible-BoldItalic.ttf differ diff --git a/asklyphe-frontend/static/font/AtkinsonHyperlegible-Italic.ttf b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Italic.ttf new file mode 100644 index 0000000..1cf113a Binary files /dev/null and b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Italic.ttf differ diff --git a/asklyphe-frontend/static/font/AtkinsonHyperlegible-Regular.ttf b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Regular.ttf new file mode 100644 index 0000000..23614a4 Binary files /dev/null and b/asklyphe-frontend/static/font/AtkinsonHyperlegible-Regular.ttf differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding-Bold.ttf b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.ttf new file mode 100644 index 0000000..36bd220 Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.ttf differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff new file mode 100644 index 0000000..2f1b9cb Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff2 b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff2 new file mode 100644 index 0000000..b99441f Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding-Bold.woff2 differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding-Regular.ttf b/asklyphe-frontend/static/font/NanumGothicCoding-Regular.ttf new file mode 100644 index 0000000..990066a Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding-Regular.ttf differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding.woff b/asklyphe-frontend/static/font/NanumGothicCoding.woff new file mode 100644 index 0000000..1f26953 Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding.woff differ diff --git a/asklyphe-frontend/static/font/NanumGothicCoding.woff2 b/asklyphe-frontend/static/font/NanumGothicCoding.woff2 new file mode 100644 index 0000000..3813615 Binary files /dev/null and b/asklyphe-frontend/static/font/NanumGothicCoding.woff2 differ diff --git a/asklyphe-frontend/static/font/OFL.txt b/asklyphe-frontend/static/font/OFL.txt new file mode 100644 index 0000000..9872707 --- /dev/null +++ b/asklyphe-frontend/static/font/OFL.txt @@ -0,0 +1,97 @@ +Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com), +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver +NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver +NanumBrush, NanumPen, Naver NanumPen. + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/asklyphe-frontend/static/img/404.png b/asklyphe-frontend/static/img/404.png new file mode 100644 index 0000000..6175399 Binary files /dev/null and b/asklyphe-frontend/static/img/404.png differ diff --git a/asklyphe-frontend/static/img/announcement.png b/asklyphe-frontend/static/img/announcement.png new file mode 100644 index 0000000..e024da2 Binary files /dev/null and b/asklyphe-frontend/static/img/announcement.png differ diff --git a/asklyphe-frontend/static/img/borderbent.png b/asklyphe-frontend/static/img/borderbent.png new file mode 100644 index 0000000..bb276e6 Binary files /dev/null and b/asklyphe-frontend/static/img/borderbent.png differ diff --git a/asklyphe-frontend/static/img/button.png b/asklyphe-frontend/static/img/button.png new file mode 100644 index 0000000..ddf11c7 Binary files /dev/null and b/asklyphe-frontend/static/img/button.png differ diff --git a/asklyphe-frontend/static/img/creature.png b/asklyphe-frontend/static/img/creature.png new file mode 100644 index 0000000..45e1c01 Binary files /dev/null and b/asklyphe-frontend/static/img/creature.png differ diff --git a/asklyphe-frontend/static/img/darkened_paper.jpg b/asklyphe-frontend/static/img/darkened_paper.jpg new file mode 100644 index 0000000..b579a27 Binary files /dev/null and b/asklyphe-frontend/static/img/darkened_paper.jpg differ diff --git a/asklyphe-frontend/static/img/imagesearch.png b/asklyphe-frontend/static/img/imagesearch.png new file mode 100644 index 0000000..d92b8d3 Binary files /dev/null and b/asklyphe-frontend/static/img/imagesearch.png differ diff --git a/asklyphe-frontend/static/img/imagesearch_selected.png b/asklyphe-frontend/static/img/imagesearch_selected.png new file mode 100644 index 0000000..ec078b9 Binary files /dev/null and b/asklyphe-frontend/static/img/imagesearch_selected.png differ diff --git a/asklyphe-frontend/static/img/logo.png b/asklyphe-frontend/static/img/logo.png new file mode 100644 index 0000000..1b3ff32 Binary files /dev/null and b/asklyphe-frontend/static/img/logo.png differ diff --git a/asklyphe-frontend/static/img/lyphe-hardhat.png b/asklyphe-frontend/static/img/lyphe-hardhat.png new file mode 100644 index 0000000..f403f8d Binary files /dev/null and b/asklyphe-frontend/static/img/lyphe-hardhat.png differ diff --git a/asklyphe-frontend/static/img/lyphebent-alpha.png b/asklyphe-frontend/static/img/lyphebent-alpha.png new file mode 100644 index 0000000..48e573f Binary files /dev/null and b/asklyphe-frontend/static/img/lyphebent-alpha.png differ diff --git a/asklyphe-frontend/static/img/lyphebent-christmas.png b/asklyphe-frontend/static/img/lyphebent-christmas.png new file mode 100644 index 0000000..f72d80a Binary files /dev/null and b/asklyphe-frontend/static/img/lyphebent-christmas.png differ diff --git a/asklyphe-frontend/static/img/lyphebent-prealpha.png b/asklyphe-frontend/static/img/lyphebent-prealpha.png new file mode 100644 index 0000000..9fe4f65 Binary files /dev/null and b/asklyphe-frontend/static/img/lyphebent-prealpha.png differ diff --git a/asklyphe-frontend/static/img/lyphebent.old b/asklyphe-frontend/static/img/lyphebent.old new file mode 100644 index 0000000..a80a824 Binary files /dev/null and b/asklyphe-frontend/static/img/lyphebent.old differ diff --git a/asklyphe-frontend/static/img/lyphebent.png b/asklyphe-frontend/static/img/lyphebent.png new file mode 100644 index 0000000..f72d80a Binary files /dev/null and b/asklyphe-frontend/static/img/lyphebent.png differ diff --git a/asklyphe-frontend/static/img/paper.jpg b/asklyphe-frontend/static/img/paper.jpg new file mode 100644 index 0000000..7087b35 Binary files /dev/null and b/asklyphe-frontend/static/img/paper.jpg differ diff --git a/asklyphe-frontend/static/img/paper_slightly_darker.jpg b/asklyphe-frontend/static/img/paper_slightly_darker.jpg new file mode 100644 index 0000000..f9181a1 Binary files /dev/null and b/asklyphe-frontend/static/img/paper_slightly_darker.jpg differ diff --git a/asklyphe-frontend/static/img/textbox.png b/asklyphe-frontend/static/img/textbox.png new file mode 100644 index 0000000..9562d55 Binary files /dev/null and b/asklyphe-frontend/static/img/textbox.png differ diff --git a/asklyphe-frontend/static/img/tinybutterfly.png b/asklyphe-frontend/static/img/tinybutterfly.png new file mode 100644 index 0000000..42d0130 Binary files /dev/null and b/asklyphe-frontend/static/img/tinybutterfly.png differ diff --git a/asklyphe-frontend/static/img/tinyletter.png b/asklyphe-frontend/static/img/tinyletter.png new file mode 100644 index 0000000..00f6856 Binary files /dev/null and b/asklyphe-frontend/static/img/tinyletter.png differ diff --git a/asklyphe-frontend/static/img/tinylyphe.png b/asklyphe-frontend/static/img/tinylyphe.png new file mode 100644 index 0000000..2240591 Binary files /dev/null and b/asklyphe-frontend/static/img/tinylyphe.png differ diff --git a/asklyphe-frontend/static/img/websearch.png b/asklyphe-frontend/static/img/websearch.png new file mode 100644 index 0000000..6bdf9ea Binary files /dev/null and b/asklyphe-frontend/static/img/websearch.png differ diff --git a/asklyphe-frontend/static/img/websearch_selected.png b/asklyphe-frontend/static/img/websearch_selected.png new file mode 100644 index 0000000..7907e82 Binary files /dev/null and b/asklyphe-frontend/static/img/websearch_selected.png differ diff --git a/asklyphe-frontend/static/js/search.js b/asklyphe-frontend/static/js/search.js new file mode 100644 index 0000000..a756bb6 --- /dev/null +++ b/asklyphe-frontend/static/js/search.js @@ -0,0 +1,190 @@ +const loading_message = "results are loading..."; +const kinda_long = "results are still loading..."; +const elapsed_message = "time elapsed"; + +let time_elapsed = 0.0; +let timer_interval; + +function updateTimer() { + if (document.getElementById("stopwatch") !== null) { + const timer_element = document.getElementById("stopwatch") + time_elapsed += 1 / 100; + timer_element.innerHTML = time_elapsed.toString(); + if (time_elapsed > 5) { + const notice1 = document.getElementById("loading_message"); + notice1.innerHTML = kinda_long; + } + } +} + +function startLoading() { + if (document.getElementById("loading") === null) { + const results_area = document.getElementById("results-area"); + const loading_element = document.createElement("div"); + loading_element.id = "loading"; + + const notice1 = document.createElement("span"); + notice1.id = "loading_message"; + notice1.innerHTML = loading_message; + loading_element.appendChild(notice1); + + const timer_notice = document.createElement("span"); + timer_notice.id = "timer_message"; + timer_notice.innerHTML = elapsed_message; + + const timer_element = document.createElement("div"); + timer_element.id = "stopwatch"; + loading_element.appendChild(timer_element); + results_area.appendChild(loading_element); + timer_interval = setInterval(updateTimer, 10); + } +} + +function stopLoading() { + if (document.getElementById("loading") !== null) { + clearInterval(timer_interval); + + const results_area = document.getElementById("results-area"); + const loading_element = document.getElementById("loading"); + results_area.removeChild(loading_element); + } +} + +startLoading(); + +function process(result) { + stopLoading(); + const json = result; //JSON.parse(result); + if (json.hasOwnProperty( "error") || !json.hasOwnProperty( "results")) { + const response_element = document.getElementsByClassName("response")[0]; + const results_area = document.getElementById("results-area"); + response_element.removeChild(results_area); + + const error_element = document.createElement("div"); + error_element.classList.add("error"); + if (json.hasOwnProperty( "error")) { + error_element.innerText = json.error; + } else { + error_element.innerText = "unknown serverside error occurred! please try your request again, and contact an administrator if the error persists!"; + } + response_element.appendChild(error_element); + } else { + const search_results = json.results; + const response_element = document.getElementsByClassName("response")[0]; + const search_result_list = document.createElement("ol"); + const results_area = document.getElementById("results-area"); + const stats_element = document.createElement("div"); + stats_element.classList.add("stats"); + stats_element.innerText = `found ${search_results.search_results.length} results in ${search_results.query_time} seconds (${search_results.page_rank_time} was pageranking)`; + results_area.appendChild(stats_element); + + if (search_results.hasOwnProperty( "note")) { + const note_element = document.createElement("div"); + note_element.classList.add("note"); + note_element.innerText = search_results.note; + results_area.insertBefore(note_element, stats_element); + } + + search_result_list.classList.add("search-result-list"); + + for (const result_obj of search_results.search_results) { + const li = document.createElement("li"); + const a = document.createElement("a"); + a.classList.add("search-result"); + a.href = result_obj.url; + const h2 = document.createElement("h2"); + h2.classList.add("search-title"); + if (result_obj.hasOwnProperty( "title")) { + h2.innerText = result_obj.title; + } else { + h2.innerText = result_obj.url; + } + a.appendChild(h2); + const resultstat = document.createElement("span"); + resultstat.classList.add("resultstat"); + if (result_obj.hasOwnProperty( "title")) { + const search_url = document.createElement("span"); + search_url.classList.add("search-url"); + search_url.innerText = result_obj.url + " "; + resultstat.appendChild(search_url); + } + const relevance = document.createElement("span"); + relevance.classList.add("search-relevance"); + relevance.innerText = `(${result_obj.percentage}%, ${result_obj.value} / ${search_results.max_relevance})`; + const enginelist = document.createElement("span"); + enginelist.classList.add("enginelist"); + if (result_obj.hasOwnProperty("asklyphe")) { + if (result_obj.asklyphe === true) { + const tinylyphe = document.createElement("img"); + tinylyphe.src = "/static/img/tinylyphe.png"; + tinylyphe.title = "from askLyphe database"; + enginelist.appendChild(tinylyphe); + } + } + if (result_obj.hasOwnProperty("bing")) { + if (result_obj.bing === true) { + const tinybutterfly = document.createElement("img"); + tinybutterfly.src = "/static/img/tinybutterfly.png"; + tinybutterfly.title = "from external search engine"; + enginelist.appendChild(tinybutterfly); + } + } + if (result_obj.hasOwnProperty("google")) { + if (result_obj.google === true) { + const tinyletter = document.createElement("img"); + tinyletter.src = "/static/img/tinyletter.png"; + tinyletter.title = "from external search engine"; + enginelist.appendChild(tinyletter); + } + } + resultstat.appendChild(relevance); + resultstat.appendChild(enginelist); + a.appendChild(resultstat); + if (result_obj.hasOwnProperty( "description")) { + const desc = document.createElement("span"); + desc.classList.add("search-description"); + desc.innerText = result_obj.description; + a.appendChild(desc); + } + li.appendChild(a); + search_result_list.appendChild(li); + } + + results_area.appendChild(search_result_list); + + if (search_results.blocked.length > 0) { + const blocked_header = document.createElement("span"); + blocked_header.classList.add("blocked-header"); + blocked_header.innerText = `${search_results.blocked.length} results were pruned from search results for the following reasons:`; + results_area.appendChild(blocked_header); + const blocked_results = document.createElement("ol"); + blocked_results.classList.add("blocked-results"); + for (const blocked of search_results.blocked) { + const li = document.createElement("li"); + li.innerText = `"${blocked.url}" because "${blocked.reason}"`; + blocked_results.appendChild(li); + } + results_area.appendChild(blocked_results); + } + } +} + +let xml_http = new XMLHttpRequest(); + +xml_http.onload = (e) => { + process(xml_http.response); +} + +let query = "Deez"; +let engines = ""; +let params = (new URL(document.location)).searchParams; +if (params.has("q")) { + query = params.get("q"); +} +if (params.has("engines")) { + engines = `&engines=${params.get("engines")}`; +} + +xml_http.open("GET", `${window.location.origin}/ask_json?q=${encodeURIComponent(query)}${engines}`); +xml_http.responseType = "json"; +xml_http.send(); \ No newline at end of file diff --git a/asklyphe-frontend/static/lyphe-christmas.png b/asklyphe-frontend/static/lyphe-christmas.png new file mode 100644 index 0000000..545fdbe Binary files /dev/null and b/asklyphe-frontend/static/lyphe-christmas.png differ diff --git a/asklyphe-frontend/static/lyphe.png b/asklyphe-frontend/static/lyphe.png new file mode 100644 index 0000000..7e89311 Binary files /dev/null and b/asklyphe-frontend/static/lyphe.png differ diff --git a/asklyphe-frontend/static/osd.xml b/asklyphe-frontend/static/osd.xml new file mode 100644 index 0000000..c60efc7 --- /dev/null +++ b/asklyphe-frontend/static/osd.xml @@ -0,0 +1,10 @@ + + + AskLyphe + the best search engine! + UTF-8 + https://asklyphe.com/favicon.ico + + https://asklyphe.com/ + + diff --git a/asklyphe-frontend/static/privacy_policy.html b/asklyphe-frontend/static/privacy_policy.html new file mode 100644 index 0000000..63710f2 --- /dev/null +++ b/asklyphe-frontend/static/privacy_policy.html @@ -0,0 +1,321 @@ + + + + + AskLyphe - Privacy Policy + + + + + +
+ +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+

PRIVACY POLICY

+

Last updated 2024-11-11

+ +

+ This Privacy Policy for Real Microsoft, LLC ("Real Microsoft", "we", "us", or "our"), describes how + and why we might access, collect, store, and/or use your personal information when you use the askLyphe software (the "Service"). +

+

+ Reading this Privacy Policy will help you understand your privacy rights and choices. We are responsible + for making decisions about how your personal information is processed. + If you do not agree with our policies and practices, please do not use our Service. +

+ +

SUMMARY OF KEY POINTS

+

+ + This summary provides key points from our Privacy Policy, but you can find out more details about + any of these topics by using the table of contents below to find the section you are looking for. + +

+

+ What personal information do we process? + Usage of the Service in its current form requires the collection and processing of only the data + you explicitly provide (such as but not limited to your username and email address), as well as your + IP address which may be used for additional account safety. You may read more about this below. +

+

+ Do we process any sensitive personal information? + Some of the information may be considered "special" or "sensitive" in certain jurisdictions, for + example your racial or ethnic origins, sexual orientation, and religious beliefs. We do not collect or + process any information of this kind. +

+

+ Do we collect any information from third parties? + We do not collect any information from third parties. +

+

+ How do we process your information? + Your information is used to provide you our Service, as well as to verify account ownership. + We may use your provided information to communicate with you, for security and fraud prevention, and + to comply with law. We process your information only when we have a valid legal reason to do so. +

+

+ In what situations and with which parties do we share personal information? + Searches are sent to the third-party search-engines which you have enabled on your account or + per-search. Otherwise, your information will only be shared with a third party in the event that we + are legally required to do so in order to comply with law. +

+

+ How do we keep your information safe? + We take information security seriously, and to the best of our efforts follow industry-standard practices + and procedures to protect your information from both malicious third parties and malicious actors + within Real Microsoft. However, no electronic transmission or information storage technology can be + guaranteed to be 100% secure, and as such we cannot promise or guarantee that unauthorized parties + will not be able to defeat our security and improperly collect, access, steal, or modify your information. +

+

+ What are your rights? + Depending on where you are located geographically, the applicable privacy law may mean you have + certain rights regarding your personal information. +

+

+ How do you exercise your rights? + The easiest way to exercise your rights is to contact us at devnull@voremicrocomputers.com via email. + We will consider and act upon any request in accordance with applicable data protection laws. +

+ +

TABLE OF CONTENTS

+ + +

1. WHAT INFORMATION DO WE COLLECT?

+

+ We collect personal information that you voluntarily provide to us when you register on the Service, + or otherwise when you contact us. +

+

+ The personal information may include the following: +

    +
  • email addresses
  • +
  • usernames
  • +
  • passwords
  • +
  • IP addresses
  • +
+

+

+ We do not collect or process "sensitive" information. +

+ +

2. HOW DO WE PROCESS YOUR INFORMATION?

+

+ We process your information in order to provide you with the Service, and to protect your private + information and security. +

+

+ The information given to us is used to facilitate account creation and otherwise account management. + We may also use the email address associated with your account in order to notify you of important + account notices, legal information, or notices in relation to the Service. +

+ +

3. WHAT LEGAL BASES DO WE RELY ON TO PROCESS YOUR INFORMATION?

+

+ This paragraph applies to you if you are located in the EU or UK. + The General Data Protection Regulation (GDPR) and UK GDPR require us to explain the valid legal bases + we rely on in order to process your information. As such, we may rely on the following legal bases + to process your personal information: +

    +
  • Consent. We may process your information if you have given us permission (i.e., consent) + to use your personal information for a specific purpose. You have the right to withdraw your consent + at any time, and may do so by contacting us at devnull@voremicrocomputers.com
  • +
  • Legal Obligations. We may process your information where we believe it is necessary + for compliance with our legal obligations, such as to cooperate with a law enforcement body or regulatory agency, + exercise or defend our legal rights, or disclose your information as evidence in litigation in which + we are involved.
  • +
  • Vital Interests. We may process your information where we believe it is necessary + to protect your vital interests or the vital interests of a third party, such as situations involving + potential threats to the safety of any person.
  • +
+

+

+ This paragraph applies to you if you are located in Canada. + We may process your information if you have given us specific permission (i.e., express consent) + to use your personal information for a specific purpose, or in situations where your permission + can be inferred (i.e., implied consent). You can withdraw your consent at any time, and may do so by + contacting us at devnull@voremicrocomputers.com. In some exceptional cases, we may be legally + permitted under applicable law to process your information without your consent, including, for example: +

    +
  • If collection is clearly in the interests of an individual and consent cannot be obtained in a timely way.
  • +
  • For investigations and fraud detection and prevention.
  • +
  • For business transactions provided certain conditions are met.
  • +
  • If it is contained in a witness statement and the collection is necessary to assess, process, + or settle an insurance claim.
  • +
  • For identifying injured, ill, or deceased persons and communicating with next of kin.
  • +
  • If we have reasonable grounds to believe an individual has been, is, or may be victim of financial abuse.
  • +
  • If it is reasonable to expect collection and use with consent would compromise the availability or + accuracy of the information and the collection is reasonable for purposes related to investigating a breach + of an agreement or a contravention of the laws of Canada or a province.
  • +
  • If disclosure is required to comply with a subpoena, warrant, court order, or rules of the court + relating to the production of records.
  • +
  • If it was produced by an individual in the course of their employment, business, or profession + and the collection is consistent with the purposes for which the information was produced.
  • +
+

+ +

4. WHEN AND WITH WHOM DO WE SHARE YOUR PERSONAL INFORMATION?

+

+ As one or more Third-Party search engine "backends" may be used for queries, these third-party + services will receive only the necessary information to provide you with their results. This + information should not consist of more than your search query. +

+

+ Otherwise, we will only share your personal information with third parties in the event that we must do so to + comply with law. In the event of a business transfer, merger, or acquisition, your data may be + deleted from our databases unless consent for the transfer is given. +

+ +

5. IS YOUR INFORMATION TRANSFERRED INTERNATIONALLY?

+

+ Our servers are located in the United States. If you are accessing our Service from outside the United States, + please be aware that your information may be transferred to, stored by, and processed by us in our facilities. +

+

+ If you are a resident in the European Economic Area (EEA), United Kingdom (UK), or Switzerland, then + the countries in which your data is stored may not necessarily have data protection laws or other + similar laws as comprehensive as those in your country. However, we will take all necessary measures + to protect your personal information in accordance with this Privacy Policy and applicable law. +

+ +

6. HOW LONG DO WE KEEP YOUR INFORMATION?

+

+ We will only keep your personal information for as long as it is necessary for the purposes set out in + this Privacy Policy, unless a longer retention period is required or permitted by law (such as tax, + accounting, or other legal requirements). No purpose in this policy will require us keeping your + personal information for longer than the period of time in which users have an account with us. +

+

+ When we have no ongoing legitimate business need to process your personal information, we will either + delete or anonymize such information, or, if this is not possible (for example, because your personal + information has been stored in backup archives), then we will securely store your personal information + and isolate it from any further processing until deletion is possible. +

+ +

7. HOW DO WE KEEP YOUR INFORMATION SAFE?

+

+ We take information security seriously, and to the best of our efforts follow industry-standard practices + and procedures to protect your information from both malicious third parties and malicious actors + within Real Microsoft. However, no electronic transmission or information storage technology can be + guaranteed to be 100% secure, and as such we cannot promise or guarantee that unauthorized parties + will not be able to defeat our security and improperly collect, access, steal, or modify your information. +

+

+ Although we will do our best to protect your personal information, transmission of personal information + to and from our Service is at your own risk. You should only access the Service within a secure environment. +

+ +

8. WHAT ARE YOUR PRIVACY RIGHTS?

+

+ In some regions (like the EEA, UK, Switzerland, and Canada), you have certain rights under applicable + data protection laws. These may include the right (i) to request, access, and obtain a copy of personal + information; (ii) to request rectification or erasure; (iii) to restrict the processing of your + personal information; (iv) if applicable, to data portability; and (v) not to be subject to automated + decision-making. In certain circumstances, you may also have the right to object to the processing + of your personal information. You can make such a request by contacting us at devnull@voremicrocomputers.com +

+

+ We will consider and act upon any request in accordance with applicable data protection laws. +

+

+ If you are located in the EEA or UK and you believe we are unlawfully processing your personal information, + you also have the right to complain to your + Member State data protection authority + or UK data protection authority. +

+

+ If you are located in Switzerland, you may contact the + Federal Data Protection and Information Commissioner. +

+

+ Withdrawing your consent: + If we are relying on your consent to process your personal information, which may be express and/or implied + consent depending on the applicable law, you have the right to withdraw your consent at any time. + You can withdraw your consent at any time by contacting us via email at devnull@voremicrocomputers.com. +

+

+ However, please note that this will not affect the lawfulness of processing before its withdrawal nor, + when applicable law allows, will it affect the processing of your personal information conducted in + reliance on lawful processing grounds other than consent. +

+

+ If you would at any time like to review or change the information in your account or terminate your + account, please contact us at devnull@voremicrocomputers.com. +

+

+ Upon your request to terminate your account, we will deactivate or delete your account and information + from our active databases. However, we may retain some information in our files to prevent fraud, + troubleshoot problems, assist with any investigations, enforce our legal terms and/or comply with + applicable legal requirements. +

+ +

9. CONTROLS FOR DO-NOT-TRACK FEATURES

+

+ Most web browsers and some mobile operating systems and mobile applications include a Do-Not-Track ("DNT") + feature or setting you can activate to signal your privacy preference not to have data about your online + browsing activities monitored and collected. +

+

+ We currently do not respond to DNT signals, as we feel that there is nothing extra that we could do + to facilitate this request. We do not automatically monitor or collect any information from your + usage of the Service except that which is required or deemed necessary to provide you with the Service, + and any information that is required to be collected for normal functionality is not shared with + any third-parties except in the rare cases specified in Section 4. +

+ +

10. DO WE MAKE UPDATES TO THIS POLICY?

+

+ We may update this Privacy Policy from time to time, such as but not limited to the introduction of new features + to our Service. +

+

+ The updated version will be indicated by an updated "Last updated" date at the top of this Privacy Policy. + If we make material changes to this Privacy Policy, we may notify you either by prominently posting a notice + of such changes or by directly sending you a notification. We encourage you to review this Privacy Policy + frequently to be informed of how we are protecting your information. +

+ +

11. HOW CAN YOU CONTACT US ABOUT THIS NOTICE?

+

+ If you have any questions or comments about this policy, you may email us at devnull@voremicrocomputers.com +

+ +

12. HOW CAN YOU REVIEW, UPDATE, OR DELETE THE DATA WE COLLECT FROM YOU?

+

+ You have the right to request access to the personal information we collect from you, details about + how we have processed it, correct inaccuracies, or delete your personal information. You may also + have the right to withdraw your consent to our processing of your personal information. These rights + may be limited in some circumstances by applicable law. To request to review, update, or delete your + personal information, please contact us at devnull@voremicrocomputers.com +

+
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/snow.gif b/asklyphe-frontend/static/snow.gif new file mode 100644 index 0000000..2ad24b8 Binary files /dev/null and b/asklyphe-frontend/static/snow.gif differ diff --git a/asklyphe-frontend/static/terms_of_use.html b/asklyphe-frontend/static/terms_of_use.html new file mode 100644 index 0000000..ff8c51b --- /dev/null +++ b/asklyphe-frontend/static/terms_of_use.html @@ -0,0 +1,648 @@ + + + + + AskLyphe - Terms Of Use + + + + + +
+ +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +
+
+
+ +
+
+
+

TERMS OF USE

+

Last updated 2024-09-01

+ +

AGREEMENT TO OUR LEGAL TERMS

+

+ We are Real Microsoft, LLC ("Real Microsoft", "we", "us", "our"). +

+

+ We operate the service askLyphe (the "Service"), where it and its related services are governed by + these legal terms (the "Legal Terms"). +

+

+ You can contact us by email at devnull@voremicrocomputers.com +

+

+ These Legal Terms constitute a legally binding agreement made between you, whether personally or on + behalf of an entity ("you"), and Real Microsoft, LLC, concerning your access to and use of + the Service. You agree that by accessing the Service, you have read, understood, and agreed to be + bound by all of these Legal Terms. +

+

+ + IF YOU DO NOT AGREE WITH ALL OF THESE LEGAL TERMS, THEN YOU ARE EXPRESSLY PROHIBITED FROM USING THE + SERVICES AND YOU MUST DISCONTINUE USE IMMEDIATELY. + +

+

+ Supplemental terms and conditions or documents that may be posted on the Service or have been posted + on the Service are hereby expressly incorporated herein by reference. We reserve the right, in our + sole discretion, to make changes or modifications to these Legal Terms. +

+

+ We will alert you about any + changes by updating the "Last updated" date of these Legal Terms, and while we may alert you (such + as but not limited to via email or a notification within the Service) to changes in the Legal Terms, + you waive the right to receive specific notice of each such change. It is your responsibility to + periodically review these Legal Terms to stay informed of updates. +

+

+ You will be subject to, and will be deemed to have been made aware of and to have accepted, the + changes in any revised Legal Terms by your continued use of the Service on and after the date such + revised Legal Terms are posted. +

+ +

TABLE OF CONTENTS

+ + +

1. OUR SERVICE

+

+ The information provided when using the Service is not intended for distribution to or use by any + person or entity in any jurisdiction or country where such distribution or use would be contrary + to law or regulation or which would subject us to any registration requirement within such + jurisdiction or country. +

+

+ Accordingly, those persons who choose to access the Service from other locations do so on their + own initiative and are solely responsible for compliance with local laws, if and to the extent + local laws are applicable. +

+ +

2. INTELLECTUAL PROPERTY RIGHTS

+

Our intellectual property

+

+ We are the owner or the licensee of all intellectual property rights in our Service, including all + source code, databases, functionality, software, website designs, audio, video, text, photographs, + and graphics in the Service (collectively, the "Content"), as well as the trademarks, service marks, + and logos contained therein (the "Marks"). +

+

+ Our Content and Marks are protected by copyright and trademark laws (and various other intellectual + property rights and unfair competition laws) and treaties in the United States and around the world. +

+

+ The Content and Marks are provided in or through the Service "AS IS" for your personal, + non-commercial use or internal business purpose only, except where specified otherwise. +

+

Your use of our Service

+

+ Subject to your compliance with these Legal Terms, including the "PROHIBITED ACTIVITIES" section + below, we grant you a non-exclusive, non-transferable, revocable license to: +

    +
  • access the Service; and
  • +
  • download or print a copy of any portion of the Content to which you have properly gained access.
  • +
+ solely for your personal, non-commercial use or internal business purpose, except where specified otherwise. +

+

+ Except as set out in this section or elsewhere in our Legal Terms, no part of the Service and no + Content or Marks may be copied, reproduced, aggregated, republished, uploaded, posted, + publicly displayed, encoded, translated, transmitted, distributed, sold, licensed, or otherwise + exploited for any commercial purpose whatsoever, without our express prior written permission. +

+

+ If you wish to make any use of the Services, Content, or Marks other than as set out in this section + or elsewhere in our Legal Terms, please email your request to devnull@voremicrocomputers.com +

+

+ If we ever grant you the permission to post, reproduce, or publicly display any part of our Service, + Content, or Marks, you must identify us as the owners or licensors of the Services, Content, + or Marks and ensure that any copyright or proprietary notice appears or is visible on posting, + reproducing, or displaying our Service, Content, or Marks, unless otherwise specified. +

+

+ We reserve all rights not expressly granted to you in and to the Service, Content, and Marks. +

+

+ Any breach of these Intellectual Property Rights will constitute a material breach of our + Legal Terms and your right to use our Service will terminate immediately. +

+

Your submissions

+

+ Please review this section and the "PROHIBITED ACTIVITIES" section carefully prior to using our + Service to understand the (a) rights you give us and (b) obligations you have when you post or + upload any content through the Service. +

+

+ By directly sending us any question, comment, suggestion, idea, feedback, or other information about + the Service ("Submissions"), you agree to assign us all intellectual property rights in such + Submission. You agree that we shall own this Submission and be entitled to its unrestricted use + and dissemination for any lawful purpose, commercial or otherwise, without acknowledgment or + compensation to you. +

+

+ You are responsible for what you post or upload. By sending us Submissions through + any part of the Service, you: +

    +
  • confirm that you have read and agree with our "PROHIBITED ACTIVITIES" and will not post, + send, publish, upload, or transmit through the Service any Submission that is illegal, + harassing, hateful, harmful, defamatory, obscene, bullying, abusive, discriminatory, + threatening to any person or group, false, inaccurate, deceitful, or misleading;
  • +
  • to the extent permissible by applicable law, waive any and all moral rights to any such + Submission;
  • +
  • warrant that any such Submissions are original to you or that you have the necessary rights + and licenses to submit Submissions and that you have full authority to grant us the + above-mentioned rights in relation to your Submissions; and
  • +
  • warrant and represent that your Submissions do not constitute confidential information.
  • +
+

+

+ You are solely responsible for your Submissions, and you expressly agree to reimburse us for any and + all losses that we may suffer because of your breach of (a) this section, (b) any third party's + intellectual property rights, or (c) applicable law. +

+ +

3. USER REPRESENTATIONS

+

+ By using the Service, you represent and warrant that: +

    +
  • all registration information you submit will be true, accurate, current, and complete;
  • +
  • you will maintain the accuracy of such information and promptly update such registration + information as necessary;
  • +
  • you have the legal capacity and you agree to comply with these Legal Terms
  • +
  • you are not a minor in the jurisdiction in which you reside, or are being represented by + someone with the legal capacity to agree to these Legal Terms in your place;
  • +
  • you will not access the Service thorugh automated or non-human means, whether through a bot, + script, or otherwise, except where expressly permitted;
  • +
  • you will not use the Service for any illegal or unauthorized purpose; and
  • +
  • your use of the Service will not violate any applicable law or regulation.
  • +
+

+

+ If you provide any information that is untrue, inaccurate, not current, or incomplete, we have the + right to suspend or terminate your account and refuse any and all current or future use of the + Service (or any portion thereof). +

+ +

4. USER REGISTRATION

+

+ You may be required to register to use the Service. You agree to keep your password confidential + and will be responsible for all use of your account and password. +

+

+ We reserve the right to remove, reclaim, or change a username you select if we determine, in our + sole discretion, that such username is inappropriate, obscene, or otherwise objectionable. +

+ +

5. PROHIBITED ACTIVITIES

+

+ You may not access or use the Service for any purpose other than that for which we make the Service + available. The Service may not be used in connection with any commercial endeavors except those that + are specifically endorsed or approved by us. +

+

+ As a user of the Service, you agree not to: +

    +
  • Systematically retrieve data or other content from the Service to create or compile, + directly or indirectly, a collection, compilation, database, or directory without written + permission from us.
  • +
  • Trick, defraud, or mislead us and other users, especially in any attempt to learn sensitive + account information such as user passwords.
  • +
  • Circumvent, disable, or otherwise interfere with security-related features of the Service, + including features that prevent or restrict the use or copying of any Content or enforce + limitations on the use of the Services and/or the Content contained therein.
  • +
  • Disparage, tarnish, or otherwise harm, in our opinion, us and/or the Service.
  • +
  • Use any information obtained from the Service in order to harass, abuse, or harm another + person.
  • +
  • Make improper use of our support services or submit false reports of abuse or misconduct.
  • +
  • Use the Service in a manner inconsistent with any applicable laws or regulations.
  • +
  • Engage in unauthorized framing of or linking to the Service.
  • +
  • Upload or transmit (or attempt to upload or to transmit) viruses, Trojan horses, or other + material, including spamming (continuous posting of repetitive text), that interferes with any + party's uninterrupted use and enjoyment of the Service or modifies, impairs, disrupts, alters, + or interferes with the use, features, functions, operation, or maintenance of the Service.
  • +
  • Engage in any automated use of the system, such as using scripts to interact with the + Service, or using any data mining, robots, or similar data gathering and extraction tools.
  • +
  • Delete the copyright or other proprietary rights notice from any Content.
  • +
  • Attempt to impersonate another user or person or use the username of another user.
  • +
  • Upload or transmit (or attempt to upload or to transmit) and material that acts as a passive + or active information collection or transmission mechanism, including without limitation, clear + graphics interchange formats ("gifs"), 1x1 pixels, web bugs, cookies, or other similar devices + (sometimes referred to as "spyware" or "passive collection mechanisms" or "pcms").
  • +
  • Interfere with, disrupt, or create an undue burden on the Service or the networks or + services connected to the Service.
  • +
  • Harass, annoy, intimidate, or threaten any of our employees or agents engaged in providing + any portion of the Service to you.
  • +
  • Attempt to bypass any measures of the Service designed to prevent or restrict access to the + Service, or any portion of the Service.
  • +
  • Copy or adapt the Service's software, including but not limited to HTML, JavaScript, or + other code, unless expressly granted permission.
  • +
  • Except as permitted by applicable law, decipher, decompile, disassemble, or reverse engineer + any of the software comprising or in any way making up a part of the Service, unless expressly + granted permission.
  • +
  • Use a buying agent or purchasing agent to make purchases on the Service.
  • +
  • Make any unauthorized use of the Service, including collecting usernames and/or email addresses + of users by electronic or other means for the purpose of sending unsolicited email, or creating + user accounts by automated means or under false pretenses.
  • +
  • Use the Service as part of any effort to compete with use or otherwise use the Service and/or + the Content for any revenue-generating endeavor or commercial enterprise.
  • +
+

+ +

6. USER GENERATED CONTRIBUTIONS

+

+ The Service does not currently offer users to submit or post content. We may provide you with the + opportunity to create, submit, post, display, transmit, perform, publish, distribute, or broadcast + content and materials to us or on the Service, including but not limited to text, writings, video, + audio, photographs, graphics, comments, suggestions, or personal information or other material + (collectively, "Contributions"). +

+

+ Contributions may be viewable by other users of the Service and through third-party websites. + As such, any Contributions you transmit may be treated in accordance with the + Service's Privacy Policy. +

+

+ When you create or make available any contributions, you thereby represent and warrant that: +

    +
  • The creation, distribution, transmission, public display, or performance, and the accessing, + downloading, or copying of your Contributions do not and will not infringe the proprietary rights, + including but not limited to the copyright, patent, trademark, trade secret, or moral rights of + any third party.
  • +
  • You are the creator and owner of or have the necessary licenses, rights, consents, releases, + and permissions to use and to authorize us, the Service, and other users of the Service to use + your Contributions in any manner contemplated by the Service and these Legal Terms.
  • +
  • You have the written consent, release, and/or permission of each and every identifiable + individual person in your Contributions to use the name or likeness of each and every such + identifiable individual person to enable inclusion and use of your Contributions in any manner + contemplated by the Service and these Legal Terms.
  • +
  • Your Contributions are not false, inaccurate, or misleading.
  • +
  • Your Contributions are not obscene, violent, harassing, libelous, slanderous, or otherwise + objectionable (as determined by us).
  • +
  • Your Contributions do not ridicule, mock, disparage, intimidate, or abuse anyone.
  • +
  • Your Contributions are not used to harass or threaten (in the legal sense of those terms) + any other person and to promote violence against a specific person or class of people.
  • +
  • Your Contributions do not violate any applicable law, regulation, or rule.
  • +
  • Your Contributions do not violate the privacy or publicity rights of any third party.
  • +
  • Your Contributions do not violate any applicable law concerning child pornography, or + otherwise intended to protect the health or well-being of minors.
  • +
  • Your Contributions do not include any offensive (as determined by us) comments, such as but + not limited to those which are connected to race, national origin, gender, sexual preference, + or physical handicap.
  • +
  • Your Contributions are not unsolicited or unauthorized advertising, promotional materials, + pyramid schemes, chain letters, spam, mass mailings, or other forms of solicitation.
  • +
  • Your Contributions do not otherwise violate, or link to material that violates, any provision + of these Legal Terms, or any applicable law or regulation.
  • +
+ Any use of the Service in violation of the foregoing violates these Legal Terms and may result in, + among other things, termination or suspension of your rights to use the Service. +

+ +

7. CONTRIBUTION LICENSE

+

+ You agree that we may access, store, process, and use any information and personal data that you + provide following the terms of the Privacy Policy and your choices (including settings). +

+

+ By submitting suggestions or other feedback regarding the Service, you agree that we can use and + share such feedback for any purpose without compensation to you. +

+

+ We do not assert any ownership over your Contributions. You retain full ownership of all of your + Contributions and any intellectual property rights or other proprietary rights associated with + your Contributions. We are not liable for any statements or representations in your Contributions + provided by you in any area on the Service. You are solely responsible for your Contributions to the + Service and you expressly agree to exonerate us from any and all responsibility and to refrain from + any legal action against us regarding your Contributions. +

+ +

8. THIRD-PARTY WEBSITES AND CONTENT

+

+ The Service may contain (or you may be sent via the Service) links to other websites ("Third-Party Websites") + as well as articles, photographs, text, graphics, pictures, designs, music, sound, video, information, + applications, software, and other content or items belonging to or originating from third parties + ("Third-Party Content"). +

+

+ Such Third-Party Websites and Third-Party Content are not investigated, monitored, or checked for + accuracy, appropriateness, or completeness by us, and we are not responsible for any Third-Party Websites + accessed through the Service or any Third-Party Content posted on, available through, or installed from + the Service, including the content, accuracy, offensiveness, opinions, reliability, privacy practices, + or other policies of or contained in the Third-Party Websites or the Third-Party Content. +

+

+ Inclusion of, linking to, or permitting the use or installation of any Third-Party Websites or any + Third-Party Content does not imply approval or endorsement thereof by us. If you decide to leave + the Service and access the Third-Party Websites or to use or install any Third-Party Content, you + do so at your own risk, and you should be aware these Legal Terms no longer govern. +

+

+ You should review the applicable terms and policies, including privacy and data gathering practices, + of any website to which you navigate from the Service or relating to any applications you use or + install from the Service. +

+

+ In general, it is recommended to always read and review the applicable terms and policies of any + website to which you navigate. +

+

+ Any purchases you make through Third-Party Websites will be through other websites and from other + companies, and we take no responsibility whatsoever in relation to such purchases which are + exclusively between you and the applicable third party. You agree and acknowledge that we do not + endorse the products or services offer on Third-Party Websites and you shall hold us blameless from + any harm caused by your purchase of such products or services. +

+

+ Additionally, you shall hold us blameless from any losses sustained by you or harm caused to you + relating to or resulting in any way from any Third-Party Content or any contact with Third-Party Websites. +

+ +

9. SERVICE MANAGEMENT

+

+ We reserve the right, but not the obligation, to: +

    +
  • monitor the Service for violations of these Legal Terms;
  • +
  • take appropriate legal action against anyone who, in our sole discretion, violates the law + or these Legal Terms, including without limitation, reporting such user to law enforcement + authorities;
  • +
  • in our sole discretion and without limitation, refuse, restrict access to, limit the + availability of, or disable (to the extent technologically feasible) any of your Contributions + or any portion thereof;
  • +
  • in our sole discretion and without limitation, notice, or liability, to remove from the + Service or otherwise disable all files and content that are excessive in size or are in any way + burdensome to our systems; and
  • +
  • otherwise manage the Service in a manner designed to protect our rights and property and to + facilitate the proper functioning of the Service.
  • +
+

+ +

10. PRIVACY POLICY

+

+ We care about data privacy and security. Please review our Privacy Policy. +

+

+ By using the Service, you agree to be bound by our Privacy Policy, which is incorporated into these + Legal Terms. Please be advised the Service is hosted in the United States. If you access the Service + from any other region of the world with laws or other requirements governing personal data collection, + use, or disclosure that differ from applicable laws in the United States, then through your continued + use of the Service, you are transferring your data to the United States, and you expressly consent to + have your data transferred to and processed in the United States. +

+ +

11. TERM AND TERMINATION

+

+ These Legal Terms shall remain in full force and effect while you use the Service. +

+

+ + WITHOUT LIMITING ANY OTHER PROVISION OF THESE LEGAL TERMS, WE RESERVE THE RIGHT TO, IN OUR + SOLE DISCRETION AND WITHOUT NOTICE OR LIABILITY, DENY ACCESS TO AND USE OF THE SERVICES + (INCLUDING BLOCKING CERTAIN IP ADDRESSES), TO ANY PERSON FOR ANY REASON OR FOR NO REASON, + INCLUDING WITHOUT LIMITATION FOR BREACH OF ANY REPRESENTATION, WARRANTY, OR COVENANT CONTAINED + IN THESE LEGAL TERMS OR OF ANY APPLICABLE LAW OR REGULATION. WE MAY TERMINATE YOUR USE OR + PARTICIPATION IN THE SERVICES OR DELETE YOUR ACCOUNT AND ANY CONTENT OR INFORMATION THAT YOU POSTED + AT ANY TIME, WITHOUT WARNING, IN OUR SOLE DISCRETION. + +

+

+ If we terminate or suspend your account for any reason, you are prohibited from registering and + creating a new account under your name, a fake or borrowed name, or the name of any third party, even + if you may be acting on behalf of the third party. In addition to terminating or suspending your + account, we reserve the right to take appropriate legal action, including without limitation + pursuing civil, criminal, and injunctive redress. +

+ +

12. MODIFICATIONS AND INTERRUPTIONS

+

+ We reserve the right to change, modify, or remove the contents of the Service at any time for any reason + at our sole discretion without notice. However, we have no obligation to update any information on + our Service. We will not be liable to you or any third party for any modification, price change, + suspension, or discontinuance of the Service. +

+

+ We cannot guarantee the Service will be available at all times. We may experience hardware, software, + or other problems or need to perform maintenance related to the Service, resulting in interruptions, + delays, or errors. We reserve the right to change, revise, update, suspend, discontinue, or otherwise + modify the Service at any time or for any reason without notice to you. You agree that we have no + liability whatsoever for any loss, damage, or inconvenience caused by your inability to access or use + the Service during any downtime or discontinuance of the Service. Nothing in these Legal Terms will + be construed to obligate us to maintain and support the Service or to supply any corrections, updates, + or releases in connection therewith. +

+ +

13. GOVERNING LAW

+

+ These Legal Terms and your use of the Service are governed by and construed in accordance with the + laws of the State of California applicable to agreements made and to be entirely performed within + the State of California, without regard to its conflict of law principles. +

+ +

14. DISPUTE RESOLUTION

+

+ Any legal action of whatever nature brought by either you or us (collectively, the "Parties" and individually, a "Party) + shall be commenced or prosecuted in the state and federal courts located in California, and the Parties + hereby consent to, and waive all defenses of lack of personal jurisdiction and forum non conveniens with + respect to venue and jurisdiction in such state and federal courts. +

+

+ Application of the United Nations Convention on Contracts for the International Sale of Goods and + the Uniform Computer Information Transaction Act (UCITA) are excluded from these Legal Terms. +

+

+ In no event shall any claim, action, or proceeding brought by either Party related in any way to the + Service be commenced more than four (4) years after the cause of action arose. +

+ +

15. CORRECTIONS

+

+ There may be information on the Service that contains typographical errors, inaccuracies, or omissions, + including descriptions, pricing, availability, and various other information. +

+

+ We reserve the right to correct any errors, inaccuracies, or omissions and to change or update the + information on the Service at any time, without prior notice. +

+ +

16. DISCLAIMER

+

+ + THE SERVICE IS PROVIDED ON AN AS-IS AND AS-AVAILABLE BASIS. YOU AGREE THAT YOUR USE OF THE SERVICES + WILL BE AT YOUR SOLE RISK. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ALL WARRANTIES, + EXPRESS OR IMPLIED, IN CONNECTION WITH THE SERVICE AND YOUR USE THEREOF, INCLUDING, WITHOUT LIMITATION, + THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. + WE MAKE NO WARRANTIES OR REPRESENTATIONS ABOUT THE ACCURACY OR COMPLETENESS OF THE SERVICE'S CONTENT + OR THE CONTENT OF ANY WEBSITES OR MOBILE APPLICATIONS LINKED TO THE SERVICE AND WE WILL ASSUME NO + LIABILITY OR RESPONSIBILITY FOR ANY (1) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT AND MATERIALS, + (2) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM YOUR ACCESS TO AND + USE OF THE SERVICES, (3) ANY UNAUTHORIZED ACCESS TO OR USE OF OUR SECURE SERVERS AND/OR ANY AND ALL + PERSONAL INFORMATION AND/OR FINANCIAL INFORMATION STORED THEREIN, (4) ANY INTERRUPTION OR CESSATION OF + TRANSMISSION TO OR FROM THE SERVICES, (5) ANY BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE WHICH MAY + BE TRANSMITTED TO OR THROUGH THE SERVICES BY ANY THIRD PARTY, AND/OR (6) ANY ERRORS OR OMISSIONS + IN ANY CONTENT AND MATERIALS OR FOR ANY LOSS OR DAMAGE OF ANY KIND INCURRED AS A RESULT OF THE + USE OF ANY CONTENT POSTED, TRANSMITTED, OR OTHERWISE MADE AVAILABLE VIA THE SERVICE. WE DO NOT + WARRANT, ENDORSE, GUARANTEE, OR ASSUME RESPONSIBILITY FOR ANY PRODUCT OR SERVICE ADVERTISED OR + OFFERED BY A THIRD PARTY THROUGH THE SERVICE, ANY HYPERLINKED WEBSITE, OR ANY WEBSITE OR MOBILE + APPLICATION FEATURED IN ANY BANNER OR OTHER ADVERTISING, AND WE WILL NOT BE A PARTY TO OR IN ANY + WAY BE RESPONSIBLE FOR MONITORING ANY TRANSACTION BETWEEN YOU AND ANY THIRD PARTY PROVIDERS OF + PRODUCTS OR SERVICES. AS WITH THE PURCHASE OF A PRODUCT OR SERVICE THROUGH ANY MEDIUM OR IN ANY + ENVIRONMENT, YOU SHOULD USE YOUR BEST JUDGEMENT AND EXERCISE CAUTION WHERE APPROPRIATE. + +

+ +

17. LIMITATIONS OF LIABILITY

+

+ + IN NO EVENT WILL WE OR OUR DIRECTORS, EMPLOYEES, OR AGENTS BE LIABLE TO YOU OR ANY THIRD PARTY + FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, SPECIAL, OR PUNITIVE DAMAGES, + INCLUDING LOST PROFIT, LOST REVENUE, LOSS OF DATA, OR OTHER DAMAGES ARISING FROM YOUR USE OF THE + SERVICE, EVEN IF WE HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. NOTWITHSTANDING ANYTHING + TO THE CONTRARY CONTAINED HEREIN, OUR LIABILITY TO YOU FOR ANY CAUSE WHATSOEVER AND REGARDLESS OF + THE FORM OF THE ACTION WILL AT ALL TIMES BE LIMITED TO THE AMOUNT PAID, IF ANY, BY YOU TO US DURING + THE SIX (6) MONTH PERIOD PRIOR TO ANY CAUSE OF ACTION ARISING. CERTAIN US STATE LAWS AND INTERNATIONAL + LAWS DO NOT ALLOW LIMITATIONS ON IMPLIED WARRANTIES OR THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES. + IF THESE LAWS APPLY TO YOU, SOME OR ALL OF THE ABOVE DISCLAIMERS OR LIMITATIONS MAY NOT APPLY TO YOU, + AND YOU MAY HAVE ADDITIONAL RIGHTS. + +

+ +

18. INDEMNIFICATION

+

+ You agree to defend, indemnify, and hold us harmless, including our subsidiaries, affiliates, and all of + our respective officers, partners, and employees, from and against any loss, damage, liability, claim, + or demand, including reasonable attorneys' fees and expenses, made by any third party due to or arising out of: +

    +
  • use of the Service;
  • +
  • breach of these Legal Terms;
  • +
  • any breach of your representations and warranties set forth in these Legal Terms;
  • +
  • your violation of the rights of a third party, including but not limited to intellectual property rights; or
  • +
  • any overt harmful act toward any other user of the Service with whom you connected via the Service.
  • +
+

+

+ Notwithstanding the foregoing, we reserve the right, at your expense, to assume the exclusive defense + and control of any matter for which you are required to indemnify us, and you agree to cooperate, at your + expense, with our defense of such claims. We will use reasonable efforts to notify you of any such claim, + action, or proceeding which is subject to this indemnification upon becoming aware of it. +

+ +

19. USER DATA

+

+ We will maintain certain data that you transmit to the Service for the purpose of managing the + performance of the Service, as well as data relating to your use of the Service. +

+

+ Although we perform regular routine backups of data, you are solely responsible for all data that + you transmit or that relates to any activity you have undertaken using the Service. +

+

+ You agree that we shall have no liability to you for any loss or corruption of any such data, and you + hereby waive any right of action against us arising from any such loss or corruption of such data. +

+ +

20. ELECTRONIC COMMUNICATIONS, TRANSACTIONS, AND SIGNATURES

+

+ Visiting the Service, sending us emails, and completing online forms constitute electronic communications. +

+

+ You consent to receive electronic communications, and you agree that all agreements, notices, disclosures, + and other communications we provide to you electronically, via email and on the Service, satisfy + any legal requirement that such communication be in writing. +

+

+ + YOU HEREBY AGREE TO THE USE OF ELECTRONIC SIGNATURES, CONTRACTS, ORDERS, AND OTHER RECORDS, AND + TO ELECTRONIC DELIVERY OF NOTICES, POLICIES, AND RECORDS OF TRANSACTIONS INITIATED OR COMPLETED + BY US OR VIA THE SERVICE. + +

+

+ You hereby waive any rights or requirements under any statutes, regulations, rules, ordinances, or + other laws in any jurisdiction which require an original signature or delivery or retention of + non-electronic records, or to payments or the granting of credits by any means other than electronic + means. +

+ +

21. CALIFORNIA USERS AND RESIDENTS

+

+ If any complaint with us is not satisfactorily resolved, you can contact the Complaint Assistance Unit + of the Division of Consumer Services of the California Department of Consumer Affairs in writing at + 1625 North Market Blvd., Suite N 112, Sacramento, California 95834 or by telephone at (800) 952-5210 or + (916) 445-1254. +

+ +

22. MISCELLANEOUS

+

+ These Legal Terms and any policies or operating rules posted by us on the Service or in respect to + the Service constitute the entire agreement and understanding between you and us. +

+

+ Our failure to exercise or enforce any right or provision of these Legal Terms shall not operate as + a waiver of such right or provision. +

+

+ These Legal Terms operate to the fullest extent permissible by law. +

+

+ We may assign any or all of our rights and obligations to others at any time. +

+

+ We shall not be responsible or liable for any loss, damage, delay, or failure to act caused by any + cause beyond our reasonable control. +

+

+ If any provision or part of a provision of these Legal Terms is determined to be unlawful, void, or + unenforceable, that provision or part of the provision is deemed severable from these Legal Terms and + does not affect the validity and enforceability of any remaining provisions. +

+

+ There is no joint venture, partnership, employment or agency relationship created between you and us + as a result of these Legal Terms or use of the Service. +

+

+ You agree that these Legal Terms will not be construed against us by virtue of having drafted them. +

+

+ You hereby waive any and all defenses you may have based on the electronic form of these Legal Terms + and the lack of signing by the parties hereto to execute these Legal Terms. +

+ +

23. CONTACT

+

+ In order to resolve a complaint regarding the Service or to receive further information regarding + use of the Service, please contact us at: devnull@voremicrocomputers.com +

+
+
+
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/classic/home.css b/asklyphe-frontend/static/themes/classic/home.css new file mode 100644 index 0000000..262e5b0 --- /dev/null +++ b/asklyphe-frontend/static/themes/classic/home.css @@ -0,0 +1,11 @@ +.front-links > ul > li > a, .front-links > ul > li > a:visited { + color: white; +} + +.bent-surrounding { + background: transparent; +} + +#lyphetitle > h2 { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/classic/inline-announcement.css b/asklyphe-frontend/static/themes/classic/inline-announcement.css new file mode 100644 index 0000000..f3c286b --- /dev/null +++ b/asklyphe-frontend/static/themes/classic/inline-announcement.css @@ -0,0 +1,73 @@ +.announcement { + background: url("/static/snow.gif"); + border: 3px inset black; + color: black; + min-width: 532px; + max-width: 640px; + min-height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + min-width: 354px; + min-height: 128px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.2em; + line-height: 1.2em; + margin: 18px 22px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.2em; + margin: 18px 22px -16px; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 1em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; +} + +.announcement > p > a:visited { +} + +.announcement-date { + float: right; + margin: 18px 12px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px 0; + color: ghostwhite; + display: block; + font-size: 0.7em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/classic/logo.png b/asklyphe-frontend/static/themes/classic/logo.png new file mode 100644 index 0000000..64e8529 Binary files /dev/null and b/asklyphe-frontend/static/themes/classic/logo.png differ diff --git a/asklyphe-frontend/static/themes/classic/search.css b/asklyphe-frontend/static/themes/classic/search.css new file mode 100644 index 0000000..b0ef6d2 --- /dev/null +++ b/asklyphe-frontend/static/themes/classic/search.css @@ -0,0 +1,80 @@ +.pagecontent { + background: url("/static/snow.gif"); + border: 3px inset black; + color: black; +} + +@media screen and (max-width: 800px) { + .pagecontent { + width: calc(100% - 4px); + } +} + +.search-result { + color: black; + text-shadow: cadetblue 0 0 3px; + padding: 10px; + border: 1px solid white; + margin: 3px; +} + +.search-result:visited { + color: darkslateblue; +} +.search-url { + color: black; +} + +.search-description { + color: black; + text-shadow: cadetblue 0 0 3px; +} + +.search-relevance { + color: darkslateblue; +} + +.wikipedia-complication { + background: rgba(0.77, 0.77, 0.77, 0.43); + border: 3px inset white; +} + +.wikipedia-image > img { + background: gray; +} + +.wikipedia-title { + color: white; +} + +.wikipedia-fromwikipedia { + color: white; + text-shadow: cadetblue 0 0 3px; +} + +.wikipedia-class { + color: white; + text-shadow: cadetblue 0 0 3px; +} + +.wikipedia-description { + color: white; +} + +.complications-note { + background: rgba(0.77, 0.77, 0.77, 0.43); + border: 3px inset white; +} + +.unit_converter-complication { + background: rgba(0.77, 0.77, 0.77, 0.43); + border: 3px inset white; +} + +.unit_converter-title { + color: white; +} + +.unit_converter-result { + color: white; +} diff --git a/asklyphe-frontend/static/themes/classic/settings.css b/asklyphe-frontend/static/themes/classic/settings.css new file mode 100644 index 0000000..3aa2239 --- /dev/null +++ b/asklyphe-frontend/static/themes/classic/settings.css @@ -0,0 +1,20 @@ +.settings-area { + background: url("/static/snow.gif"); + border: 1px solid white; +} + +@media screen and (max-width: 800px) { + .settings-area { + width: calc(100% - 1px); + } +} + +.settings-section { + background: rgba(0.77, 0.77, 0.77, 0.43); + border: 3px inset black; + color: white; +} + +p { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/classic/shell.css b/asklyphe-frontend/static/themes/classic/shell.css new file mode 100644 index 0000000..0de6941 --- /dev/null +++ b/asklyphe-frontend/static/themes/classic/shell.css @@ -0,0 +1,95 @@ +body { + background: url("/static/bluestars.gif"); +} + +.main { + background: rgba(77,77,77,0.3); + border: 1px solid cadetblue; + color: white; + font-family: sans-serif; + font-weight: normal; + display: flex; + flex-direction: column; + align-items: center; + flex-grow: 1; +} + +input[type=text] { + background: white; + height: 24px; + border: 3px inset black; + font-family: sans-serif; + font-weight: normal; +} + +input[type=text]:focus { + border: 3px inset black; +} + +button, .button { + background: lightgray; + height: 24px; + border: 1px solid dimgray; + font-family: sans-serif; + font-size: 12px; + font-weight: normal; + color: black; + line-height: 0; + padding: 0; + border-radius: 6px; + vertical-align: unset; +} + +.bent-surrounding { + background: transparent; +} + +.user-bar > form > button { + background: lightgray; + border: 1px solid dimgray; + height: 24px; + vertical-align: unset; + font-family: sans-serif; + font-weight: normal; + line-height: 0; + color: black; +} + +.user-bar > a.button { + background: lightgray; + border: 1px solid dimgray; + height: 24px; + vertical-align: unset; + font-family: sans-serif; + font-weight: normal; + line-height: 26px; + color: black; +} + +#lyphetitle > img { + content: url("/static/themes/classic/logo.png"); +} + +#lyphetitlenav > img { + content: url("/static/themes/classic/logo.png"); +} + +.index-bar { + background-color: rgba(0,0,0,0.1) !important; +} + +#websearch-img { + content: url("/static/themes/dark/websearch.png"); +} + +#websearch-img-selected { + content: url("/static/themes/dark/websearch_selected.png"); +} + +#imagesearch-img { + content: url("/static/themes/dark/imagesearch.png"); +} + +#imagesearch-img-selected { + content: url("/static/themes/dark/imagesearch_selected.png"); +} diff --git a/asklyphe-frontend/static/themes/dark/announcement.png b/asklyphe-frontend/static/themes/dark/announcement.png new file mode 100644 index 0000000..d77774c Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/announcement.png differ diff --git a/asklyphe-frontend/static/themes/dark/borderbent.png b/asklyphe-frontend/static/themes/dark/borderbent.png new file mode 100644 index 0000000..09578d1 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/borderbent.png differ diff --git a/asklyphe-frontend/static/themes/dark/button.png b/asklyphe-frontend/static/themes/dark/button.png new file mode 100644 index 0000000..f160b14 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/button.png differ diff --git a/asklyphe-frontend/static/themes/dark/darkeneder_paper.jpg b/asklyphe-frontend/static/themes/dark/darkeneder_paper.jpg new file mode 100644 index 0000000..5fad603 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/darkeneder_paper.jpg differ diff --git a/asklyphe-frontend/static/themes/dark/home.css b/asklyphe-frontend/static/themes/dark/home.css new file mode 100644 index 0000000..6d60bf0 --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/home.css @@ -0,0 +1,17 @@ +.front-links > ul > li > a, .front-links > ul > li > a:visited { + text-decoration: none; + color: white; +} + +.bent-surrounding { + background: url("/static/themes/dark/borderbent.png") no-repeat center; + background-size: 90%; + display: grid; + height: auto; +} + +#lyphetitle > h2 { + font-family: NanumGothicCoding, monospace; + font-size: 175%; + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/dark/imagesearch.css b/asklyphe-frontend/static/themes/dark/imagesearch.css new file mode 100644 index 0000000..cf4d49e --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/imagesearch.css @@ -0,0 +1,57 @@ +.pagecontent { + background-image: url("/static/themes/dark/darkeneder_paper.jpg"); +} +.search-result { + color: white; +} + +.search-result:visited { + color: steelblue; +} +.search-url { + color: lightgray; +} + +.search-description { + color: gray; +} + +.search-relevance { + color: lightgray; +} + +.wikipedia-complication { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.wikipedia-title { + color: white; +} + +.wikipedia-fromwikipedia { + color: lightslategray; +} + +.wikipedia-class { + color: lightslategray; +} + +.wikipedia-description { + color: white; +} + +.complications-note { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.unit_converter-complication { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.unit_converter-title { + color: white; +} + +.unit_converter-result { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/dark/imagesearch.png b/asklyphe-frontend/static/themes/dark/imagesearch.png new file mode 100644 index 0000000..82304ef Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/imagesearch.png differ diff --git a/asklyphe-frontend/static/themes/dark/imagesearch_selected.png b/asklyphe-frontend/static/themes/dark/imagesearch_selected.png new file mode 100644 index 0000000..4077a11 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/imagesearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/dark/inline-announcement.css b/asklyphe-frontend/static/themes/dark/inline-announcement.css new file mode 100644 index 0000000..25258f9 --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/inline-announcement.css @@ -0,0 +1,101 @@ +#preview { + color: white; + display: flex; + flex-direction: column; + align-items: center; + font-family: monospace; + font-weight: bold; +} + +#preview a { + text-decoration: unset; + color: unset; + background-image: unset; + text-shadow: unset; + box-shadow: unset; + color: unset; + min-height: unset; + border: unset; + border-radius: unset; + padding: unset; + margin: unset; + font-size: unset; + transition: unset; + font-family: unset; + font-weight: unset; +} + +.announcement { + background: url("/static/themes/dark/announcement.png"); + width: 532px; + height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.3em; + line-height: 1.2em; + margin: 28px 32px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + font-size: 1.1em; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.1em; + margin: 24px 32px -16px; + line-height: 1em; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 0.9em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; + color: #00c1ff; +} + +.announcement > p > a:visited { + color: #00c1ff; +} + +.announcement-date { + float: right; + margin: 32px 32px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px -5px; + color: ghostwhite; + display: block; + font-size: 0.6em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/dark/logo.png b/asklyphe-frontend/static/themes/dark/logo.png new file mode 100644 index 0000000..b04b3af Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/logo.png differ diff --git a/asklyphe-frontend/static/themes/dark/search.css b/asklyphe-frontend/static/themes/dark/search.css new file mode 100644 index 0000000..cf4d49e --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/search.css @@ -0,0 +1,57 @@ +.pagecontent { + background-image: url("/static/themes/dark/darkeneder_paper.jpg"); +} +.search-result { + color: white; +} + +.search-result:visited { + color: steelblue; +} +.search-url { + color: lightgray; +} + +.search-description { + color: gray; +} + +.search-relevance { + color: lightgray; +} + +.wikipedia-complication { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.wikipedia-title { + color: white; +} + +.wikipedia-fromwikipedia { + color: lightslategray; +} + +.wikipedia-class { + color: lightslategray; +} + +.wikipedia-description { + color: white; +} + +.complications-note { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.unit_converter-complication { + background-image: url("/static/img/darkened_paper.jpg"); +} + +.unit_converter-title { + color: white; +} + +.unit_converter-result { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/dark/settings.css b/asklyphe-frontend/static/themes/dark/settings.css new file mode 100644 index 0000000..e3627ea --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/settings.css @@ -0,0 +1,12 @@ +.settings-area { + background-image: url("/static/themes/dark/darkeneder_paper.jpg"); +} + +.settings-section { + background-image: url("/static/img/darkened_paper.jpg"); + color: white; +} + +p { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/dark/shell.css b/asklyphe-frontend/static/themes/dark/shell.css new file mode 100644 index 0000000..66bafaa --- /dev/null +++ b/asklyphe-frontend/static/themes/dark/shell.css @@ -0,0 +1,89 @@ +body { + background-color: #18181a; +} + +.main { + background-image: url("/static/img/darkened_paper.jpg"); + color: white; +} + +.footer-inner { + /*margin: 2vw;*/ + margin: 2vw 0; + background-color: rgba(77,77,77,0.3); + border: 1px solid cadetblue; + color: white; + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; +} + +input[type=text] { + background: url("/static/themes/dark/textbox.png") no-repeat center; + background-size: 256px 64px; + width: 232px; + height: 64px; + border: none; + padding-inline: 10px 10px; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + color: white; +} + +input[type=text]:focus { + border: none; +} + +button, .button { + display: inline-block; + background: url("/static/themes/dark/button.png") no-repeat center; + background-size: 138px 64px; + width: 138px; + height: 64px; + vertical-align: bottom; + padding-top: 6px; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 1.2em; + text-decoration: none; + line-height: 58px; + color: white; +} + +.user-bar > form > button { + background: url("/static/themes/dark/button.png") no-repeat center; + background-size: 69px 32px; + color: white; +} + +.user-bar > a.button { + background: url("/static/themes/dark/button.png") no-repeat center; + background-size: 69px 32px; + color: white; +} + +#lyphetitle > img { + content: url("/static/themes/dark/logo.png"); +} + +#lyphetitlenav > img { + content: url("/static/themes/dark/logo.png"); +} + +#websearch-img { + content: url("/static/themes/dark/websearch.png"); +} + +#websearch-img-selected { + content: url("/static/themes/dark/websearch_selected.png"); +} + +#imagesearch-img { + content: url("/static/themes/dark/imagesearch.png"); +} + +#imagesearch-img-selected { + content: url("/static/themes/dark/imagesearch_selected.png"); +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/dark/textbox.png b/asklyphe-frontend/static/themes/dark/textbox.png new file mode 100644 index 0000000..c3a627e Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/textbox.png differ diff --git a/asklyphe-frontend/static/themes/dark/websearch.png b/asklyphe-frontend/static/themes/dark/websearch.png new file mode 100644 index 0000000..b8bf015 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/websearch.png differ diff --git a/asklyphe-frontend/static/themes/dark/websearch_selected.png b/asklyphe-frontend/static/themes/dark/websearch_selected.png new file mode 100644 index 0000000..e445b13 Binary files /dev/null and b/asklyphe-frontend/static/themes/dark/websearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/default/404.css b/asklyphe-frontend/static/themes/default/404.css new file mode 100644 index 0000000..daea1c2 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/404.css @@ -0,0 +1,16 @@ +body { + background: white; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; +} + +a { + color: black; +} + +img { + width: 640px; + height: 480px; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/announcement.css b/asklyphe-frontend/static/themes/default/announcement.css new file mode 100644 index 0000000..3498961 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/announcement.css @@ -0,0 +1,115 @@ +.lyphe-says { + text-align: left; + min-width: 20%; + max-height: 128px; + border: 3px inset black; + padding: 10px; + background-image: url("/static/snow.gif"); +} + +.lyphe-says > img { + height: 100px; + float: left; + margin-right: 10px; +} + +.lyphe-says > h5, p { + color: black; + word-break: break-word; +} + +.lyphe-says > h5 { + padding: 0; + margin: 0; + line-height: 2em; +} + +.ask { + text-align: left; + width: 85%; +} + +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} +.announcement-area { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; +} + +.announcement-content { + width: 70%; + min-height: 120px; + background-image: url("/static/img/paper.jpg"); + margin: 50px 90px; + padding: 20px; + text-align: left; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; + color: black; +} + +@media screen and (max-width: 800px) { + .announcement-content { + width: 100%; + margin: 20px 0; + padding: 20px 0; + text-align: center; + } +} + +.pagecontent { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +.announcement-date { + color: #454545; + font-weight: lighter; +} + +.announcement-author { + color: #454545; + font-weight: lighter; +} + +.announcement-body { + margin-top: 30px; + font-weight: normal; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/docs.css b/asklyphe-frontend/static/themes/default/docs.css new file mode 100644 index 0000000..aeeb729 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/docs.css @@ -0,0 +1,98 @@ +#content { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; + display: flex; + flex-wrap: wrap; + justify-content: center; +} + +#lyphebig { + display: flex; + margin: 3px auto; + width: 30%; +} + +@media screen and (max-width: 800px) { + #lyphebig { + grid-auto-flow: row; + } +} + +#lyphetitle { + margin-left: 5px; + padding-top: 8%; +} + +@media screen and (max-width: 800px) { + #lyphetitle { + padding-top: 0; + } +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 90%; + display: grid; + height: auto; +} + +#lypheimg { + width: 90%; + margin: auto; +} + +#lyphetitle > img { + width: 100%; + margin: 0; +} + +#lyphetitle > p { + font-family: NanumGothicCoding, monospace; + font-size: 24px; + color: #9baba4; +} + +@media screen and (max-width: 800px) { + #lyphetitle > h2 { + font-size: 100%; + } +} + +form { + margin-top: 10%; +} + +.pagecontent { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +#docsarea { + margin-top: 64px; + color: white; + width: 85% +} + +ul { + width: 30%; + margin: auto; +} + +a, a:visited { + color: #ffe7e7; +} + +strong { + font-weight: bold; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/frontpage.css b/asklyphe-frontend/static/themes/default/frontpage.css new file mode 100644 index 0000000..b6eae26 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/frontpage.css @@ -0,0 +1,161 @@ +.feature > p > a { + color: #2a4678; +} + +.feature > p { + font-weight: lighter; +} + +.front-links > ul { + margin: auto; + padding: 0; + display: flex; + justify-content: center; +} + +@media screen and (max-width: 800px) { + .front-links > ul { + flex-direction: column; + } +} + +.front-links > ul > li > a, .front-links > ul > li > a:visited { + text-decoration: none; + color: #586761; +} + +.front-links > ul > li { + list-style: none; + text-align: center; + margin: 10px; + padding: 0; +} + +#features { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; + display: flex; + flex-wrap: wrap; + justify-content: center; +} + +.feature { + width: 40%; + background-image: url("/static/img/paper.jpg"); + margin: 20px 30px 20px 30px; + padding: 20px; + text-align: left; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; + color: black; +} + +.feature > img { + float: right; + width: 35%; + margin-left: 20px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +@media screen and (max-width: 800px) { + .feature { + width: 99%; + } +} + +#useful-fun { + flex-grow: 1; +} + +#fourth-box { + width: 30%; +} + +@media screen and (max-width: 800px) { + #fourth-box { + width: 99%; + } +} + +.front-links { + color: black; +} + +.response { + display: flex; + flex-direction: column; + align-items: center; +} + +#lyphebig { + display: grid; + margin: 7% 10% 0 10%; + grid-auto-flow: column; + width: 55%; +} + +@media screen and (max-width: 800px) { + #lyphebig { + grid-auto-flow: row; + } +} + +#lyphetitle { + display: grid; + margin-left: 5px; + padding-top: 20%; +} + +@media screen and (max-width: 800px) { + #lyphetitle { + padding-top: 0; + } +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 90%; + display: grid; + height: auto; +} + +#lypheimg { + width: 90%; + margin: auto; +} + +#lyphetitle > img { + width: 100%; + margin: 0; +} + +#lyphetitle > p { + font-family: NanumGothicCoding, monospace; + font-size: 175%; + color: #9baba4; +} + +@media screen and (max-width: 800px) { + #lyphetitle > h2 { + font-size: 100%; + } +} + +form { + margin-top: 10%; +} + +.pagecontent { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/home.css b/asklyphe-frontend/static/themes/default/home.css new file mode 100644 index 0000000..79db06c --- /dev/null +++ b/asklyphe-frontend/static/themes/default/home.css @@ -0,0 +1,98 @@ +.front-links > ul { + margin: auto; + padding: 0; + display: flex; + justify-content: center; +} + +.front-links > ul > li > a, .front-links > ul > li > a:visited { + text-decoration: none; + color: #586761; +} + +.front-links > ul > li { + list-style: none; + text-align: center; + margin: 10px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .front-links > ul { + flex-direction: column; + } +} + +.response { + display: flex; + flex-direction: column; + align-items: center; +} + +#lyphebig { + display: grid; + margin: 7% 10% 0 10%; + grid-auto-flow: column; + width: 55%; +} + +@media screen and (max-width: 800px) { + #lyphebig { + grid-auto-flow: row; + } +} + +#lyphetitle { + display: grid; + margin-left: 5px; + padding-top: 20%; +} + +@media screen and (max-width: 800px) { + #lyphetitle { + padding-top: 0; + } +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 90%; + display: grid; + height: auto; +} + +#lypheimg { + width: 90%; + margin: auto; +} + +#lyphetitle > img { + width: 100%; + margin: 0; +} + +#lyphetitle > h2 { + font-family: NanumGothicCoding, monospace; + font-size: 175%; + color: #9baba4; +} + +@media screen and (max-width: 800px) { + #lyphetitle > h2 { + font-size: 100%; + } +} + +form { + margin-top: 10%; +} + +.pagecontent { + margin: 0; + min-height: 100vh; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + flex-grow: 1; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/imagesearch.css b/asklyphe-frontend/static/themes/default/imagesearch.css new file mode 100644 index 0000000..2dcc933 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/imagesearch.css @@ -0,0 +1,339 @@ +.lyphe-says { + text-align: left; + min-width: 20%; + max-height: 128px; + border: 3px inset black; + padding: 10px; + background-image: url("/static/snow.gif"); +} + +.lyphe-says > img { + height: 100px; + float: left; + margin-right: 10px; +} + +.lyphe-says > h5, p { + color: black; + word-break: break-word; +} + +.lyphe-says > h5 { + padding: 0; + margin: 0; + line-height: 2em; +} + +.ask { + text-align: left; + width: 85%; +} + +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} + +.pagecontent { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +.response { + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; + padding: 20px 20px 0 20px; +} + +.resultstat { +} + +.enginelist { + display: flex; + height: 20px; +} + +.search-result-list { + width: 100%; + padding-left: 0; + list-style: none; + flex-grow: 1; +} + +.search-result-list > li { + list-style-type: none; + padding: 10px; + width: 63%; + border-top: 1px black solid; + margin-top: 5px; + display: flex; + flex-direction: column; + word-break: auto-phrase; + overflow-wrap: anywhere; +} + +@media screen and (max-width: 800px) { + .search-result-list > li { + flex-direction: column; + word-break: auto-phrase; + width: 90%; + } +} + +.search-result { + color: lightblue; + display: flex; + flex-direction: column; + text-decoration: none; +} + +.search-result:visited { + color: lightblue; +} + +.search-title { + margin: 2px 0 2px; + line-height: 1em; + font-size: 1.3em; + width: 45%; + font-weight: bold; +} + +@media screen and (max-width: 800px) { + .search-title { + width: unset; + } +} + +.search-url { + font-size: 0.8em; + color: lightgray; +} + +.search-description { + color: white; + width: 35%; + font-size: 14px; + font-weight: lighter; +} + +@media screen and (max-width: 800px) { + .search-description { + width: unset; + } +} + +.search-relevance { + font-size: 0.8em; + color: lightgray; +} + +.results-area { + width: 100%; +} + +@media screen and (max-width: 800px) { + .results-area { + display: flex; + flex-direction: column; + align-items: center; + } +} + +.complications { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + float: right; + width: 30%; + padding: 0 10px 10px 10px; + margin: 0 10px 10px 10px; +} + +@media screen and (max-width: 800px) { + .complications { + float: none; + width: unset; + } +} + +.wikipedia-complication { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.wikipedia-complication > * { + margin: auto; + text-decoration: none; + width: 100%; +} + +.wikipedia-complication > a:visited { + text-decoration: none; +} + +.wikipedia-image > img { + max-width: 100%; + max-height: 256px; + margin-top: 8px; + margin-bottom: 8px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.wikipedia-header { + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; +} + +.wikipedia-title { + text-decoration: none; + color: black; + font-size: 2em; + font-weight: bold; + display: inline-block; +} + +.wikipedia-fromwikipedia { + color: #586761; + font-size: 0.8em; + display: inline-block; +} + +.wikipedia-class { + font-size: 0.9em; + color: #333333; + margin-bottom: 8px; + display: inline-block; +} + +.wikipedia-description { + text-align: left; + display: inline-block; + color: black; + font-weight: lighter; +} + +.complications-note { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.unit_converter-complication { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.unit_converter-title { + font-size: 1.2em; + color: #586761; + font-weight: lighter; + width: 100%; + display: inline-block; +} + +.unit_converter-result { + font-size: 2em; + font-weight: bold; + display: inline-block; + word-break: break-word; + color: black; +} + +.index-bar { + display: flex; + width: 97.5%; + flex-direction: row; + align-items: start; + height: 32px; + padding-left: 2.5%; + box-shadow: inset rgba(0,0,0,0.3) 0 0 10px; + background-color: rgba(0,0,0,0.4); +} + +.index-bar > a > img { + height: 32px; +} + +.image-result-list { + width: 100%; + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: flex-start; + gap: 10px; +} + +.image-result > a > img { + height: 256px; + background-color: white; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; + max-width: 85vw; +} + +@media screen and (max-width: 800px) { + .image-result > a > img { + height: auto; + } +} + +.image-result { + flex-grow: 1; + height: 256px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-decoration: none; +} + +@media screen and (max-width: 800px) { + .image-result { + height: auto; + } + +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/inline-announcement.css b/asklyphe-frontend/static/themes/default/inline-announcement.css new file mode 100644 index 0000000..956f892 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/inline-announcement.css @@ -0,0 +1,96 @@ +#preview { + color: #9baba4; + display: flex; + flex-direction: column; + align-items: center; + font-family: monospace; + font-weight: bold; +} + +#preview a { + text-decoration: unset; + color: unset; + background-image: unset; + text-shadow: unset; + box-shadow: unset; + color: unset; + min-height: unset; + border: unset; + border-radius: unset; + padding: unset; + margin: unset; + font-size: unset; + transition: unset; + font-family: unset; + font-weight: unset; +} + +.announcement { + background: url("/static/img/announcement.png"); + width: 532px; + height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.3em; + line-height: 1.2em; + margin: 28px 32px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + font-size: 1.1em; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.1em; + margin: 24px 32px -16px; + line-height: 1em; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 0.9em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; +} + +.announcement-date { + float: right; + margin: 32px 32px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px -5px; + color: black; + display: block; + font-size: 0.6em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/default/legal.css b/asklyphe-frontend/static/themes/default/legal.css new file mode 100644 index 0000000..fea5500 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/legal.css @@ -0,0 +1,38 @@ +@font-face { + font-family: AtkinsonHyperlegible; + src: url("/static/font/AtkinsonHyperlegible-Regular.ttf"); + font-weight: normal; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: AtkinsonHyperlegible; + src: url("/static/font/AtkinsonHyperlegible-Bold.ttf"); + font-weight: bold; + font-style: normal; + font-display: swap; +} + +* { + font-family: "AtkinsonHyperlegible", sans-serif; + text-align: left; + font-weight: normal; + line-height: 2; +} + +ul { + margin-left: 10px; +} + +strong { + color: #c6ebf4; +} + +h1, h2, h3 { + font-weight: bold; + color: #c8ffd4; +} + +li { + margin-bottom: 30px; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/register.css b/asklyphe-frontend/static/themes/default/register.css new file mode 100644 index 0000000..5733a17 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/register.css @@ -0,0 +1,34 @@ +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.register-form { + text-align: center; + margin: auto; +} + +.register-form table { + margin: auto; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/search.css b/asklyphe-frontend/static/themes/default/search.css new file mode 100644 index 0000000..4e8d652 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/search.css @@ -0,0 +1,300 @@ +.lyphe-says { + text-align: left; + min-width: 20%; + max-height: 128px; + border: 3px inset black; + padding: 10px; + background-image: url("/static/snow.gif"); +} + +.lyphe-says > img { + height: 100px; + float: left; + margin-right: 10px; +} + +.lyphe-says > h5, p { + color: black; + word-break: break-word; +} + +.lyphe-says > h5 { + padding: 0; + margin: 0; + line-height: 2em; +} + +.ask { + text-align: left; + width: 85%; +} + +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} + +.pagecontent { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +.response { + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; + padding: 20px 20px 0 20px; +} + +.resultstat { +} + +.enginelist { + display: flex; + height: 20px; +} + +.search-result-list { + width: 100%; + padding-left: 0; + list-style: none; + flex-grow: 1; +} + +.search-result-list > li { + list-style-type: none; + padding: 10px; + width: 63%; + border-top: 1px black solid; + margin-top: 5px; + display: flex; + flex-direction: column; + word-break: auto-phrase; + overflow-wrap: anywhere; +} + +@media screen and (max-width: 800px) { + .search-result-list > li { + flex-direction: column; + word-break: auto-phrase; + width: 90%; + } +} + +.search-result { + color: lightblue; + display: flex; + flex-direction: column; + text-decoration: none; +} + +.search-result:visited { + color: lightblue; +} + +.search-title { + margin: 2px 0 2px; + line-height: 1em; + font-size: 1.3em; + width: 45%; + font-weight: bold; +} + +@media screen and (max-width: 800px) { + .search-title { + width: unset; + } +} + +.search-url { + font-size: 0.8em; + color: lightgray; +} + +.search-description { + color: white; + width: 35%; + font-size: 14px; + font-weight: lighter; +} + +@media screen and (max-width: 800px) { + .search-description { + width: unset; + } +} + +.search-relevance { + font-size: 0.8em; + color: lightgray; +} + +.results-area { + width: 100%; +} + +@media screen and (max-width: 800px) { + .results-area { + display: flex; + flex-direction: column; + align-items: center; + } +} + +.complications { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + float: right; + width: 30%; + padding: 0 10px 10px 10px; + margin: 0 10px 10px 10px; +} + +@media screen and (max-width: 800px) { + .complications { + float: none; + width: unset; + } +} + +.wikipedia-complication { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.wikipedia-complication > * { + margin: auto; + text-decoration: none; + width: 100%; +} + +.wikipedia-complication > a:visited { + text-decoration: none; +} + +.wikipedia-image > img { + max-width: 100%; + max-height: 256px; + margin-top: 8px; + margin-bottom: 8px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.wikipedia-header { + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; +} + +.wikipedia-title { + text-decoration: none; + color: black; + font-size: 2em; + font-weight: bold; + display: inline-block; +} + +.wikipedia-fromwikipedia { + color: #586761; + font-size: 0.8em; + display: inline-block; +} + +.wikipedia-class { + font-size: 0.9em; + color: #333333; + margin-bottom: 8px; + display: inline-block; +} + +.wikipedia-description { + text-align: left; + display: inline-block; + color: black; + font-weight: lighter; +} + +.complications-note { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.unit_converter-complication { + width: 100%; + background-image: url("/static/img/paper.jpg"); + padding: 10px; + margin: 10px; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; +} + +.unit_converter-title { + font-size: 1.2em; + color: #586761; + font-weight: lighter; + width: 100%; + display: inline-block; +} + +.unit_converter-result { + font-size: 2em; + font-weight: bold; + display: inline-block; + word-break: break-word; + color: black; +} + +.index-bar { + display: flex; + width: 97.5%; + flex-direction: row; + align-items: start; + height: 32px; + padding-left: 2.5%; + box-shadow: inset rgba(0,0,0,0.3) 0 0 10px; + background-color: rgba(0,0,0,0.4); +} + +.index-bar > a > img { + height: 32px; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/settings.css b/asklyphe-frontend/static/themes/default/settings.css new file mode 100644 index 0000000..c398275 --- /dev/null +++ b/asklyphe-frontend/static/themes/default/settings.css @@ -0,0 +1,125 @@ +.lyphe-says { + text-align: left; + min-width: 20%; + max-height: 128px; + border: 3px inset black; + padding: 10px; + background-image: url("/static/snow.gif"); +} + +.lyphe-says > img { + height: 100px; + float: left; + margin-right: 10px; +} + +.lyphe-says > h5, p { + color: black; + word-break: break-word; +} + +.lyphe-says > h5 { + padding: 0; + margin: 0; + line-height: 2em; +} + +.ask { + text-align: left; + width: 85%; +} + +.lyphe { + display: flex; + flex-direction: row; + width: 85%; + color: white; + text-decoration: none; +} + +.lyphe > * { + margin-top: auto; + margin-bottom: 1rem; +} + +.lyphe-text { + vertical-align: bottom; + display: inline; +} + +.lyphe-text > h2 { + display: inline; +} + +.lyphe-icon { + height: 120px; + margin-right: 20px; +} +.settings-area { + background-image: url("/static/img/darkened_paper.jpg"); + width: 100%; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px), + linear-gradient(to right, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px), + linear-gradient(to left, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 30px); + margin: 0; + min-height: 100vh; + width: 100%; + display: flex; + flex-direction: column; +} + +.settings-row { + display: flex; + flex-direction: row; +} + +@media screen and (max-width: 800px) { + .settings-row { + flex-direction: column; + } +} + +.settings-section { + width: 10%; + min-height: 120px; + background-image: url("/static/img/paper.jpg"); + margin: 50px 90px 30px 90px; + padding: 20px; + text-align: left; + box-shadow: rgba(0,0,0,0.3) 0 0 10px; + color: black; +} + +@media screen and (max-width: 800px) { + .settings-section { + width: 79%; + margin: 20px auto; + } +} + +.pagecontent { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +#email { + flex-grow: 1; +} + +#theme { + flex-basis: 45%; +} + +form { + display: flex; + flex-direction: column; +} + +#theme-submit { + font-size: 1em; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/default/shell.css b/asklyphe-frontend/static/themes/default/shell.css new file mode 100644 index 0000000..81f829e --- /dev/null +++ b/asklyphe-frontend/static/themes/default/shell.css @@ -0,0 +1,227 @@ +@font-face { + font-family: NanumGothicCoding; + src: url("/static/font/NanumGothicCoding.woff2") format("woff2"), + url("/static/font/NanumGothicCoding.woff") format("woff"); + font-weight: normal; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: NanumGothicCoding; + src: url("/static/font/NanumGothicCoding-Bold.woff2") format("woff2"), + url("/static/font/NanumGothicCoding-Bold.woff") format("woff"); + font-weight: bold; + font-style: normal; + font-display: swap; +} + +body { + text-align: center; + background-color: #4e6e7e; + min-height: 100vh; + margin: 0; + padding: 0; +} + +@media screen and (max-width: 800px) { + body { + padding: 0; + margin: 0; + } +} + +.main { + background-image: url("/static/img/paper.jpg"); + min-height: 100vh; + margin: 0 7% 0 7%; + color: #9baba4; + font-family: monospace; + font-weight: bold; + display: flex; + flex-direction: column; + align-items: center; + flex-grow: 1; +} + +@media screen and (max-width: 800px) { + .main { + margin: 0; + padding: 0; + width: auto; + } + + #alpha-warning, h2, h3 { + margin: 5px; + } +} + +.main > img { + max-width: 35vw; +} + +.footer { + bottom: 0; + left: 0; + width: 100%; + margin-top: 6%; +} + +.footer-inner { + /*margin: 2vw;*/ + margin: 2vw 0; + background-color: rgba(77,77,77,0.3); + border: 1px solid cadetblue; + color: white; + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; +} + +.footer-inner > ul { + padding: 0; + margin: 0; + list-style: none; + display: flex; + flex-wrap: wrap; +} + +.footer-list { + display: flex; + line-height: 1.5em; + align-items: center; +} + +.footer-item { + padding: 10px 12px; + text-align: center; +} + +.footer-item a { + color: white; + text-decoration: none; +} + +.lyphe-label { + display: block; +} + +input[type=text] { + background: url("/static/img/textbox.png") no-repeat center; + background-size: 256px 64px; + width: 232px; + height: 64px; + border: none; + padding-inline: 10px 10px; + font-family: NanumGothicCoding, monospace; + font-weight: bold; +} + +input[type=text]:focus { + border: none; +} + +button, .button { + display: inline-block; + background: url("/static/img/button.png") no-repeat center; + background-size: 138px 64px; + width: 138px; + height: 64px; + vertical-align: bottom; + padding-top: 6px; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 1.2em; + text-decoration: none; + line-height: 58px; + color: black; +} + +button:hover, .button:hover { + filter: brightness(78%); + cursor: pointer; +} + +#lyphesmall { + margin-top: 1%; + display: flex; + flex-direction: row; + height: 10%; + text-align: left; +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; + background-size: 85px; + display: grid; + height: 85px; + margin: auto; +} + +#lypheimg { + width: 85px; + margin: auto; +} + +#lyphetitlenav > img { + height: 72px; + padding-top: 20px; + margin: auto; +} + +.navbar { + width: 95%; + margin-bottom: 1%; +} + +.user-bar { + display: flex; + width: 100%; + flex-direction: row; + align-items: center; + justify-content: right; +} + +.user-bar > form { + margin: 0; +} + +.user-bar > span { + margin-top: auto; + margin-bottom: auto; +} + +.user-bar > form > button { + display: inline-block; + background: url("/static/img/button.png") no-repeat center; + background-size: 69px 32px; + width: 69px; + height: 32px; + margin-top: -6px; + vertical-align: bottom; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 0.9em; + text-decoration: none; + line-height: 10px; + color: #586761; +} + +.user-bar > a.button { + display: inline-block; + background: url("/static/img/button.png") no-repeat center; + background-size: 69px 32px; + width: 69px; + height: 32px; + margin-top: -6px; + vertical-align: bottom; + border: none; + font-family: NanumGothicCoding, monospace; + font-weight: bold; + font-size: 0.9em; + text-decoration: none; + line-height: 2.1; + color: #586761; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/freaky/inline-announcement.css b/asklyphe-frontend/static/themes/freaky/inline-announcement.css new file mode 100644 index 0000000..c8810ca --- /dev/null +++ b/asklyphe-frontend/static/themes/freaky/inline-announcement.css @@ -0,0 +1,94 @@ +#preview { + color: #9baba4; + display: flex; + flex-direction: column; + align-items: center; + font-family: monospace; + font-weight: bold; +} + +#preview a { + text-decoration: unset; + color: unset; + background-image: unset; + text-shadow: unset; + box-shadow: unset; + color: unset; + min-height: unset; + border: unset; + border-radius: unset; + padding: unset; + margin: unset; + font-size: unset; + transition: unset; + font-family: unset; + font-weight: unset; +} + +.announcement { + background: url("/static/img/announcement.png"); + width: 532px; + height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.0em; + line-height: 1.2em; + margin: 28px 32px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 0.8em; + margin: 24px 32px -16px; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 0.6em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; +} + +.announcement-date { + float: right; + margin: 32px 32px 0 3px; + font-size: 0.6em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px 0; + color: black; + display: block; + font-size: 0.6em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/freaky/logo.png b/asklyphe-frontend/static/themes/freaky/logo.png new file mode 100644 index 0000000..eaab1a6 Binary files /dev/null and b/asklyphe-frontend/static/themes/freaky/logo.png differ diff --git a/asklyphe-frontend/static/themes/freaky/papyrus.ttf b/asklyphe-frontend/static/themes/freaky/papyrus.ttf new file mode 100644 index 0000000..b530afb Binary files /dev/null and b/asklyphe-frontend/static/themes/freaky/papyrus.ttf differ diff --git a/asklyphe-frontend/static/themes/freaky/shell.css b/asklyphe-frontend/static/themes/freaky/shell.css new file mode 100644 index 0000000..8679e8a --- /dev/null +++ b/asklyphe-frontend/static/themes/freaky/shell.css @@ -0,0 +1,19 @@ +@font-face { + font-family: Papyrus; + src: url("/static/themes/freaky/papyrus.ttf"); + font-weight: normal; + font-style: normal; + font-display: swap; +} + +* { + font-family: Papyrus !important; +} + +#lyphetitle > img { + content: url("/static/themes/freaky/logo.png"); +} + +#lyphetitlenav > img { + content: url("/static/themes/freaky/logo.png"); +} diff --git a/asklyphe-frontend/static/themes/gloss/home.css b/asklyphe-frontend/static/themes/gloss/home.css new file mode 100644 index 0000000..329a94a --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/home.css @@ -0,0 +1,20 @@ +.front-links > ul > li > a, .front-links > ul > li > a:visited { + font-family: "Segoe UI", sans-serif; + color: black; + text-shadow: 0 0 8px white; +} + +.front-links > ul > li > a:hover { + color: #ffffff; + text-shadow: 0 0 12px #00c1ff; +} + +#lyphetitle > h2 { + font-family: "Segoe UI", sans-serif; + color: dimgray; + text-shadow: 0 0 8px white; +} + +.main { + background: rgba(240, 240, 240, 0.6) !important; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/gloss/imagesearch.css b/asklyphe-frontend/static/themes/gloss/imagesearch.css new file mode 100644 index 0000000..aa9bb2c --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/imagesearch.css @@ -0,0 +1,58 @@ +.main { + background: radial-gradient(circle at 75% 0, rgba(206, 255, 212, 0.6), rgba(134, 255, 128, 0.6)); +} + +.pagecontent { + background: rgba(240, 240, 240, 1.0); +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0, rgba(0, 0, 0, 0) 10px); +} + +.search-result-list > li { + border-top: 1px solid #484d50; +} + +.search-result { + color: #1b1b1b; +} + +.search-result:visited { + color: #404e50; +} + +.search-title { + margin: 2px 0 2px; + line-height: 1em; + font-size: 1.3em; + width: 45%; + font-weight: bold; +} + +.search-url { + color: dimgray; +} + +.search-description { + color: black; + font-size: 12px; + font-weight: normal; +} + +.search-relevance { + font-size: 0.8em; + color: dimgray; +} + +.wikipedia-complication, .unit_converter-complication { + border: 1px solid rgba(0,0,0,.7); + box-shadow: 2px 2px 10px 1px rgba(0,0,0,.7), inset 0 0 0 1px #fffa; + background: rgba(240, 240, 240, 0.6); + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + color: #1b1b1b; + width: 100%; + padding: 20px; +} diff --git a/asklyphe-frontend/static/themes/gloss/imagesearch.png b/asklyphe-frontend/static/themes/gloss/imagesearch.png new file mode 100644 index 0000000..c2efc78 Binary files /dev/null and b/asklyphe-frontend/static/themes/gloss/imagesearch.png differ diff --git a/asklyphe-frontend/static/themes/gloss/imagesearch_selected.png b/asklyphe-frontend/static/themes/gloss/imagesearch_selected.png new file mode 100644 index 0000000..b937405 Binary files /dev/null and b/asklyphe-frontend/static/themes/gloss/imagesearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/gloss/inline-announcement.css b/asklyphe-frontend/static/themes/gloss/inline-announcement.css new file mode 100644 index 0000000..fc47e5c --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/inline-announcement.css @@ -0,0 +1,97 @@ +#preview { + color: #9baba4; + display: flex; + flex-direction: column; + align-items: center; + font-family: monospace; + font-weight: bold; +} + +#preview a { + text-decoration: unset; + color: unset; + background-image: unset; + text-shadow: unset; + box-shadow: unset; + color: unset; + min-height: unset; + border: unset; + border-radius: unset; + padding: unset; + margin: unset; + font-size: unset; + transition: unset; + font-family: unset; + font-weight: unset; +} + +.announcement { + border: 1px solid rgba(0, 0, 0, .7); + box-shadow: 2px 2px 10px 1px rgba(0, 0, 0, .7), inset 0 0 0 1px #fffa; + background: rgba(240, 240, 240, 0.6); + font-family: "Segoe UI", sans-serif; + width: 532px; + height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.4em; + line-height: 1.2em; + margin: 28px 32px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.2em; + margin: 24px 32px -16px; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 1em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; +} + +.announcement-date { + float: right; + margin: 32px 32px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px 0; + color: black; + display: block; + font-size: 0.7em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/gloss/search.css b/asklyphe-frontend/static/themes/gloss/search.css new file mode 100644 index 0000000..aa9bb2c --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/search.css @@ -0,0 +1,58 @@ +.main { + background: radial-gradient(circle at 75% 0, rgba(206, 255, 212, 0.6), rgba(134, 255, 128, 0.6)); +} + +.pagecontent { + background: rgba(240, 240, 240, 1.0); +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0, rgba(0, 0, 0, 0) 10px); +} + +.search-result-list > li { + border-top: 1px solid #484d50; +} + +.search-result { + color: #1b1b1b; +} + +.search-result:visited { + color: #404e50; +} + +.search-title { + margin: 2px 0 2px; + line-height: 1em; + font-size: 1.3em; + width: 45%; + font-weight: bold; +} + +.search-url { + color: dimgray; +} + +.search-description { + color: black; + font-size: 12px; + font-weight: normal; +} + +.search-relevance { + font-size: 0.8em; + color: dimgray; +} + +.wikipedia-complication, .unit_converter-complication { + border: 1px solid rgba(0,0,0,.7); + box-shadow: 2px 2px 10px 1px rgba(0,0,0,.7), inset 0 0 0 1px #fffa; + background: rgba(240, 240, 240, 0.6); + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + color: #1b1b1b; + width: 100%; + padding: 20px; +} diff --git a/asklyphe-frontend/static/themes/gloss/segoeui.ttf b/asklyphe-frontend/static/themes/gloss/segoeui.ttf new file mode 100644 index 0000000..fc18ebd Binary files /dev/null and b/asklyphe-frontend/static/themes/gloss/segoeui.ttf differ diff --git a/asklyphe-frontend/static/themes/gloss/settings.css b/asklyphe-frontend/static/themes/gloss/settings.css new file mode 100644 index 0000000..5c1c420 --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/settings.css @@ -0,0 +1,22 @@ +.pagecontent { + background: rgba(240, 240, 240, 1.0); +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0, rgba(0, 0, 0, 0) 10px); +} + +.settings-area { + background: rgba(240, 240, 240, 1.0); +} + +.settings-section { + border: 1px solid rgba(0, 0, 0, .7); + box-shadow: 2px 2px 10px 1px rgba(0, 0, 0, .7), inset 0 0 0 1px #fffa; + background: rgba(240, 240, 240, 0.6); + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + color: #1b1b1b; + padding: 20px; +} diff --git a/asklyphe-frontend/static/themes/gloss/shell.css b/asklyphe-frontend/static/themes/gloss/shell.css new file mode 100644 index 0000000..99b1dca --- /dev/null +++ b/asklyphe-frontend/static/themes/gloss/shell.css @@ -0,0 +1,136 @@ +@font-face { + font-family: "Segoe UI"; + src: url("/static/themes/gloss/segoeui.ttf"); + font-weight: normal; + font-style: normal; + font-display: swap; +} +body { + background: radial-gradient(circle at 55% 45%, #74b2d1, #131c1f); +} + +.main { + border: 1px solid rgba(0,0,0,.7); + box-shadow: 2px 2px 10px 1px rgba(0,0,0,.7), inset 0 0 0 1px #fffa; + background: radial-gradient(circle at 75% 0, rgba(101, 137, 106, 0.6), rgba(145, 255, 145, 0.6)); + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + color: #1b1b1b; +} + +#lyphebig { + border: 1px solid rgba(0,0,0,.7); + border-radius: 6px; + box-shadow: 2px 2px 10px 1px rgba(0,0,0,.4), inset 0 0 0 1px #fffa; + background: rgba(240, 240, 240, 0.6); + padding: 30px; +} + +input[type=text] { + background: white; + width: unset; + height: 23px; + border: 1px solid #ccc; + border-top: 1px solid #8e8f8f; + box-sizing: border-box; + padding: 3px 4px 5px; + padding-inline: unset; + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; +} + +input[type=text]:focus { + border: 1px solid #ccc; + border-top: 1px solid #8e8f8f; +} + +button, .button { + background: linear-gradient(to bottom, #f2f2f2 45%, #ebebeb 45%, #cfcfcf); + border: 1px solid #8e8f8f; + border-radius: 3px; + width: unset; + height: 23px; + vertical-align: center; + padding: 0 12px; + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: normal; + color: black; +} + +button:hover, .button:hover { + filter: unset; + cursor: pointer; + border-color: #3c7fb1; +} + +.user-bar > form > button { + background: linear-gradient(to bottom, #f2f2f2 45%, #ebebeb 45%, #cfcfcf); + width: 69px; + height: 23px; + margin-top: unset; + vertical-align: bottom; + border: 1px solid #8e8f8f; + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: normal; + color: black; +} + +.user-bar > a.button { + background: linear-gradient(to bottom, #f2f2f2 45%, #ebebeb 45%, #cfcfcf); + width: 69px; + height: 21px; + margin: 3px; + vertical-align: bottom; + border: 1px solid #8e8f8f; + font-family: "Segoe UI", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: normal; + color: black; + padding: unset; +} + +.user-bar > form > button:hover, .user-bar > a.button:hover { + cursor: pointer; + border-color: #3c7fb1; +} + +.index-bar { + align-items: center !important; + justify-content: start; + height: 26px !important; +} + +.index-bar > a > img { + width: 57px; + height: 23px !important; +} + +.index-bar > a { + height: 23px !important; +} + +#websearch-img { + content: url("/static/themes/gloss/websearch.png"); +} + +#websearch-img-selected { + content: url("/static/themes/gloss/websearch_selected.png"); +} + +#imagesearch-img { + content: url("/static/themes/gloss/imagesearch.png"); +} + +#imagesearch-img-selected { + content: url("/static/themes/gloss/imagesearch_selected.png"); +} diff --git a/asklyphe-frontend/static/themes/gloss/websearch.png b/asklyphe-frontend/static/themes/gloss/websearch.png new file mode 100644 index 0000000..49ca542 Binary files /dev/null and b/asklyphe-frontend/static/themes/gloss/websearch.png differ diff --git a/asklyphe-frontend/static/themes/gloss/websearch_selected.png b/asklyphe-frontend/static/themes/gloss/websearch_selected.png new file mode 100644 index 0000000..c336359 Binary files /dev/null and b/asklyphe-frontend/static/themes/gloss/websearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/oled/home.css b/asklyphe-frontend/static/themes/oled/home.css new file mode 100644 index 0000000..90d2028 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/home.css @@ -0,0 +1,11 @@ +.front-links > ul > li > a, .front-links > ul > li > a:visited { + color: white; +} + +.bent-surrounding { + background: black; +} + +#lyphetitle > h2 { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/oled/imagesearch.css b/asklyphe-frontend/static/themes/oled/imagesearch.css new file mode 100644 index 0000000..5871574 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/imagesearch.css @@ -0,0 +1,68 @@ +.pagecontent { + background: black; + border: 1px solid white; +} +.search-result { + color: white; + padding: 10px; + border: 1px solid white; + margin: 3px; +} + +.search-result:visited { + color: steelblue; +} +.search-url { + color: lightgray; +} + +.search-description { + color: gray; +} + +.search-relevance { + color: lightgray; +} + +.wikipedia-complication { + background: black; + border: 1px solid white; +} + +.wikipedia-image > img { + background: gray; +} + +.wikipedia-title { + color: white; +} + +.wikipedia-fromwikipedia { + color: lightslategray; +} + +.wikipedia-class { + color: lightslategray; +} + +.wikipedia-description { + color: white; +} + +.complications-note { + background: black; + border: 1px solid white; +} + +.unit_converter-complication { + background: black; + border: 1px solid white; +} + +.unit_converter-title { + color: white; +} + +.unit_converter-result { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/oled/imagesearch.png b/asklyphe-frontend/static/themes/oled/imagesearch.png new file mode 100644 index 0000000..0dd3ca1 Binary files /dev/null and b/asklyphe-frontend/static/themes/oled/imagesearch.png differ diff --git a/asklyphe-frontend/static/themes/oled/imagesearch_selected.png b/asklyphe-frontend/static/themes/oled/imagesearch_selected.png new file mode 100644 index 0000000..d7343c2 Binary files /dev/null and b/asklyphe-frontend/static/themes/oled/imagesearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/oled/inline-announcement.css b/asklyphe-frontend/static/themes/oled/inline-announcement.css new file mode 100644 index 0000000..dccc3d9 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/inline-announcement.css @@ -0,0 +1,72 @@ +.announcement { + border: 1px solid white; + width: 532px; + height: 148px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.4em; + line-height: 1.2em; + margin: 18px 24px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.2em; + margin: 18px 24px -16px; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 1em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; + color: #00c1ff; +} + +.announcement > p > a:visited { + color: #00c1ff; +} + +.announcement-date { + float: right; + margin: 24px 24px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px 0; + color: ghostwhite; + display: block; + font-size: 0.7em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/oled/logo.png b/asklyphe-frontend/static/themes/oled/logo.png new file mode 100644 index 0000000..5d28bdb Binary files /dev/null and b/asklyphe-frontend/static/themes/oled/logo.png differ diff --git a/asklyphe-frontend/static/themes/oled/search.css b/asklyphe-frontend/static/themes/oled/search.css new file mode 100644 index 0000000..5871574 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/search.css @@ -0,0 +1,68 @@ +.pagecontent { + background: black; + border: 1px solid white; +} +.search-result { + color: white; + padding: 10px; + border: 1px solid white; + margin: 3px; +} + +.search-result:visited { + color: steelblue; +} +.search-url { + color: lightgray; +} + +.search-description { + color: gray; +} + +.search-relevance { + color: lightgray; +} + +.wikipedia-complication { + background: black; + border: 1px solid white; +} + +.wikipedia-image > img { + background: gray; +} + +.wikipedia-title { + color: white; +} + +.wikipedia-fromwikipedia { + color: lightslategray; +} + +.wikipedia-class { + color: lightslategray; +} + +.wikipedia-description { + color: white; +} + +.complications-note { + background: black; + border: 1px solid white; +} + +.unit_converter-complication { + background: black; + border: 1px solid white; +} + +.unit_converter-title { + color: white; +} + +.unit_converter-result { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/oled/settings.css b/asklyphe-frontend/static/themes/oled/settings.css new file mode 100644 index 0000000..8528c74 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/settings.css @@ -0,0 +1,20 @@ +.settings-area { + background: black; + border: 1px solid white; +} + +@media screen and (max-width: 800px) { + .settings-area { + width: calc(100% - 1px); + } +} + +.settings-section { + background: black; + border: 1px solid white; + color: white; +} + +p { + color: white; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/oled/shell.css b/asklyphe-frontend/static/themes/oled/shell.css new file mode 100644 index 0000000..9f52489 --- /dev/null +++ b/asklyphe-frontend/static/themes/oled/shell.css @@ -0,0 +1,74 @@ +body { + background-color: black; +} + +.main { + background: black; + color: white; + border: 1px solid white; + border-top-color: black; + border-bottom-color: black; +} + +input[type=text] { + background: black; + background-size: 256px 64px; + height: 40px; + color: white; + border: 1px solid white; + padding: 0; +} + +button, .button { + background: black; + background-size: 138px 64px; + height: 42px; + color: white; + border: 1px solid white; + line-height: 0; + padding: 0; +} + +.bent-surrounding { + background: url("/static/img/borderbent.png") no-repeat center; +} + +.user-bar > form > button { + background: black; + border: 1px solid white; + width: 69px; + height: 32px; + color: white; +} + +.user-bar > a.button { + background: black; + border: 1px solid white; + width: 69px; + height: 30px; + color: white; +} + +#lyphetitle > img { + content: url("/static/themes/oled/logo.png"); +} + +#lyphetitlenav > img { + content: url("/static/themes/oled/logo.png"); +} + +#websearch-img { + content: url("/static/themes/oled/websearch.png"); +} + +#websearch-img-selected { + content: url("/static/themes/oled/websearch_selected.png"); +} + +#imagesearch-img { + content: url("/static/themes/oled/imagesearch.png"); +} + +#imagesearch-img-selected { + content: url("/static/themes/oled/imagesearch_selected.png"); +} diff --git a/asklyphe-frontend/static/themes/oled/websearch.png b/asklyphe-frontend/static/themes/oled/websearch.png new file mode 100644 index 0000000..7a20c0b Binary files /dev/null and b/asklyphe-frontend/static/themes/oled/websearch.png differ diff --git a/asklyphe-frontend/static/themes/oled/websearch_selected.png b/asklyphe-frontend/static/themes/oled/websearch_selected.png new file mode 100644 index 0000000..b17a6ed Binary files /dev/null and b/asklyphe-frontend/static/themes/oled/websearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/water/bg.png b/asklyphe-frontend/static/themes/water/bg.png new file mode 100644 index 0000000..1e1a9af Binary files /dev/null and b/asklyphe-frontend/static/themes/water/bg.png differ diff --git a/asklyphe-frontend/static/themes/water/border.png b/asklyphe-frontend/static/themes/water/border.png new file mode 100644 index 0000000..990f30f Binary files /dev/null and b/asklyphe-frontend/static/themes/water/border.png differ diff --git a/asklyphe-frontend/static/themes/water/button_mid.png b/asklyphe-frontend/static/themes/water/button_mid.png new file mode 100644 index 0000000..d2110df Binary files /dev/null and b/asklyphe-frontend/static/themes/water/button_mid.png differ diff --git a/asklyphe-frontend/static/themes/water/button_small.png b/asklyphe-frontend/static/themes/water/button_small.png new file mode 100644 index 0000000..802bf6f Binary files /dev/null and b/asklyphe-frontend/static/themes/water/button_small.png differ diff --git a/asklyphe-frontend/static/themes/water/home.css b/asklyphe-frontend/static/themes/water/home.css new file mode 100644 index 0000000..99bfcc4 --- /dev/null +++ b/asklyphe-frontend/static/themes/water/home.css @@ -0,0 +1,9 @@ +.front-links > ul > li > a, .front-links > ul > li > a:visited { + font-family: "Lucida Grande", sans-serif; + color: gray; +} + +#lyphetitle > h2 { + font-family: "Lucida Grande", sans-serif; + color: gray; +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/water/imagesearch.css b/asklyphe-frontend/static/themes/water/imagesearch.css new file mode 100644 index 0000000..bac7976 --- /dev/null +++ b/asklyphe-frontend/static/themes/water/imagesearch.css @@ -0,0 +1,54 @@ +.pagecontent { + background: white; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +.search-result-list > li { + list-style-type: none; + padding: 10px; + border-top: 1px dimgray solid; + margin-top: 5px; + display: flex; + flex-direction: column; + word-break: break-all; +} + +.search-result { + color: black; +} + +.search-title { + font-size: 14px; +} + +.search-result:visited { + color: dimgray; +} + +.search-url { + font-size: 0.8em; + color: dimgray; +} + +.search-relevance { + color: dimgray; +} + +.search-description { + color: black; + font-size: 12px; +} + +.wikipedia-complication, .unit_converter-complication { + background-image: url("/static/themes/water/bg.png"); + border-radius: 6px; + width: 100%; + padding: 20px; + box-shadow: dimgray 0 0 10px; +} diff --git a/asklyphe-frontend/static/themes/water/imagesearch.png b/asklyphe-frontend/static/themes/water/imagesearch.png new file mode 100644 index 0000000..c6634af Binary files /dev/null and b/asklyphe-frontend/static/themes/water/imagesearch.png differ diff --git a/asklyphe-frontend/static/themes/water/imagesearch_selected.png b/asklyphe-frontend/static/themes/water/imagesearch_selected.png new file mode 100644 index 0000000..ead483a Binary files /dev/null and b/asklyphe-frontend/static/themes/water/imagesearch_selected.png differ diff --git a/asklyphe-frontend/static/themes/water/inline-announcement.css b/asklyphe-frontend/static/themes/water/inline-announcement.css new file mode 100644 index 0000000..4f084bb --- /dev/null +++ b/asklyphe-frontend/static/themes/water/inline-announcement.css @@ -0,0 +1,96 @@ +#preview { + color: #9baba4; + display: flex; + flex-direction: column; + align-items: center; + font-family: monospace; + font-weight: bold; +} + +#preview a { + text-decoration: unset; + color: unset; + background-image: unset; + text-shadow: unset; + box-shadow: unset; + color: unset; + min-height: unset; + border: unset; + border-radius: unset; + padding: unset; + margin: unset; + font-size: unset; + transition: unset; + font-family: unset; + font-weight: unset; +} + +.announcement { + background-image: url("/static/themes/water/bg.png"); + border-radius: 6px; + width: 532px; + height: 148px; + box-shadow: dimgray 0 0 10px; +} + +@media screen and (max-width: 800px) { + .announcement { + margin-top: 10px; + background-size: cover; + width: 354px; + height: 98px; + } +} + +.announcement > h4 { + text-align: left; + font-weight: bold; + font-size: 1.4em; + line-height: 1.2em; + margin: 28px 32px -16px; + padding: 0; +} + +@media screen and (max-width: 800px) { + .announcement > h4 { + margin: 8px 12px -16px; + } +} + +.announcement > p { + text-align: left; + font-weight: normal; + font-size: 1.2em; + margin: 24px 32px -16px; +} + +@media screen and (max-width: 800px) { + .announcement > p { + margin: 14px 12px -12px; + font-size: 1em; + } +} + +.announcement > p > a { + font-size: 0.6em !important; + font-family: monospace !important; + font-weight: bold !important; +} + +.announcement-date { + float: right; + margin: 32px 32px 0 3px; + font-size: 0.8em; +} + +@media screen and (max-width: 800px) { + .announcement-date { + float: none; + text-align: left; + margin: 14px 12px 0; + color: black; + display: block; + font-size: 0.7em; + line-height: 0; + } +} diff --git a/asklyphe-frontend/static/themes/water/logo.png b/asklyphe-frontend/static/themes/water/logo.png new file mode 100644 index 0000000..6baaf2f Binary files /dev/null and b/asklyphe-frontend/static/themes/water/logo.png differ diff --git a/asklyphe-frontend/static/themes/water/lucidagrande.ttf b/asklyphe-frontend/static/themes/water/lucidagrande.ttf new file mode 100755 index 0000000..63c3d97 Binary files /dev/null and b/asklyphe-frontend/static/themes/water/lucidagrande.ttf differ diff --git a/asklyphe-frontend/static/themes/water/search.css b/asklyphe-frontend/static/themes/water/search.css new file mode 100644 index 0000000..bac7976 --- /dev/null +++ b/asklyphe-frontend/static/themes/water/search.css @@ -0,0 +1,54 @@ +.pagecontent { + background: white; +} + +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 0, rgba(0, 0, 0, 0) 50px); + margin: 0; + min-height: 100vh; + width: 100%; +} + +.search-result-list > li { + list-style-type: none; + padding: 10px; + border-top: 1px dimgray solid; + margin-top: 5px; + display: flex; + flex-direction: column; + word-break: break-all; +} + +.search-result { + color: black; +} + +.search-title { + font-size: 14px; +} + +.search-result:visited { + color: dimgray; +} + +.search-url { + font-size: 0.8em; + color: dimgray; +} + +.search-relevance { + color: dimgray; +} + +.search-description { + color: black; + font-size: 12px; +} + +.wikipedia-complication, .unit_converter-complication { + background-image: url("/static/themes/water/bg.png"); + border-radius: 6px; + width: 100%; + padding: 20px; + box-shadow: dimgray 0 0 10px; +} diff --git a/asklyphe-frontend/static/themes/water/settings.css b/asklyphe-frontend/static/themes/water/settings.css new file mode 100644 index 0000000..85cdce0 --- /dev/null +++ b/asklyphe-frontend/static/themes/water/settings.css @@ -0,0 +1,20 @@ +.pagegradient { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 0, rgba(0, 0, 0, 0) 50px); +} + +.settings-area { + background: white; + width: 100%; +} + +.settings-section { + background-image: url("/static/themes/water/bg.png"); + border-radius: 6px; + padding: 20px; + box-shadow: dimgray 0 0 10px; +} + +#theme-submit { + margin-top: 10px; + background-image: url("/static/themes/water/button_mid.png"); +} \ No newline at end of file diff --git a/asklyphe-frontend/static/themes/water/shell.css b/asklyphe-frontend/static/themes/water/shell.css new file mode 100644 index 0000000..c29d0e4 --- /dev/null +++ b/asklyphe-frontend/static/themes/water/shell.css @@ -0,0 +1,138 @@ +@font-face { + font-family: "Lucida Grande"; + src: url("/static/themes/water/lucidagrande.ttf"); + font-weight: normal; + font-style: normal; + font-display: swap; +} + +#lyphetitle > img { + content: url("/static/themes/water/logo.png"); +} + +#lyphetitlenav > img { + content: url("/static/themes/water/logo.png"); +} + +body { + background: url("/static/themes/water/bg.png"); +} + +.main { + background: white; + color: black; + font-family: "Lucida Grande", sans-serif; + font-weight: bold; + font-size: 12px; + box-shadow: 0 0 40px 0 dimgray; +} + +label { + margin-bottom: 10px; +} + +button, .button { + display: inline-block; + background: url("/static/themes/water/button_small.png") no-repeat center; + width: 100px; + height: 21px; + vertical-align: unset; + padding: 3px; + border: none; + font-family: "Lucida Grande", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: 0; + color: black; +} + +button:hover, .button:hover { + filter: brightness(95%); + cursor: pointer; +} + +input[type=text] { + background: linear-gradient(to bottom, #ebebeb 0%, white 20%); + border-radius: 7px; + width: 300px; + height: 19px; + padding: 3px; + border: 1px solid dimgray; + padding-inline: 3px 0; + font-family: "Lucida Grande", sans-serif; + font-weight: normal; + font-size: 12px; +} + +.user-bar { + color: dimgray; + font-family: "Lucida Grande", sans-serif; + font-weight: normal; + font-size: 12px; +} + +.user-bar > form > button { + background: url("/static/themes/water/button_small.png") no-repeat center; + width: 64px; + height: 21px; + margin: unset; + vertical-align: bottom; + border: none; + font-family: "Lucida Grande", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: 10px; + color: black; +} + +.user-bar > a.button { + background: url("/static/themes/water/button_small.png") no-repeat center; + width: 64px; + height: 21px; + margin: 0; + vertical-align: unset; + border: none; + font-family: "Lucida Grande", sans-serif; + font-weight: normal; + font-size: 12px; + text-decoration: none; + line-height: 21px; + color: black; +} + +.footer-inner { + color: black; +} + +.footer-item a { + color: black; +} + +.index-bar { + background: url("/static/themes/water/bg.png"); + align-items: center !important; + justify-content: start; +} + +.index-bar > a > img { + width: 54px; + height: 21px !important; +} + +#websearch-img { + content: url("/static/themes/water/websearch.png"); +} + +#websearch-img-selected { + content: url("/static/themes/water/websearch_selected.png"); +} + +#imagesearch-img { + content: url("/static/themes/water/imagesearch.png"); +} + +#imagesearch-img-selected { + content: url("/static/themes/water/imagesearch_selected.png"); +} diff --git a/asklyphe-frontend/static/themes/water/websearch.png b/asklyphe-frontend/static/themes/water/websearch.png new file mode 100644 index 0000000..b2af012 Binary files /dev/null and b/asklyphe-frontend/static/themes/water/websearch.png differ diff --git a/asklyphe-frontend/static/themes/water/websearch_selected.png b/asklyphe-frontend/static/themes/water/websearch_selected.png new file mode 100644 index 0000000..5d5667a Binary files /dev/null and b/asklyphe-frontend/static/themes/water/websearch_selected.png differ diff --git a/asklyphe-frontend/templates/404.html b/asklyphe-frontend/templates/404.html new file mode 100644 index 0000000..66f0d82 --- /dev/null +++ b/asklyphe-frontend/templates/404.html @@ -0,0 +1,23 @@ + + + + + + + AskLyphe - Not Found + + + + + + + +

404 - Not Found

+

lyphe couldn't find the requested page :(

+back to frontpage! + + + diff --git a/asklyphe-frontend/templates/admin/allusers.html b/asklyphe-frontend/templates/admin/allusers.html new file mode 100644 index 0000000..861767e --- /dev/null +++ b/asklyphe-frontend/templates/admin/allusers.html @@ -0,0 +1,23 @@ +{% extends "admin/shell.html" %} + +{% block title %}User Listing{% endblock %} + +{% block head %} +{% endblock %} + +{% block page %} +

lyphe users

+

important note

+

+ one user in this list has their username truncated to 32 characters, their full username is shown below. + i promised this person that they could keep their super long username, and i will fulfil this promise. +
+ liyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliyliy +

+ + + {% for user in users %} + + {% endfor %} +
usernameemailverifiedadministrator
{{ user.username }}{{ user.email }}{{ user.verified }}{{ user.admin }}
+{% endblock %} diff --git a/asklyphe-frontend/templates/admin/announcement.html b/asklyphe-frontend/templates/admin/announcement.html new file mode 100644 index 0000000..44085f2 --- /dev/null +++ b/asklyphe-frontend/templates/admin/announcement.html @@ -0,0 +1,39 @@ +{% extends "admin/shell.html" %} + +{% block title %}Announcement Writer{% endblock %} + +{% block head %} + +{% endblock %} + +{% block page %} +{% match error %} +{% when Some with (error) %} +

{{ error }}

+{% when None %} +{% endmatch %} +
+

announcement writer!

+

you will be writing announcements as {{ username }}

+ + + + + + + + + + + +
+
+

this is what your announcement will look like on the frontpage!

+
+ Mon, 18 Nov 2024 21:00:00 +0000 +

filled in by javascript

+

+

Read More...

+
+
+{% endblock %} diff --git a/asklyphe-frontend/templates/admin/error.html b/asklyphe-frontend/templates/admin/error.html new file mode 100644 index 0000000..ba86ac3 --- /dev/null +++ b/asklyphe-frontend/templates/admin/error.html @@ -0,0 +1,13 @@ +{% extends "admin/shell.html" %} + +{% block title %}Error!{% endblock %} + +{% block head %} +{% endblock %} + +{% block page %} +

uh oh!

+

an internal server error occurred:

+

{{ error }}

+

report to supervisor!

+{% endblock %} diff --git a/asklyphe-frontend/templates/admin/home.html b/asklyphe-frontend/templates/admin/home.html new file mode 100644 index 0000000..cf9e1e7 --- /dev/null +++ b/asklyphe-frontend/templates/admin/home.html @@ -0,0 +1,25 @@ +{% extends "admin/shell.html" %} + +{% block title %}Home{% endblock %} + +{% block head %} +{% endblock %} + +{% block page %} +

hello administrator!

+
+
+

user count: {{ user_count }}

+

of those users, {{ admin_count }} are administrators

+

currently, there are {{ active_verification_requests }} unverified accounts

+
+
+

last ten users registered:

+
    + {% for user in last_ten_users %} +
  1. {{user}}
  2. + {% endfor %} +
+
+
+{% endblock %} diff --git a/asklyphe-frontend/templates/admin/invitecode.html b/asklyphe-frontend/templates/admin/invitecode.html new file mode 100644 index 0000000..f7c7039 --- /dev/null +++ b/asklyphe-frontend/templates/admin/invitecode.html @@ -0,0 +1,33 @@ +{% extends "admin/shell.html" %} + +{% block title %}Home{% endblock %} + +{% block head %} +{% endblock %} + +{% block page %} +

invite code page

+
+

invite code generator!

+

you will be inserting codes as {{ username }}

+ + + + + +
+

active invite codes

+ + + {% for code in active_codes %} + + {% endfor %} +
codeissuerroot issuerissued oncomment
{{ code.code }}{{ code.creator }}{{ code.root_creator }}{{ code.created_at }}{{ code.comment }}
+

used invite codes (fixme: separate into pages to prevent long load times in the future)

+ + + {% for code in used_codes %} + + {% endfor %} +
codeissuerroot issuerissued onused onused bycomment
{{ code.code }}{{ code.creator }}{{ code.root_creator }}{{ code.created_at }}{{ code.used_at.as_ref().unwrap() }}{{ code.used_by.as_ref().unwrap() }}{{ code.comment }}
+{% endblock %} diff --git a/asklyphe-frontend/templates/admin/shell.html b/asklyphe-frontend/templates/admin/shell.html new file mode 100644 index 0000000..c81ffa5 --- /dev/null +++ b/asklyphe-frontend/templates/admin/shell.html @@ -0,0 +1,32 @@ + + + + + + + AskLyphe Administrator Panel - {% block title %}{% endblock %} + + + + {% block head %}{% endblock %} + + + +
+ +
+ {% block page %}{% endblock %} +
+
+ + \ No newline at end of file diff --git a/asklyphe-frontend/templates/announcement.html b/asklyphe-frontend/templates/announcement.html new file mode 100644 index 0000000..2b0e566 --- /dev/null +++ b/asklyphe-frontend/templates/announcement.html @@ -0,0 +1,44 @@ +{% extends "shell.html" %} + +{% block title %}{{ announcement.title }}{% endblock %} + +{% block head %} + +{% endblock %} + +{% block page %} +
+ + +
+
+
+
+
+

{{ announcement.title }}

+
{{ announcement.date }}
+
posted by {{ announcement.creator }}
+
+

{{ announcement.full|safe }}

+
+
+
+
+
+
+ + {% include "ui/footer.html" %} +
+{% endblock %} \ No newline at end of file diff --git a/asklyphe-frontend/templates/frontpage.html b/asklyphe-frontend/templates/frontpage.html new file mode 100644 index 0000000..7b84662 --- /dev/null +++ b/asklyphe-frontend/templates/frontpage.html @@ -0,0 +1,158 @@ +{% extends "shell.html" %} + +{% block title %}the best search engine{% endblock %} + +{% block head %} + + +{% endblock %} + +{% block page %} +
+ {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% endif %} + {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% endmatch %} +
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +

a user-first, customizable, useful, and fun search engine!

+
+
+

currently in invite-only alpha, you must have an invite code to register (:

+

invites are currently given out at our discretion. please don't email us begging us for an invite code (:

+ +

{{ count }} sites indexed!

+ + + {% match announcement %} + {% when Some with (a) %} +
+ {{ a.date }} +

{{ a.title }}

+

{{ a.content }}

+

Read More...

+
+ {% when None %} + {% endmatch %} + +
+
+
+
+

user-first

+ lorem ipsum dolor sit amet +

+ we will never serve a single ad. +
+
+ since we will earn money off of subscriptions and do not accept investments or vc funding, + our platform is not a two-sided market, + and thus we do not have anyone we need to please other than our users! +
+
+ furthermore, we will attempt to be as transparent about our methods as possible; + all public-facing search engine software will be open-sourced under AGPL, and we will maintain a publicly + viewable + list of the websites that we derank or block, including a reason with each one. +
+
+ finally, we do not claim to be in any way "apolitical". + we recognize the responsibility we are taking upon ourselves by running a search engine, + and will always respect ethics. +

+
+
+

customizable

+ lorem ipsum dolor sit amet +

+ we aim to design askLyphe in a way that makes personalizing your search results easy and fun! +
+
+ currently we provide a short list of unique themes to let you properly express yourself through your + searching experience, however in the future we also plan to let you customize many more aspects of + the experience, such as through manual ranking personalisation and complications! +

+
+
+

useful, but fun!

+ lorem ipsum dolor sit amet +

+ our search engine does not rely on (however may still include, for completeness) results from + Google, Bing, or any other search engine out there. +
+
+ because of this, we're able to find websites that other search engines would have trouble finding, + and bring personality and humanity back to the web! +
+ however, we also recognize that there are many queries that we simply do not have enough information + to handle + in order to fix this issue, we have a system called +
+ complications! +
+
+ askLyphe complications act in a similar way to watch complications, they show relevant answers to + your + queries with information from trusted sources! +
+ want to find information on the microsoft corporation? + just search "microsoft" to get results from our wikipedia complication! + need to convert 500 feet to kilometers? + just search "500 ft to km" to get results from our unit conversion complication! +
+
+ plus, we're constantly working on developing new complications, and will allow full customization of the + complications + that you see in your results! +

+
+
+

fourth box!

+ lorem ipsum dolor sit amet +

+ i haven't decided what to put here yet! we're still in alpha so i'm sure i'll come up with something + eventually, but i wanted this fourth box because i feel like the design flows nicer with it (: +
+
+ ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo + consequat. + duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla + pariatur. +
+ excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id + est laborum. +

+
+
+
+
+ +{% include "ui/footer.html" %} +{% endblock %} diff --git a/asklyphe-frontend/templates/home.html b/asklyphe-frontend/templates/home.html new file mode 100644 index 0000000..0d6296d --- /dev/null +++ b/asklyphe-frontend/templates/home.html @@ -0,0 +1,74 @@ +{% extends "shell.html" %} + +{% block title %}Home{% endblock %} + +{% block head %} + + + +{% endblock %} + +{% block page %} +
+ {% include "ui/userbar.html" %} + {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% endif %} +
+
+
+ image of lyphe, our mascot! +
+
+ ask Lyphe! +

the best search engine!

+
+
+
+ + + +
+ +
+

{{ count }} sites indexed!

+ + + + {% match announcement %} + {% when Some with (a) %} +
+ {{ a.date }} +

{{ a.title }}

+

{{ a.content }}

+

Read More...

+
+ {% when None %} + {% endmatch %} +
+ {% include "ui/footer.html" %} +
+{% endblock %} \ No newline at end of file diff --git a/asklyphe-frontend/templates/image_search.html b/asklyphe-frontend/templates/image_search.html new file mode 100644 index 0000000..0adb67c --- /dev/null +++ b/asklyphe-frontend/templates/image_search.html @@ -0,0 +1,64 @@ +{% extends "shell.html" %} + +{% block title %}Images - {{ search_query }}{% endblock %} + +{% block head %} + + +{% if search_query == "notnite" %}{% endif %} +{% endblock %} + +{% block page %} +
+ {% include "ui/userbar.html" %} + {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% endif %} + {% include "ui/navbar_image.html" %} + + + +
+
+
+ {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% match note %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% endmatch %} +
+
+ {% for result in search_results %} +
+ + image result + +
+ {% endfor %} +
+ {% if blocked.len() > 0 %} + {{ blocked.len() }} results were pruned from search results for the following reasons: +
    + {% for (url, reason) in blocked %} +
  1. "{{ url }}" because "{{ reason }}"
  2. + {% endfor %} +
+ {% endif %} +
+ {% endmatch %} +
+
+
+ + {% include "ui/footer.html" %} +
+{% endblock %} \ No newline at end of file diff --git a/asklyphe-frontend/templates/loremipsum.html b/asklyphe-frontend/templates/loremipsum.html new file mode 100644 index 0000000..dab8b7b --- /dev/null +++ b/asklyphe-frontend/templates/loremipsum.html @@ -0,0 +1,20 @@ +onsectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +
+
+ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. +duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla +pariatur. +
+excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id +est laborum. +
+
+sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, +totam +rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt +explicabo. +
+nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur +magni +dolores eos qui ratione voluptatem sequi nesciunt. diff --git a/asklyphe-frontend/templates/search.html b/asklyphe-frontend/templates/search.html new file mode 100644 index 0000000..db6868b --- /dev/null +++ b/asklyphe-frontend/templates/search.html @@ -0,0 +1,100 @@ +{% extends "shell.html" %} + +{% block title %}{{ search_query }}{% endblock %} + +{% block head %} + + +{% if search_query == "notnite" %}{% endif %} +{% endblock %} + +{% block page %} +
+ {% include "ui/userbar.html" %} + {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% endif %} + {% include "ui/navbar.html" %} + + + +
+
+
+ {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% match note %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} + {% endmatch %} +
found {{ search_results.len() }} results in {{ query_time }} seconds ({{ + page_rank_time + }} was pageranking) +
+
+
+ {% if complications.disabled %} +
+ complications disabled for this query +
+ {% endif %} + {% match complications.unit_converter %} + {% when Some with (conversion) %} +
+ lyphe unit converter + {{ conversion.value }} {{ conversion.unit_a }} = {{ conversion.equals }} {{ conversion.unit_b }} +
+ {% when None %} + {% endmatch %} + {% match complications.wikipedia %} + {% when Some with (wikipedia) %} + + {% when None %} + {% endmatch %} +
+
    + {% for result in search_results %} + {% include "ui/search_result.html" %} + {% endfor %} +
+ {% if blocked.len() > 0 %} + {{ blocked.len() }} results were pruned from search results for the following reasons: +
    + {% for (url, reason) in blocked %} +
  1. "{{ url }}" because "{{ reason }}"
  2. + {% endfor %} +
+ {% endif %} +
+ {% endmatch %} +
+
+
+ + {% include "ui/footer.html" %} +
+{% endblock %} \ No newline at end of file diff --git a/asklyphe-frontend/templates/search_js.html b/asklyphe-frontend/templates/search_js.html new file mode 100644 index 0000000..aa55755 --- /dev/null +++ b/asklyphe-frontend/templates/search_js.html @@ -0,0 +1,79 @@ +{% extends "shell.html" %} + +{% block title %}{{ search_query }}{% endblock %} + +{% block head %} + + +{% if search_query == "notnite" %}{% endif %} + +{% endblock %} + +{% block page %} +
+ {% include "ui/userbar.html" %} + {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% endif %} + {% include "ui/navbar.html" %} + + + +
+
+
+ {% match error %} + {% when Some with (val) %} +
{{ val }}
+ {% when None %} +
+
+ {% if complications.disabled %} +
+ complications disabled for this query +
+ {% endif %} + {% match complications.unit_converter %} + {% when Some with (conversion) %} +
+ lyphe unit converter + {{ conversion.value }} {{ conversion.unit_a }} = {{ conversion.equals }} {{ conversion.unit_b }} +
+ {% when None %} + {% endmatch %} + {% match complications.wikipedia %} + {% when Some with (wikipedia) %} + + {% when None %} + {% endmatch %} +
+
+ {% endmatch %} +
+
+
+ + {% include "ui/footer.html" %} +
+{% endblock %} \ No newline at end of file diff --git a/asklyphe-frontend/templates/shell.html b/asklyphe-frontend/templates/shell.html new file mode 100644 index 0000000..aa1802e --- /dev/null +++ b/asklyphe-frontend/templates/shell.html @@ -0,0 +1,22 @@ + + + + + + + AskLyphe - {% block title %}{% endblock %} + + + + + + + {% block head %}{% endblock %} + + + {% block page %}{% endblock %} + + \ No newline at end of file diff --git a/asklyphe-frontend/templates/ui/footer.html b/asklyphe-frontend/templates/ui/footer.html new file mode 100644 index 0000000..4764e6c --- /dev/null +++ b/asklyphe-frontend/templates/ui/footer.html @@ -0,0 +1,31 @@ + \ No newline at end of file diff --git a/asklyphe-frontend/templates/ui/navbar.html b/asklyphe-frontend/templates/ui/navbar.html new file mode 100644 index 0000000..b9c6424 --- /dev/null +++ b/asklyphe-frontend/templates/ui/navbar.html @@ -0,0 +1,32 @@ + \ No newline at end of file diff --git a/asklyphe-frontend/templates/ui/navbar_image.html b/asklyphe-frontend/templates/ui/navbar_image.html new file mode 100644 index 0000000..9d2bfee --- /dev/null +++ b/asklyphe-frontend/templates/ui/navbar_image.html @@ -0,0 +1,33 @@ + \ No newline at end of file diff --git a/asklyphe-frontend/templates/ui/search_result.html b/asklyphe-frontend/templates/ui/search_result.html new file mode 100644 index 0000000..772e511 --- /dev/null +++ b/asklyphe-frontend/templates/ui/search_result.html @@ -0,0 +1,25 @@ +
  • + +

    {% match result.title %}{% when Some with (title) %}{{ title }}{% when None %}{{ result.url }}{% endmatch %}

    + + {% match result.title %} + {% when Some with (_) %}{{ result.url }}{% when None %} + {% endmatch %} + ({{ result.percentage }}%, {{ result.value }} / {{ max_relevance }}) + + {% if result.asklyphe %} + + {% endif %} + {% if result.bing %} + + {% endif %} + {% if result.google %} + + {% endif %} + + + {% match result.description %}{% when Some with (description) %} + {{ description }} + {% when None %}{% endmatch %} +
    +
  • \ No newline at end of file diff --git a/asklyphe-frontend/templates/ui/userbar.html b/asklyphe-frontend/templates/ui/userbar.html new file mode 100644 index 0000000..a14dc4f --- /dev/null +++ b/asklyphe-frontend/templates/ui/userbar.html @@ -0,0 +1,10 @@ +
    + welcome {{ info.username }}! + {%if info.administrator %} + admin + {% endif %} + settings +
    + +
    +
    diff --git a/asklyphe-frontend/templates/user_settings.html b/asklyphe-frontend/templates/user_settings.html new file mode 100644 index 0000000..c09a8f8 --- /dev/null +++ b/asklyphe-frontend/templates/user_settings.html @@ -0,0 +1,68 @@ +{% extends "shell.html" %} + +{% block title %}{{ search_query }}{% endblock %} + +{% block head %} + + +{% endblock %} + +{% block page %} +
    + {% include "ui/userbar.html" %} + {% if alpha %}WARNING! askLyphe is in alpha! user experience is in no way representative of the final product!{% + endif %} + {% include "ui/navbar.html" %} + +
    +
    + {% match error %} + {% when Some with (val) %} +
    {{ val }}
    + {% when None %} + {% endmatch %} +
    +
    +
    +

    username

    + {{ info.username }} (cannot currently be changed) +
    +
    +

    email

    + {{ info.email }} +
    + to change your email, you must email an administrator at devnull@voremicrocomputers.com +
    + (this will be changed in the future) +
    +
    +

    change password

    + this cannot currently be performed (which we are also working on fixing) +
    +
    +
    +
    +

    theme

    + {% for t in themes %} + {%if theme==t.value%} +

    your current theme is: "{{t.name}}"

    + {%endif%} + {% endfor %} +
    + + + +
    +
    +
    +
    +
    +
    + + {% include "ui/footer.html" %} +
    +{% endblock %} \ No newline at end of file diff --git a/authservice/.gitignore b/authservice/.gitignore new file mode 100644 index 0000000..3a8cabc --- /dev/null +++ b/authservice/.gitignore @@ -0,0 +1,2 @@ +/target +.idea diff --git a/authservice/Cargo.toml b/authservice/Cargo.toml new file mode 100644 index 0000000..0f1a003 --- /dev/null +++ b/authservice/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "authservice" +version = "0.1.0" +edition = "2021" +license = "AGPL-3" +license-file = "LICENSE" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } +tokio = { version = "1.0", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +sea-orm = { version = "1.0.0", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono"]} +entity = { path = "./entity" } +rmp-serde = "1.1.2" +async-nats = "0.38.0" +chrono = "0.4.26" +once_cell = "1.18.0" +ulid = "1.0.0" +rand = "0.8.5" +futures = "0.3.30" +log = "0.4.20" +env_logger = "0.10.2" +argon2 = "0.5.3" +regex = "1.10.3" +lettre = "0.11.10" \ No newline at end of file diff --git a/authservice/entity/Cargo.toml b/authservice/entity/Cargo.toml new file mode 100644 index 0000000..42b47fc --- /dev/null +++ b/authservice/entity/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "entity" +version = "0.1.0" +edition = "2021" + +[dependencies] +sea-orm = { version = "1.0.0", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono"]} diff --git a/authservice/entity/src/announcement.rs b/authservice/entity/src/announcement.rs new file mode 100644 index 0000000..1d6093c --- /dev/null +++ b/authservice/entity/src/announcement.rs @@ -0,0 +1,37 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "announcement")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub slug: String, + pub title: String, + pub short_text_notice: String, + pub full_markdown_notice: String, + pub creator_id: String, + pub created_on: DateTime, + pub updated_on: Option, + pub flags: i32, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::user::Entity", + from = "Column::CreatorId", + to = "super::user::Column::Id", + on_update = "NoAction", + on_delete = "NoAction" + )] + User, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::User.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/entity/src/invite_code.rs b/authservice/entity/src/invite_code.rs new file mode 100644 index 0000000..5876a27 --- /dev/null +++ b/authservice/entity/src/invite_code.rs @@ -0,0 +1,40 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "invite_code")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: String, + #[sea_orm(unique)] + pub code: String, + pub issuer: Option, + pub root_issuer: String, + pub comment: Option, + pub created_on: DateTime, + pub used: bool, + pub used_on: Option, + pub used_by: Option, + pub flags: Option, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::user::Entity", + from = "Column::UsedBy", + to = "super::user::Column::Id", + on_update = "NoAction", + on_delete = "SetNull" + )] + User, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::User.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/entity/src/lib.rs b/authservice/entity/src/lib.rs new file mode 100644 index 0000000..a699391 --- /dev/null +++ b/authservice/entity/src/lib.rs @@ -0,0 +1,10 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +pub mod prelude; + +pub mod announcement; +pub mod invite_code; +pub mod user; +pub mod user_session; +pub mod user_settings; +pub mod verification_code; diff --git a/authservice/entity/src/prelude.rs b/authservice/entity/src/prelude.rs new file mode 100644 index 0000000..32f9675 --- /dev/null +++ b/authservice/entity/src/prelude.rs @@ -0,0 +1,8 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +pub use super::announcement::Entity as Announcement; +pub use super::invite_code::Entity as InviteCode; +pub use super::user::Entity as User; +pub use super::user_session::Entity as UserSession; +pub use super::user_settings::Entity as UserSettings; +pub use super::verification_code::Entity as VerificationCode; diff --git a/authservice/entity/src/user.rs b/authservice/entity/src/user.rs new file mode 100644 index 0000000..66a3526 --- /dev/null +++ b/authservice/entity/src/user.rs @@ -0,0 +1,57 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "user")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: String, + #[sea_orm(unique)] + pub username: String, + pub display_name: Option, + pub email: String, + pub new_email: Option, + pub password: String, + pub flags: i64, + pub created_on: DateTime, + pub last_updated: DateTime, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm(has_many = "super::announcement::Entity")] + Announcement, + #[sea_orm(has_many = "super::invite_code::Entity")] + InviteCode, + #[sea_orm(has_many = "super::user_session::Entity")] + UserSession, + #[sea_orm(has_one = "super::user_settings::Entity")] + UserSettings, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Announcement.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::InviteCode.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::UserSession.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::UserSettings.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/entity/src/user_session.rs b/authservice/entity/src/user_session.rs new file mode 100644 index 0000000..e222ab8 --- /dev/null +++ b/authservice/entity/src/user_session.rs @@ -0,0 +1,38 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "user_session")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: String, + pub user: String, + pub display_id: String, + #[sea_orm(unique)] + pub token: String, + pub flags: i64, + pub ip_address: Option, + pub created_on: DateTime, + pub death_date: DateTime, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::user::Entity", + from = "Column::User", + to = "super::user::Column::Id", + on_update = "NoAction", + on_delete = "Cascade" + )] + User, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::User.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/entity/src/user_settings.rs b/authservice/entity/src/user_settings.rs new file mode 100644 index 0000000..eed2cd5 --- /dev/null +++ b/authservice/entity/src/user_settings.rs @@ -0,0 +1,31 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "user_settings")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub user: String, + pub theme: String, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::user::Entity", + from = "Column::User", + to = "super::user::Column::Id", + on_update = "NoAction", + on_delete = "Cascade" + )] + User, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::User.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/entity/src/verification_code.rs b/authservice/entity/src/verification_code.rs new file mode 100644 index 0000000..b53ad3b --- /dev/null +++ b/authservice/entity/src/verification_code.rs @@ -0,0 +1,23 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 + +use sea_orm::entity::prelude::*; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "verification_code")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: String, + pub user: String, + pub set_new_email: bool, + #[sea_orm(unique)] + pub code: String, + pub created_on: DateTime, + pub death_date: DateTime, + pub used: bool, + pub used_on: Option, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/authservice/migration/Cargo.toml b/authservice/migration/Cargo.toml new file mode 100644 index 0000000..9fa1bb2 --- /dev/null +++ b/authservice/migration/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "migration" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +name = "migration" +path = "src/lib.rs" + +[dependencies] +async-std = { version = "1", features = ["attributes", "tokio1"] } + +[dependencies.sea-orm-migration] +version = "1.0.0" +features = [ + # Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI. + # View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime. + # e.g. + "runtime-tokio-rustls", # `ASYNC_RUNTIME` feature + "sqlx-postgres", # `DATABASE_DRIVER` feature +] diff --git a/authservice/migration/README.md b/authservice/migration/README.md new file mode 100644 index 0000000..3b438d8 --- /dev/null +++ b/authservice/migration/README.md @@ -0,0 +1,41 @@ +# Running Migrator CLI + +- Generate a new migration file + ```sh + cargo run -- generate MIGRATION_NAME + ``` +- Apply all pending migrations + ```sh + cargo run + ``` + ```sh + cargo run -- up + ``` +- Apply first 10 pending migrations + ```sh + cargo run -- up -n 10 + ``` +- Rollback last applied migrations + ```sh + cargo run -- down + ``` +- Rollback last 10 applied migrations + ```sh + cargo run -- down -n 10 + ``` +- Drop all tables from the database, then reapply all migrations + ```sh + cargo run -- fresh + ``` +- Rollback all applied migrations, then reapply all migrations + ```sh + cargo run -- refresh + ``` +- Rollback all applied migrations + ```sh + cargo run -- reset + ``` +- Check the status of all migrations + ```sh + cargo run -- status + ``` diff --git a/authservice/migration/src/lib.rs b/authservice/migration/src/lib.rs new file mode 100644 index 0000000..2936978 --- /dev/null +++ b/authservice/migration/src/lib.rs @@ -0,0 +1,24 @@ +pub use sea_orm_migration::prelude::*; + +mod m20240814_013106_create_user; +mod m20240814_013750_create_invite_code; +mod m20240814_014654_create_user_session; +mod m20240814_015232_create_verification_code; +mod m20240829_214347_create_user_settings; +mod m20241115_003101_create_announcement; + +pub struct Migrator; + +#[async_trait::async_trait] +impl MigratorTrait for Migrator { + fn migrations() -> Vec> { + vec![ + Box::new(m20240814_013106_create_user::Migration), + Box::new(m20240814_013750_create_invite_code::Migration), + Box::new(m20240814_014654_create_user_session::Migration), + Box::new(m20240814_015232_create_verification_code::Migration), + Box::new(m20240829_214347_create_user_settings::Migration), + Box::new(m20241115_003101_create_announcement::Migration), + ] + } +} diff --git a/authservice/migration/src/m20240814_013106_create_user.rs b/authservice/migration/src/m20240814_013106_create_user.rs new file mode 100644 index 0000000..2e16d3c --- /dev/null +++ b/authservice/migration/src/m20240814_013106_create_user.rs @@ -0,0 +1,47 @@ +use sea_orm_migration::{prelude::*, schema::*}; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(User::Table) + .if_not_exists() + .col(ColumnDef::new(User::Id).string().not_null().primary_key()) + .col(ColumnDef::new(User::Username).string().not_null().unique_key()) + .col(ColumnDef::new(User::DisplayName).string()) + .col(ColumnDef::new(User::Email).string().not_null()) + .col(ColumnDef::new(User::NewEmail).string()) + .col(ColumnDef::new(User::Password).string().not_null()) + .col(ColumnDef::new(User::Flags).big_unsigned().not_null()) + .col(ColumnDef::new(User::CreatedOn).date_time().not_null()) + .col(ColumnDef::new(User::LastUpdated).date_time().not_null()) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(User::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +pub enum User { + Table, + Id, + Username, + DisplayName, + Email, + NewEmail, + Password, + Flags, + CreatedOn, + LastUpdated, +} diff --git a/authservice/migration/src/m20240814_013750_create_invite_code.rs b/authservice/migration/src/m20240814_013750_create_invite_code.rs new file mode 100644 index 0000000..382c8b0 --- /dev/null +++ b/authservice/migration/src/m20240814_013750_create_invite_code.rs @@ -0,0 +1,54 @@ +use sea_orm_migration::{prelude::*, schema::*}; +use crate::m20240814_013106_create_user::User; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(InviteCode::Table) + .if_not_exists() + .col(ColumnDef::new(InviteCode::Id).string().not_null().primary_key()) + .col(ColumnDef::new(InviteCode::Code).string().not_null().unique_key()) + .col(ColumnDef::new(InviteCode::Issuer).string()) + .col(ColumnDef::new(InviteCode::RootIssuer).string().not_null()) + .col(ColumnDef::new(InviteCode::Comment).string()) + .col(ColumnDef::new(InviteCode::CreatedOn).date_time().not_null()) + .col(ColumnDef::new(InviteCode::Used).boolean().not_null()) + .col(ColumnDef::new(InviteCode::UsedOn).date_time()) + .col(ColumnDef::new(InviteCode::UsedBy).string()) + .col(ColumnDef::new(InviteCode::Flags).big_unsigned()) + .foreign_key(ForeignKey::create().name("fk-invitecode-usedby") + .from(InviteCode::Table, InviteCode::UsedBy) + .to(User::Table, User::Id) + .on_delete(ForeignKeyAction::SetNull)) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(InviteCode::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +pub enum InviteCode { + Table, + Id, + Code, + Issuer, + RootIssuer, + Comment, + CreatedOn, + Used, + UsedOn, + UsedBy, + Flags, +} diff --git a/authservice/migration/src/m20240814_014654_create_user_session.rs b/authservice/migration/src/m20240814_014654_create_user_session.rs new file mode 100644 index 0000000..7678d52 --- /dev/null +++ b/authservice/migration/src/m20240814_014654_create_user_session.rs @@ -0,0 +1,51 @@ +use sea_orm_migration::{prelude::*, schema::*}; +use crate::m20240814_013106_create_user::User; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(UserSession::Table) + .if_not_exists() + .col(ColumnDef::new(UserSession::Id).string().not_null().primary_key()) + .col(ColumnDef::new(UserSession::User).string().not_null()) + .col(ColumnDef::new(UserSession::DisplayId).string().not_null()) + .col(ColumnDef::new(UserSession::Token).string().not_null().unique_key()) + .col(ColumnDef::new(UserSession::Flags).big_unsigned().not_null()) + .col(ColumnDef::new(UserSession::IPAddress).string()) + .col(ColumnDef::new(UserSession::CreatedOn).date_time().not_null()) + .col(ColumnDef::new(UserSession::DeathDate).date_time().not_null()) + .foreign_key(ForeignKey::create() + .name("fk-usersession-user") + .from(UserSession::Table, UserSession::User) + .to(User::Table, User::Id) + .on_delete(ForeignKeyAction::Cascade)) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(UserSession::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +enum UserSession { + Table, + Id, + User, + DisplayId, + Token, + Flags, + IPAddress, + CreatedOn, + DeathDate, +} diff --git a/authservice/migration/src/m20240814_015232_create_verification_code.rs b/authservice/migration/src/m20240814_015232_create_verification_code.rs new file mode 100644 index 0000000..71dc28f --- /dev/null +++ b/authservice/migration/src/m20240814_015232_create_verification_code.rs @@ -0,0 +1,45 @@ +use sea_orm_migration::{prelude::*, schema::*}; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(VerificationCode::Table) + .if_not_exists() + .col(ColumnDef::new(VerificationCode::Id).string().not_null().primary_key()) + .col(ColumnDef::new(VerificationCode::User).string().not_null()) + .col(ColumnDef::new(VerificationCode::SetNewEmail).boolean().not_null()) + .col(ColumnDef::new(VerificationCode::Code).string().not_null().unique_key()) + .col(ColumnDef::new(VerificationCode::CreatedOn).date_time().not_null()) + .col(ColumnDef::new(VerificationCode::DeathDate).date_time().not_null()) + .col(ColumnDef::new(VerificationCode::Used).boolean().not_null()) + .col(ColumnDef::new(VerificationCode::UsedOn).date_time()) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(VerificationCode::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +enum VerificationCode { + Table, + Id, + User, + Code, + SetNewEmail, + CreatedOn, + DeathDate, + Used, + UsedOn, +} diff --git a/authservice/migration/src/m20240829_214347_create_user_settings.rs b/authservice/migration/src/m20240829_214347_create_user_settings.rs new file mode 100644 index 0000000..6a65b76 --- /dev/null +++ b/authservice/migration/src/m20240829_214347_create_user_settings.rs @@ -0,0 +1,40 @@ +use sea_orm_migration::{prelude::*, schema::*}; +use crate::m20240814_013106_create_user::User; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(UserSettings::Table) + .if_not_exists() + .col(ColumnDef::new(UserSettings::User).string().not_null().primary_key()) + .col(ColumnDef::new(UserSettings::Theme).string().not_null()) + .foreign_key(ForeignKey::create() + .name("fk-usersettings-user") + .from(UserSettings::Table, UserSettings::User) + .to(User::Table, User::Id) + .on_delete(ForeignKeyAction::Cascade) + ) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(UserSettings::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +enum UserSettings { + Table, + User, // used as id also + Theme, +} diff --git a/authservice/migration/src/m20241115_003101_create_announcement.rs b/authservice/migration/src/m20241115_003101_create_announcement.rs new file mode 100644 index 0000000..de39161 --- /dev/null +++ b/authservice/migration/src/m20241115_003101_create_announcement.rs @@ -0,0 +1,52 @@ +use sea_orm_migration::{prelude::*, schema::*}; +use crate::m20240814_013106_create_user::User; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(Announcement::Table) + .if_not_exists() + .col(ColumnDef::new(Announcement::Slug).string().not_null().unique_key().primary_key()) + .col(ColumnDef::new(Announcement::Title).string().not_null()) + .col(ColumnDef::new(Announcement::ShortTextNotice).string().not_null()) + .col(ColumnDef::new(Announcement::FullMarkdownNotice).string().not_null()) + .col(ColumnDef::new(Announcement::CreatorId).string().not_null()) + .col(ColumnDef::new(Announcement::CreatedOn).date_time().not_null()) + .col(ColumnDef::new(Announcement::UpdatedOn).date_time()) + .col(ColumnDef::new(Announcement::Flags).integer().not_null()) + .foreign_key(ForeignKey::create() + .name("fk-announcement-user") + .from(Announcement::Table, Announcement::CreatorId) + .to(User::Table, User::Id) + .on_delete(ForeignKeyAction::NoAction) + ) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(Announcement::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +enum Announcement { + Table, + Slug, + Title, + ShortTextNotice, + FullMarkdownNotice, + CreatorId, + CreatedOn, + UpdatedOn, + Flags, +} diff --git a/authservice/migration/src/main.rs b/authservice/migration/src/main.rs new file mode 100644 index 0000000..c6b6e48 --- /dev/null +++ b/authservice/migration/src/main.rs @@ -0,0 +1,6 @@ +use sea_orm_migration::prelude::*; + +#[async_std::main] +async fn main() { + cli::run_cli(migration::Migrator).await; +} diff --git a/authservice/src/db/announcements.rs b/authservice/src/db/announcements.rs new file mode 100644 index 0000000..3a502e4 --- /dev/null +++ b/authservice/src/db/announcements.rs @@ -0,0 +1,145 @@ +/* + * authservice db/announcements.rs + * - pgsql announcement functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use log::error; +use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter, QueryOrder}; +use sea_orm::ActiveValue::Set; +use entity::announcement; + +#[derive(Debug)] +pub enum AnnouncementInsertError { + SlugInUse, + DatabaseError, +} + +pub async fn create_announcement(db: &DatabaseConnection, slug: String, title: String, short: String, full: String, creator_uid: String) -> Result<(), AnnouncementInsertError> { + if announcement::Entity::find().filter(announcement::Column::Slug.eq(&slug)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATEANNOUNCEMENT (check if slug free): {e}"); + AnnouncementInsertError::DatabaseError + })?.is_some() { + return Err(AnnouncementInsertError::SlugInUse); + } + + let record = announcement::ActiveModel { + slug: Set(slug), + title: Set(title), + short_text_notice: Set(short), + full_markdown_notice: Set(full), + creator_id: Set(creator_uid), + created_on: Set(chrono::Utc::now().naive_utc()), + updated_on: Default::default(), + flags: Set(0), + }; + + record.insert(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATEANNOUNCEMENT (insert): {e}"); + AnnouncementInsertError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum AnnouncementUpdateError { + SlugNotFound, + DatabaseError, +} + +pub async fn update_announcement(db: &DatabaseConnection, slug: String, title: String, short: String, full: String) -> Result<(), AnnouncementUpdateError> { + if let Some(record) = announcement::Entity::find_by_id(&slug).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE UPDATEANNOUNCEMENT (find): {e}"); + AnnouncementUpdateError::DatabaseError + })? { + let mut record = record.into_active_model(); + record.title = Set(title); + record.short_text_notice = Set(short); + record.full_markdown_notice = Set(full); + record.updated_on = Set(Some(chrono::Utc::now().naive_utc())); + + record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE UPDATEANNOUNCEMENT (update): {e}"); + AnnouncementUpdateError::DatabaseError + })?; + + Ok(()) + } else { + Err(AnnouncementUpdateError::SlugNotFound) + } +} + +pub struct AnnouncementRecord { + pub slug: String, + pub title: String, + pub short: String, + pub full: String, + pub creator_uid: String, + pub created_on: chrono::DateTime, + pub updated_on: Option>, +} + +#[derive(Debug)] +pub enum AnnouncementFetchError { + SlugNotFound, + DatabaseError, +} + +pub async fn get_announcement(db: &DatabaseConnection, slug: String) -> Result { + Ok(announcement::Entity::find_by_id(slug).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE GETANNOUNCEMENT: {e}"); + AnnouncementFetchError::DatabaseError + })?.ok_or(AnnouncementFetchError::SlugNotFound).map(|v| { + AnnouncementRecord { + slug: v.slug, + title: v.title, + short: v.short_text_notice, + full: v.full_markdown_notice, + creator_uid: v.creator_id, + created_on: v.created_on.and_utc(), + updated_on: v.updated_on.map(|v| v.and_utc()), + } + })?) +} + +pub async fn get_all_announcements(db: &DatabaseConnection) -> Result, AnnouncementFetchError> { + Ok(announcement::Entity::find().order_by_desc(announcement::Column::CreatedOn).all(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE ALLANNOUNCEMENT: {e}"); + AnnouncementFetchError::DatabaseError + })?.into_iter().map(|v| { + AnnouncementRecord { + slug: v.slug, + title: v.title, + short: v.short_text_notice, + full: v.full_markdown_notice, + creator_uid: v.creator_id, + created_on: v.created_on.and_utc(), + updated_on: v.updated_on.map(|v| v.and_utc()), + } + }).collect()) +} + +pub async fn latest_announcement(db: &DatabaseConnection) -> Result { + Ok(announcement::Entity::find().order_by_desc(announcement::Column::CreatedOn).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE LATESTANNOUNCEMENT: {e}"); + AnnouncementFetchError::DatabaseError + })?.ok_or(AnnouncementFetchError::SlugNotFound).map(|v| { + AnnouncementRecord { + slug: v.slug, + title: v.title, + short: v.short_text_notice, + full: v.full_markdown_notice, + creator_uid: v.creator_id, + created_on: v.created_on.and_utc(), + updated_on: v.updated_on.map(|v| v.and_utc()), + } + })?) +} \ No newline at end of file diff --git a/authservice/src/db/invite_code.rs b/authservice/src/db/invite_code.rs new file mode 100644 index 0000000..88260af --- /dev/null +++ b/authservice/src/db/invite_code.rs @@ -0,0 +1,119 @@ +/* + * authservice db/invite_code.rs + * - pgsql invite code functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::time::Instant; +use log::error; +use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter}; +use sea_orm::ActiveValue::Set; +use entity::{invite_code, user}; +use crate::db::genid; + +#[derive(Debug)] +pub enum ConsumeInviteCodeError { + InviteCodeAlreadyUsed, + InvalidInviteCode, + InvalidUser, + DatabaseError, +} + +/// consumes an invite code by relating invite_code_used_by to the given user id +/// and setting the user's invite_code_assigned flag; +/// fails if the invite code is already used, the invite code isn't real, or the given user is invalid +pub async fn consume_invite_code(db: &DatabaseConnection, invite_code: String, user_id: String) -> Result<(), ConsumeInviteCodeError> { + + // is the invite code real? + let record = invite_code::Entity::find().filter(invite_code::Column::Code.eq(&invite_code)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CONSUMEINVITECODE (check if real): {e}"); + ConsumeInviteCodeError::DatabaseError + })?.ok_or(ConsumeInviteCodeError::InvalidInviteCode)?; + + // has it been used? + + if record.used == true { + return Err(ConsumeInviteCodeError::InvalidInviteCode); + } + + // is user real? + user::Entity::find_by_id(&user_id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CONSUMEINVITECODE (check if user good): {e}"); + ConsumeInviteCodeError::DatabaseError + })?.ok_or(ConsumeInviteCodeError::InvalidUser)?; + + // we should be good to go, relate and set flags + + let mut record = record.into_active_model(); + record.used = Set(true); + record.used_by = Set(Some(user_id)); + record.used_on = Set(Some(chrono::Utc::now().naive_utc())); + + record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CONSUME INVITE CODE (update): {e}"); + ConsumeInviteCodeError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum InviteCodeGenerationError { + CodeAlreadyInserted, + DatabaseError, +} + +pub async fn insert_new_invitecode(db: &DatabaseConnection, invite_code: String, issuer: String, root_issuer: String, comment: String) -> Result<(), InviteCodeGenerationError> { + let id = genid(); + if invite_code::Entity::find().filter(invite_code::Column::Code.eq(&invite_code)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE INSERTINVITECODE (check if name free): {e}"); + InviteCodeGenerationError::DatabaseError + })?.is_some() { + return Err(InviteCodeGenerationError::CodeAlreadyInserted); + } + + let record = invite_code::ActiveModel { + id: Set(id), + code: Set(invite_code), + issuer: Set(Some(issuer)), + root_issuer: Set(root_issuer), + comment: Set(Some(comment)), + created_on: Set(chrono::Utc::now().naive_utc()), + used: Set(false), + used_on: Default::default(), + used_by: Default::default(), + flags: Set(Some(0)), + }; + + record.insert(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE INSERTINVITECODE (insert): {e}"); + InviteCodeGenerationError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum InviteCodeListError { + DatabaseError, +} + +pub async fn list_invite_codes(db: &DatabaseConnection, show_used: bool) -> Result, InviteCodeListError> { + let mut query = invite_code::Entity::find(); + if show_used { + query = query.filter(invite_code::Column::Used.eq(true)); + } else { + query = query.filter(invite_code::Column::Used.eq(false)); + } + query.all(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE LISTINVITECODES: {e}"); + InviteCodeListError::DatabaseError + }) +} \ No newline at end of file diff --git a/authservice/src/db/mod.rs b/authservice/src/db/mod.rs new file mode 100644 index 0000000..c29f88a --- /dev/null +++ b/authservice/src/db/mod.rs @@ -0,0 +1,22 @@ +/* + * authservice db/mod.rs + * - module file for pgsql database functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod user; +pub mod invite_code; +pub mod session; +pub mod usersettings; +pub mod announcements; + +pub fn genid() -> String { + ulid::Ulid::new().to_string() +} \ No newline at end of file diff --git a/authservice/src/db/session.rs b/authservice/src/db/session.rs new file mode 100644 index 0000000..b64326d --- /dev/null +++ b/authservice/src/db/session.rs @@ -0,0 +1,158 @@ +/* + * authservice db/session.rs + * - pgsql session functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use chrono::{DateTime, Duration, TimeDelta, Utc}; +use log::error; +use rand::Rng; +use sea_orm::ActiveValue::Set; +use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter}; +use serde::{Deserialize, Serialize}; +use entity::user_session; +use crate::db::{genid, user}; +use crate::db::user::FetchUserError; + +// todo: make this configurable +// 10 days +pub const SESSION_TTL_SECONDS: u64 = 10 * 24 * 60 * 60; + +fn generate_session_token() -> String { + rand::thread_rng() + .sample_iter(&rand::distributions::Alphanumeric) + .take(64) + .map(char::from) + .collect() +} + +#[derive(Debug)] +pub enum CreateSessionError { + UserDoesntExist, + DatabaseError, +} + +pub async fn create_session(db: &DatabaseConnection, user_id: String, ip_address: String) -> Result { + user::check_if_user_exists(db, user_id.to_string()).await.map_err(|e| match e { + FetchUserError::UserNotFound => { CreateSessionError::UserDoesntExist } + FetchUserError::DatabaseError => { CreateSessionError::DatabaseError } + })?; + + let display_id = genid(); + let token = generate_session_token(); + let now = Utc::now(); + let death = now + Duration::try_seconds(SESSION_TTL_SECONDS as i64).expect("BAD SESSION TTL SECONDS"); + + let record = user_session::ActiveModel { + id: Set(display_id.clone()), + user: Set(user_id), + display_id: Set(display_id), + token: Set(token.clone()), + flags: Set(0), + ip_address: Set(Some(ip_address)), + created_on: Set(now.naive_utc()), + death_date: Set(death.naive_utc()), + }; + + user_session::Entity::insert(record).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATESESSION: {e}"); + CreateSessionError::DatabaseError + })?; + + Ok(token) +} + +#[derive(Debug)] +pub enum DeleteSessionError { + /// session doesn't exist + SessionDoesntExist, + DatabaseError, +} + +/// deletes the given session from the session table, logging out the user +/// returns an error if the user or session doesn't exist, will delete the session regardless of +/// if it is expired +pub async fn delete_session(db: &DatabaseConnection, token: String) -> Result<(), DeleteSessionError> { + match check_if_session_died(db, token.clone(), false, false).await { + Ok(_) => {} + Err(e) => match e { + FetchSessionError::SessionInvalid => {} + FetchSessionError::SessionDoesntExist => { return Err(DeleteSessionError::SessionDoesntExist); } + FetchSessionError::DatabaseError => { return Err(DeleteSessionError::DatabaseError); } + } + } + + user_session::Entity::delete(user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE DELETESESSION (query): {e}"); + DeleteSessionError::DatabaseError + })?.ok_or(DeleteSessionError::SessionDoesntExist)?.into_active_model()).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE DELETESESSION (delete): {e}"); + DeleteSessionError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum FetchSessionError { + /// death date reached + SessionInvalid, + /// session doesn't exist + SessionDoesntExist, + DatabaseError, +} + +pub async fn check_if_session_died(db: &DatabaseConnection, token: String, extend_life: bool, rm_session: bool) -> Result<(), FetchSessionError> { + let record = user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CHECKSESSIONDIED (query): {e}"); + FetchSessionError::DatabaseError + })?.ok_or(FetchSessionError::SessionDoesntExist)?; + + let now = Utc::now(); + // is now bigger than death date? + if record.death_date.signed_duration_since(now.naive_utc()) <= TimeDelta::nanoseconds(0) { + // died + if rm_session { + user_session::Entity::delete(record.into_active_model()).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CHECKSESSIONDIED (delete): {e}"); + FetchSessionError::DatabaseError + })?; + } + return Err(FetchSessionError::SessionInvalid); + } + + if extend_life { + let death = now + Duration::try_seconds(SESSION_TTL_SECONDS as i64).expect("BAD SESSION TTL SECONDS"); + let mut record = record.into_active_model(); + record.death_date = Set(death.naive_utc()); + record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CHECKSESSIONDIED (update): {e}"); + FetchSessionError::DatabaseError + })?; + } + + Ok(()) +} + +pub async fn get_session_death_date(db: &DatabaseConnection, token: String) -> Result, FetchSessionError> { + check_if_session_died(db, token.clone(), false, true).await?; + Ok(user_session::Entity::find().filter(user_session::Column::Token.eq(token)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE GETSESSIONDEATHDATE: {e}"); + FetchSessionError::DatabaseError + })?.ok_or(FetchSessionError::SessionDoesntExist)?.death_date.and_utc()) +} + +pub async fn get_userid_from_session(db: &DatabaseConnection, token: String, extend_life: bool) -> Result { + check_if_session_died(db, token.clone(), extend_life, true).await?; + Ok(user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE SESSION2USERID: {e}"); + FetchSessionError::DatabaseError + })?.ok_or(FetchSessionError::SessionDoesntExist)?.user) +} \ No newline at end of file diff --git a/authservice/src/db/user.rs b/authservice/src/db/user.rs new file mode 100644 index 0000000..1f6ce8a --- /dev/null +++ b/authservice/src/db/user.rs @@ -0,0 +1,485 @@ +/* + * authservice db/user.rs + * - pgsql user functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use argon2::{Argon2, PasswordHasher, PasswordVerifier}; +use argon2::password_hash::rand_core::OsRng; +use argon2::password_hash::SaltString; +use chrono::{Days, Utc}; +use futures::FutureExt; +use log::{debug, error}; +use once_cell::sync::Lazy; +use regex::Regex; +use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, ModelTrait, NotSet, PaginatorTrait, QueryFilter, QueryOrder, QuerySelect}; +use sea_orm::ActiveValue::Set; +use sea_orm::prelude::Expr; +use sea_orm::sea_query::{BinOper, ExprTrait}; +use entity::{user, verification_code}; +use crate::db::genid; + +static EMAIL_REGEX: Lazy = Lazy::new(|| Regex::new(r#"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"#).expect("BAD EMAIL REGEX")); + +#[repr(i64)] +pub enum UserFlag { + Verified = 1 << 0, + NewEmail = 1 << 1, + Administrator = 1 << 2, +} + +#[derive(Debug)] +pub enum CreateUserError { + /// user already exists with this username + UsernameTaken, + /// user already exists with this email + EmailTaken, + /// username contains invalid (not alphanumeric with dashes and underscores allowed) characters, or is arbitrarily too long + UsernameError, + /// display name contains invalid (not alphanumeric with dashes and underscores and spaces (but not at the beginning or end, or twice in a row) characters, or is arbitrarily too long + DisplayNameError, + /// email doesn't match funny email regex + EmailError, + /// password weak (not implemented yet) + PasswordError, + /// arbitrary database error, check logs + DatabaseError, +} + +#[derive(Debug)] +pub enum FetchUserError { + UserNotFound, + DatabaseError, +} + +/// takes a user id and returns Ok if the user exists +pub async fn check_if_user_exists(db: &DatabaseConnection, user_id: String) -> Result<(), FetchUserError> { + if user::Entity::find_by_id(&user_id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE USER EXIST CHECK: {e}"); + FetchUserError::DatabaseError + })?.is_none() { + return Err(FetchUserError::UserNotFound); + } + Ok(()) +} + +/// takes a username and returns the associated user id, or an error if the user does not exist +pub async fn username_to_userid(db: &DatabaseConnection, username: String) -> Result { + let user_id: Option = user::Entity::find().filter(user::Column::Username.eq(&username)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE USERNAME2USERID: {e}"); + FetchUserError::DatabaseError + })?.map(|v| v.id); + if user_id.is_none() { + return Err(FetchUserError::UserNotFound); + } + Ok(user_id.unwrap()) +} + +/// takes an email and returns the associated user id, or an error if the user does not exist +pub async fn email_to_userid(db: &DatabaseConnection, email: String) -> Result { + let user_id: Option = user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE EMAIL2USERID: {e}"); + FetchUserError::DatabaseError + })?.map(|v| v.id); + if user_id.is_none() { + return Err(FetchUserError::UserNotFound); + } + Ok(user_id.unwrap()) +} + + +/// creates a user in the database, you'll probably want to register an email verification code after this +/// returns id on success +pub async fn create_user(db: &DatabaseConnection, username: String, display_name: String, email: String, password: String) -> Result { + // rustrover gives some warnings here but don't change the regex because it's directly + // taken from the html standard + if !EMAIL_REGEX.is_match(&email) { + return Err(CreateUserError::EmailError); + } + + if username.len() > 32 { + return Err(CreateUserError::UsernameError); + } + + if user::Entity::find().filter(user::Column::Username.eq(&username)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATE USER (username taken check (database)): {e}"); + CreateUserError::DatabaseError + })?.is_some() { + return Err(CreateUserError::UsernameTaken); + } + if user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATE USER (email taken check (database)): {e}"); + CreateUserError::DatabaseError + })?.is_some() { + return Err(CreateUserError::EmailTaken); + } + + let id = genid(); + let salt = SaltString::generate(&mut OsRng); + let argon2 = Argon2::default(); + let password_hash = argon2.hash_password(password.as_bytes(), &salt) + .expect("argon2 error").to_string(); + let now = Utc::now(); + + let record = user::ActiveModel { + id: Set(id.clone()), + username: Set(username), + display_name: Set(Some(display_name)), + email: Set(email), + new_email: Set(None), + password: Set(password_hash), + flags: Set(0), + created_on: Set(now.naive_utc()), + last_updated: Set(now.naive_utc()), + }; + + user::Entity::insert(record).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CREATE USER (insert user): {e}"); + CreateUserError::DatabaseError + })?; + + Ok(id) +} + +#[derive(Debug)] +pub enum DeleteUserError { + UserDoesntExist, + DatabaseError, +} + +/// deletes the given user from the user table, doesn't do any other cleanup so be careful! +/// returns an error if the user doesn't exist +pub async fn delete_user(db: &DatabaseConnection, id: String) -> Result<(), DeleteUserError> { + let record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE DELETEUSER (exist check (database)): {e}"); + DeleteUserError::DatabaseError + })?; + if record.is_none() { + return Err(DeleteUserError::UserDoesntExist); + } + + record.unwrap().delete(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE DELETEUSER (delete (database)): {e}"); + DeleteUserError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum RegisterVerificationCodeError { + /// user is already verified, and thus we do not need a new verification code + /// note that for email changes, we use the new_verified field which is true until a new email is set + UserIsVerifiedAndNotChangingTheirEmail, + /// user seemingly doesn't exist in the database, this should be + /// shown to the user as an invalid session error, or an internal server error, depending + /// on the situation + UserDoesntExist, + DatabaseError, +} + +/// inserts a new email verification code into the user flags for this user, +/// user is verified after you verify_verification_code +pub async fn register_verification_code(db: &DatabaseConnection, id: String, verification_code: String) -> Result<(), RegisterVerificationCodeError> { + let record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE REGISTERVERIFICATIONCODE (record for flags check (query)): {e}"); + RegisterVerificationCodeError::DatabaseError + })?.ok_or(RegisterVerificationCodeError::UserDoesntExist)?; + + // if verified and not asking for new email + if record.flags & UserFlag::Verified as i64 != 0 && record.flags & UserFlag::NewEmail as i64 == 0 { + return Err(RegisterVerificationCodeError::UserIsVerifiedAndNotChangingTheirEmail); + } + + let vc_record = verification_code::ActiveModel { + id: Set(genid()), + user: Set(id.clone()), + code: Set(verification_code), + set_new_email: Set(false), + created_on: Set(Utc::now().naive_utc()), + death_date: Set(Utc::now().checked_add_days(Days::new(10)).unwrap().naive_utc()), + used: Set(false), + used_on: NotSet, + }; + + verification_code::Entity::insert(vc_record).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE REGISTERVERIFICATIONCODE (insert verification code): {e}"); + RegisterVerificationCodeError::DatabaseError + })?; + + Ok(()) +} + +#[derive(Debug)] +pub enum VerifyVerificationCodeError { + UserAlreadyVerified, + VerificationCodeInvalid, + UserDoesntExist, + DatabaseError, +} + +/// verifies that the verification code is correct, and sets the user as verified if so +pub async fn verify_verification_code(db: &DatabaseConnection, id: String, verification_code: String) -> Result<(), VerifyVerificationCodeError> { + let vc_record = verification_code::Entity::find().filter(verification_code::Column::Code.eq(&verification_code)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (code record select): {e}"); + VerifyVerificationCodeError::DatabaseError + })?.ok_or(VerifyVerificationCodeError::VerificationCodeInvalid)?; + + if vc_record.user != id { + return Err(VerifyVerificationCodeError::UserDoesntExist); + } + + let user_record = user::Entity::find_by_id(&vc_record.user).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (user record select): {e}"); + VerifyVerificationCodeError::DatabaseError + })?.ok_or(VerifyVerificationCodeError::UserDoesntExist)?; + + // if verified and not asking for new email + if user_record.flags & UserFlag::Verified as i64 != 0 && user_record.flags & UserFlag::NewEmail as i64 == 0 { + return Err(VerifyVerificationCodeError::UserAlreadyVerified); + } + + let mut user_record = user_record.into_active_model(); + + user_record.flags = Set((*user_record.flags.as_ref() | UserFlag::Verified as i64) & !(UserFlag::NewEmail as i64)); + + if vc_record.set_new_email { + if let Some(email) = user_record.new_email.as_ref() { + user_record.email = Set(email.clone()); + user_record.new_email = Set(None); + } else { + error!("vc record is SetNewEmail, but no new email exists for this user {id}!!! INVESTIGATE ASAP"); + } + } + + let mut vc_record = vc_record.into_active_model(); + + vc_record.used = Set(true); + vc_record.used_on = Set(Some(Utc::now().naive_utc())); + + user_record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (user record update): {e}"); + VerifyVerificationCodeError::DatabaseError + })?; + + vc_record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (vc record update): {e}"); + VerifyVerificationCodeError::DatabaseError + })?; + + Ok(()) +} + +/// checks if the user can log-in with their current registration status +pub async fn check_if_verified(db: &DatabaseConnection, id: String) -> Result { + let user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CHECKVERIFICATION (user record select): {e}"); + FetchUserError::DatabaseError + })?.ok_or(FetchUserError::UserNotFound)?; + + Ok(user_record.flags & UserFlag::Verified as i64 != 0) +} + +#[derive(Debug)] +pub enum VerifyEmailPassComboError { + ComboInvalid, + UserDoesntExist, + DatabaseError, +} + +/// verifies that the given email/pass combo are correct for the account associated with the email +/// password must be unhashed +pub async fn verify_email_pass_combo(db: &DatabaseConnection, email: String, password: String) -> Result<(), VerifyEmailPassComboError> { + let password_hash = user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE VERIFYEMAILPASSCOMBO (password hash query): {e}"); + VerifyEmailPassComboError::DatabaseError + })?.ok_or(VerifyEmailPassComboError::UserDoesntExist)?.password; + let password_hash = argon2::PasswordHash::new(&password_hash).map_err(|e| { + error!("invalid password hash found for {email}! check database for corruption! argon2 error: {e}"); + VerifyEmailPassComboError::DatabaseError + })?; + if Argon2::default().verify_password(password.as_bytes(), &password_hash).is_err() { + return Err(VerifyEmailPassComboError::ComboInvalid); + } + Ok(()) +} + +#[derive(Debug)] +pub struct UserInfo { + pub username: String, + pub email: String, + pub new_email: Option, + pub admin: bool, + pub verified: bool, +} + +/// gets all user info (: +pub async fn user_info(db: &DatabaseConnection, id: String) -> Result { + user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE USERINFO: {e}"); + FetchUserError::DatabaseError + })?.ok_or(FetchUserError::UserNotFound).map(|v| { + UserInfo { + username: v.username, + email: v.email, + new_email: v.new_email, + admin: v.flags & UserFlag::Administrator as i64 != 0, + verified: v.flags & UserFlag::Verified as i64 != 0, + } + }) +} + +#[derive(Debug)] +pub enum EmailChangeError { + UserNotFound, + NewEmailIsInvalid, + DatabaseError, +} + +/// starts the process for changing a user's email +pub async fn start_email_change(db: &DatabaseConnection, id: String, new_email: String, verification_code: String) -> Result<(), EmailChangeError> { + if !EMAIL_REGEX.is_match(&new_email) { + return Err(EmailChangeError::NewEmailIsInvalid); + } + + let user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE STARTEMAILCHANGE (user query): {e}"); + EmailChangeError::DatabaseError + })?.ok_or(EmailChangeError::UserNotFound)?; + + let flags = user_record.flags; + let mut user_record = user_record.into_active_model(); + user_record.new_email = Set(Some(new_email)); + user_record.flags = Set(flags | UserFlag::NewEmail as i64); + user_record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE STARTEMAILCHANGE (user update): {e}"); + EmailChangeError::DatabaseError + })?; + + let old_vc_records = verification_code::Entity::delete_many() + .filter(verification_code::Column::User.eq(&id)) + .filter(verification_code::Column::SetNewEmail.eq(true)) + .exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE STARTEMAILCHANGE (delete old email codes): {e}"); + EmailChangeError::DatabaseError + })?; + debug!("deleted {} old vc code records during email change", old_vc_records.rows_affected); + + let vc_record = verification_code::ActiveModel { + id: Set(genid()), + user: Set(id.clone()), + code: Set(verification_code), + set_new_email: Set(true), + created_on: Set(Utc::now().naive_utc()), + death_date: Set(Utc::now().checked_add_days(Days::new(10)).unwrap().naive_utc()), + used: Set(false), + used_on: NotSet, + }; + + verification_code::Entity::insert(vc_record).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE STARTEMAILCHANGE (insert verification code): {e}"); + EmailChangeError::DatabaseError + })?; + + Ok(()) +} + +/// cancels any in-progress user email change +pub async fn cancel_email_change(db: &DatabaseConnection, id: String) -> Result<(), FetchUserError> { + verification_code::Entity::delete_many() + .filter(verification_code::Column::User.eq(&id)) + .filter(verification_code::Column::SetNewEmail.eq(true)) + .exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (delete old email codes): {e}"); + FetchUserError::DatabaseError + })?; + + let mut user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (query user): {e}"); + FetchUserError::DatabaseError + })?.ok_or(FetchUserError::UserNotFound)?.into_active_model(); + + let flags = *user_record.flags.as_ref(); + + user_record.new_email = Set(None); + // unset new email + user_record.flags = Set(flags & !(UserFlag::NewEmail as i64)); + + user_record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (user update): {e}"); + FetchUserError::DatabaseError + })?; + + Ok(()) +} + +/// returns the last 10 users added to the database as usernames +pub async fn last_ten_usernames(db: &DatabaseConnection) -> Result, FetchUserError> { + Ok(user::Entity::find() + .order_by_desc(user::Column::CreatedOn) + .limit(Some(10)) + .all(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE LASTTENUSERNAMES: {e}"); + FetchUserError::DatabaseError + })?.into_iter().map(|v| v.username).collect()) +} + +pub async fn all_users(db: &DatabaseConnection) -> Result, FetchUserError> { + Ok(user::Entity::find().all(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE ALLUSERS: {e}"); + FetchUserError::DatabaseError + })?.into_iter().map(|v| { + UserInfo { + username: v.username, + email: v.email, + new_email: v.new_email, + admin: v.flags & UserFlag::Administrator as i64 != 0, + verified: v.flags & UserFlag::Verified as i64 != 0, + } + }).collect()) +} + +/// returns the number of users in the database +pub async fn user_count(db: &DatabaseConnection) -> Result { + Ok(user::Entity::find().count(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE USERCOUNT: {e}"); + FetchUserError::DatabaseError + })? as usize) +} + +/// returns the number of users in the database who are admins +pub async fn admin_count(db: &DatabaseConnection) -> Result { + // dont fucking touch this, i don't know why it works but it does, it's actually evil + Ok(user::Entity::find().filter(user::Column::Flags.into_expr().binary(BinOper::LShift, Expr::value(63 - 2)).lt(1 << (63 - 2))) + .count(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE ADMINCOUNT: {e}"); + FetchUserError::DatabaseError + })? as usize) +} + +/// returns the number of unverified accounts (this does NOT count email change requests) +pub async fn unverified_count(db: &DatabaseConnection) -> Result { + Ok(verification_code::Entity::find().filter(verification_code::Column::SetNewEmail.eq(false)).filter(verification_code::Column::Used.eq(false)) + .count(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE UNVERIFIEDCOUNT: {e}"); + FetchUserError::DatabaseError + })? as usize) +} + +/// returns a list of all (username, email) to send announcement emails to +pub async fn email_list(db: &DatabaseConnection) -> Result, FetchUserError> { + // fixme: filter by who wants emails and who doesn't when we implement that + Ok(user::Entity::find().all(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE EMAILLIST: {e}"); + FetchUserError::DatabaseError + })?.into_iter().map(|v| { + (v.username, v.email) + }).collect()) +} \ No newline at end of file diff --git a/authservice/src/db/usersettings.rs b/authservice/src/db/usersettings.rs new file mode 100644 index 0000000..27f486b --- /dev/null +++ b/authservice/src/db/usersettings.rs @@ -0,0 +1,79 @@ +/* + * authservice db/usersettings.rs + * - pgsql usersettings functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use log::error; +use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, IntoActiveModel}; +use sea_orm::ActiveValue::Set; +use entity::user_settings; +use crate::db::user::{check_if_user_exists, FetchUserError}; + +#[derive(Debug, Clone)] +pub struct UserSettings { + pub theme: String, +} + +#[derive(Debug)] +pub enum FetchUserSettingsError { + UserNotFound, + DatabaseError, +} + +pub async fn get_or_create_default_user_settings(db: &DatabaseConnection, user_id: String) -> Result { + if let Some(us) = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE FETCH USER SETTINGS: {e}"); + FetchUserSettingsError::DatabaseError + })? { + return Ok(UserSettings { + theme: us.theme + }); + } + + check_if_user_exists(db, user_id.clone()).await.map_err(|e| { + match e { + FetchUserError::UserNotFound => {FetchUserSettingsError::UserNotFound} + FetchUserError::DatabaseError => {FetchUserSettingsError::DatabaseError} + } + })?; + + let us_record = user_settings::ActiveModel { + user: Set(user_id), + theme: Set("default".to_string()), + }; + + user_settings::Entity::insert(us_record).exec(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}"); + FetchUserSettingsError::DatabaseError + })?; + + Ok(UserSettings { + theme: "default".to_string(), + }) +} + +pub async fn set_theme(db: &DatabaseConnection, user_id: String, theme: String) -> Result<(), FetchUserSettingsError> { + get_or_create_default_user_settings(db, user_id.clone()).await?; + + let mut us_record = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}"); + FetchUserSettingsError::DatabaseError + })?.ok_or(FetchUserSettingsError::UserNotFound)?.into_active_model(); + + us_record.theme = Set(theme); + + us_record.update(db).await.map_err(|e| { + error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}"); + FetchUserSettingsError::DatabaseError + })?; + + Ok(()) +} \ No newline at end of file diff --git a/authservice/src/email/mod.rs b/authservice/src/email/mod.rs new file mode 100644 index 0000000..b5f0f37 --- /dev/null +++ b/authservice/src/email/mod.rs @@ -0,0 +1,176 @@ +/* + * authservice email/mod.rs + * - email thread, most of everything needed for emails are in this file + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod templates; + +use lettre::{Message, SmtpTransport, Transport}; +use lettre::message::header::ContentType; +use lettre::transport::smtp::authentication::Credentials; +use log::{error, info}; +use tokio::sync::{mpsc, OnceCell}; +use crate::{SMTP_DISABLE, SMTP_PASSWORD, SMTP_URL, SMTP_USERNAME}; + +pub enum EmailMessage { + VerificationCode { + to: String, + username: String, + url: String, + }, + DeveloperWarning { + message: String, + }, + Announcement { + to: String, + username: String, + title: String, + text_contents: String, + } +} + +static EMAIL_SENDER: OnceCell> = OnceCell::const_new(); +const EMAIL_RETRY_TIME_SECS: u64 = 10; +const DEVWARNING_TARGET: &str = "AskLyphe Developer "; + +pub fn send_devwarn_email(message: &str) { + EMAIL_SENDER.get().unwrap().send(EmailMessage::DeveloperWarning { + message: message.to_string(), + }).unwrap(); +} + +pub fn send_verification_code_email(to: &str, username: &str, url: &str) { + EMAIL_SENDER.get().unwrap().send(EmailMessage::VerificationCode { + to: to.to_string(), + username: username.to_string(), + url: url.to_string(), + }).unwrap(); +} + +pub fn send_announcement_email(to: &str, username: &str, title: &str, content: &str) { + EMAIL_SENDER.get().unwrap().send(EmailMessage::Announcement { + to: to.to_string(), + username: username.to_string(), + title: title.to_string(), + text_contents: content.to_string(), + }).unwrap() +} + +pub async fn email_init() { + let (email_sender, email_receiver) = mpsc::unbounded_channel(); + EMAIL_SENDER.set(email_sender).unwrap(); + + tokio::spawn(async move { + info!("email thread spawned"); + if *SMTP_DISABLE { + info!("SMTP disable"); + } + let creds = Credentials::new(SMTP_USERNAME.to_string(), SMTP_PASSWORD.to_string()); + let mailer = SmtpTransport::starttls_relay(&SMTP_URL).expect("FAILED TO CONNECT TO EMAIL SMTP RELAY") + .credentials(creds) + .build(); + let mut rx = email_receiver; + + loop { + if let Ok(message) = rx.try_recv() { + match message { + EmailMessage::VerificationCode { to, username, url } => { + if *SMTP_DISABLE { + info!("not sending smtp verification code due to smtp disable"); + continue; + } + let body = templates::gen_verification_code_email(&url); + let email = Message::builder() + .from("Vore Microcomputers No-Reply ".parse().unwrap()) + .reply_to("Vore Microcomputers Support ".parse().unwrap()); + let to_mbox = format!("{username} <{to}>").parse(); + if let Err(e) = to_mbox { + error!("couldn't parse \"to\" field for verification code email! \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't parse \"to\" field for verification code email! \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + let email = email.to(to_mbox.unwrap()) + .subject("AskLyphe Account Verification") + .header(ContentType::TEXT_PLAIN) + .body(body); + if let Err(e) = email { + error!("couldn't generate email for verification! \"{e}\" \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't generate verification code email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + let email = email.unwrap(); + + if let Err(e) = mailer.send(&email) { + error!("couldn't send email for verification! \"{e}\" \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't send verification code email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + } + EmailMessage::DeveloperWarning { message } => { + if *SMTP_DISABLE { + info!("not sending smtp developer warning due to smtp disable"); + continue; + } + let body = templates::gen_developer_warning_email(&message); + let email = Message::builder() + .from("Vore Microcomputers No-Reply ".parse().unwrap()) + .to(DEVWARNING_TARGET.parse().unwrap()) + .subject("AskLyphe Developer Warning") + .header(ContentType::TEXT_PLAIN) + .body(body); + if let Err(e) = email { + error!("couldn't generate email for developer warning!! \"{e}\" \"{message}\""); + continue; + } + let email = email.unwrap(); + + if let Err(e) = mailer.send(&email) { + error!("couldn't send email for developer warning!!! \"{e}\" \"{message}\""); + continue; + } + } + EmailMessage::Announcement { to, username, title, text_contents } => { + if *SMTP_DISABLE { + info!("not sending smtp announcement due to smtp disable"); + continue; + } + let body = templates::gen_announcement_email(&text_contents); + let email = Message::builder() + .from("Vore Microcomputers No-Reply ".parse().unwrap()) + .reply_to("Vore Microcomputers Support ".parse().unwrap()); + let to_mbox = format!("{username} <{to}>").parse(); + if let Err(e) = to_mbox { + error!("couldn't parse \"to\" field for announcement email! \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't parse \"to\" field for announcement email! \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + let email = email.to(to_mbox.unwrap()) + .subject(format!("AskLyphe Announcement: {title}").as_str()) + .header(ContentType::TEXT_PLAIN) + .body(body); + if let Err(e) = email { + error!("couldn't generate email for announcement! \"{e}\" \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't generate announcement email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + let email = email.unwrap(); + + if let Err(e) = mailer.send(&email) { + error!("couldn't send email for announcement! \"{e}\" \"{username}\" \"{to}\""); + send_devwarn_email(&format!("couldn't send announcement email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate")); + continue; + } + } + } + } + } + }); +} diff --git a/authservice/src/email/templates.rs b/authservice/src/email/templates.rs new file mode 100644 index 0000000..ed28582 --- /dev/null +++ b/authservice/src/email/templates.rs @@ -0,0 +1,54 @@ +/* + * authservice email/templates.rs + * - high tech templating system for emails + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub fn gen_verification_code_email(url: &str) -> String { + format!(r#"thank you for signing up for AskLyphe! +before you can ask lyphe, you must verify your account by opening the link below! +{url} + +please note that if your email client has a feature which generates a preview of the link, +your account may already be verified and the url will show an error. +in this case, you can just go ahead and login, hopefully without any further issues! + +this issue will be fixed by the end of beta testing. + +we won't email you much, but if you don't want us to email you regarding updates to the service that +we consider important, please email devnull@voremicrocomputers.com with your username and we will +opt you out of future announcements. + +please note that this email account (no-reply@voremicrocomputers.com) is not checked for received +mail, and all inquiries should be sent to devnull@voremicrocomputers.com + +thank you (: +"#) +} + +pub fn gen_developer_warning_email(message: &str) -> String { + format!(r#"hello asklyphe developer! +an error occurred within the authservice which needs attention! +the given message is as follows: +{message} +"#) +} + +pub fn gen_announcement_email(contents: &str) -> String { + format!(r#"{contents} + +--- +this email was automatically sent because an announcement was posted, +if you would like to not receive these emails in the future, please email us at devnull@voremicrocomputers.com +in the future, you will be able to configure this on your account settings page + +we try to keep our email send count as minimal as possible, and we don't want to fill your inbox with spam (: +"#) +} \ No newline at end of file diff --git a/authservice/src/main.rs b/authservice/src/main.rs new file mode 100644 index 0000000..b57b85d --- /dev/null +++ b/authservice/src/main.rs @@ -0,0 +1,92 @@ +/* + * authservice main.rs + * - entrypoint for the asklyphe authentication service + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod process; +pub mod db; +mod email; + +use std::string::ToString; +use std::sync::Arc; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use asklyphe_common::nats::authservice::AuthServiceResponse; +use async_nats::jetstream; +use log::{debug, error, info, warn}; +use once_cell::sync::Lazy; +use asklyphe_common::nats::comms; +use sea_orm::Database; +use crate::email::email_init; + +pub static NATS_URL: Lazy = Lazy::new(|| std::env::var("NATS_URL").expect("NO NATS DEFINED")); +pub static NATS_CERT: Lazy = Lazy::new(|| std::env::var("NATS_CERT").expect("NO NATS_CERT DEFINED")); +pub static NATS_KEY: Lazy = Lazy::new(|| std::env::var("NATS_KEY").expect("NO NATS_KEY DEFINED")); +pub static DB_URL: Lazy = Lazy::new(|| std::env::var("DB_URL").expect("NO DB_URL DEFINED")); + +pub static SMTP_DISABLE: Lazy = Lazy::new(|| std::env::var("SMTP_DISABLE").is_ok()); +pub static SMTP_URL: Lazy = Lazy::new(|| std::env::var("SMTP_URL").expect("NO SMTP_URL DEFINED")); +pub static SMTP_USERNAME: Lazy = Lazy::new(|| std::env::var("SMTP_USERNAME").expect("NO SMTP_USERNAME DEFINED")); +pub static SMTP_PASSWORD: Lazy = Lazy::new(|| std::env::var("SMTP_PASSWORD").expect("NO SMTP_PASSWORD DEFINED")); + +pub static PROCESSES_HANDLED: AtomicU64 = AtomicU64::new(0); +pub static LAST_MESSAGE: AtomicI64 = AtomicI64::new(0); + +#[tokio::main] +async fn main() { + env_logger::init(); + info!("authservice began at {}", chrono::Utc::now().to_string()); + + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(NATS_CERT.as_str().into(), NATS_KEY.as_str().into()) + .connect(NATS_URL.as_str()) + .await; + if let Err(e) = nats { + error!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + + email_init().await; + + info!("authservice thread spawned"); + + async fn on_recv(query: comms::Query) -> comms::ServiceResponse { + debug!("recv"); + let db = Database::connect(DB_URL.as_str()).await; + if let Err(e) = db { + error!("FATAL ERROR, COULDN'T CONNECT TO DATABASE: {e}"); + return comms::ServiceResponse::AuthService(AuthServiceResponse::OtherError("FATAL ERROR, COULDN'T CONNECT TO DATABASE".to_string())); + } + let db = db.unwrap(); + let now = chrono::Utc::now().timestamp(); + LAST_MESSAGE.store(now, Ordering::Relaxed); + + let response = match query { + comms::Query::AuthService(query) => { + process::process(query, db).await + } + _ => { + AuthServiceResponse::InvalidRequest + } + }; + + if PROCESSES_HANDLED.load(Ordering::Relaxed) % 100 == 0 { + info!("handled {} requests!", PROCESSES_HANDLED.load(Ordering::Relaxed)); + } + PROCESSES_HANDLED.fetch_add(1, Ordering::Relaxed); + comms::ServiceResponse::AuthService(response) + } + + if let Err(e) = comms::subscribe_service(comms::Service::AuthService, &nats, Arc::new(on_recv)).await { + error!("failed to subscribe to authservice nats! reason {:?}", e); + } +} diff --git a/authservice/src/process/admin.rs b/authservice/src/process/admin.rs new file mode 100644 index 0000000..d6ee108 --- /dev/null +++ b/authservice/src/process/admin.rs @@ -0,0 +1,361 @@ +/* + * authservice process/admin.rs + * - admin request functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::future::Future; +use asklyphe_common::nats::authservice::admin::{AdminCreateAnnouncementRequest, AdminCreateAnnouncementResponse, AdminInviteCodeGenerateRequest, AdminInviteCodeGenerateResponse, AdminListAllUsersRequest, AdminListAllUsersResponse, AdminListInviteCodesRequest, AdminListInviteCodesResponse, AdminUpdateAnnouncementRequest, AdminUpdateAnnouncementResponse, InviteCodeSerialized, Stats, StatsRequest, StatsResponse, UserSerialized}; +use log::error; +use sea_orm::DatabaseConnection; +use entity::invite_code::Model; +use crate::db::{announcements, invite_code, session, user}; +use crate::db::announcements::{AnnouncementInsertError, AnnouncementUpdateError}; +use crate::db::invite_code::{InviteCodeGenerationError, InviteCodeListError}; +use crate::db::session::FetchSessionError; +use crate::db::user::{FetchUserError, UserInfo}; +use crate::email::send_announcement_email; + +async fn admin_info(db: &DatabaseConnection, token: String) -> Result, FetchSessionError> { + let uid = match session::get_userid_from_session(db, token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + Err(FetchSessionError::SessionInvalid) + } + FetchSessionError::SessionDoesntExist => { + Err(FetchSessionError::SessionDoesntExist) + } + FetchSessionError::DatabaseError => { + Err(FetchSessionError::DatabaseError) + } + } + } + }; + let info = match user::user_info(db, uid).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { + Err(FetchSessionError::SessionDoesntExist) + } + FetchUserError::DatabaseError => { + Err(FetchSessionError::DatabaseError) + } + } + }; + if !info.admin { + return Ok(None); + } + Ok(Some(info)) +} + +pub async fn stats(db: &DatabaseConnection, request: StatsRequest) -> StatsResponse { + let info = admin_info(db, request.token).await; + let _info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return StatsResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + StatsResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + StatsResponse::Logout + } + FetchSessionError::DatabaseError => { + StatsResponse::InternalServerError("database error".to_string()) + } + }; + }; + + let last_ten_users = match user::last_ten_usernames(db).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { unreachable!() } + FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )} + } + }; + let user_count = match user::user_count(db).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { unreachable!() } + FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )} + } + }; + let admin_count = match user::admin_count(db).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { unreachable!() } + FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )} + } + }; + let active_verification_requests = match user::unverified_count(db).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { unreachable!() } + FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )} + } + }; + + StatsResponse::Success(Stats { + last_ten_users, + user_count, + admin_count, + active_verification_requests, + }) +} + +pub async fn admin_invite_code_gen(db: &DatabaseConnection, request: AdminInviteCodeGenerateRequest) -> AdminInviteCodeGenerateResponse { + let info = admin_info(db, request.token).await; + let info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return AdminInviteCodeGenerateResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + AdminInviteCodeGenerateResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + AdminInviteCodeGenerateResponse::Logout + } + FetchSessionError::DatabaseError => { + AdminInviteCodeGenerateResponse::InternalServerError("database error".to_string()) + } + }; + }; + + let issuer = info.username; + + match invite_code::insert_new_invitecode(db, request.invite_code, issuer.clone(), issuer, request.comment).await { + Ok(_) => { + AdminInviteCodeGenerateResponse::Success + } + Err(e) => match e { + InviteCodeGenerationError::CodeAlreadyInserted => { + AdminInviteCodeGenerateResponse::CodeAlreadyExists + } + InviteCodeGenerationError::DatabaseError => { + AdminInviteCodeGenerateResponse::InternalServerError("database error".to_string()) + } + } + } +} + +pub async fn admin_create_announcement(db: &DatabaseConnection, request: AdminCreateAnnouncementRequest) -> AdminCreateAnnouncementResponse { + let info = admin_info(db, request.token).await; + let info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return AdminCreateAnnouncementResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + AdminCreateAnnouncementResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + AdminCreateAnnouncementResponse::Logout + } + FetchSessionError::DatabaseError => { + AdminCreateAnnouncementResponse::InternalServerError("database error".to_string()) + } + }; + }; + + let uid = match user::username_to_userid(db, info.username.clone()).await { + Ok(v) => v, + Err(e) => { + match e { + FetchUserError::UserNotFound => { + error!("user id not found for username {}", info.username); + } + FetchUserError::DatabaseError => { + } + } + return AdminCreateAnnouncementResponse::InternalServerError("database error".to_string()); + } + }; + + match announcements::create_announcement(db, request.slug, request.title.clone(), request.short_text, request.full_markdown_text.clone(), uid).await { + Ok(_) => { + if request.send_emails { + let email_list = user::email_list(db).await.unwrap_or_else(|e| match e { + FetchUserError::UserNotFound => { + unreachable!() + } + FetchUserError::DatabaseError => { + error!("couldn't send announcement emails due to a database error! you will need to send them manually!"); + vec![] + } + }); + for (username, email) in email_list { + send_announcement_email(&email, &username, &request.title, &request.full_markdown_text); + } + } + AdminCreateAnnouncementResponse::Success + } + Err(e) => match e { + AnnouncementInsertError::SlugInUse => { + AdminCreateAnnouncementResponse::SlugTaken + } + AnnouncementInsertError::DatabaseError => { + AdminCreateAnnouncementResponse::InternalServerError("database error".to_string()) + } + } + } +} + +pub async fn admin_update_announcement(db: &DatabaseConnection, request: AdminUpdateAnnouncementRequest) -> AdminUpdateAnnouncementResponse { + let info = admin_info(db, request.token).await; + let _info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return AdminUpdateAnnouncementResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + AdminUpdateAnnouncementResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + AdminUpdateAnnouncementResponse::Logout + } + FetchSessionError::DatabaseError => { + AdminUpdateAnnouncementResponse::InternalServerError("database error".to_string()) + } + }; + }; + + match announcements::update_announcement(db, request.slug, request.new_title, request.new_short_text, request.new_full_markdown_text).await { + Ok(_) => { + AdminUpdateAnnouncementResponse::Success + } + Err(e) => match e { + AnnouncementUpdateError::SlugNotFound => { + AdminUpdateAnnouncementResponse::OriginalNotFound + } + AnnouncementUpdateError::DatabaseError => { + AdminUpdateAnnouncementResponse::InternalServerError("database error".to_string()) + } + } + } +} + +pub async fn admin_list_invite_codes(db: &DatabaseConnection, request: AdminListInviteCodesRequest) -> AdminListInviteCodesResponse { + let info = admin_info(db, request.token).await; + let _info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return AdminListInviteCodesResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + AdminListInviteCodesResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + AdminListInviteCodesResponse::Logout + } + FetchSessionError::DatabaseError => { + AdminListInviteCodesResponse::InternalServerError("database error".to_string()) + } + }; + }; + + match invite_code::list_invite_codes(db, request.show_used).await { + Ok(v) => { + let mut serialized = vec![]; + for v in v { + let used_by = if let Some(used_by) = v.used_by { + Some(match user::user_info(db, used_by.clone()).await { + Ok(v) => { v.username } + Err(v) => { format!("error fetching {}, err is {:?}", used_by, v) } + }) + } else { + None + }; + serialized.push( + InviteCodeSerialized { + code: v.code, + comment: v.comment.unwrap_or_default(), + creator: v.issuer.unwrap_or_default(), + root_creator: v.root_issuer, + created_at: v.created_on.and_utc().to_string(), + used_at: v.used_on.map(|v| v.and_utc().to_string()), + used_by, + }); + } + AdminListInviteCodesResponse::Success(serialized) + } + Err(e) => { + match e { + InviteCodeListError::DatabaseError => { + AdminListInviteCodesResponse::InternalServerError("database error".to_string()) + } + } + } + } +} + +pub async fn admin_list_all_users(db: &DatabaseConnection, request: AdminListAllUsersRequest) -> AdminListAllUsersResponse { + let info = admin_info(db, request.token).await; + let _info = if let Ok(info) = info { + if let Some(info) = info { + info + } else { + return AdminListAllUsersResponse::AccessDenied; + } + } else { + return match info.unwrap_err() { + FetchSessionError::SessionInvalid => { + AdminListAllUsersResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + AdminListAllUsersResponse::Logout + } + FetchSessionError::DatabaseError => { + AdminListAllUsersResponse::InternalServerError("database error".to_string()) + } + }; + }; + + match user::all_users(db).await { + Ok(v) => { + AdminListAllUsersResponse::Success(v.into_iter().map(|v| { + UserSerialized { + username: v.username, + email: v.email, + verified: v.verified, + admin: v.admin, + } + }).collect()) + } + Err(e) => { + match e { + FetchUserError::UserNotFound => { + unreachable!("usernotfound should not be returned from user::all_users!") + } + FetchUserError::DatabaseError => { + AdminListAllUsersResponse::InternalServerError("database error".to_string()) + } + } + } + } +} \ No newline at end of file diff --git a/authservice/src/process/announcements.rs b/authservice/src/process/announcements.rs new file mode 100644 index 0000000..cb7fe7c --- /dev/null +++ b/authservice/src/process/announcements.rs @@ -0,0 +1,104 @@ +/* + * authservice process/announcements.rs + * - announcement-related request functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::future::Future; +use asklyphe_common::nats::authservice::announcements::{AnnouncementFull, AnnouncementFullRequest, AnnouncementFullResponse, AnnouncementListRequest, AnnouncementListResponse, AnnouncementShortForm, LatestAnnouncementRequest, LatestAnnouncementResponse}; +use log::warn; +use sea_orm::DatabaseConnection; +use crate::db::{announcements, user}; +use crate::db::announcements::{AnnouncementFetchError, AnnouncementRecord}; +use crate::db::user::{FetchUserError, UserInfo}; + +pub async fn latest_announcement(db: &DatabaseConnection, request: LatestAnnouncementRequest) -> LatestAnnouncementResponse { + match announcements::latest_announcement(db).await { + Ok(v) => { + LatestAnnouncementResponse::Some(AnnouncementShortForm { + title: v.title, + short_text: v.short, + date: v.created_on.timestamp(), + slug: v.slug, + }) + } + Err(e) => match e { + AnnouncementFetchError::SlugNotFound => { + LatestAnnouncementResponse::None + } + AnnouncementFetchError::DatabaseError => { + LatestAnnouncementResponse::InternalServerError("database error".to_string()) + } + } + } +} + +// fixme: listen to limit and actually limit the amount returned +pub async fn announcement_list(db: &DatabaseConnection, request: AnnouncementListRequest) -> AnnouncementListResponse { + match announcements::get_all_announcements(db).await { + Ok(v) => { + AnnouncementListResponse::Success(v.into_iter().map(|v| { + AnnouncementShortForm { + title: v.title, + short_text: v.short, + date: v.created_on.timestamp(), + slug: v.slug, + } + }).collect()) + } + Err(e) => match e { + AnnouncementFetchError::SlugNotFound => { + AnnouncementListResponse::Success(vec![]) + } + AnnouncementFetchError::DatabaseError => { + AnnouncementListResponse::InternalServerError("database error".to_string()) + } + } + } +} + +pub async fn announcement_full(db: &DatabaseConnection, request: AnnouncementFullRequest) -> AnnouncementFullResponse { + match announcements::get_announcement(db, request.slug).await { + Ok(v) => { + let username = match user::user_info(db, v.creator_uid.clone()).await { + Ok(v) => { + v.username + } + Err(e) => { + match e { + FetchUserError::UserNotFound => { + warn!("creator {} not found for announcement", v.creator_uid); + } + FetchUserError::DatabaseError => { + warn!("database error while getting full announcement"); + } + } + "lyphe".to_string() + } + }; + AnnouncementFullResponse::Some(AnnouncementFull { + title: v.title, + created_on: v.created_on.timestamp(), + updated_on: v.updated_on.map(|v| v.timestamp()), + slug: v.slug, + creator: username, + markdown_text: v.full, + }) + } + Err(e) => match e { + AnnouncementFetchError::SlugNotFound => { + AnnouncementFullResponse::NotFound + } + AnnouncementFetchError::DatabaseError => { + AnnouncementFullResponse::InternalServerError("database error".to_string()) + } + } + } +} \ No newline at end of file diff --git a/authservice/src/process/basic_accounts.rs b/authservice/src/process/basic_accounts.rs new file mode 100644 index 0000000..bbefa51 --- /dev/null +++ b/authservice/src/process/basic_accounts.rs @@ -0,0 +1,349 @@ +/* + * authservice process/basic_accounts.rs + * - basic authentication + creation for accounts, as well as a few other things + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::future::Future; +use asklyphe_common::nats::authservice::{AuthError, AuthRequest, AuthResponse, AuthServiceResponse, CancelEmailChangeRequest, CancelEmailChangeResponse, EmailChangeRequest, EmailChangeResponse, EmailError, LoginError, LoginRequest, LoginResponse, LogoutRequest, LogoutResponse, PasswordError, RegisterError, RegisterRequest, RegisterResponse, TokenAssignment, UsernameError, VerifyEmailRequest, VerifyEmailResponse}; +use chrono::{DateTime, Utc}; +use log::{debug, error}; +use rand::Rng; +use sea_orm::DatabaseConnection; +use crate::db::{invite_code, session, user}; +use crate::db::invite_code::ConsumeInviteCodeError; +use crate::db::session::{CreateSessionError, DeleteSessionError, FetchSessionError}; +use crate::db::user::{CreateUserError, DeleteUserError, EmailChangeError, FetchUserError, RegisterVerificationCodeError, VerifyEmailPassComboError, VerifyVerificationCodeError}; +use crate::email; + +fn generate_email_verification_code() -> String { + rand::thread_rng() + .sample_iter(&rand::distributions::Alphanumeric) + .take(16) + .map(char::from) + .collect() +} + +pub async fn register_request(db: &DatabaseConnection, request: RegisterRequest) -> RegisterResponse { + // goes something like: + // 1. create user in db + // 2. try to consume invite code + // 2.5. if that fails, delete user from db + // 3. otherwise, register email verification code in db + // 4. this is where we'd send emails out with the verification code, if we had that set up... + let user = user::create_user( + db, + request.username.clone(), + request.username.clone(), + request.email.clone(), + request.password).await; + if let Err(e) = user { + return match e { + CreateUserError::UsernameTaken => { + RegisterResponse::Failure(RegisterError::Username(UsernameError::Taken)) + } + CreateUserError::EmailTaken => { + RegisterResponse::Failure(RegisterError::Email(EmailError::EmailTaken)) + } + CreateUserError::UsernameError => { + RegisterResponse::Failure(RegisterError::Username(UsernameError::InvalidCharacters)) + } + CreateUserError::DisplayNameError => { + unimplemented!("we don't explicitly allow display names to be set, username error would be hit before display name error") + } + CreateUserError::EmailError => { + RegisterResponse::Failure(RegisterError::Email(EmailError::InvalidEmail)) + } + CreateUserError::PasswordError => { + // todo: actual password errors that tell you why it's bad + RegisterResponse::Failure(RegisterError::Password(PasswordError::TooShort)) + } + CreateUserError::DatabaseError => { + RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string())) + } + }; + } + let user_id = user.unwrap(); + if let Err(e) = invite_code::consume_invite_code(db, request.invite_code.clone(), user_id.clone()).await { + if let Err(e) = user::delete_user(db, user_id.clone()).await { + return match e { + DeleteUserError::UserDoesntExist => { + RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string())) + } + DeleteUserError::DatabaseError => { + RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string())) + } + }; + } + return match e { + ConsumeInviteCodeError::InvalidUser => { + RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string())) + } + ConsumeInviteCodeError::DatabaseError => { + RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string())) + } + _ => { + RegisterResponse::Failure(RegisterError::BadInviteCode) + } + }; + } + + let verification_code = generate_email_verification_code(); + if let Err(e) = user::register_verification_code(db, user_id.clone(), verification_code.clone()).await { + if let Err(e) = user::delete_user(db, user_id.clone()).await { + match e { + DeleteUserError::UserDoesntExist => { + error!("failed to register verify code during signup, and couldn't delete the user because they don't exist?") + } + DeleteUserError::DatabaseError => { + error!("database error while trying to delete user after registering verify code failed during signup") + } + } + } + return match e { + RegisterVerificationCodeError::UserIsVerifiedAndNotChangingTheirEmail => { + RegisterResponse::Failure(RegisterError::InternalServer("unexpected corrupt user struct".to_string())) + } + RegisterVerificationCodeError::UserDoesntExist => { + RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string())) + } + RegisterVerificationCodeError::DatabaseError => { + RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string())) + } + }; + } + + debug!("verification code for {} is \"{}\"", request.username, verification_code); + email::send_verification_code_email(&request.email, &request.username, format!("https://auth.asklyphe.com/verify?username={}&token={}", request.username, verification_code).as_str()); + + RegisterResponse::Success +} + +pub async fn verify_email(db: &DatabaseConnection, request: VerifyEmailRequest) -> VerifyEmailResponse { + let user_id = user::username_to_userid(db, request.username).await; + if let Err(e) = user_id { + return match e { + FetchUserError::UserNotFound => { + VerifyEmailResponse::InvalidToken + } + FetchUserError::DatabaseError => { + VerifyEmailResponse::InternalServerError("database error during username2userid".to_string()) + } + }; + } + let user_id = user_id.unwrap(); + + if let Err(e) = user::verify_verification_code(db, user_id, request.token).await { + return match e { + VerifyVerificationCodeError::UserAlreadyVerified => { + VerifyEmailResponse::InvalidToken + } + VerifyVerificationCodeError::VerificationCodeInvalid => { + VerifyEmailResponse::InvalidToken + } + VerifyVerificationCodeError::UserDoesntExist => { + VerifyEmailResponse::InvalidToken + } + VerifyVerificationCodeError::DatabaseError => { + VerifyEmailResponse::InternalServerError("database error during username2userid".to_string()) + } + }; + } + + VerifyEmailResponse::Success +} + +pub async fn login(db: &DatabaseConnection, request: LoginRequest) -> LoginResponse { + // 1. verify that credentials are correct + // 2. create session + // 3. return token + if let Err(e) = user::verify_email_pass_combo(db, request.email.clone(), request.password).await { + return match e { + VerifyEmailPassComboError::ComboInvalid => { + LoginResponse::Failure(LoginError::InvalidAccount) + } + VerifyEmailPassComboError::UserDoesntExist => { + LoginResponse::Failure(LoginError::InvalidAccount) + } + VerifyEmailPassComboError::DatabaseError => { + LoginResponse::Failure(LoginError::InternalServer("database error while verifying email/pass combo".to_string())) + } + }; + } + let user_id = match user::email_to_userid(db, request.email).await { + Ok(user_id) => { user_id } + Err(e) => { + return match e { + FetchUserError::UserNotFound => { + LoginResponse::Failure(LoginError::InvalidAccount) + } + FetchUserError::DatabaseError => { + LoginResponse::Failure(LoginError::InternalServer("database error while converting email to userid".to_string())) + } + }; + } + }; + + match user::check_if_verified(db, user_id.clone()).await { + Ok(b) => { + if !b { + return LoginResponse::Failure(LoginError::AccountNotVerified); + } + } + Err(e) => { + return match e { + FetchUserError::UserNotFound => { + LoginResponse::Failure(LoginError::InvalidAccount) + } + FetchUserError::DatabaseError => { + LoginResponse::Failure(LoginError::InternalServer("database error while checking verification status".to_string())) + } + }; + } + } + + let session_token = match session::create_session(db, user_id, "".to_string()).await { + Ok(s) => s, + Err(e) => { + return match e { + CreateSessionError::UserDoesntExist => { + LoginResponse::Failure(LoginError::InvalidAccount) + } + CreateSessionError::DatabaseError => { + LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string())) + } + }; + } + }; + + let death_date = match session::get_session_death_date(db, session_token.clone()).await { + Ok(s) => s, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + error!("unexpected session invalid after just creating it during login!"); + LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string())) + } + FetchSessionError::SessionDoesntExist => { + error!("unexpected session not found after just creating it during login!"); + LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string())) + } + FetchSessionError::DatabaseError => { + LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string())) + } + }; + } + }; + + LoginResponse::Success(TokenAssignment { + token: session_token, + ttl: death_date.timestamp(), + }) +} + +pub async fn verify_session(db: &DatabaseConnection, request: AuthRequest) -> AuthResponse { + let uid = match session::get_userid_from_session(db, request.token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + AuthResponse::Failure(AuthError::TokenExpired) + } + FetchSessionError::SessionDoesntExist => { + AuthResponse::Failure(AuthError::TokenInvalid) + } + FetchSessionError::DatabaseError => { + AuthResponse::Failure(AuthError::InternalServer("database error while querying user id".to_string())) + } + }; + } + }; + + AuthResponse::Success(uid) +} + +pub async fn logout(db: &DatabaseConnection, request: LogoutRequest) -> LogoutResponse { + match session::delete_session(db, request.token).await { + Ok(_) => LogoutResponse::Success, + Err(e) => match e { + DeleteSessionError::SessionDoesntExist => { LogoutResponse::BadTokenError } + DeleteSessionError::DatabaseError => { LogoutResponse::InternalServerError("database error while deleting session".to_string()) } + } + } +} + +pub async fn email_change(db: &DatabaseConnection, request: EmailChangeRequest) -> EmailChangeResponse { + let uid = match session::get_userid_from_session(db, request.token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + EmailChangeResponse::InvalidToken + } + FetchSessionError::SessionDoesntExist => { + EmailChangeResponse::InvalidToken + } + FetchSessionError::DatabaseError => { + EmailChangeResponse::InternalError + } + }; + } + }; + + let verification_code = generate_email_verification_code(); + let res = user::start_email_change(db, uid.clone(), request.new_email, verification_code.clone()).await; + if let Err(e) = res { + return match e { + EmailChangeError::UserNotFound => { + EmailChangeResponse::InvalidToken + } + EmailChangeError::NewEmailIsInvalid => { + EmailChangeResponse::InvalidEmail + } + EmailChangeError::DatabaseError => { + EmailChangeResponse::InternalError + } + }; + } + debug!("verification code for new email on {} is \"{}\"", {user::user_info(db, uid.clone()).await.map(|v| v.username).unwrap_or(uid.clone())}, verification_code); + EmailChangeResponse::Success +} + +pub async fn cancel_email_change(db: &DatabaseConnection, request: CancelEmailChangeRequest) -> CancelEmailChangeResponse { + let uid = match session::get_userid_from_session(db, request.token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + CancelEmailChangeResponse::InvalidToken + } + FetchSessionError::SessionDoesntExist => { + CancelEmailChangeResponse::InvalidToken + } + FetchSessionError::DatabaseError => { + CancelEmailChangeResponse::InternalError + } + }; + } + }; + + if let Err(e) = user::cancel_email_change(db, uid).await { + return match e { + FetchUserError::UserNotFound => { + CancelEmailChangeResponse::InvalidToken + } + FetchUserError::DatabaseError => { + CancelEmailChangeResponse::InternalError + } + }; + } + + CancelEmailChangeResponse::Success +} diff --git a/authservice/src/process/mod.rs b/authservice/src/process/mod.rs new file mode 100644 index 0000000..b78700e --- /dev/null +++ b/authservice/src/process/mod.rs @@ -0,0 +1,94 @@ +/* + * authservice process/mod.rs + * - route incoming nats requests to their specific functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod basic_accounts; +mod profile; +mod admin; +mod announcements; + +use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse}; +use sea_orm::DatabaseConnection; +use crate::process::admin::{admin_create_announcement, admin_invite_code_gen, admin_list_all_users, admin_list_invite_codes, admin_update_announcement, stats}; +use crate::process::announcements::{announcement_full, announcement_list, latest_announcement}; +use crate::process::basic_accounts::{cancel_email_change, email_change, login, logout, register_request, verify_email, verify_session}; +use crate::process::profile::{change_theme, user_info}; + +pub async fn process(query: AuthServiceQuery, db: DatabaseConnection) -> AuthServiceResponse { + // a future is used so that the whole program doesn't die if an algorithm panics + // yes i know that's probably not the best way to do it, i'll fix it eventually + let response = tokio::spawn(async move { + match query.request { + AuthServiceRequest::RegisterRequest(req) => { + AuthServiceResponse::RegisterResponse(register_request(&db, req).await) + } + AuthServiceRequest::VerifyEmailRequest(req) => { + AuthServiceResponse::VerifyEmailResponse(verify_email(&db, req).await) + } + AuthServiceRequest::LoginRequest(req) => { + AuthServiceResponse::LoginResponse(login(&db, req).await) + } + AuthServiceRequest::AuthRequest(req) => { + AuthServiceResponse::AuthResponse(verify_session(&db, req).await) + } + AuthServiceRequest::LogoutRequest(req) => { + AuthServiceResponse::LogoutResponse(logout(&db, req).await) + } + AuthServiceRequest::UserInfoRequest(req) => { + AuthServiceResponse::UserInfoResponse(user_info(&db, req).await) + } + AuthServiceRequest::EmailChangeRequest(req) => { + AuthServiceResponse::EmailChangeResponse(email_change(&db, req).await) + } + AuthServiceRequest::CancelEmailChangeRequest(req) => { + AuthServiceResponse::CancelEmailChangeResponse(cancel_email_change(&db, req).await) + } + AuthServiceRequest::ThemeChangeRequest(req) => { + AuthServiceResponse::ThemeChangeResponse(change_theme(&db, req).await) + } + AuthServiceRequest::StatsRequest(req) => { + AuthServiceResponse::StatsResponse(stats(&db, req).await) + } + AuthServiceRequest::AdminInviteCodeGenerateRequest(req) => { + AuthServiceResponse::AdminInviteCodeGenerateResponse(admin_invite_code_gen(&db, req).await) + } + AuthServiceRequest::LatestAnnouncementRequest(req) => { + AuthServiceResponse::LatestAnnouncementResponse(latest_announcement(&db, req).await) + } + AuthServiceRequest::AnnouncementListRequest(req) => { + AuthServiceResponse::AnnouncementListResponse(announcement_list(&db, req).await) + } + AuthServiceRequest::AnnouncementFullRequest(req) => { + AuthServiceResponse::AnnouncementFullResponse(announcement_full(&db, req).await) + } + AuthServiceRequest::AdminCreateAnnouncementRequest(req) => { + AuthServiceResponse::AdminCreateAnnouncementResponse(admin_create_announcement(&db, req).await) + } + AuthServiceRequest::AdminUpdateAnnouncementRequest(req) => { + AuthServiceResponse::AdminUpdateAnnouncementResponse(admin_update_announcement(&db, req).await) + } + AuthServiceRequest::AdminListInviteCodesRequest(req) => { + AuthServiceResponse::AdminListInviteCodesResponse(admin_list_invite_codes(&db, req).await) + } + AuthServiceRequest::AdminListAllUsersRequest(req) => { + AuthServiceResponse::AdminListAllUsersResponse(admin_list_all_users(&db, req).await) + } + }}).await; + + if let Ok(response) = response { + response + } else if let Err(e) = response { + AuthServiceResponse::OtherError(e.to_string()) + } else { + unreachable!() + } +} \ No newline at end of file diff --git a/authservice/src/process/profile.rs b/authservice/src/process/profile.rs new file mode 100644 index 0000000..99731a9 --- /dev/null +++ b/authservice/src/process/profile.rs @@ -0,0 +1,105 @@ +/* + * authservice process/profile.rs + * - "customization-related" request functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use asklyphe_common::nats::authservice::{AuthError, AuthResponse}; +use asklyphe_common::nats::authservice::profile::{ThemeChangeRequest, ThemeChangeResponse, UserInfo, UserInfoRequest, UserInfoResponse}; +use sea_orm::DatabaseConnection; +use crate::db::{session, user, usersettings}; +use crate::db::session::FetchSessionError; +use crate::db::user::FetchUserError; +use crate::db::usersettings::{FetchUserSettingsError, UserSettings}; + +pub async fn user_info(db: &DatabaseConnection, request: UserInfoRequest) -> UserInfoResponse { + let uid = match session::get_userid_from_session(db, request.token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + UserInfoResponse::TokenExpired + } + FetchSessionError::SessionDoesntExist => { + UserInfoResponse::TokenInvalid + } + FetchSessionError::DatabaseError => { + UserInfoResponse::InternalServerError("database error while querying user id".to_string()) + } + }; + } + }; + + let user_info = match user::user_info(db, uid.clone()).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserError::UserNotFound => { + UserInfoResponse::TokenInvalid + } + FetchUserError::DatabaseError => { + UserInfoResponse::InternalServerError("database error while querying user id".to_string()) + } + } + }; + + let user_settings = match usersettings::get_or_create_default_user_settings(db, uid).await { + Ok(u) => u, + Err(e) => return match e { + FetchUserSettingsError::UserNotFound => { + UserInfoResponse::InternalServerError("database error while querying user id".to_string()) + } + FetchUserSettingsError::DatabaseError => { + UserInfoResponse::InternalServerError("database error while querying user id".to_string()) + } + } + }; + + UserInfoResponse::Success(UserInfo { + username: user_info.username, + email: user_info.email, + new_email: user_info.new_email, + theme: user_settings.theme, + administrator: user_info.admin, + }) +} + +pub async fn change_theme(db: &DatabaseConnection, request: ThemeChangeRequest) -> ThemeChangeResponse { + let uid = match session::get_userid_from_session(db, request.token, true).await { + Ok(u) => u, + Err(e) => { + return match e { + FetchSessionError::SessionInvalid => { + ThemeChangeResponse::Logout + } + FetchSessionError::SessionDoesntExist => { + ThemeChangeResponse::Logout + } + FetchSessionError::DatabaseError => { + ThemeChangeResponse::InternalServerError + } + }; + } + }; + match usersettings::set_theme(db, uid, request.theme).await { + Ok(_) => { + ThemeChangeResponse::Success + } + Err(e) => { + match e { + FetchUserSettingsError::UserNotFound => { + ThemeChangeResponse::Logout + } + FetchUserSettingsError::DatabaseError => { + ThemeChangeResponse::InternalServerError + } + } + } + } +} \ No newline at end of file diff --git a/bingservice/.gitignore b/bingservice/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/bingservice/.gitignore @@ -0,0 +1 @@ +/target diff --git a/bingservice/Cargo.toml b/bingservice/Cargo.toml new file mode 100644 index 0000000..f66fc3d --- /dev/null +++ b/bingservice/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "bingservice" +version = "0.1.0" +edition = "2021" + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } +tokio = { version = "1.0", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +isahc = { version = "1.7.2", features = ["json"] } +async-nats = "0.38.0" +once_cell = "1.18.0" +log = "0.4.20" +env_logger = "0.10.2" +url_encoded_data = "0.6.1" +chrono = "0.4.38" +scraper = "0.20.0" \ No newline at end of file diff --git a/bingservice/src/bing.rs b/bingservice/src/bing.rs new file mode 100644 index 0000000..9754bfb --- /dev/null +++ b/bingservice/src/bing.rs @@ -0,0 +1,259 @@ +/* + * bingservice bing.rs + * - parsing of bing + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::atomic::Ordering; +use std::time::Duration; +use asklyphe_common::nats::bingservice::{BingImageResult, BingSearchResult}; +use isahc::{AsyncReadResponseExt, HttpClient, Request, RequestExt}; +use isahc::auth::Authentication; +use isahc::config::RedirectPolicy; +use isahc::prelude::Configurable; +use log::{debug, error, warn}; +use scraper::{CaseSensitivity, Element, Html, Selector}; +use scraper::selector::CssLocalName; +use serde::Deserialize; +use crate::{BING_KEY, NEXT_PROXY, PROXIES}; +use crate::proxy::Proxy; + +#[derive(Debug)] +pub enum BingQueryError { + CouldNotSendRequest, + CouldNotDeserialize, +} + +pub async fn proxy() -> Option { + if !PROXIES.is_empty() { + let mut next_proxy = NEXT_PROXY.fetch_add(1, Ordering::Relaxed); + if next_proxy >= PROXIES.len() { + next_proxy = 0; + NEXT_PROXY.store(1, Ordering::Relaxed); + } + //debug!("proxy {}", next_proxy); + let p = PROXIES[next_proxy].clone(); + return Some(p); + } + None +} + +pub async fn generate_cvid() -> Result { + // query https://www.bing.com + // look for cookie header setting the "IG" cookie + let proxy = proxy().await; + let mut client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)); + if let Some(proxy) = proxy { + client = client.proxy(Some(proxy.address.parse().expect("BAD PROXY ADDR"))); + if let Some(proxy_auth) = proxy.credentials { + client = client.proxy_authentication(Authentication::basic()); + client = client.proxy_credentials(proxy_auth); + } + } + + let client = client + .build().expect("FAILED TO CONSTRUCT HTTP CLIENT"); + + + let res = Request::get("https://www.bing.com/") + .header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8") + .header("accept-language", "en-US,en;q=0.5") + .redirect_policy(RedirectPolicy::Follow) + .body(()).unwrap(); + let mut res = client.send_async(res).await.map_err(|e| { + error!("FAILED TO ATTEMPT CVID GEN, COULDN'T SEND HTTP REQUEST: {e}"); + BingQueryError::CouldNotSendRequest + })?; + + for (name, val) in res.headers().iter() { + if name.as_str() == "set-cookie" { + let val_str = String::from_utf8_lossy(val.as_bytes()); + if val_str.contains("IG=") { + let start = val_str.find("IG=").unwrap(); + let start = start + "IG=".len(); + let end = val_str[start..].find(";").ok_or(BingQueryError::CouldNotDeserialize)?; + let cvid = val_str[start..(start + end)].trim(); + if cvid.len() != 32 { + warn!("cvid len was not 32 (actually \"{}\") while retrieving cvid, continuing but this may cause issues", cvid); + } + return Ok(cvid.to_string()); + } + } + } + + error!("FAILED CVID GEN! NO CVID FOUND!"); + Err(BingQueryError::CouldNotDeserialize) +} + +pub async fn query_bing(query: String, cvid: &str, first: usize) -> Result, BingQueryError> { + let query = url_encoded_data::stringify(&[("q", query.as_str())]); + + let proxy = proxy().await; + let mut client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)); + let mut proxy_name = "none".to_string(); + if let Some(proxy) = proxy { + client = client.proxy(Some(proxy.address.parse().expect("BAD PROXY ADDR"))); + proxy_name = proxy.address.clone(); + if let Some(proxy_auth) = proxy.credentials { + client = client.proxy_authentication(Authentication::basic()); + client = client.proxy_credentials(proxy_auth); + } + } + + let client = client + .build().expect("FAILED TO CONSTRUCT HTTP CLIENT"); + + let url = format!("https://www.bing.com/search?{query}&form=QBLH&sp=-1&ghc=1&lq=0&p{query}&sc=11-9&qs=n&sk=&cvid={cvid}&ghsh=0&ghacc=0&ghpl="); + + let res = Request::get(&url) + .header("user-agent", "Mozilla/5.0 (Linux; Android 9; KFTRWI) AppleWebKit/537.36 (KHTML, like Gecko) Silk/126.6.2 like Chrome/126.0.6478.238 Safari/537.36") + .header("accept-language", "en-US,en;q=0.5") + .body(()).unwrap(); + let mut res = client.send_async(res).await.map_err(|e| { + error!("FAILED TO SEND REQUEST TO BING: {e} ({query}) (proxy: {proxy_name})"); + BingQueryError::CouldNotSendRequest + })?; + let body = res.text().await.map_err(|e| { + error!("COULD NOT READ BING RESPONSE TEXT: {e}"); + BingQueryError::CouldNotDeserialize + })?; + + let document = Html::parse_document(body.as_str()); + let ol_sel = Selector::parse("ol").unwrap(); + + let results = document.select(&ol_sel).find(|v| {v.value().id().unwrap_or_default() == "b_results"}).ok_or_else(|| { + error!("COULD NOT FIND
      IN BING RESPONSE"); + debug!("body: {body}"); + BingQueryError::CouldNotDeserialize + })?; + + let li_sel = Selector::parse("li").unwrap(); + let h2_sel = Selector::parse("h2").unwrap(); + let cite_sel = Selector::parse("a.tilk").unwrap(); + let p_sel = Selector::parse("p").unwrap(); + + let mut final_results = vec![]; + + for element in results.select(&li_sel) { + if !element.value().has_class("b_algo", CaseSensitivity::AsciiCaseInsensitive) { + // non-text search result + continue; + } + + let title = element.select(&h2_sel).next(); + if title.is_none() { + continue; + } + let url = element.select(&cite_sel).next().map(|v| v.attr("href").map(|v| v.to_string())).flatten(); + if url.is_none() { + continue; + } + + let desc = element.select(&p_sel).next(); + + let title = title.unwrap().text().collect::>(); + let title = title.join(" "); + + let url = url.unwrap(); + + if url.contains("javascript") { + warn!("javascript url encountered, full cite: {:?}", element.select(&cite_sel).collect::>()); + } + + let desc = if let Some(desc) = desc { + let desc = desc.text().into_iter().collect::>(); + let desc = desc.join(" "); + Some(desc) + } else { + None + }; + + final_results.push(BingSearchResult { + url, + title: Some(title), + description: desc, + }); + } + + if final_results.is_empty() { + debug!("no results, body: {body}"); + } + + Ok(final_results) +} + +// first starts at 1 and goes up by multiples of 12, first = (page * 12) + 1 +pub async fn query_bing_images(query: String, first: usize) -> Result, BingQueryError> { + let query = url_encoded_data::stringify(&[("q", query.as_str())]); + + let proxy = proxy().await; + let mut client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)); + let mut proxy_name = "none".to_string(); + if let Some(proxy) = proxy { + client = client.proxy(Some(proxy.address.parse().expect("BAD PROXY ADDR"))); + proxy_name = proxy.address.clone(); + if let Some(proxy_auth) = proxy.credentials { + client = client.proxy_authentication(Authentication::basic()); + client = client.proxy_credentials(proxy_auth); + } + } + + let client = client + .build().expect("FAILED TO CONSTRUCT HTTP CLIENT"); + + let url = format!("https://www.bing.com/images/search?{query}&first={first}"); + + let res = Request::get(&url) + .header("user-agent", "Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaX7-00/021.004; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.1.21 Mobile Safari/533.4 3gpp-gba") + .header("accept-language", "en-US,en;q=0.5") + .body(()).unwrap(); + let mut res = client.send_async(res).await.map_err(|e| { + error!("FAILED TO SEND REQUEST TO BING: {e} ({query}) (proxy: {proxy_name})"); + BingQueryError::CouldNotSendRequest + })?; + let body = res.text().await.map_err(|e| { + error!("COULD NOT READ BING RESPONSE TEXT: {e}"); + BingQueryError::CouldNotDeserialize + })?; + + let document = Html::parse_document(body.as_str()); + let link_sel = Selector::parse("div>a").unwrap(); + let img_sel = Selector::parse("div>img").unwrap(); + + let results = document.select(&link_sel).collect::>(); + + let mut final_results = vec![]; + + for element in results { + let img = element.select(&img_sel).next(); + if img.is_none() { + continue; + } + let url = element.attr("href"); + if url.is_none() { + warn!("no href in image result"); + continue; + } + let url = url.unwrap().to_string(); + + final_results.push(BingImageResult { + url, + }); + } + + if final_results.is_empty() { + debug!("no results, body: {body}"); + } + + Ok(final_results) +} diff --git a/bingservice/src/main.rs b/bingservice/src/main.rs new file mode 100644 index 0000000..e8223fd --- /dev/null +++ b/bingservice/src/main.rs @@ -0,0 +1,139 @@ +/* + * bingservice main.rs + * - entrypoint for the asklyphe bing backend + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod process; +mod bing; +pub mod proxy; + +use std::io::Read; +use std::str::FromStr; +use std::sync::Arc; +use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use asklyphe_common::nats::authservice::AuthServiceResponse; +use asklyphe_common::nats::bingservice::BingServiceResponse; +use asklyphe_common::nats::comms; +use async_nats::jetstream; +use isahc::{Request, RequestExt}; +use log::{debug, error, info}; +use once_cell::sync::{Lazy, OnceCell}; +use crate::bing::BingQueryError; +use crate::proxy::Proxy; + +pub static PROXIES: Lazy> = Lazy::new(|| { + if let Ok(proxy_file) = std::env::var("PROXY_FILE") { + let contents = std::fs::read_to_string(proxy_file); + let mut proxies = vec![]; + + for line in contents.expect("FAILED TO READ FILE").lines() { + proxies.push(Proxy::from_str(line).expect("INVALID PROXY")); + } + + info!("loaded {} proxies", proxies.len()); + + proxies + } else { + vec![] + } +}); + +pub static NEXT_PROXY: AtomicUsize = AtomicUsize::new(0); + +pub static NATS_URL: Lazy = Lazy::new(|| std::env::var("NATS_URL").expect("NO NATS DEFINED")); +pub static NATS_CERT: Lazy = Lazy::new(|| std::env::var("NATS_CERT").expect("NO NATS_CERT DEFINED")); +pub static NATS_KEY: Lazy = Lazy::new(|| std::env::var("NATS_KEY").expect("NO NATS_KEY DEFINED")); +pub static DB_URL: Lazy = Lazy::new(|| std::env::var("DB_URL").expect("NO DB_URL DEFINED")); +pub static BING_KEY: Lazy = Lazy::new(|| std::env::var("BING_KEY").expect("NO BING_KEY DEFINED")); +pub static PROCESSES_HANDLED: AtomicU64 = AtomicU64::new(0); +pub static LAST_MESSAGE: AtomicI64 = AtomicI64::new(0); + +/* +fn main() { + let mut args: Vec = std::env::args().collect(); + // remove first argument (path) + args.remove(0); + let query = args.join(" "); + let query = url_encoded_data::stringify(&[("q", query.as_str())]); + + let mut res = Request::get(format!("https://api.bing.microsoft.com/v7.0/search?{query}&safeSearch=Off")) + .header("user-agent", USER_AGENT.as_str()) + .header("Ocp-Apim-Subscription-Key", BING_KEY.as_str()) + .body(()).unwrap().send().expect("FAILED TO SEND REQUEST"); + + let mut str = "".to_string(); + + res.body_mut().read_to_string(&mut str).unwrap(); + + println!("{str}"); +} +*/ + +static CVID: OnceCell> = OnceCell::new(); + +#[tokio::main] +async fn main() { + env_logger::init(); + info!("bingservice began at {}", chrono::Utc::now().to_string()); + + let cvid = bing::generate_cvid().await; + if let Err(e) = cvid { + match e { + BingQueryError::CouldNotSendRequest => { + error!("EXITING DUE TO FAILED CVID GENERATION: COULDN'T SEND REQUEST"); + } + BingQueryError::CouldNotDeserialize => { + error!("EXITING DUE TO FAILED CVID GENERATION: COULDN'T FIND CVID"); + } + } + return; + } + let cvid = Arc::new(cvid.unwrap()); + info!("cvid: {cvid}"); + CVID.set(cvid.clone()).unwrap(); + + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(NATS_CERT.as_str().into(), NATS_KEY.as_str().into()) + .connect(NATS_URL.as_str()) + .await; + if let Err(e) = nats { + error!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + + async fn on_recv(query: comms::Query) -> comms::ServiceResponse { + debug!("recv"); + let cvid = CVID.get().unwrap().clone(); + let now = chrono::Utc::now().timestamp(); + LAST_MESSAGE.store(now, Ordering::Relaxed); + + let response = match query { + comms::Query::BingService(query) => { + process::process(query, cvid).await + } + _ => { + BingServiceResponse::InvalidRequest + } + }; + + if PROCESSES_HANDLED.load(Ordering::Relaxed) % 100 == 0 { + info!("handled {} requests!", PROCESSES_HANDLED.load(Ordering::Relaxed)); + } + PROCESSES_HANDLED.fetch_add(1, Ordering::Relaxed); + comms::ServiceResponse::BingService(response) + } + + if let Err(e) = comms::subscribe_service(comms::Service::BingService, &nats, Arc::new(on_recv)).await { + error!("failed to subscribe to bingservice nats! reason {:?}", e); + } +} diff --git a/bingservice/src/process/mod.rs b/bingservice/src/process/mod.rs new file mode 100644 index 0000000..e0959ab --- /dev/null +++ b/bingservice/src/process/mod.rs @@ -0,0 +1,77 @@ +/* + * bingservice process/mod.rs + * - route incoming nats requests to their specific functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use asklyphe_common::nats::bingservice::{BingServiceQuery, BingServiceRequest, BingServiceResponse, SearchResponse}; +use crate::bing; +use crate::bing::BingQueryError; + +pub async fn process(query: BingServiceQuery, cvid: Arc) -> BingServiceResponse { + // a future is used so that the whole program doesn't die if an algorithm panics + let response = tokio::spawn(async move { + match query.request { + BingServiceRequest::SearchRequest(q) => { + let res = bing::query_bing(q.query, &cvid, 1).await; + if let Err(e) = res { + match e { + BingQueryError::CouldNotSendRequest => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + BingQueryError::CouldNotDeserialize => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + } + } else { + BingServiceResponse::SearchResponse(SearchResponse { + results: res.unwrap(), + blocked: vec![], + }) + } + } + BingServiceRequest::ImageRequest(q) => { + const IMAGE_PAGES: usize = 1; + let mut all_results = vec![]; + let mut error = None; + for page in 0..IMAGE_PAGES { + let res = bing::query_bing_images(q.query.clone(), (page * 12) + 1).await; + if let Err(e) = res { + error = Some(match e { + BingQueryError::CouldNotSendRequest => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + BingQueryError::CouldNotDeserialize => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + }); + break; + } else { + all_results.extend(res.unwrap()); + } + } + if !all_results.is_empty() { + BingServiceResponse::ImageResponse(all_results) + } else { + error.unwrap_or(BingServiceResponse::OtherError( + "bing failed".to_string())) + } + } + }}).await; + + if let Ok(response) = response { + response + } else if let Err(e) = response { + BingServiceResponse::OtherError(e.to_string()) + } else { + unreachable!() + } +} \ No newline at end of file diff --git a/bingservice/src/proxy.rs b/bingservice/src/proxy.rs new file mode 100644 index 0000000..4559a95 --- /dev/null +++ b/bingservice/src/proxy.rs @@ -0,0 +1,46 @@ +/* + * bingservice proxy.rs + * - helper structs for proxies + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::str::FromStr; +use isahc::auth::Credentials; + +#[derive(Clone)] +pub struct Proxy { + pub address: String, + pub credentials: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProxyError { + InvalidProxyFormat, +} + +impl FromStr for Proxy { + type Err = ProxyError; + + fn from_str(s: &str) -> Result { + let mut parts = s.split(':'); + let host = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + let port = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + let auth = if let Some(user) = parts.next() { + let pass = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + Some(Credentials::new(user, pass)) + } else { + None + }; + Ok(Proxy { + address: format!("{}:{}", host, port), + credentials: auth, + }) + } +} \ No newline at end of file diff --git a/googleservice/.gitignore b/googleservice/.gitignore new file mode 100644 index 0000000..620f8f6 --- /dev/null +++ b/googleservice/.gitignore @@ -0,0 +1,27 @@ +# ---> Rust +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# RustRover +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + + +# Added by cargo + +/target diff --git a/googleservice/Cargo.toml b/googleservice/Cargo.toml new file mode 100644 index 0000000..21d50f8 --- /dev/null +++ b/googleservice/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "googleservice" +version = "0.1.0" +edition = "2021" + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } +tokio = { version = "1.0", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +isahc = { version = "1.7.2", features = ["json"] } +async-nats = "0.38.0" +once_cell = "1.18.0" +log = "0.4.20" +env_logger = "0.10.2" +url_encoded_data = "0.6.1" +chrono = "0.4.38" +scraper = "0.20.0" diff --git a/googleservice/src/google.rs b/googleservice/src/google.rs new file mode 100644 index 0000000..8d967bc --- /dev/null +++ b/googleservice/src/google.rs @@ -0,0 +1,239 @@ +/* + * googleservice google.rs + * - google parsing + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::atomic::Ordering; +use std::time::Duration; +use asklyphe_common::nats::bingservice::{BingImageResult, BingSearchResult}; +use isahc::{AsyncReadResponseExt, HttpClient, Request, RequestExt}; +use isahc::auth::Authentication; +use isahc::config::RedirectPolicy; +use isahc::prelude::Configurable; +use log::{debug, error, warn}; +use scraper::{CaseSensitivity, Element, Html, Selector}; +use scraper::selector::CssLocalName; +use serde::Deserialize; +use crate::{NEXT_PROXY, PROXIES}; +use crate::proxy::Proxy; + +#[derive(Debug)] +pub enum GoogleQueryError { + CouldNotSendRequest, + CouldNotDeserialize, +} + +pub async fn proxy() -> Option { + if !PROXIES.is_empty() { + let mut next_proxy = NEXT_PROXY.fetch_add(1, Ordering::Relaxed); + if next_proxy >= PROXIES.len() { + next_proxy = 0; + NEXT_PROXY.store(1, Ordering::Relaxed); + } + //debug!("proxy {}", next_proxy); + let p = PROXIES[next_proxy].clone(); + return Some(p); + } + None +} + +pub async fn query_google(query: String) -> Result, GoogleQueryError> { + let query = url_encoded_data::stringify(&[("q", query.as_str())]); + + let proxy = proxy().await; + let mut client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)); + let mut proxy_name = "none".to_string(); + if let Some(proxy) = proxy { + client = client.proxy(Some(proxy.address.parse().expect("BAD PROXY ADDR"))); + proxy_name = proxy.address.clone(); + if let Some(proxy_auth) = proxy.credentials { + client = client.proxy_authentication(Authentication::basic()); + client = client.proxy_credentials(proxy_auth); + } + } + + let client = client + .build().expect("FAILED TO CONSTRUCT HTTP CLIENT"); + + let url = format!("https://www.google.com/search?{query}&lr=lang_en"); + + let res = Request::get(&url) + .header("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)-619") + .header("accept-language", "en-US,en;q=0.5") + .body(()).unwrap(); + let mut res = client.send_async(res).await.map_err(|e| { + error!("FAILED TO SEND REQUEST TO GOOGLE: {e} ({query}) (proxy: {proxy_name})"); + GoogleQueryError::CouldNotSendRequest + })?; + let body = res.text().await.map_err(|e| { + error!("COULD NOT READ GOOGLE RESPONSE TEXT: {e}"); + GoogleQueryError::CouldNotDeserialize + })?; + + let document = Html::parse_document(body.as_str()); + + // windows phone google layout + // div 0 - search bar + // div 1 - results + (potential) info panel + + let res_sel = Selector::parse("body>div>div>div>div>div").unwrap(); + + let link_sel = Selector::parse("a").unwrap(); + let title_sel = Selector::parse("a>span").unwrap(); + let desc_sel = Selector::parse("td>div>div>span").unwrap(); + let span_sel = Selector::parse("span").unwrap(); + + let link_results = document.select(&res_sel).collect::>(); + + let mut final_results = vec![]; + + for element in link_results { + let link = element.select(&link_sel).next(); + if link.is_none() { + warn!("link is none"); + continue; + } + let link = link.unwrap(); + let link = link.value().attr("href").unwrap(); + let link = link.trim_start_matches("/url"); + let link = url_encoded_data::from(link); + let link = link.get("q"); + if link.is_none() { + warn!("link is none"); + continue; + } + let link = link.unwrap(); + let url = link[0].to_string(); + let title = element.select(&title_sel).next(); + if title.is_none() { + warn!("title is none"); + continue; + } + let title = title.unwrap(); + let title = title.text().collect::(); + + let desc = element.select(&desc_sel).next(); + if desc.is_none() { + warn!("desc is none"); + continue; + } + let desc = desc.unwrap(); + let desc = desc.select(&span_sel).last(); + if desc.is_none() { + warn!("desc is none"); + continue; + } + let desc = desc.unwrap().text().collect::(); + + if title.is_empty() || desc.is_empty() { + warn!("title or desc is empty"); + continue; + } + let title = title.trim(); + let desc = desc.trim(); + final_results.push(BingSearchResult { + url, + title: Some(title.to_string()), + description: Some(desc.to_string()), + }) + } + + if final_results.is_empty() { + debug!("no results, body: {body}"); + } + + Ok(final_results) +} + +// first starts at 0 and goes up by multiples of 20 +pub async fn query_google_images(query: String, first: usize) -> Result, GoogleQueryError> { + let query = url_encoded_data::stringify(&[("q", query.as_str())]); + + let proxy = proxy().await; + let mut client = HttpClient::builder() + .redirect_policy(RedirectPolicy::Limit(10)); + let mut proxy_name = "none".to_string(); + if let Some(proxy) = proxy { + client = client.proxy(Some(proxy.address.parse().expect("BAD PROXY ADDR"))); + proxy_name = proxy.address.clone(); + if let Some(proxy_auth) = proxy.credentials { + client = client.proxy_authentication(Authentication::basic()); + client = client.proxy_credentials(proxy_auth); + } + } + + let client = client + .build().expect("FAILED TO CONSTRUCT HTTP CLIENT"); + + let url = format!("https://www.google.com/search?{query}&lr=lang_en&tbm=isch&start={first}"); + + let res = Request::get(&url) + .header("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)-619") + .header("accept-language", "en-US,en;q=0.5") + .body(()).unwrap(); + let mut res = client.send_async(res).await.map_err(|e| { + error!("FAILED TO SEND REQUEST TO GOOGLE: {e} ({query}) (proxy: {proxy_name})"); + GoogleQueryError::CouldNotSendRequest + })?; + let body = res.text().await.map_err(|e| { + error!("COULD NOT READ GOOGLE RESPONSE TEXT: {e}"); + GoogleQueryError::CouldNotDeserialize + })?; + + let document = Html::parse_document(body.as_str()); + + // windows phone google layout + // div 0 - search bar + // div 1 - results + (potential) info panel + + let res_sel = Selector::parse("div>div>a").unwrap(); + + let img_sel = Selector::parse("div>img").unwrap(); + + let link_results = document.select(&res_sel).collect::>(); + + let mut final_results = vec![]; + + for element in link_results { + let img = element.select(&img_sel).next(); + if img.is_none() { + continue; + } + let url = element.attr("href"); + if url.is_none() { + warn!("no href in image result"); + continue; + } + let url = url.unwrap(); + let link = url.trim_start_matches("/imgres"); + let link = url_encoded_data::from(link); + let link = link.get("imgurl"); + if link.is_none() { + warn!("link is none"); + continue; + } + let url = link.unwrap()[0].to_string(); + // fixme: this is a bad hack for removing facebook urls since they don't play nicely with non-google clients + if url.contains("lookaside.fbsbx.com") { + continue; + } + final_results.push(BingImageResult { + url, + }) + } + + if final_results.is_empty() { + debug!("no results, body: {body}"); + } + + Ok(final_results) +} diff --git a/googleservice/src/main.rs b/googleservice/src/main.rs new file mode 100644 index 0000000..0c1b20b --- /dev/null +++ b/googleservice/src/main.rs @@ -0,0 +1,125 @@ +/* + * googleservice main.rs + * - entrypoint for the asklyphe google backend + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +mod google; +mod process; +pub mod proxy; + +use std::io::Read; +use std::str::FromStr; +use std::sync::Arc; +use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use asklyphe_common::nats::authservice::AuthServiceResponse; +use asklyphe_common::nats::bingservice::BingServiceResponse; +use asklyphe_common::nats::comms; +use async_nats::jetstream; +use isahc::{Request, RequestExt}; +use log::{debug, error, info}; +use once_cell::sync::{Lazy, OnceCell}; +use crate::proxy::Proxy; + +pub static PROXIES: Lazy> = Lazy::new(|| { + if let Ok(proxy_file) = std::env::var("PROXY_FILE") { + let contents = std::fs::read_to_string(proxy_file); + let mut proxies = vec![]; + + for line in contents.expect("FAILED TO READ FILE").lines() { + proxies.push(Proxy::from_str(line).expect("INVALID PROXY")); + } + + info!("loaded {} proxies", proxies.len()); + + proxies + } else { + vec![] + } +}); + +pub static NEXT_PROXY: AtomicUsize = AtomicUsize::new(0); + +pub static NATS_URL: Lazy = Lazy::new(|| std::env::var("NATS_URL").expect("NO NATS DEFINED")); +pub static NATS_CERT: Lazy = Lazy::new(|| std::env::var("NATS_CERT").expect("NO NATS_CERT DEFINED")); +pub static NATS_KEY: Lazy = Lazy::new(|| std::env::var("NATS_KEY").expect("NO NATS_KEY DEFINED")); +pub static DB_URL: Lazy = Lazy::new(|| std::env::var("DB_URL").expect("NO DB_URL DEFINED")); +pub static PROCESSES_HANDLED: AtomicU64 = AtomicU64::new(0); +pub static LAST_MESSAGE: AtomicI64 = AtomicI64::new(0); + +//#[tokio::main] +//async fn main() { +// env_logger::init(); +// let mut args: Vec = std::env::args().collect(); +// // remove first argument (path) +// args.remove(0); +// let query = args.join(" "); +// +// let res = query_bing(query).await; +// if let Err(e) = res { +// match e { +// BingQueryError::CouldNotSendRequest => { +// error!("EXITING DUE TO FAILED BING QUERY: COULDN'T SEND REQUEST"); +// } +// BingQueryError::CouldNotDeserialize => { +// error!("EXITING DUE TO FAILED BING QUERY: COULDN'T FIND BING QUERY"); +// } +// } +// return; +// } +// if let Ok(res) = res { +// for res in res { +// println!("# {} ({})", res.title.unwrap_or_default(), res.url); +// println!(" {}", res.description.unwrap_or_default()); +// } +// } +//} + +#[tokio::main] +async fn main() { + env_logger::init(); + info!("googleservice began at {}", chrono::Utc::now().to_string()); + + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(NATS_CERT.as_str().into(), NATS_KEY.as_str().into()) + .connect(NATS_URL.as_str()) + .await; + if let Err(e) = nats { + error!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + + async fn on_recv(query: comms::Query) -> comms::ServiceResponse { + debug!("recv"); + let now = chrono::Utc::now().timestamp(); + LAST_MESSAGE.store(now, Ordering::Relaxed); + + let response = match query { + comms::Query::GoogleService(query) => { + process::process(query).await + } + _ => { + BingServiceResponse::InvalidRequest + } + }; + + if PROCESSES_HANDLED.load(Ordering::Relaxed) % 100 == 0 { + info!("handled {} requests!", PROCESSES_HANDLED.load(Ordering::Relaxed)); + } + PROCESSES_HANDLED.fetch_add(1, Ordering::Relaxed); + comms::ServiceResponse::BingService(response) + } + + if let Err(e) = comms::subscribe_service(comms::Service::GoogleService, &nats, Arc::new(on_recv)).await { + error!("failed to subscribe to bingservice nats! reason {:?}", e); + } +} diff --git a/googleservice/src/process/mod.rs b/googleservice/src/process/mod.rs new file mode 100644 index 0000000..6e31070 --- /dev/null +++ b/googleservice/src/process/mod.rs @@ -0,0 +1,77 @@ +/* + * googleservice process/mod.rs + * - route incoming nats requests to their specific functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use asklyphe_common::nats::bingservice::{BingServiceQuery, BingServiceRequest, BingServiceResponse, SearchResponse}; +use crate::google; +use crate::google::GoogleQueryError; + +pub async fn process(query: BingServiceQuery) -> BingServiceResponse { + // a future is used so that the whole program doesn't die if an algorithm panics + let response = tokio::spawn(async move { + match query.request { + BingServiceRequest::SearchRequest(q) => { + let res = google::query_google(q.query).await; + if let Err(e) = res { + match e { + GoogleQueryError::CouldNotSendRequest => { + BingServiceResponse::OtherError("google failed".to_string()) + } + GoogleQueryError::CouldNotDeserialize => { + BingServiceResponse::OtherError("google failed".to_string()) + } + } + } else { + BingServiceResponse::SearchResponse(SearchResponse { + results: res.unwrap(), + blocked: vec![], + }) + } + } + BingServiceRequest::ImageRequest(q) => { + const IMAGE_PAGES: usize = 1; + let mut all_results = vec![]; + let mut error = None; + for page in 0..IMAGE_PAGES { + let res = google::query_google_images(q.query.clone(), page * 20).await; + if let Err(e) = res { + error = Some(match e { + GoogleQueryError::CouldNotSendRequest => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + GoogleQueryError::CouldNotDeserialize => { + BingServiceResponse::OtherError("bing failed".to_string()) + } + }); + break; + } else { + all_results.extend(res.unwrap()); + } + } + if !all_results.is_empty() { + BingServiceResponse::ImageResponse(all_results) + } else { + error.unwrap_or(BingServiceResponse::OtherError( + "bing failed".to_string())) + } + } + }}).await; + + if let Ok(response) = response { + response + } else if let Err(e) = response { + BingServiceResponse::OtherError(e.to_string()) + } else { + unreachable!() + } +} \ No newline at end of file diff --git a/googleservice/src/proxy.rs b/googleservice/src/proxy.rs new file mode 100644 index 0000000..3532d81 --- /dev/null +++ b/googleservice/src/proxy.rs @@ -0,0 +1,46 @@ +/* + * googleservice proxy.rs + * - helper structs for proxies + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::str::FromStr; +use isahc::auth::Credentials; + +#[derive(Clone)] +pub struct Proxy { + pub address: String, + pub credentials: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProxyError { + InvalidProxyFormat, +} + +impl FromStr for Proxy { + type Err = ProxyError; + + fn from_str(s: &str) -> Result { + let mut parts = s.split(':'); + let host = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + let port = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + let auth = if let Some(user) = parts.next() { + let pass = parts.next().ok_or(ProxyError::InvalidProxyFormat)?; + Some(Credentials::new(user, pass)) + } else { + None + }; + Ok(Proxy { + address: format!("{}:{}", host, port), + credentials: auth, + }) + } +} \ No newline at end of file diff --git a/lyphe_setup_tutorial.txt b/lyphe_setup_tutorial.txt new file mode 100644 index 0000000..5689e89 --- /dev/null +++ b/lyphe_setup_tutorial.txt @@ -0,0 +1,108 @@ +HOW TO HOST UR OWN LYPHE INSTANCE!! :D +niko vcs - real microsoft llc founder + +asklyphe is structured in a way that should hopefully promote easy scaling +in the future, i.e. we can easily add more machines or better hardware to +our pre-existing machines and lyphe just becomes faster without any changes +to code. + +because of this, we're using a stateless microservice architecture. that means +that core functionality is split into "services" which all do one kind of +task. + +authservice handles authentication (and also anything that touches the postgres +database, might be changed in the future) + +searchservice handles requests for searches, then compiles the results from the +search database and returns them. + +etc. + +the "stateless" part means that ideally, any service can be restarted and act +the exact same as if it were running continuously. +we don't store state in memory, and everything goes in databases. + +all of this is to say that there's a reason that the architecture may at first +look a little complicated. + +== MINIMUM VIABLE SETUP == +this setup will get you an asklyphe setup that you can log into. you won't be +able to search for anything, but the website will generally start up and show +stuff. + +you'll need: +- rust compiler +- nats-server binary (https://nats.io/) +- postgres server +- caddy (https://caddyserver.com/) + (alternatively, some other webserver with reverse-proxy + static file hosting + and willingness to convert our caddyfiles) + +and the asklyphe services: +- authservice + (https://forge.voremicrocomputers.com/asklyphe-public/authservice) +- asklyphe-frontend + (https://forge.voremicrocomputers.com/asklyphe-public/asklyphe-frontend) +- asklyphe-auth-frontend + (https://forge.voremicrocomputers.com/asklyphe-public/asklyphe-auth-frontend) + +first, compile all the asklyphe services. should be as simple as running +`cargo build --release` (or without the --release flag if you want to debug) + +secondly, you'll want to start up your postgres server and run the migrations +go to authservice/migration and run `cargo run -- up -u ` +e.g. `cargo run -- up -u postgres://postgres:postgres@127.0.0.1/postgres` + +thirdly, you'll want to start the nats server. just go to the directory +where you put nats-server and run `./nats-server -js` + +finally, you can run each of the asklyphe service binaries you built. +they'll all need to have the following environment variables set: + +RUST_LOG= (something like info or debug is good, this is optional) +NATS_URL="127.0.0.1:4222" (or whereever your nats server is) +NATS_KEY= (used for nats tls, see below) +NATS_CERT= (used for nats tls, see below) + +KEY AND CERT ARE REQUIRED!!! however, you can use a dummy key and cert if you +don't feel like setting up tls on nats. + +certain services need extra environment variables: + +-- authservice -- +DB_URL= +SMTP_DISABLE=1 (or, see below) +SMTP_URL= (server must support starttls) +SMTP_USERNAME= +SMTP_PASSWORD= + +-- asklyphe-auth-frontend -- +ASKLYPHE_URL="http://127.0.0.1:8002" (alternatively, whatever url your instance + is on) + +-- asklyphe-frontend -- +AUTH_URL="http://127.0.0.1:8001" (alternatively, whatever url your + auth-frontend is on) + +finally, you can run caddy with the caddyfile provided in the +asklyphe-auth-frontend git tree, and run all the services + +you *hopefully* *should* be able to connect to https://127.0.0.1:8002 and see +the asklyphe homepage! insert an invite code into the database and you can +create an account! + +== ADDING SOME SEARCH SERVICES == + +bingservice and googleservice should be fine by just compiling and running +without anything other than the NATS_* environment variables, however +running searchservice will take a bit more work + +searchservice requires a foundationdb instance be running, specifically version +7.1.3 (will be changed in the future once we move to our own database system) + +once you follow the setup instructions at https://www.foundationdb.org/ you +should be good to go (foundationdb uses a file in /etc to authenticate, +no envvars needed) + +that should be all that's needed! there's probably stuff i'm forgetting so i'll +update this file as needed diff --git a/searchservice/.gitignore b/searchservice/.gitignore new file mode 100644 index 0000000..3a8cabc --- /dev/null +++ b/searchservice/.gitignore @@ -0,0 +1,2 @@ +/target +.idea diff --git a/searchservice/Cargo.toml b/searchservice/Cargo.toml new file mode 100644 index 0000000..6167503 --- /dev/null +++ b/searchservice/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "searchservice" +version = "0.1.0" +edition = "2021" +license = "AGPL-3" +license-file = "LICENSE" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +asklyphe-common = { path = "../asklyphe-common" } +tokio = { version = "1.0", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +rmp-serde = "1.1.2" +async-nats = "0.38.0" +chrono = "0.4.26" +once_cell = "1.18.0" +ulid = "1.0.0" +rand = "0.8.5" +async-recursion = "1.0.5" +futures = "0.3.30" +log = "0.4.20" +env_logger = "0.10.2" \ No newline at end of file diff --git a/searchservice/src/algorithm.rs b/searchservice/src/algorithm.rs new file mode 100644 index 0000000..54c0b6a --- /dev/null +++ b/searchservice/src/algorithm.rs @@ -0,0 +1,1213 @@ +/* + * searchservice algorithm.rs + * - how search works + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::ops::Mul; +use async_recursion::async_recursion; +use once_cell::sync::Lazy; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use log::{debug, info}; +use rand::Rng; +use asklyphe_common::db; +use asklyphe_common::db::{STRHASH}; +use asklyphe_common::foundationdb::Database; +use asklyphe_common::nats::searchservice; + +pub struct SearchResult { + pub url: String, + pub title: Option, + pub description: Option, + pub url_contains_result: Option, + pub word_occurs: f64, + pub authorword_occurs: f64, + pub descriptionword_occurs: f64, + pub keyword_occurs: f64, + pub sitename_occurs: f64, + pub linkword_occurs: f64, + pub pagerank: f64, + pub relavence: f64, + pub words_contained: BTreeSet, + pub total_query_words: f64, + pub words: BTreeMap, + pub closest_match: f64, + pub phrase_match_count: f64, + pub match_acc: f64, + pub match_c: f64, + pub highest_match: f64, +} + +impl SearchResult { + pub fn relavence(&self, no_separator_flag: bool) -> f64 { + if !no_separator_flag { + ((self.word_occurs * 1.3) + (self.descriptionword_occurs * 1.2) + (self.keyword_occurs * 0.5) + (self.authorword_occurs * 1.2) + (self.sitename_occurs * 1.3) + (self.linkword_occurs * 2.9) + (self.pagerank.powi(4)).max(0.001)) + .max(0.01) + * + if self.total_query_words > 1.0 { + ((1.0001 - if self.match_c > 0.0 { (self.match_acc / self.match_c) / self.highest_match.max(0.01) } else { 0.1 }) + + if !self.words_contained.is_empty() { (self.total_query_words / self.words_contained.len() as f64).max(0.002) } else { 1.0 }).max(0.001) + * self.phrase_match_count.max(0.02).powi(5) + } else { + 1.0 + } + } else { + if self.total_query_words > 1.0 { + (1.0001 - if self.match_c > 0.0 { (self.match_acc / self.match_c) / self.highest_match.max(0.01) } else { 0.1 }) + * self.phrase_match_count.max(0.02).powi(8) + } else { + 1.0 + } + } + } +} + +pub static PRECALCED_PAGERANKS: Lazy>> = Lazy::new(|| Mutex::new(BTreeMap::new())); +pub static CACHED_PAGERANKS: Lazy>> = Lazy::new(|| Mutex::new(BTreeMap::new())); +pub static VISITED_PAGERANKS: Lazy>> = Lazy::new(|| Mutex::new(BTreeSet::new())); +pub static VISITED_PAGERANKS2: Lazy>> = Lazy::new(|| Mutex::new(BTreeSet::new())); +pub static HASH_CACHE: Lazy> = Lazy::new(|| HashCache::new(Arc::new(Mutex::new(BTreeMap::new())))); +pub static UNHASH_CACHE: Lazy> = Lazy::new(|| HashCache::new(Arc::new(Mutex::new(BTreeMap::new())))); +pub static TITLE_CACHE: Lazy>> = Lazy::new(|| HashCache::new(Arc::new(Mutex::new(BTreeMap::new())))); +pub static DESC_CACHE: Lazy>> = Lazy::new(|| HashCache::new(Arc::new(Mutex::new(BTreeMap::new())))); + +pub struct HashCache { + inner: Arc>>, +} + +pub enum EntryBuilder { + Found(V), + NeedsInsert((K, Arc>>)), +} + +impl EntryBuilder { + pub async fn or_insert(self, value: impl futures::Future) -> V { + match self { + EntryBuilder::Found(v) => { v } + EntryBuilder::NeedsInsert((key, inner)) => { + let value = (value).await; + inner.lock().unwrap().insert(key, value.clone()); + value + } + } + } +} + +impl HashCache { + pub fn new(inner: Arc>>) -> Self { + Self { + inner, + } + } + + pub fn entry(&self, key: K) -> EntryBuilder { + if let Some(value) = self.inner.lock().unwrap().get(&key).cloned() { + EntryBuilder::Found(value) + } else { + EntryBuilder::NeedsInsert((key, self.inner.clone())) + } + } + + pub fn unconditional(&self, key: K) -> EntryBuilder { + EntryBuilder::NeedsInsert((key, self.inner.clone())) + } +} + +pub async fn cached_hash(db: &Database, key: String) -> STRHASH { + HASH_CACHE.entry(key.clone()).or_insert(db::foa_strhash(db, &key)).await +} + +pub async fn cached_unhash(db: &Database, key: STRHASH) -> String { + UNHASH_CACHE.entry(key).or_insert(db::unhash(db, key)).await +} + +pub async fn cached_title(db: &Database, key: STRHASH) -> Option { + if let Some(title) = TITLE_CACHE.entry(key).or_insert(db::info_title(db, key)).await { + Some(title) + } else { + TITLE_CACHE.unconditional(key).or_insert(db::info_title(db, key)).await + } +} + +pub async fn cached_desc(db: &Database, key: STRHASH) -> Option { + if let Some(desc) = DESC_CACHE.entry(key).or_insert(db::info_description(db, key)).await { + Some(desc) + } else { + DESC_CACHE.unconditional(key).or_insert(db::info_description(db, key)).await + } +} + +#[async_recursion] +pub async fn pagerank(db: &Database, url: STRHASH) -> f64 { + if let Some(precalc) = PRECALCED_PAGERANKS.lock().unwrap().get(&url) { + return *precalc; + } + if let Some(precalc_db) = db::page_pagerank(db, url).await { + //debug!("url {} in db {}", url, precalc_db); + if precalc_db == 0.0 { + //debug!("but 0 ):"); + } else { + CACHED_PAGERANKS.lock().unwrap().insert(url, precalc_db); + return precalc_db; + } + } + let mut accum = 0.0; + let incoming = { + db::page_links_entering(db, url).await + }; + let d = { + db::page_damping(db, url).await.unwrap_or(0.85) + }; + let d = (1.0 - d).max(0.0); + for url in incoming { + if PRECALCED_PAGERANKS.lock().unwrap().get(&url).is_none() && VISITED_PAGERANKS2.lock().unwrap().contains(&url) { + continue; + } + let c = { + db::page_links_exiting_count(db, url).await + }; + if c == 0 { continue; } + if let Some(precalc) = PRECALCED_PAGERANKS.lock().unwrap().get(&url) { + if *precalc != 0.0 { + accum += *precalc / c as f64; + continue; + } + } + VISITED_PAGERANKS2.lock().unwrap().insert(url); + let pr = pagerank(db, url).await; + accum += pr / c as f64; + } + + let pr = (1.0 - d) + (d * accum); + db::document_set_pagerank(db, url, pr, chrono::Utc::now().timestamp()).await; + PRECALCED_PAGERANKS.lock().unwrap().insert(url, pr); + CACHED_PAGERANKS.lock().unwrap().insert(url, pr); + pr +} + +pub const MAX_PAGERANK_APPROX_DEPTH: u64 = 1; + +#[async_recursion] +pub async fn pagerank_approx(db: &Database, url: STRHASH, depth: u64) -> f64 { + if depth > MAX_PAGERANK_APPROX_DEPTH { + return 0.8; + } + if let Some(precalc) = PRECALCED_PAGERANKS.lock().unwrap().get(&url) { + return *precalc; + } else if let Some(precalc) = CACHED_PAGERANKS.lock().unwrap().get(&url) { + return *precalc; + } + + let mut not_in_db = false; + let mut in_db_but_zero = false; + + if let Some(precalc_db) = db::page_pagerank(db, url).await { + //debug!("url {} in db {}", url, precalc_db); + if precalc_db == 0.0 { + //debug!("but 0 ):"); + + // uncomment when we want to eventually try to recalc 0.0 prs + //not_in_db = true; + //in_db_but_zero = true; + if depth == 0 { + tokio::spawn(async move { + info!("task spawned to calc real pagerank..."); + let db = Database::default().expect("couldn't connect to foundation db!"); + let pr = pagerank(&db, url).await; + info!("finished calculating {} real pagerank: {}", url, pr); + }); + } + }// else { + CACHED_PAGERANKS.lock().unwrap().insert(url, precalc_db); + return precalc_db; + //} + } else { + not_in_db = true; + } + + // spawn task to eventually calculate real pagerank + if depth == 0 && not_in_db { + tokio::spawn(async move { + //info!("task spawned to calc real pagerank..."); + let db = Database::default().expect("couldn't connect to foundation db!"); + pagerank(&db, url).await; + //info!("finished calculating {} real pagerank: {}", url, pr); + }); + } + + if in_db_but_zero { + CACHED_PAGERANKS.lock().unwrap().insert(url, 0.0); + return 0.0; + } + + let mut accum = 0.0; + let incoming = { + db::page_links_entering(db, url).await + }; + let d = { + db::page_damping(db, url).await.unwrap_or(0.85) + }; + let d = (1.0 - d).max(0.0); + for url in incoming { + if PRECALCED_PAGERANKS.lock().unwrap().get(&url).is_none() && CACHED_PAGERANKS.lock().unwrap().get(&url).is_none() && VISITED_PAGERANKS.lock().unwrap().contains(&url) { + continue; + } + let c = { + db::page_links_exiting_count(db, url).await + }; + if c == 0 { continue; } + if let Some(precalc) = PRECALCED_PAGERANKS.lock().unwrap().get(&url) { + accum += *precalc / c as f64; + continue; + } + if let Some(precalc) = CACHED_PAGERANKS.lock().unwrap().get(&url) { + accum += *precalc / c as f64; + continue; + } + VISITED_PAGERANKS.lock().unwrap().insert(url); + let pr = pagerank_approx(db, url, depth + 1).await; + CACHED_PAGERANKS.lock().unwrap().insert(url, pr); + accum += pr / c as f64; + } + + let pr = (1.0 - d) + (d * accum); + CACHED_PAGERANKS.lock().unwrap().insert(url, pr); + pr +} + +fn multiword_penalty(dist_a: f64, dist_b: f64) -> f64 { + if (dist_b - dist_a).is_sign_negative() { + // second comes before first, not good! + (dist_b - dist_a) + } else { + 1.0 - (dist_b - dist_a) + } +} + +pub async fn search(db: &Database, args: Vec, no_separator_flag: bool) -> Option { + let mut results: BTreeMap = BTreeMap::new(); + let start_t = chrono::Utc::now(); + + if args.is_empty() { + return None; + } + + let args_count = args.len(); + + let arg_words = args.clone(); + + //let word = format!("_{}_", word); + + let first_query = args.first().cloned(); + + let mut hash = vec![]; + for (i, word) in args.into_iter().enumerate() { + hash.push((i, cached_hash(db, word.clone()).await)); + //hash.push((i, cached_hash(db, format!("{}.", word)).await)); + //hash.push((i, cached_hash(db, format!(".{}", word)).await)); + //hash.push((i, cached_hash(db, format!(".{}.", word)).await)); + //hash.push((i, cached_hash(db, format!("{}s", word)).await)); + } + + //let hash: Vec<(usize, STRHASH)> = hash.into_iter().filter_map(|v| v.1.map(|b| (v.0, b))).collect(); + + if hash.is_empty() { + println!("none in database"); + return None; + } + + let first_query = first_query.unwrap(); + + let SECONDARY_WORDS = [ + db::hash("how"), + db::hash("is"), + db::hash("are"), + db::hash("the"), + db::hash("a"), + db::hash("when"), + db::hash("what"), + db::hash("why"), + db::hash("to"), + db::hash("where"), + db::hash("from"), + db::hash("best"), + db::hash("for"), + db::hash("like"), + ]; + + let mut secondary_indices = BTreeSet::new(); + + let mut word_occurs = BTreeMap::new(); + for hash in &hash { + if SECONDARY_WORDS.contains(&hash.1) { + secondary_indices.insert(hash.0); + } + word_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + db::word_occurs(db, hash.1).await); + } + //let mut authorword_occurs = BTreeMap::new(); + let mut descriptionword_occurs = BTreeMap::new(); + let mut keyword_occurs = BTreeMap::new(); + //let mut sitenameword_occurs = BTreeMap::new(); + for hash in &hash { + //authorword_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + // db::metaword_occurs(db, db::hash("author"), hash.1).await); + descriptionword_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + db::metaword_occurs(db, db::hash("description"), hash.1).await); + keyword_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + db::metaword_occurs(db, db::hash("keywords"), hash.1).await); + //sitenameword_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + // db::metaword_occurs(db, db::hash("site_name"), hash.1).await); + } + let mut linkword_occurs = BTreeMap::new(); + for hash in &hash { + linkword_occurs.entry(hash.0).or_insert(VecDeque::new()).extend( + db::linkword_occurs(db, hash.1).await); + } + + let mut urls = vec![]; + + for (_, vals) in &word_occurs { + for (url, _) in vals { + urls.push(*url); + } + } + for (_, vals) in &linkword_occurs { + for (url, _) in vals { + urls.push(*url); + } + } + for (_, vals) in &descriptionword_occurs { + for (url, _) in vals { + urls.push(*url); + } + } + for (_, vals) in &keyword_occurs { + for (url, _) in vals { + urls.push(*url); + } + } + + let mut useless_urls = vec![]; + + // we want to remove urls that aren't contained in every word index (i.e. urls that don't contain every word of the search query) + // however, we don't want to remove the url if it's not contained in a secondary index (i.e. if someone searches "best x", + // we don't want to remove results that don't contain the word "best") + // we also don't want to remove results if the page doesn't have that word, but the linkwords / metawords does + for url in &urls { + // for every word index... + for (index, vals) in &word_occurs { + // don't worry about secondary indices + if secondary_indices.contains(index) { + continue; + } + // collect urls + let urls: Vec = vals.iter().map(|(url, _)| *url).collect(); + // is this url not in the words bucket for this index? + if !urls.contains(url) { + // does another bucket contain it for this index? + let mut found_elsewhere = 0; + if linkword_occurs.get(index).unwrap().iter() + .map(|(url, _)| *url).collect::>().contains(url) { + found_elsewhere += 1; + } + if descriptionword_occurs.get(index).unwrap().iter() + .map(|(url, _)| *url).collect::>().contains(url) { + found_elsewhere += 1; + } + if keyword_occurs.get(index).unwrap().iter() + .map(|(url, _)| *url).collect::>().contains(url) { + found_elsewhere += 1; + } + + if found_elsewhere < 2 { + // not found anywhere else, thus this url doesn't match every meaningful word in the query + useless_urls.push(*url); + } + } + } + } + + //for (_, vals) in &authorword_occurs { + // for (url, _) in vals { + // urls.push(*url); + // } + //} + //for (_, vals) in &sitenameword_occurs { + // for (url, _) in vals { + // urls.push(*url); + // } + //} + //for url in &urls { + // for (_, vals) in &linkword_occurs { + // let urls: Vec = vals.iter().map(|(u, _)| *u).collect(); + // if !urls.contains(url) { + // useless_urls.push(*url); + // } + // } + //} + + urls.sort(); + urls.dedup(); + urls.retain(|u| !useless_urls.contains(u)); + + for vals in word_occurs.values_mut() { + vals.retain(|(u, _)| !useless_urls.contains(u)); + } + for vals in linkword_occurs.values_mut() { + vals.retain(|(u, _)| !useless_urls.contains(u)); + } + for vals in descriptionword_occurs.values_mut() { + vals.retain(|(u, _)| !useless_urls.contains(u)); + } + for vals in keyword_occurs.values_mut() { + vals.retain(|(u, _)| !useless_urls.contains(u)); + } + + let start = chrono::Utc::now(); + + let mut word_count = Arc::new(Mutex::new(BTreeMap::new())); + + let mut allowed = Arc::new(AtomicUsize::new(0)); + let mut pr_acc = 0.0; + + const ALLOWED_BEFORE_PRUNE: usize = 512; + const ALLOWED_BEFORE_MEGAPRUNE: usize = 777; + const ALLOWED_BEFORE_GIGAPRUNE: usize = 2048; + //const ICKY_WORDS: &[&str] = &[ + // "distrowatch.com", // distrowatch is taking up too many results at the moment, remove this later + // "mariowiki.com", // mariowiki is taking up too many results at the moment, remove this later + // "wired.com", // we have too many wired articles + // "wired.cz", // we are very targeted at an english audience, they probably don't want czech wired articles at the moment + // "neocities.org/browse?", // people probably don't want to visit neocities tag lists + // "https://distrowatch.com/?language=", // people probably aren't looking for the distrowatch homepage in a random language + // "https://distrowatch.com/weekly.php/weekly.php?issue=", // a lot of results are unrelated distrowatch weekly posts + // "terms", // people probably aren't looking for tos pages + // "statement", // people probably aren't looking for tos pages + // "3cx", // nonenglish voip company, takes up unrelated search queries + // "1377x", // phishing site pretending to be 1337x, temporary fix until we can implement something like site blocking + // "//kickasstorrents.", // kickasstorrents has been down for years, only remaining sites are likely phishing scams + // "//kickasstorrent.", // kickasstorrents has been down for years, only remaining sites are likely phishing scams + // "//katcr.to", // fake kickasstorrents site + // "//kat.am", // fake kickasstorrents site + // "//kikass.to", // fake kickasstorrents site + // "//thepiratebays.com", // fake thepiratebay site + // ".fandom.com", // fuck fandom.com (todo: remove this since ultimately, it should be the user's choice to block fandom) + //]; + + // todo: since our list is so small this is okay for now, but we should cache this in the future + let deranks = Arc::new(db::get_deranked_websites(db).await); + + let mut initial_pruned = Arc::new(Mutex::new(vec![])); + // url, reason + let mut blocked: Arc>> = Arc::new(Mutex::new(vec![])); + + debug!("checking {} urls", urls.len()); + + let mut url_tasks = vec![]; + for (i, url) in urls.into_iter().enumerate() { + let allowed = allowed.clone(); + let blocked = blocked.clone(); + let initial_pruned = initial_pruned.clone(); + let word_count = word_count.clone(); + let arg_words = arg_words.clone(); + let deranks = deranks.clone(); + url_tasks.push(tokio::spawn(async move { + if i > ALLOWED_BEFORE_GIGAPRUNE { + initial_pruned.lock().unwrap().push(url); + return; + } + let db = Database::default().expect("FAILED TO CREATE NEW FDB HANDLE"); + let surl = { + cached_unhash(&db, url).await + }.to_lowercase(); + let mut contains_query_word = false; + for w in &arg_words { + if surl.contains(w) { + contains_query_word = true; + break; + } + } + let mut prepruned = false; + for (_, derank) in deranks.iter() { + if surl.contains(&derank.urlmatch) || surl.contains(&derank.urlmatch.replace("//", ".")) { + if let Some(and) = &derank.and { + if !surl.contains(and) { + continue; + } + } + if let Some(unless) = &derank.unless { + if surl.contains(unless) { + continue; + } + } + if !contains_query_word && + (i > ALLOWED_BEFORE_MEGAPRUNE || (i > ALLOWED_BEFORE_PRUNE && derank.amount < 0.85)) && + !contains_query_word { + initial_pruned.lock().unwrap().push(url); + prepruned = true; + } + if derank.amount == 0.0 { + initial_pruned.lock().unwrap().push(url); + blocked.lock().unwrap().push((surl.clone(), derank.comment.clone())); + prepruned = true; + } + } + } + if prepruned { + return; + } + let pr = pagerank_approx(&db, url, 0).await; + if i > ALLOWED_BEFORE_PRUNE { + let mut contains_query_word = false; + for w in &arg_words { + if surl.contains(w) { + contains_query_word = true; + break; + } + } + if contains_query_word || (pr > (((pr_acc / i as f64).max(0.01)) * if i > ALLOWED_BEFORE_MEGAPRUNE { 4.0 } else { 1.0 }) || (i < ALLOWED_BEFORE_MEGAPRUNE)) { + let wc = db::page_word_count(&db, url).await; + word_count.lock().unwrap().insert(url, wc); + pr_acc += pr; + allowed.fetch_add(1, Ordering::Relaxed); + } else { + initial_pruned.lock().unwrap().push(url); + } + } else { + let wc = db::page_word_count(&db, url).await; + word_count.lock().unwrap().insert(url, wc); + pr_acc += pr; + allowed.fetch_add(1, Ordering::Relaxed); + } + //let url = { + //}; + //debug!("{} pr: {}", url, pr); + //debug!("{} wc: {}", url, wc); + + // precache values + cached_unhash(&db, url).await; + cached_title(&db, url).await; + cached_desc(&db, url).await; + })); + } + + for url_task in url_tasks { + url_task.await.expect("url task failure"); + } + + let initial_pruned = initial_pruned.lock().unwrap().clone(); + let word_count = word_count.lock().unwrap().clone(); + + debug!("pruned {} results ({pr_acc}, {})", initial_pruned.len(), allowed.load(Ordering::Relaxed)); + + for vals in word_occurs.values_mut() { + vals.retain(|(u, _)| !initial_pruned.contains(u)); + } + for vals in linkword_occurs.values_mut() { + vals.retain(|(u, _)| !initial_pruned.contains(u)); + } + for vals in descriptionword_occurs.values_mut() { + vals.retain(|(u, _)| !initial_pruned.contains(u)); + } + for vals in keyword_occurs.values_mut() { + vals.retain(|(u, _)| !initial_pruned.contains(u)); + } + + let pagerank_secs = chrono::Utc::now().signed_duration_since(start).num_milliseconds() as f64 / 1000.0; + + info!("pageranks in {} secs", pagerank_secs); + + //word_occurs.sort_by(|a, b| { + // let av = *PRECALCED_PAGERANKS.lock().unwrap().get(&b.1.0).unwrap(); + // av.total_cmp(PRECALCED_PAGERANKS.lock().unwrap().get(&a.1.0).unwrap()) + //}); + //metaword_occurs.sort_by(|a, b| { + // let av = *PRECALCED_PAGERANKS.lock().unwrap().get(&b.1.0).unwrap(); + // av.total_cmp(PRECALCED_PAGERANKS.lock().unwrap().get(&a.1.0).unwrap()) + //}); + //linkword_occurs.sort_by(|a, b| { + // let av = *PRECALCED_PAGERANKS.lock().unwrap().get(&b.1.0).unwrap(); + // av.total_cmp(PRECALCED_PAGERANKS.lock().unwrap().get(&a.1.0).unwrap()) + //}); + + pub const MULTIWORD_PENALTY: f64 = 0.0001; + pub const PHRASE_PERCENTAGE: f64 = 0.7; + + for ((position, vals)) in word_occurs.iter() { + if let Some(vals2) = word_occurs.get(&(*position + 1)) { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distacc = 0.0; + let mut distc = 0; + let mut smallest = f64::MAX; + let mut largest = 0.0; + let mut phrase_matches = 0; + for i in 0..occurs { + let offset = (i * 2) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + for (url_b, occurs_b) in vals2 { + if url_a != url_b { + continue; + } + let occurs2 = u64::from_be_bytes(occurs_b.split_at(std::mem::size_of::()).0.try_into().unwrap()); + for j in 0..occurs2 { + let offset2 = (j * 2) + 8; + let dist2 = occurs_b[offset2 as usize] as f64 / 255.0; + distacc += (dist2 - dist); + if (dist2 - dist) >= 0.0 && (dist2 - dist) < smallest { + smallest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) > largest { + largest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) <= (2.1 / (*word_count.get(url_a).unwrap_or(&1) as f64).max(1.0)) { + phrase_matches += 1; + } + distc += 1; + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0) * multiword_penalty(dist, dist2); + } + } + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: acc, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: 0.0, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: f64::MAX, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.word_occurs = acc; + res.words_contained.insert(*position); + res.match_acc += distacc; + res.match_c += distc as f64; + if smallest < res.closest_match { + res.closest_match = smallest; + } + if largest < res.highest_match { + res.highest_match = largest; + } + res.phrase_match_count += phrase_matches as f64; + *res.words.entry(*position).or_insert(0) += 1; + } + } else { + for (urlv, occursv) in vals { + let url = { + cached_unhash(db, *urlv).await + }; + let occurs = u64::from_be_bytes(occursv.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distc = 0; + for i in 0..occurs { + let offset = (i * 2) + 8; + let dist = occursv[offset as usize] as f64 / 255.0; + //distc += 1; + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0); + } + let res = results.entry(*urlv).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *urlv).await, + description: cached_desc(db, *urlv).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: acc, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: 0.0, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: 0.0, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.word_occurs = acc; + res.words_contained.insert(*position); + *res.words.entry(*position).or_insert(0) += 1; + } + } + } + + for ((position, vals)) in linkword_occurs.iter() { + if let Some(vals2) = linkword_occurs.get(&(*position + 1)) { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distacc = 0.0; + let mut distc = 0; + let mut smallest = f64::MAX; + let mut largest = 0.0; + let mut phrase_matches = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + for (url_b, occurs_b) in vals2 { + if url_a != url_b { + distc -= 4; + continue; + } + let occurs2 = u64::from_be_bytes(occurs_b.split_at(std::mem::size_of::()).0.try_into().unwrap()); + for j in 0..occurs2 { + let offset2 = (j) + 8; + let dist2 = occurs_b[offset2 as usize] as f64 / 255.0; + distacc += (dist2 - dist) * 12.0; + distc += 1; + if (dist2 - dist) < smallest { + smallest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) > largest { + largest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) <= (2.1 / (*word_count.get(url_a).unwrap_or(&1) as f64).max(20.0)) { + phrase_matches += 1; + } + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0) * multiword_penalty(dist, dist2); + } + } + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: f64::MAX, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.linkword_occurs = acc; + res.match_acc += distacc; + res.match_c += distc as f64; + if smallest < res.closest_match { + res.closest_match = smallest; + } + res.phrase_match_count += phrase_matches as f64; + *res.words.entry(*position).or_insert(0) += 1; + } + } else { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distc = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + //distc += 1; + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0); + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: 0.0, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.linkword_occurs = acc; + res.words_contained.insert(*position); + *res.words.entry(*position).or_insert(0) += 1; + } + } + } + + for ((position, vals)) in descriptionword_occurs.iter() { + if let Some(vals2) = descriptionword_occurs.get(&(*position + 1)) { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distacc = 0.0; + let mut distc = 0; + let mut smallest = f64::MAX; + let mut largest = 0.0; + let mut phrase_matches = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + for (url_b, occurs_b) in vals2 { + if url_a != url_b { + distc -= 4; + continue; + } + let occurs2 = u64::from_be_bytes(occurs_b.split_at(std::mem::size_of::()).0.try_into().unwrap()); + for j in 0..occurs2 { + let offset2 = (j) + 8; + let dist2 = occurs_b[offset2 as usize] as f64 / 255.0; + distacc += (dist2 - dist) * 12.0; + distc += 1; + if (dist2 - dist) < smallest { + smallest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) > largest { + largest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) <= (2.1 / (*word_count.get(url_a).unwrap_or(&1) as f64).max(20.0)) { + phrase_matches += 1; + } + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0) * multiword_penalty(dist, dist2); + } + } + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: f64::MAX, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.descriptionword_occurs = acc; + res.match_acc += distacc; + res.match_c += distc as f64; + if smallest < res.closest_match { + res.closest_match = smallest; + } + res.phrase_match_count += phrase_matches as f64; + *res.words.entry(*position).or_insert(0) += 1; + } + } else { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distc = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + //distc += 1; + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0); + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: 0.0, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.descriptionword_occurs = acc; + res.words_contained.insert(*position); + *res.words.entry(*position).or_insert(0) += 1; + } + } + } + + for ((position, vals)) in keyword_occurs.iter() { + if let Some(vals2) = keyword_occurs.get(&(*position + 1)) { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distacc = 0.0; + let mut distc = 0; + let mut smallest = f64::MAX; + let mut largest = 0.0; + let mut phrase_matches = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + for (url_b, occurs_b) in vals2 { + if url_a != url_b { + distc -= 4; + continue; + } + let occurs2 = u64::from_be_bytes(occurs_b.split_at(std::mem::size_of::()).0.try_into().unwrap()); + for j in 0..occurs2 { + let offset2 = (j) + 8; + let dist2 = occurs_b[offset2 as usize] as f64 / 255.0; + distacc += (dist2 - dist) * 12.0; + distc += 1; + if (dist2 - dist) < smallest { + smallest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) > largest { + largest = (dist2 - dist); + } + if (dist2 - dist) >= 0.0 && (dist2 - dist) <= (2.1 / (*word_count.get(url_a).unwrap_or(&1) as f64).max(20.0)) { + phrase_matches += 1; + } + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0) * multiword_penalty(dist, dist2); + } + } + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: f64::MAX, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.keyword_occurs = acc; + res.match_acc += distacc; + res.match_c += distc as f64; + if smallest < res.closest_match { + res.closest_match = smallest; + } + res.phrase_match_count += phrase_matches as f64; + *res.words.entry(*position).or_insert(0) += 1; + } + } else { + for (url_a, occurs_a) in vals { + let url = { + cached_unhash(db, *url_a).await + }; + let occurs = u64::from_be_bytes(occurs_a.split_at(std::mem::size_of::()).0.try_into().unwrap()); + let mut acc = 0.0; + let mut distc = 0; + for i in 0..occurs { + let offset = (i) + 8; + let dist = occurs_a[offset as usize] as f64 / 255.0; + //distc += 1; + acc += ((-(2.0 * dist + 1.0).log(1.2) / 30.0) + 1.0); + } + let res = results.entry(*url_a).or_insert(SearchResult { + url: url.clone(), + title: cached_title(db, *url_a).await, + description: cached_desc(db, *url_a).await, + url_contains_result: if url.contains(&first_query) { Some(url.len()) } else { None }, + word_occurs: 0.0, + authorword_occurs: 0.0, + descriptionword_occurs: 0.0, + keyword_occurs: 0.0, + sitename_occurs: 0.0, + linkword_occurs: acc, + pagerank: 0.0, + relavence: 0.0, + words_contained: BTreeSet::new(), + total_query_words: args_count as f64, + words: Default::default(), + closest_match: 0.0, + phrase_match_count: 0.0, + match_acc: 0.0, + match_c: 0.0, + highest_match: 0.0, + }); + res.keyword_occurs = acc; + res.words_contained.insert(*position); + *res.words.entry(*position).or_insert(0) += 1; + } + } + } + + let mut max_relavence = 0.0; + let mut longest_url = 1; + let mut max_words = 1; + + let mut phrase_found = false; + + // todo: move to database + + results.iter_mut().for_each(|v| { + v.1.pagerank = *PRECALCED_PAGERANKS.lock().unwrap().get(v.0).unwrap_or( + CACHED_PAGERANKS.lock().unwrap().get(v.0).unwrap() + ); + + //debug!("{},{}", v.1.phrase_match_count, args_count); + if v.1.phrase_match_count + 1.0 >= args_count as f64 { + phrase_found = true; + } + if v.1.url.len() > longest_url { + longest_url = v.1.url.len(); + } + let mut wc = 1; + for word in &arg_words { + if v.1.url.to_lowercase().contains(word) { + wc += 1; + } + } + if wc > max_words { + max_words = wc; + } + + v.1.relavence = v.1.relavence(no_separator_flag); + + //debug!("{} -> {}/{}", v.1.url, v.1.words_contained, v.1.total_query_words); + if v.1.relavence > max_relavence { + max_relavence = v.1.relavence; + } + }); + + results.iter_mut().for_each(|v| { + let url_multiplier = ((v.1.url.len() as f64 * 2.3) / (longest_url as f64)); + //debug!("url {} multiplier {}", v.1.url, url_multiplier); + let mut word_multiplier = 1; + for word in &arg_words { + if v.1.url.to_lowercase().contains(word) { + word_multiplier += 1; + } + } + let word_multiplier = (word_multiplier as f64 * 4.0) / max_words as f64; + + let mut icky_found = 1.0; + for (_, derank) in deranks.iter() { + if v.1.url.contains(&derank.urlmatch) { + if let Some(and) = &derank.and { + if !v.1.url.contains(and) { + continue; + } + } + if let Some(unless) = &derank.unless { + if v.1.url.contains(unless) { + continue; + } + } + icky_found *= derank.amount; + } + } + + v.1.relavence *= word_multiplier.powi(8).min((max_words as f64).powi(8)); + v.1.relavence /= url_multiplier.max(1.0).powi(4); + v.1.relavence *= icky_found; + }); + + //results.iter_mut().for_each(|v| v.relevance /= max_occurs as f64); + + let mut results: Vec = results.into_iter().map(|v| v.1).collect(); + + max_relavence = 0.0; + results.sort_by(|a, b| { + if a.relavence > max_relavence { + max_relavence = a.relavence; + } + if b.relavence > max_relavence { + max_relavence = a.relavence; + } + b.relavence.total_cmp(&a.relavence) + }); + + let mut results_final = vec![]; + for result in results { + results_final.push(searchservice::SearchResult { + url: result.url, + relevance: result.relavence, + title: result.title, + description: result.description, + }); + } + + let time = chrono::Utc::now().signed_duration_since(start_t).num_milliseconds() as f64 / 1000.0; + + let blocked = blocked.lock().unwrap(); + + Some(searchservice::SearchResponse { + results: results_final, + blocked: blocked.clone(), + pagerank_time_seconds: pagerank_secs, + total_query_seconds: time, + max_relevance: max_relavence, + exact_phrase_found: phrase_found, + }) +} \ No newline at end of file diff --git a/searchservice/src/hacks.rs b/searchservice/src/hacks.rs new file mode 100644 index 0000000..2134715 --- /dev/null +++ b/searchservice/src/hacks.rs @@ -0,0 +1,62 @@ +/* + * searchservice hacks.rs + * - awful awful solutions to our issues + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::ops::{ RangeInclusive}; + +const BURMESE_RANGE: RangeInclusive = '\u{1000}'..='\u{104f}'; +const CHINESE_RANGE1: RangeInclusive = '\u{4e00}'..='\u{9fff}'; +const CHINESE_RANGE2: RangeInclusive = '\u{3400}'..='\u{4dbf}'; +const CHINESE_RANGE3: RangeInclusive = '\u{20000}'..='\u{2a6df}'; +const CHINESE_RANGE4: RangeInclusive = '\u{2A700}'..='\u{2B73F}'; +const CHINESE_RANGE5: RangeInclusive = '\u{2B740}'..='\u{2B81F}'; +const CHINESE_RANGE6: RangeInclusive = '\u{2B820}'..='\u{2CEAF}'; +const CHINESE_RANGE7: RangeInclusive = '\u{2CEB0}'..='\u{2EBEF}'; +const CHINESE_RANGE8: RangeInclusive = '\u{30000}'..='\u{3134F}'; +const CHINESE_RANGE9: RangeInclusive = '\u{31350}'..='\u{323AF}'; +const CHINESE_RANGE10: RangeInclusive = '\u{2EBF0}'..='\u{2EE5F}'; +const CHINESE_RANGE11: RangeInclusive = '\u{F900}'..='\u{FAFF}'; +const JAPANESE_RANGE1: RangeInclusive = '\u{3040}'..='\u{309F}'; +/// KATAKANA +const JAPANESE_RANGE2: RangeInclusive = '\u{30A0}'..='\u{30FF}'; +const JAVANESE_RANGE: RangeInclusive = '\u{A980}'..='\u{A9DF}'; +const KHMER_RANGE1: RangeInclusive = '\u{1780}'..='\u{17FF}'; +const KHMER_RANGE2: RangeInclusive = '\u{19E0}'..='\u{19FF}'; +const LAO_RANGE: RangeInclusive = '\u{0E80}'..='\u{0EFF}'; +const PHAGSPA_RANGE: RangeInclusive = '\u{A840}'..='\u{A87F}'; +const TAITHAM_RANGE: RangeInclusive = '\u{1A20}'..='\u{1AAF}'; +const THAI_RANGE: RangeInclusive = '\u{0E00}'..='\u{E07F}'; +const TIBETAN_RANGE: RangeInclusive = '\u{0F00}'..='\u{0FFF}'; +const NO_WORD_BOUNDRIES: &[RangeInclusive] = &[ + BURMESE_RANGE, + CHINESE_RANGE1, CHINESE_RANGE2, CHINESE_RANGE3, CHINESE_RANGE4, CHINESE_RANGE5, CHINESE_RANGE6, CHINESE_RANGE7, CHINESE_RANGE8, CHINESE_RANGE9, CHINESE_RANGE10, CHINESE_RANGE11, + JAPANESE_RANGE1, JAPANESE_RANGE2, + JAVANESE_RANGE, + KHMER_RANGE1, KHMER_RANGE2, + LAO_RANGE, + PHAGSPA_RANGE, + TAITHAM_RANGE, + THAI_RANGE, + TIBETAN_RANGE, +]; + +pub fn is_from_language_that_doesnt_use_word_separators(str: &str) -> bool { + for c in str.chars() { + for range in NO_WORD_BOUNDRIES { + if range.contains(&c) { + return true; + } + } + } + + false +} \ No newline at end of file diff --git a/searchservice/src/main.rs b/searchservice/src/main.rs new file mode 100644 index 0000000..570f820 --- /dev/null +++ b/searchservice/src/main.rs @@ -0,0 +1,91 @@ +/* + * searchservice main.rs + * - entrypoint for the asklyphe search service + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +pub mod algorithm; +pub mod hacks; +mod process; + +use std::cmp::max; +use std::future::Future; +use std::io::Read; +use std::string::ToString; +use std::sync::Arc; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::time::Duration; +use async_nats::jetstream; +use async_nats::jetstream::consumer::PullConsumer; +use async_nats::jetstream::stream::RetentionPolicy; +use futures::StreamExt; +use log::{error, info, warn}; +use once_cell::sync::Lazy; +use tokio::sync::Mutex; +use tokio::task::JoinHandle; +use asklyphe_common::{db, foundationdb}; +use asklyphe_common::foundationdb::Database; +use asklyphe_common::nats::comms; +use asklyphe_common::nats::comms::{Service, ServiceResponse}; +use asklyphe_common::nats::searchservice::SearchSrvcResponse; + +pub static NATS_URL: Lazy = Lazy::new(|| std::env::var("NATS_URL").expect("NO NATS DEFINED")); +pub static NATS_CERT: Lazy = Lazy::new(|| std::env::var("NATS_CERT").expect("NO NATS_CERT DEFINED")); +pub static NATS_KEY: Lazy = Lazy::new(|| std::env::var("NATS_KEY").expect("NO NATS_KEY DEFINED")); + +pub static PROCESSES_HANDLED: AtomicU64 = AtomicU64::new(0); +pub static LAST_MESSAGE: AtomicI64 = AtomicI64::new(0); + +#[tokio::main] +async fn main() { + let _guard = unsafe { foundationdb::boot() }; + env_logger::init(); + info!("searchservice began at {}", chrono::Utc::now().to_string()); + let nats = async_nats::ConnectOptions::new() + .add_client_certificate(NATS_CERT.as_str().into(), NATS_KEY.as_str().into()) + .connect(NATS_URL.as_str()) + .await; + if let Err(e) = nats { + error!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e); + return; + } + let nats = nats.unwrap(); + let nats = jetstream::new(nats); + + info!("searchbot spawned"); + + async fn on_recv(query: comms::Query) -> ServiceResponse { + let db = Database::default().expect("couldn't connect to foundation db!"); + let now = chrono::Utc::now().timestamp(); + LAST_MESSAGE.store(now, Ordering::Relaxed); + + let response = match query { + comms::Query::SearchService(query) => { + process::process(query, db).await + } + _ => { + SearchSrvcResponse::InvalidRequest + } + }; + + if PROCESSES_HANDLED.load(Ordering::Relaxed) % 100 == 0 { + info!("handled {} requests!", PROCESSES_HANDLED.load(Ordering::Relaxed)); + } + PROCESSES_HANDLED.fetch_add(1, Ordering::Relaxed); + ServiceResponse::SearchService(response) + } + + if let Err(e) = comms::subscribe_service(Service::SearchService, &nats, Arc::new(on_recv)).await { + error!("failed to subscribe to searchservice nats! reason {:?}", e); + } + + // we will respawn tasks if they crash + drop(_guard); +} diff --git a/searchservice/src/process.rs b/searchservice/src/process.rs new file mode 100644 index 0000000..8a990f3 --- /dev/null +++ b/searchservice/src/process.rs @@ -0,0 +1,118 @@ +/* + * searchservice process.rs + * - route incoming nats requests to their specific functions + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use std::sync::Arc; +use async_nats::{jetstream, Subject}; +use log::{debug, error, warn}; +use tokio::sync::Mutex; +use futures::StreamExt; +use asklyphe_common::db::tables::{INFO_TABLE, WEBSITE_TABLE}; +use asklyphe_common::foundationdb::{Database, KeySelector, RangeOption}; +use asklyphe_common::foundationdb::options::{StreamingMode, TransactionOption}; +use asklyphe_common::foundationdb::tuple::{pack, Subspace}; +use asklyphe_common::nats::searchservice; +use asklyphe_common::nats::searchservice::{SearchSrvcQuery, SearchSrvcRequest, SearchSrvcResponse, SearchRequest, SiteCountResponse, SearchResponse}; +use crate::{algorithm, hacks}; + +pub async fn process(query: SearchSrvcQuery, db: Database) -> SearchSrvcResponse { + // a future is used so that the whole program doesn't die if an algorithm panics + let response = tokio::spawn(async move { + match query.request { + SearchSrvcRequest::SearchRequest(req) => { + search_request(req, &db).await + } + SearchSrvcRequest::SiteCountRequest => { + count_websites(&db).await + } + }}).await; + + if let Ok(response) = response { + response + } else if let Err(e) = response { + SearchSrvcResponse::OtherError(e.to_string()) + } else { + unreachable!() + } +} + +pub async fn search_request(req: SearchRequest, db: &Database) -> SearchSrvcResponse { + let words_initial: Vec = req.query.split_whitespace().map(|s| s.to_string()).collect(); + let mut words = vec![]; + let mut no_separator_flag = false; + for word in words_initial { + if hacks::is_from_language_that_doesnt_use_word_separators(&word) { + words.extend(word.chars().map(|c| c.to_string()).collect::>()); + no_separator_flag = true; + } else { + words.push(word); + } + } + + match algorithm::search(&db, words, no_separator_flag).await { + Some(results) => { + SearchSrvcResponse::SearchResponse(results) + } + None => { + SearchSrvcResponse::SearchResponse(SearchResponse { + results: vec![], + blocked: vec![], + pagerank_time_seconds: 0.0, + total_query_seconds: 0.0, + max_relevance: 0.0, + exact_phrase_found: false, + }) + } + } +} + +pub async fn count_websites(db: &Database) -> SearchSrvcResponse { + let mut counter: u64 = 0; + let subspace = Subspace::from(WEBSITE_TABLE); + let mut last_key = subspace.range().0; + let final_key = subspace.range().1; + + for _failsafe in 0..10000 { + let trx = db.create_trx(); + if let Err(e) = trx { + error!("DATABASE ERROR page_links_exiting_count {e}"); + } else { + let trx = trx.unwrap(); + // link -> from -> * + let mut range = RangeOption::from((last_key.clone(), final_key.clone())); + range.mode = StreamingMode::Iterator; + range.limit = Some(10096); + + let mut stream = trx.get_ranges_keyvalues(range, true); + + let mut this_time = 0; + + while let Some(kv) = stream.next().await { + if let Ok(kv) = kv { + counter += 1; + this_time += 1; + last_key = kv.key().to_vec(); + } else if let Err(e) = kv { + eprintln!("err while counting {e}"); + } + } + + if this_time <= 10 { + return SearchSrvcResponse::SiteCountResponse(SiteCountResponse { + count: counter / 8, + }); + } + } + + } + SearchSrvcResponse::OtherError("couldn't retrieve count ):".to_string()) +} \ No newline at end of file diff --git a/unit_converter/.gitignore b/unit_converter/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/unit_converter/.gitignore @@ -0,0 +1 @@ +/target diff --git a/unit_converter/Cargo.toml b/unit_converter/Cargo.toml new file mode 100644 index 0000000..ed6c2d1 --- /dev/null +++ b/unit_converter/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "unit_converter" +version = "0.1.0" +edition = "2021" +license = "AGPL-3" +license-file = "LICENSE" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +astro-float = "0.9.2" +once_cell = "1.19.0" \ No newline at end of file diff --git a/unit_converter/src/length_units.rs b/unit_converter/src/length_units.rs new file mode 100644 index 0000000..511dcf8 --- /dev/null +++ b/unit_converter/src/length_units.rs @@ -0,0 +1,848 @@ +/* + * unit_converter length_units.rs + * - definitions of length units + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use crate::unit_defs::{BestUnit, ConvertTo, FromUnitName, MetricPrefix, UnitName}; +use astro_float::{BigFloat, RoundingMode}; +use once_cell::sync::Lazy; +use std::collections::BTreeMap; + +pub const PRECISION: usize = 1024; + +// length unit -> value in meters +pub static LENGTH_STORE: Lazy> = Lazy::new(|| { + let mut store = BTreeMap::new(); + + store.insert( + LengthUnit::Meter(MetricPrefix::Pico), + BigFloat::from_f64(0.000000000001, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Nano), + BigFloat::from_f64(0.000000001, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Micro), + BigFloat::from_f64(0.000001, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Milli), + BigFloat::from_f64(0.001, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Centi), + BigFloat::from_f64(0.01, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Deci), + BigFloat::from_f64(0.1, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::None), + BigFloat::from_f64(1.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Deca), + BigFloat::from_f64(10.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Hecto), + BigFloat::from_f64(100.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Kilo), + BigFloat::from_f64(1000.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Mega), + BigFloat::from_f64(1_000_000.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Giga), + BigFloat::from_f64(1_000_000_000.0, PRECISION), + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Tera), + BigFloat::from_f64(1_000_000_000_000.0, PRECISION), + ); + // inch is 2.54 cm + store.insert( + LengthUnit::Inch, + store + .get(&LengthUnit::Meter(MetricPrefix::Centi)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(2.54, PRECISION)), + ); + // thou is 1/1000 inches + store.insert( + LengthUnit::Thou, + store + .get(&LengthUnit::Inch) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1.0 / 1000.0, PRECISION)), + ); + // foot is 12 inches + store.insert( + LengthUnit::Foot, + store + .get(&LengthUnit::Inch) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(12.0, PRECISION)), + ); + // yard is 3 feet + store.insert( + LengthUnit::Yard, + store + .get(&LengthUnit::Foot) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(3.0, PRECISION)), + ); + // mile is 5280 feet + store.insert( + LengthUnit::Mile, + store + .get(&LengthUnit::Foot) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(5280.0, PRECISION)), + ); + // league is 3 miles + store.insert( + LengthUnit::League, + store + .get(&LengthUnit::Mile) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(3.0, PRECISION)), + ); + // fathom is 2 yards + store.insert( + LengthUnit::Fathom, + store + .get(&LengthUnit::Yard) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(2.0, PRECISION)), + ); + // nautical mile is 1852 m + store.insert( + LengthUnit::NauticalMile, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1852.0, PRECISION)), + ); + // chain is 22 yards + store.insert( + LengthUnit::Chain, + store + .get(&LengthUnit::Yard) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(22.0, PRECISION)), + ); + // rod is 5 / 12 yards + store.insert( + LengthUnit::Rod, + store + .get(&LengthUnit::Yard) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(5.5, PRECISION)), + ); + // earth radius is 6371 km + store.insert( + LengthUnit::EarthRadius, + store + .get(&LengthUnit::Meter(MetricPrefix::Kilo)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(6371.0, PRECISION)), + ); + // lunar distance is 384402 km + store.insert( + LengthUnit::LunarDistance, + store + .get(&LengthUnit::Meter(MetricPrefix::Kilo)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(384402.0, PRECISION)), + ); + // astronomical unit is 149597870700 m + store.insert( + LengthUnit::AstronomicalUnit, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(149597870700.0, PRECISION)), + ); + // lightyear is 9460730472580.8 km + store.insert( + LengthUnit::LightYear, + store + .get(&LengthUnit::Meter(MetricPrefix::Kilo)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(9460730472580.8, PRECISION)), + ); + // parsec is 30856775814671.9 km + store.insert( + LengthUnit::Parsec, + store + .get(&LengthUnit::Meter(MetricPrefix::Kilo)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(30856775814671.9, PRECISION)), + ); + // hubble length is 14400000000 light years + store.insert( + LengthUnit::HubbleLength, + store + .get(&LengthUnit::LightYear) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(14400000000.0, PRECISION)), + ); + // planck length is 0.000000000000000000000000000000000016163 meters + store.insert( + LengthUnit::PlanckLength, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64( + 0.000000000000000000000000000000000016163, + PRECISION, + )), + ); + // cana is 1.57 meters + store.insert( + LengthUnit::Cana, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1.57, PRECISION)), + ); + // cubit is 52.92 cm + store.insert( + LengthUnit::Cubit, + store + .get(&LengthUnit::Meter(MetricPrefix::Centi)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(52.92, PRECISION)), + ); + // rope is 6.096 meters + store.insert( + LengthUnit::Rope, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(6.096, PRECISION)), + ); + // li is 500 meters + store.insert( + LengthUnit::Li, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(500.0, PRECISION)), + ); + // pace is 0.75 meters + store.insert( + LengthUnit::Pace, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(0.75, PRECISION)), + ); + // verst is 1.0668 km + store.insert( + LengthUnit::Verst, + store + .get(&LengthUnit::Meter(MetricPrefix::Kilo)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1.0668, PRECISION)), + ); + // double decker bus is 10 meters + store.insert( + LengthUnit::DoubleDeckerBus, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(10.0, PRECISION)), + ); + // football field is 100 yards + store.insert( + LengthUnit::FootballField, + store + .get(&LengthUnit::Yard) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(100.0, PRECISION)), + ); + // human hair thickness is 0.08 mm + store.insert( + LengthUnit::HumanHairThickness, + store + .get(&LengthUnit::Meter(MetricPrefix::Milli)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(0.08, PRECISION)), + ); + // furlong is 1/8 mile + store.insert( + LengthUnit::Furlong, + store + .get(&LengthUnit::Mile) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1.0 / 8.0, PRECISION)), + ); + // horse is 2.4 meters + store.insert( + LengthUnit::HorseLength, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(2.4, PRECISION)), + ); + // horizontal pitch is 5.08 mm + store.insert( + LengthUnit::HorizontalPitch, + store + .get(&LengthUnit::Meter(MetricPrefix::Milli)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(5.08, PRECISION)), + ); + // hammer unit is 19.05 mm + store.insert( + LengthUnit::HammerUnit, + store + .get(&LengthUnit::Meter(MetricPrefix::Milli)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(19.05, PRECISION)), + ); + // rack unit is 1.75 inches + store.insert( + LengthUnit::RackUnit, + store + .get(&LengthUnit::Inch) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(1.75, PRECISION)), + ); + // hand is 4 inches + store.insert( + LengthUnit::Hand, + store + .get(&LengthUnit::Inch) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(4.0, PRECISION)), + ); + // light nanosecond is 29.9792458 cm + store.insert( + LengthUnit::LightNanosecond, + store + .get(&LengthUnit::Meter(MetricPrefix::Centi)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(29.9792458, PRECISION)), + ); + // metric foot is 300 mm + store.insert( + LengthUnit::MetricFoot, + store + .get(&LengthUnit::Meter(MetricPrefix::Milli)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(300.0, PRECISION)), + ); + // boat length is 19 meters + store.insert( + LengthUnit::BoatLength, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(19.0, PRECISION)), + ); + // block is 150 meters + store.insert( + LengthUnit::Block, + store + .get(&LengthUnit::Meter(MetricPrefix::None)) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(150.0, PRECISION)), + ); + // siriometer is 15.8 light years + store.insert( + LengthUnit::Siriometer, + store + .get(&LengthUnit::LightYear) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(15.8, PRECISION)), + ); + // banana is 8 inches + store.insert( + LengthUnit::Banana, + store + .get(&LengthUnit::Inch) + .unwrap() + .mul_full_prec(&BigFloat::from_f64(8.0, PRECISION)), + ); + + store +}); + +// length unit -> Vec<(name, plural)> +pub static LENGTH_NAMES: Lazy>> = Lazy::new(|| { + let mut store = BTreeMap::new(); + + store.insert( + LengthUnit::Meter(MetricPrefix::Pico), + vec![("picometer", "picometers")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Nano), + vec![("nanometer", "nanometers")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Micro), + vec![("micrometer", "micrometers")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Milli), + vec![("millimeter", "millimeters"), ("mm", "mm")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Centi), + vec![("centimeter", "centimeters"), ("cm", "cm")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Deci), + vec![("decimeter", "decimeters")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::None), + vec![ + ("meter", "meters"), + ("m", "m"), + ("minecraft block", "minecraft blocks"), + ], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Deca), + vec![("decameter", "decameters")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Hecto), + vec![("hectometer", "hectometers")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Kilo), + vec![("kilometer", "kilometers"), ("km", "km")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Mega), + vec![("megameter", "megameters")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Giga), + vec![("gigameter", "gigameters")], + ); + store.insert( + LengthUnit::Meter(MetricPrefix::Tera), + vec![("terameter", "terameters")], + ); + // inch is 25.4 m + store.insert( + LengthUnit::Inch, + vec![("inch", "inches"), ("in", "in"), ("\"", "\"")], + ); + // thou is 1/1000 inches + store.insert(LengthUnit::Thou, vec![("thou", "thous")]); + // foot is 12 inches + store.insert( + LengthUnit::Foot, + vec![("foot", "feet"), ("ft", "ft"), ("'", "'ft'")], + ); + // yard is 3 feet + store.insert(LengthUnit::Yard, vec![("yard", "yards"), ("yd", "yd")]); + // mile is 5280 feet + store.insert(LengthUnit::Mile, vec![("mile", "miles")]); + // league is 3 miles + store.insert(LengthUnit::League, vec![("league", "leagues")]); + // fathom is 2 yards + store.insert(LengthUnit::Fathom, vec![("fathom", "fathoms")]); + // nautical mile is 1852 m + store.insert( + LengthUnit::NauticalMile, + vec![("nautical mile", "nautical miles")], + ); + // chain is 22 yards + store.insert(LengthUnit::Chain, vec![("chain", "chains")]); + // rod is 5 / 12 yards + store.insert(LengthUnit::Rod, vec![("rod", "rods")]); + // earth radius is 6371 km + store.insert( + LengthUnit::EarthRadius, + vec![("earth radius", "earth radii")], + ); + // lunar distance is 384402 km + store.insert( + LengthUnit::LunarDistance, + vec![("lunar distance", "lunar distances")], + ); + // astronomical unit is 149597870700 m + store.insert( + LengthUnit::AstronomicalUnit, + vec![("astronomical unit", "astronomical units")], + ); + // lightyear is 9460730472580.8 km + store.insert(LengthUnit::LightYear, vec![("lightyear", "lightyears")]); + // parsec is 30856775814671.9 km + store.insert(LengthUnit::Parsec, vec![("parsec", "parsecs")]); + // hubble length is 14400000000 light years + store.insert( + LengthUnit::HubbleLength, + vec![("hubble length", "hubble lengths")], + ); + // planck length is 0.000000000000000000000000000000000016163 meters + store.insert( + LengthUnit::PlanckLength, + vec![("planck length", "planck lengths")], + ); + // cana is 1.57 meters + store.insert(LengthUnit::Cana, vec![("cana", "canas")]); + // cubit is 52.92 cm + store.insert(LengthUnit::Cubit, vec![("cubit", "cubits")]); + // rope is 6.096 meters + store.insert(LengthUnit::Rope, vec![("rope", "ropes")]); + // li is 500 meters + store.insert(LengthUnit::Li, vec![("li", "lis")]); + // pace is 0.75 meters + store.insert(LengthUnit::Pace, vec![("pace", "paces")]); + // verst is 1.0668 km + store.insert(LengthUnit::Verst, vec![("verst", "versts")]); + // double decker bus is 10 meters + store.insert( + LengthUnit::DoubleDeckerBus, + vec![("double decker bus", "double decker busses")], + ); + // football field is 100 yards + store.insert( + LengthUnit::FootballField, + vec![("football field", "football fields")], + ); + // human hair thickness is 0.08 mm + store.insert( + LengthUnit::HumanHairThickness, + vec![("human hair thickness", "human hair thicknesses")], + ); + // furlong is 1/8 mile + store.insert(LengthUnit::Furlong, vec![("furlong", "furlongs")]); + // horse is 2.4 meters + store.insert( + LengthUnit::HorseLength, + vec![("horse", "horses"), ("horse length", "horse lengths")], + ); + // horizontal pitch is 5.08 mm + store.insert( + LengthUnit::HorizontalPitch, + vec![("horizontal pitch", "horizontal pitches")], + ); + // hammer unit is 19.05 mm + store.insert( + LengthUnit::HammerUnit, + vec![("hammer unit", "hammer units")], + ); + // rack unit is 1.75 inches + store.insert(LengthUnit::RackUnit, vec![("rack unit", "rack units")]); + // hand is 4 inches + store.insert(LengthUnit::Hand, vec![("hand", "hands")]); + // light nanosecond is 29.9792458 cm + store.insert( + LengthUnit::LightNanosecond, + vec![("light nanosecond", "light nanoseconds")], + ); + // metric foot is 300 mm + store.insert(LengthUnit::MetricFoot, vec![("metric foot", "metric feet")]); + // boat length is 19 meters + store.insert( + LengthUnit::BoatLength, + vec![("boat length", "boat lengths")], + ); + // block is 150 meters + store.insert(LengthUnit::Block, vec![("block", "blocks")]); + // siriometer is 15.8 light years + store.insert(LengthUnit::Siriometer, vec![("siriometer", "siriometers")]); + // banana is 8 inches + store.insert(LengthUnit::Banana, vec![("banana", "bananas")]); + + let mut store_string = BTreeMap::new(); + for (k, v) in store { + store_string.insert( + k, + v.into_iter() + .map(|(s1, s2)| (s1.to_string(), s2.to_string())) + .collect(), + ); + } + store_string +}); + +#[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Debug)] +pub enum LengthUnit { + Meter(MetricPrefix), + // 1/1000 inch + Thou, + + // 25.4 mm + Inch, + + // 12 inches + Foot, + + // 3 feet + Yard, + + // 5280 feet + Mile, + + // 3 miles + League, + + // 2 yards + Fathom, + + // 1852 m + NauticalMile, + + // 22 yards + Chain, + + // 5 1/2 yards + Rod, + + // 6371 km + EarthRadius, + + // 384402 km + LunarDistance, + + // 149597870700 m + AstronomicalUnit, + + // 9460730472580.8 km + LightYear, + + // 30856775814671.9 km + Parsec, + + // 14400000000 light years + HubbleLength, + + // 0.000000000000000000000000000000000016163 meters + PlanckLength, + + // 1.57 meters + Cana, + + // 52.92 cm + Cubit, + + // 6.096 meters + Rope, + + // 500 meters + Li, + + // 0.75 meters + Pace, + + // 1.0668 kilometers + Verst, + + // 10 meters + DoubleDeckerBus, + + // 100 yards + FootballField, + + // 0.08 mm + HumanHairThickness, + + // 1/8 mile + Furlong, + + // 2.4 meters + HorseLength, + + // 5.08 mm + HorizontalPitch, + + // 19.05 mm + HammerUnit, + + // 1.75 inches + RackUnit, + + // 4 inches + Hand, + + // 29.9792458 cm + LightNanosecond, + + // 300 mm + MetricFoot, + + // 19 meters + BoatLength, + + // 150 meters + Block, + + // 15.8 light years + Siriometer, + + // 8 inches + Banana, +} + +impl ConvertTo for LengthUnit { + // convert to meters: + // 1. find the desired type in the length store + // 2. multiply value by the type's meter value + fn convert_to(self, value: BigFloat, into: LengthUnit) -> BigFloat { + match self { + LengthUnit::Meter(prefix) => { + // unprefix + let denom = LENGTH_STORE.get(&LengthUnit::Meter(prefix)).unwrap(); + let store_value = LENGTH_STORE.get(&into).unwrap(); + value + .mul_full_prec(denom) + .div(store_value, PRECISION, RoundingMode::None) + } + _ => { + match into { + LengthUnit::Meter(prefix) => { + // unprefix + let denom = LENGTH_STORE.get(&LengthUnit::Meter(prefix)).unwrap(); + let store_value = LENGTH_STORE.get(&self).unwrap(); + value + .mul_full_prec(store_value) + .div(denom, PRECISION, RoundingMode::None) + } + _ => { + // convert to meters, then to desired value + let meters = self.convert_to(value, LengthUnit::Meter(MetricPrefix::None)); + LengthUnit::Meter(MetricPrefix::None).convert_to(meters, into) + } + } + } + } + } +} + +impl BestUnit for LengthUnit { + fn best_unit(self, value: BigFloat) -> Self { + let mut lowest_remainder = BigFloat::from_f64(f64::MAX, PRECISION); + let mut lowest_value = BigFloat::from_f64(f64::MAX, PRECISION); + let mut best_unit = LengthUnit::Meter(MetricPrefix::None); + + for unit in LENGTH_STORE.keys() { + if *unit == self { + continue; + } + match self { + LengthUnit::Meter(prefix) => { + // convert to meters, then to desired value + let meters = self + .convert_to(value.clone(), LengthUnit::Meter(MetricPrefix::None)); + let store_value = LENGTH_STORE.get(unit).unwrap(); + let rem = meters.rem(store_value); + let div = meters.div(store_value, PRECISION, RoundingMode::None); + if rem.le(&lowest_remainder) && div.le(&lowest_value) && div.ge(&BigFloat::from_f64(1.0, PRECISION)) { + lowest_remainder = rem; + lowest_value = div; + best_unit = *unit; + } + } + _ => { + match unit { + LengthUnit::Meter(prefix) => { + // unprefix + let denom = LENGTH_STORE.get(&LengthUnit::Meter(*prefix)).unwrap(); + let store_value = LENGTH_STORE.get(&self).unwrap(); + let rem = value.mul_full_prec(store_value).rem(denom); + let div = value.mul_full_prec(store_value).div( + denom, + PRECISION, + RoundingMode::None, + ); + if rem.le(&lowest_remainder) && div.le(&lowest_value) && div.ge(&BigFloat::from_f64(1.0, PRECISION)) { + lowest_remainder = rem; + lowest_value = div; + best_unit = *unit; + } + } + _ => { + // convert to meters, then to desired value + let meters = self + .convert_to(value.clone(), LengthUnit::Meter(MetricPrefix::None)); + let store_value = LENGTH_STORE.get(unit).unwrap(); + let rem = meters.rem(store_value); + let div = meters.div(store_value, PRECISION, RoundingMode::None); + if rem.le(&lowest_remainder) && div.le(&lowest_value) && div.ge(&BigFloat::from_f64(1.0, PRECISION)) { + lowest_remainder = rem; + lowest_value = div; + best_unit = *unit; + } + } + } + } + } + } + + best_unit + } +} + +impl FromUnitName for LengthUnit { + fn parse(value: String) -> Option<(LengthUnit, String)> { + let mut sorted_checklist: Vec<(String, String, LengthUnit)> = vec![]; + + for (unit, names) in LENGTH_NAMES.iter() { + for (single, plural) in names { + sorted_checklist.push((single.clone(), plural.clone(), *unit)); + } + } + + sorted_checklist.sort_by(|b, a| a.1.len().cmp(&b.1.len())); + let input = value.trim_start(); + let diff = value.len() - input.len(); + + for (name, plural, unit) in sorted_checklist { + if input.to_lowercase().starts_with(&name) || input.to_lowercase().starts_with(&plural) + { + let len = if plural.len() > name.len() { + if input.to_lowercase().starts_with(&plural) { + plural.len() + } else { + name.len() + } + } else if input.to_lowercase().starts_with(&name) { + name.len() + } else { + plural.len() + }; + return Some((unit, value[diff + len..].to_string())); + } + } + + None + } +} + +impl UnitName for LengthUnit { + fn unit_name(self, value: BigFloat) -> String { + if value == BigFloat::from_f64(1.0, PRECISION) { + // singular + LENGTH_NAMES.get(&self).unwrap().first().unwrap().0.clone() + } else { + // plural + LENGTH_NAMES.get(&self).unwrap().first().unwrap().1.clone() + } + } +} diff --git a/unit_converter/src/lib.rs b/unit_converter/src/lib.rs new file mode 100644 index 0000000..11e498c --- /dev/null +++ b/unit_converter/src/lib.rs @@ -0,0 +1,181 @@ +/* + * unit_converter lib.rs + * - main library file for the asklyphe unit converter + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use crate::length_units::{LengthUnit, LENGTH_NAMES, LENGTH_STORE, PRECISION}; +use crate::unit_defs::{ConvertTo, MetricPrefix}; +use astro_float::{BigFloat, Consts, Radix, RoundingMode}; + +pub const MAX_PRECISION: usize = 1024; + +pub mod length_units; +pub mod unit_defs; + +/// removes a leading conversion word +pub fn remove_leading_conversion_word(input_str: &str) -> String { + const CONVERSION_WORDS: &[&str] = &["to", "into", "as", "in", "using"]; + + let input_str = input_str.trim_start(); + + for word in CONVERSION_WORDS { + if input_str.starts_with(word) { + return input_str.strip_prefix(word).unwrap().to_string(); + } + } + input_str.to_string() +} + +/// takes an input starting with a number value, and returns it as a bigfloat, plus whatevers left +pub fn parse_number(input_str: &str) -> (BigFloat, String) { + let mut cc = Consts::new().expect("constants cache not initialized!"); + // parse digits, scientific notation, inf, and nan + let mut buf = "".to_string(); + let mut input = input_str.chars(); + let mut first = true; + let mut exp = false; + let mut nan = 0; + let mut inf = 0; + let mut cursor = 0; + while let Some(c) = input.next() { + cursor += 1; + if c == ',' || c.is_whitespace() { + continue; + } + if exp && c == '+' && first { + buf.push('+'); + first = false; + continue; + } + if c.is_numeric() || (c == '-' && first) || c == '.' { + buf.push(c); + first = false; + } else { + let lower = c.to_ascii_lowercase(); + if inf > 0 { + if inf == 1 && lower == 'n' { + buf.push('n'); + inf += 1; + } else if inf == 2 && lower == 'f' { + buf.push('f'); + break; + } else if inf == 1 { + buf.pop(); // pop i + cursor -= 1; + cursor -= 1; + break; + } else if inf == 2 { + buf.pop(); // pop n + buf.pop(); // pop i + cursor -= 1; + cursor -= 2; + break; + } + } else if nan > 0 { + if nan == 1 && lower == 'a' { + buf.push('a'); + nan += 1; + } else if nan == 2 && lower == 'n' { + buf.push('n'); + break; + } else if nan == 1 { + buf.pop(); // pop n + cursor -= 1; + cursor -= 1; + break; + } else if nan == 2 { + buf.pop(); // pop a + buf.pop(); // pop n + cursor -= 1; + cursor -= 2; + break; + } + } else if !exp { + if lower == 'e' { + exp = true; + first = true; + buf.push('e'); + } else if lower == 'i' { + inf = 1; + buf.push('i'); + } else if lower == 'n' { + nan = 1; + buf.push('n'); + } else { + cursor -= 1; + break; + } + } else { + cursor -= 1; + break; + } + } + } + let mut output = "".to_string(); + let input = input_str.chars(); + for c in input { + if cursor > 0 { + cursor -= 1; + } else { + output.push(c); + } + } + + let value = BigFloat::parse(&buf, Radix::Dec, MAX_PRECISION, RoundingMode::None, &mut cc); + + (value, output) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::unit_defs::{BestUnit, ConvertTo, FromUnitName}; + use std::str::FromStr; + + #[test] + fn it_works() { + let (number, remainder) = parse_number(" 2 meter to foot"); + println!("number:{} remainder:{}", number, remainder); + let (unit_a, remainder) = LengthUnit::parse(remainder).unwrap(); + println!("unit_a: {:?}, remainer: {}", unit_a, remainder); + let remainder = remove_leading_conversion_word(&remainder); + println!("stripped: {}", remainder); + let (unit_b, _) = LengthUnit::parse(remainder).unwrap(); + println!("unit_b: {:?}", unit_b); + let conversion = unit_a.convert_to(number, unit_b); + let approx = f64::from_str(&format!("{}", conversion)).unwrap(); + //conversion.set_exponent(Exponent::from(1)); + println!("conversion: {}", conversion); + println!( + "approx: {} {}", + approx, + LENGTH_NAMES.get(&unit_b).unwrap().first().unwrap().1 + ); + } + #[test] + fn best_unit() { + let (number, remainder) = parse_number(" 25 ft"); + println!("number:{} remainder:{}", number, remainder); + let (unit_a, remainder) = LengthUnit::parse(remainder).unwrap(); + println!("unit_a: {:?}, remainer: {}", unit_a, remainder); + let best_unit = unit_a.best_unit(number.clone()); + println!("best unit: {:?}", best_unit); + let conversion = unit_a.convert_to(number, best_unit); + let approx = f64::from_str(&format!("{}", conversion)).unwrap(); + //conversion.set_exponent(Exponent::from(1)); + println!("conversion: {}", conversion); + println!( + "approx: {} {}", + approx, + LENGTH_NAMES.get(&best_unit).unwrap().first().unwrap().1 + ); + } +} diff --git a/unit_converter/src/unit_defs.rs b/unit_converter/src/unit_defs.rs new file mode 100644 index 0000000..83e7dd2 --- /dev/null +++ b/unit_converter/src/unit_defs.rs @@ -0,0 +1,49 @@ +/* + * unit_converter length_units.rs + * - generic stuff for all units + * + * Copyright (C) 2025 Real Microsoft, LLC + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +use crate::length_units::LengthUnit; +use astro_float::BigFloat; + +pub trait ConvertTo { + fn convert_to(self, value: BigFloat, into: B) -> BigFloat; +} +pub trait BestUnit { + fn best_unit(self, value: BigFloat) -> Self; +} +pub trait UnitName { + fn unit_name(self, value: BigFloat) -> String; +} +pub trait FromUnitName { + fn parse(value: String) -> Option<(T, String)>; +} + +pub enum Unit { + Length(LengthUnit), +} + +#[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Debug)] +pub enum MetricPrefix { + Pico, + Nano, + Micro, + Milli, + Centi, + Deci, + None, + Deca, + Hecto, + Kilo, + Mega, + Giga, + Tera, +}