From f78be4dd18569fcb2a8ce38cda399dbeadc28165 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 18 Oct 2024 08:22:02 +0700 Subject: [PATCH] Mail protocol testing --- .gitignore | 3 + Cargo.lock | 556 +++++++++++++++--- crates/core/src/bc/model.rs | 10 + crates/core/src/bc/xml.rs | 96 ++- crates/core/src/bc_protocol.rs | 1 + .../src/bc_protocol/connection/udpsource.rs | 7 +- crates/core/src/bc_protocol/email.rs | 264 +++++++++ crates/core/src/bc_protocol/errors.rs | 10 +- crates/mailnoti/Cargo.toml | 22 + crates/mailnoti/README.md | 6 + crates/mailnoti/src/config.rs | 67 +++ crates/mailnoti/src/main.rs | 189 ++++++ crates/mailnoti/src/opt.rs | 16 + crates/mailnoti/src/utils.rs | 155 +++++ crates/pushnoti/Cargo.toml | 7 +- crates/pushnoti/src/config.rs | 20 +- crates/pushnoti/src/main.rs | 12 + src/common/instance.rs | 2 +- 18 files changed, 1345 insertions(+), 98 deletions(-) create mode 100644 crates/core/src/bc_protocol/email.rs create mode 100644 crates/mailnoti/Cargo.toml create mode 100644 crates/mailnoti/README.md create mode 100644 crates/mailnoti/src/config.rs create mode 100644 crates/mailnoti/src/main.rs create mode 100644 crates/mailnoti/src/opt.rs create mode 100644 crates/mailnoti/src/utils.rs diff --git a/.gitignore b/.gitignore index f85854a..8ecf383 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ # The token file for the FCM tests token.toml + +# Debug FCM build +./crates/fcm-push-listener/ \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 2b0b264..567f61f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -130,6 +130,154 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand 2.0.2", + "futures-lite 2.3.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 2.3.3", + "async-lock 3.4.0", + "blocking", + "futures-lite 2.3.0", + "once_cell", +] + +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock 2.8.0", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite 1.13.0", + "log", + "parking", + "polling 2.8.0", + "rustix 0.37.27", + "slab", + "socket2 0.4.10", + "waker-fn", +] + +[[package]] +name = "async-io" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" +dependencies = [ + "async-lock 3.4.0", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.3.0", + "parking", + "polling 3.7.2", + "rustix 0.38.32", + "slab", + "tracing", + "windows-sys 0.52.0", +] + +[[package]] +name = "async-lock" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" +dependencies = [ + "event-listener 2.5.3", +] + +[[package]] +name = "async-lock" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +dependencies = [ + "event-listener 5.3.1", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-std" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62565bb4402e926b29953c785397c6dc0391b7b446e45008b0049eb43cec6f5d" +dependencies = [ + "async-channel 1.9.0", + "async-global-executor", + "async-io 1.13.0", + "async-lock 2.8.0", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 1.13.0", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "atomic_refcell" version = "0.1.13" @@ -175,6 +323,15 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" +[[package]] +name = "base64-compat" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a8d4d2746f89841e49230dd26917df1876050f95abafafbe34f47cb534b88d7" +dependencies = [ + "byteorder", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -196,6 +353,25 @@ 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.3.0", + "piper", +] + +[[package]] +name = "bufstream-fresh" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c431e5d450eceb6f5096c371f502946ae1cc65407935bc2cae8f1d625a2035f" + [[package]] name = "bumpalo" version = "3.15.4" @@ -326,6 +502,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" +[[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 = "cookie-factory" version = "0.3.3" @@ -592,6 +777,42 @@ dependencies = [ "windows-sys 0.52.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.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" +dependencies = [ + "event-listener 5.3.1", + "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.0.2" @@ -618,6 +839,25 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "fcm-push-listener" +version = "3.0.0" +dependencies = [ + "base64 0.21.7", + "ece", + "log", + "prost", + "prost-build", + "rand", + "reqwest", + "serde", + "serde_with", + "tokio", + "tokio-rustls 0.23.4", + "uuid", + "webpki-roots", +] + [[package]] name = "fixedbitset" version = "0.4.2" @@ -713,6 +953,34 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[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.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" +dependencies = [ + "fastrand 2.0.2", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.30" @@ -885,6 +1153,18 @@ dependencies = [ "system-deps", ] +[[package]] +name = "gloo-timers" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b995a66bb87bebce9a0f4a95aed01daca4872c050bfcb21653361c03bc35e5c" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "gobject-sys" version = "0.20.0" @@ -1150,6 +1430,12 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + [[package]] name = "hex" version = "0.4.3" @@ -1246,7 +1532,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2", + "socket2 0.5.6", "tokio", "tower-service", "tracing", @@ -1295,16 +1581,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "idna" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - [[package]] name = "idna" version = "0.5.0" @@ -1315,12 +1591,6 @@ dependencies = [ "unicode-normalization", ] -[[package]] -name = "if_chain" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" - [[package]] name = "indexmap" version = "1.9.3" @@ -1357,6 +1627,26 @@ dependencies = [ "generic-array", ] +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi 0.3.9", + "libc", + "windows-sys 0.48.0", +] + [[package]] name = "ipnet" version = "2.9.0" @@ -1369,7 +1659,7 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "windows-sys 0.52.0", ] @@ -1407,6 +1697,15 @@ dependencies = [ "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.4.0" @@ -1429,6 +1728,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + [[package]] name = "linux-raw-sys" version = "0.4.13" @@ -1450,6 +1755,58 @@ name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +dependencies = [ + "value-bag", +] + +[[package]] +name = "mailin" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff08fefa0913a8fb1cbd31bd83a4841db8b6eb78320d517b31fcf60e2541d57a" +dependencies = [ + "base64-compat", + "either", + "log", + "nom", + "ternop", +] + +[[package]] +name = "mailin-embedded" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "143ac497c8c38d22407344e2252767ffd8253593a3d2464acc8619c8ef15835c" +dependencies = [ + "bufstream-fresh", + "cfg-if", + "log", + "mailin", + "rustls 0.22.3", + "rustls-pemfile 2.1.1", + "scoped_threadpool", +] + +[[package]] +name = "mailnoti" +version = "0.6.3-rc.3" +dependencies = [ + "anyhow", + "async-std", + "clap", + "env_logger 0.10.2", + "get_if_addrs", + "lazy_static", + "log", + "mailin-embedded", + "neolink_core", + "once_cell", + "regex", + "serde", + "tokio", + "toml", + "validator", +] [[package]] name = "md5" @@ -1538,7 +1895,7 @@ dependencies = [ "crossbeam-channel", "dirs", "env_logger 0.11.3", - "fcm-push-listener", + "fcm-push-listener 2.0.3", "futures", "gstreamer", "gstreamer-app", @@ -1560,7 +1917,7 @@ dependencies = [ "tokio-util", "toml", "uuid", - "validator 0.18.1", + "validator", ] [[package]] @@ -1575,7 +1932,7 @@ dependencies = [ "crc32fast", "crossbeam-channel", "delegate", - "env_logger 0.10.2", + "env_logger 0.11.3", "futures", "get_if_addrs", "indoc", @@ -1601,7 +1958,7 @@ dependencies = [ "aes", "anyhow", "cfb-mode", - "env_logger 0.10.2", + "env_logger 0.11.3", "hex-string", "log", "md5", @@ -1659,7 +2016,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", ] @@ -1746,6 +2103,12 @@ dependencies = [ "paste", ] +[[package]] +name = "parking" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" + [[package]] name = "parking_lot" version = "0.12.1" @@ -1803,12 +2166,54 @@ 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.0.2", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi 0.4.0", + "pin-project-lite", + "rustix 0.38.32", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -1934,16 +2339,16 @@ dependencies = [ "anyhow", "clap", "env_logger 0.10.2", - "fcm-push-listener", + "fcm-push-listener 2.0.3", "lazy_static", "log", "neolink_core", + "once_cell", "regex", "serde", "tokio", "toml", - "validator 0.16.1", - "validator_derive 0.16.0", + "validator", ] [[package]] @@ -2164,6 +2569,20 @@ version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" +[[package]] +name = "rustix" +version = "0.37.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea8ca367a3a01fe35e6943c400addf443c0f57670e6ec51196f71a4b8762dd2" +dependencies = [ + "bitflags 1.3.2", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + [[package]] name = "rustix" version = "0.38.32" @@ -2173,7 +2592,7 @@ dependencies = [ "bitflags 2.6.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.4.13", "windows-sys 0.52.0", ] @@ -2267,6 +2686,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" + [[package]] name = "scopeguard" version = "1.2.0" @@ -2454,6 +2879,16 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" +[[package]] +name = "socket2" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +dependencies = [ + "libc", + "winapi 0.3.9", +] + [[package]] name = "socket2" version = "0.5.6" @@ -2572,8 +3007,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", - "fastrand", - "rustix", + "fastrand 2.0.2", + "rustix 0.38.32", "windows-sys 0.52.0", ] @@ -2586,6 +3021,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "ternop" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d4ae32d0a4605a89c28534371b056919c12e7a070ee07505af75130ff030111" + [[package]] name = "textwrap" version = "0.15.2" @@ -2699,7 +3140,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.6", "tokio-macros", "tracing", "windows-sys 0.48.0", @@ -2918,7 +3359,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" dependencies = [ "form_urlencoded", - "idna 0.5.0", + "idna", "percent-encoding", ] @@ -2950,51 +3391,20 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "validator" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b92f40481c04ff1f4f61f304d61793c7b56ff76ac1469f1beb199b1445b253bd" -dependencies = [ - "idna 0.4.0", - "lazy_static", - "regex", - "serde", - "serde_derive", - "serde_json", - "url", -] - [[package]] name = "validator" version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db79c75af171630a3148bd3e6d7c4f42b6a9a014c2945bc5ed0020cbb8d9478e" dependencies = [ - "idna 0.5.0", + "idna", "once_cell", "regex", "serde", "serde_derive", "serde_json", "url", - "validator_derive 0.18.1", -] - -[[package]] -name = "validator_derive" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc44ca3088bb3ba384d9aecf40c6a23a676ce23e09bdaca2073d99c207f864af" -dependencies = [ - "if_chain", - "lazy_static", - "proc-macro-error", - "proc-macro2", - "quote", - "regex", - "syn 1.0.109", - "validator_types", + "validator_derive", ] [[package]] @@ -3012,14 +3422,10 @@ dependencies = [ ] [[package]] -name = "validator_types" -version = "0.16.0" +name = "value-bag" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111abfe30072511849c5910134e8baf8dc05de4c0e5903d681cbd5c9c4d611e3" -dependencies = [ - "proc-macro2", - "syn 1.0.109", -] +checksum = "5a84c137d37ab0142f0f2ddfe332651fdbf252e7b7dbb4e67b6c1f1b2e925101" [[package]] name = "vcpkg" @@ -3039,6 +3445,12 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[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" @@ -3158,7 +3570,7 @@ dependencies = [ "either", "home", "once_cell", - "rustix", + "rustix 0.38.32", ] [[package]] diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index f377161..2e8dd05 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -36,6 +36,10 @@ pub const MSG_ID_MOTION: u32 = 33; pub const MSG_ID_SET_SERVICE_PORTS: u32 = 36; /// Get service ports pub const MSG_ID_GET_SERVICE_PORTS: u32 = 37; +/// Get Email setting +pub const MSG_ID_GET_EMAIL: u32 = 42; +/// Set email settings +pub const MSG_ID_SET_EMAIL: u32 = 43; /// Version messages have this ID pub const MSG_ID_VERSION: u32 = 80; /// Ping messages have this ID @@ -50,6 +54,8 @@ pub const MSG_ID_SNAP: u32 = 109; pub const MSG_ID_UID: u32 = 114; /// Used to pass the token and client ID for push notifications pub const MSG_ID_PUSH_INFO: u32 = 124; +/// Send a test email configuration +pub const MSG_ID_TEST_EMAIL: u32 = 141; /// StreamInfoList messages have this ID pub const MSG_ID_STREAM_INFO_LIST: u32 = 146; /// Used to get the abilities of a user @@ -70,6 +76,10 @@ pub const MSG_ID_SET_LED_STATUS: u32 = 209; pub const MSG_ID_GET_PIR_ALARM: u32 = 212; /// Setting PIR status messages have this ID pub const MSG_ID_START_PIR_ALARM: u32 = 213; +/// Set Email Task +pub const MSG_ID_SET_EMAIL_TASK: u32 = 216; +/// Get Email Task +pub const MSG_ID_GET_EMAIL_TASK: u32 = 217; /// UDP Keep alive pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234; /// Battery message initiaed by the camera diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 0719a71..c046d24 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -132,6 +132,12 @@ pub struct BcXml { /// For changing rtmp server port #[serde(rename = "OnvifPort", skip_serializing_if = "Option::is_none")] pub onvif_port: Option, + /// Email for setting the email notifications + #[serde(rename = "Email", skip_serializing_if = "Option::is_none")] + pub email: Option, + /// EmailTask for turning the email notifications on/off + #[serde(rename = "EmailTask", skip_serializing_if = "Option::is_none")] + pub email_task: Option, } impl BcXml { @@ -490,8 +496,9 @@ pub struct TimeBlockList { pub struct TimeBlock { /// Whether to enable or disable for this time block pub enable: u8, - /// The day of the week for this block - pub weekDay: String, + /// The day of the week for this block, Monday, Tuesday, Etc + #[serde(rename = "weekDay")] + pub week_day: String, /// Time to start this block #[serde(rename = "beginHour")] pub begin_hour: u8, @@ -930,7 +937,7 @@ pub struct FloodlightTask { #[serde(skip_serializing_if = "Option::is_none")] pub brightness_min: Option, /// Schedule fot auto floodlight - pub schedule: Schedule, + pub schedule: ScheduleFloodLight, /// Threshold settings for light sensor to consider nightime #[serde(rename = "lightSensThreshold")] pub light_sens_threshold: LightSensThreshold, @@ -947,7 +954,7 @@ pub struct FloodlightTask { /// Schedule for Floodlight Task #[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] -pub struct Schedule { +pub struct ScheduleFloodLight { /// startHour #[serde(rename = "startHour")] pub start_hour: u32, @@ -1478,6 +1485,87 @@ pub struct OnvifPort { pub enable: Option, } +/// Email settings for notificaitons +#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)] +pub struct Email { + /// XML Version + #[serde(rename = "@version")] + pub version: String, + /// SMTP server address + #[serde(rename = "smtpServer")] + pub smtp_server: String, + /// SMTP username + #[serde(rename = "userName")] + pub user_name: String, + /// SMTP password + pub password: String, + /// Send email address + pub address1: String, + /// Send email address can be empty + pub address2: String, + /// Send email address can be empty + pub address3: String, + /// 465 + #[serde(rename = "smtpPort")] + pub smtp_port: u16, + /// Name of recipient to use on the email + #[serde(rename = "sendNickname")] + pub send_nickname: String, + /// Observed value `1` + pub attachment: u8, + /// Observed value `picture`, `video` + #[serde(rename = "attachmentType", skip_serializing_if = "Option::is_none")] + pub attachment_type: Option, + /// Observed value `withText` + #[serde(rename = "textType")] + pub text_type: String, + /// Observed value `1` + pub ssl: u8, + /// Observed value `30` + pub interval: u32, + /// Max length of message. Observed value `127` + /// Read Only + #[serde(rename = "senderMaxLen", skip_serializing_if = "Option::is_none")] + pub sender_max_len: Option, +} + +/// EmailTask settings that controls the times/enables the email +/// notifications +#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] +pub struct EmailTask { + /// XML Version + #[serde(rename = "@version")] + pub version: String, + /// Channel number + #[serde(rename = "channelId")] + pub channel_id: u8, + /// 1 for enable 0 for disable + #[serde(rename = "enable")] + pub enable: u8, + /// The list of schedule to turn on/off the email notifications + #[serde(rename = "ScheduleList", skip_serializing_if = "Option::is_none")] + pub schedule_list: Option, +} + +/// List of schedule items for turning on/off the notifications +#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] +pub struct ScheduleList { + /// List of schedules + #[serde(rename = "Schedule")] + pub schedule: Schedule, +} + +/// Schedule item for turning on/off the notifications +#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)] +pub struct Schedule { + /// The alarm type. Observed values: `MD` + #[serde(rename = "alarmType")] + pub alarm_type: String, + /// The list of time blocks + #[serde(rename = "timeBlockList")] + pub time_block_list: TimeBlockList, +} + /// Convience function to return the xml version used throughout the library pub fn xml_ver() -> String { "1.1".to_string() diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index b7cc604..cf67809 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -16,6 +16,7 @@ mod abilityinfo; mod battery; mod connection; mod credentials; +mod email; mod errors; mod floodlight; mod keepalive; diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index fa12beb..3a9fc77 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -1,6 +1,7 @@ use super::DiscoveryResult; use crate::bc::codex::BcCodex; use crate::bc::model::*; +use crate::bc_protocol::errors::BcUdpDropReciverKind; use crate::bcudp::codex::BcUdpCodex; use crate::bcudp::{model::*, xml::*}; use crate::{Credentials, Error, Result}; @@ -354,10 +355,10 @@ impl UdpPayloadInner { } packet = inner.next() => { log::trace!("Cam->App"); - let packet = packet.ok_or(Error::BcUdpDropReciver)??; + let packet = packet.ok_or(Error::BcUdpDropReciver(BcUdpDropReciverKind::NoneRecieved))??; recv_timeout.as_mut().reset(Instant::now() + Duration::from_secs(TIME_OUT)); // let packet = socket_rx.next().await.ok_or(Error::BcUdpDropReciver)??; - socket_out_tx.try_send(packet).map_err(|_| Error::BcUdpDropReciver)?; + socket_out_tx.try_send(packet).map_err(|e| Error::BcUdpDropReciver(BcUdpDropReciverKind::SendFailed(format!("{e:?}"))))?; continue; }, packet = socket_in_rx.next() => { @@ -509,7 +510,7 @@ impl UdpPayloadInner { log::trace!("Camera->App"); // Incomming from socket // Outgoing to application - let (item, addr) = v.ok_or(Error::BcUdpDropReciver)?; + let (item, addr) = v.ok_or(Error::BcUdpDropReciver(BcUdpDropReciverKind::NoneRecieved))?; if addr == camera_addr { match item { BcUdp::Discovery(UdpDiscovery{ diff --git a/crates/core/src/bc_protocol/email.rs b/crates/core/src/bc_protocol/email.rs new file mode 100644 index 0000000..d855a47 --- /dev/null +++ b/crates/core/src/bc_protocol/email.rs @@ -0,0 +1,264 @@ +//! Email controlling methods +//! +use super::{BcCamera, Error, Result}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Get the current Email XML + pub async fn get_email(&self) -> Result { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(MSG_ID_GET_EMAIL, msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_GET_EMAIL, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavailable { + id: msg.meta.msg_id, + code: msg.meta.response_code, + }); + } + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + email: Some(email), .. + })), + .. + }) = msg.body + { + Ok(email) + } else { + Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected Email xml but it was not recieved", + }) + } + } + + /// Set the Email XML + pub async fn set_email(&self, email: Email) -> Result<()> { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(MSG_ID_SET_EMAIL, msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_SET_EMAIL, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: None, + payload: Some(BcPayloads::BcXml(BcXml { + email: Some(email), + ..Default::default() + })), + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavailable { + id: msg.meta.msg_id, + code: msg.meta.response_code, + }); + } + Ok(()) + } + + /// Test the Email with this XML + pub async fn test_email(&self, email: Email) -> Result<()> { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(MSG_ID_TEST_EMAIL, msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_TEST_EMAIL, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: None, + payload: Some(BcPayloads::BcXml(BcXml { + email: Some(email), + ..Default::default() + })), + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavailable { + id: msg.meta.msg_id, + code: msg.meta.response_code, + }); + } + Ok(()) + } + + /// Get the current EmailTask XML + pub async fn get_email_task(&self) -> Result { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(MSG_ID_GET_EMAIL_TASK, msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_GET_EMAIL_TASK, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: None, + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavailable { + id: msg.meta.msg_id, + code: msg.meta.response_code, + }); + } + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + email_task: Some(email_task), + .. + })), + .. + }) = msg.body + { + Ok(email_task) + } else { + Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected EmailTask xml but it was not recieved", + }) + } + } + + /// Setup the Email Task + pub async fn set_email_task(&self, email_task: EmailTask) -> Result<()> { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(MSG_ID_SET_EMAIL_TASK, msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_SET_EMAIL_TASK, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: Some(BcPayloads::BcXml(BcXml { + email_task: Some(email_task), + ..Default::default() + })), + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavailable { + id: msg.meta.msg_id, + code: msg.meta.response_code, + }); + } + Ok(()) + } + + /// Turn on Email notifications + pub async fn email_on(&self) -> Result<()> { + self.set_email_task(EmailTask { + version: xml_ver(), + channel_id: self.channel_id, + enable: 1, + schedule_list: None, + }) + .await + } + + /// Turn off Email notifications + pub async fn email_off(&self) -> Result<()> { + self.set_email_task(EmailTask { + version: xml_ver(), + channel_id: self.channel_id, + enable: 0, + schedule_list: None, + }) + .await + } + + /// Turn on Email notifications all the time + pub async fn email_on_always(&self) -> Result<()> { + const DOW: [&str; 7] = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ]; + self.set_email_task(EmailTask { + version: xml_ver(), + channel_id: self.channel_id, + enable: 1, + schedule_list: Some(ScheduleList { + schedule: Schedule { + alarm_type: "MD".to_owned(), + time_block_list: TimeBlockList { + time_block: DOW + .iter() + .map(|d| TimeBlock { + enable: 1, + week_day: d.to_string(), + begin_hour: 0, + end_hour: 23, + }) + .collect(), + }, + }, + }), + }) + .await + } +} diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index d0e6db3..8f16a13 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -89,8 +89,8 @@ pub enum Error { BcUdpTimeout, /// Raised when a BcUdp incomming connection is dropped - #[error("BcUDP reciver dropped")] - BcUdpDropReciver, + #[error("BcUDP reciver dropped: {0:?}")] + BcUdpDropReciver(BcUdpDropReciverKind), /// Raised when a BcUdp outgoing connection is dropped #[error("BcUDP sender dropped")] @@ -236,6 +236,12 @@ pub enum Error { OtherString(String), } +#[derive(Debug, Clone)] +pub enum BcUdpDropReciverKind { + NoneRecieved, + SendFailed(String), +} + impl From for Error { fn from(k: std::io::Error) -> Self { // Check for other error that is already an Error of this type diff --git a/crates/mailnoti/Cargo.toml b/crates/mailnoti/Cargo.toml new file mode 100644 index 0000000..02aafa5 --- /dev/null +++ b/crates/mailnoti/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "mailnoti" +version = "0.6.3-rc.3" +edition = "2021" + + +[dependencies] +anyhow = "1.0.71" +async-std = "1.12.0" +clap = { version = "4.2.2", features = ["derive", "cargo"] } +env_logger = "0.10.0" +get_if_addrs = "0.5.3" +lazy_static = "1.4.0" +log = { version = "0.4.17", features = [ "release_max_level_debug" ] } +mailin-embedded = "0.8.2" +neolink_core = { path = "../core", version = "0.6.3-rc.3" } +once_cell = "1.19.0" +regex = "1.8.1" +serde = "1.0.163" +tokio = { version = "1.28.1", features = ["full"] } +toml = "0.8.2" +validator = {version="0.18.1", features = ["derive"] } diff --git a/crates/mailnoti/README.md b/crates/mailnoti/README.md new file mode 100644 index 0000000..546ea9a --- /dev/null +++ b/crates/mailnoti/README.md @@ -0,0 +1,6 @@ +# Reolink Mail Notifications + +Because google FCM has removed the push notification api we use +we now must resort to email notifications for PIR messages + +This is a test crate to investigate this diff --git a/crates/mailnoti/src/config.rs b/crates/mailnoti/src/config.rs new file mode 100644 index 0000000..93f4fcf --- /dev/null +++ b/crates/mailnoti/src/config.rs @@ -0,0 +1,67 @@ +use neolink_core::bc_protocol::DiscoveryMethods; +use once_cell::sync::Lazy; +use regex::Regex; +use serde::Deserialize; +use std::clone::Clone; +use validator::{Validate, ValidationError}; + +static RE_MAXENC_SRC: Lazy = Lazy::new(|| { + Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap() +}); + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct Config { + #[validate(nested)] + pub(crate) cameras: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +#[validate(schema(function = "validate_camera_config"))] +pub(crate) struct CameraConfig { + pub(crate) name: String, + + #[serde(rename = "address")] + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, + + pub(crate) username: String, + pub(crate) password: Option, + + #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] + #[serde(default = "default_channel_id", alias = "channel")] + pub(crate) channel_id: u8, + + #[serde(default = "default_discovery")] + pub(crate) discovery: DiscoveryMethods, + + #[serde(default = "default_maxenc")] + #[validate(regex( + path = *RE_MAXENC_SRC, + message = "Invalid maximum encryption method", + code = "max_encryption" + ))] + pub(crate) max_encryption: String, +} + +fn default_discovery() -> DiscoveryMethods { + DiscoveryMethods::Relay +} + +fn default_maxenc() -> String { + "Aes".to_string() +} + +fn default_channel_id() -> u8 { + 0 +} + +fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { + match (&camera_config.camera_addr, &camera_config.camera_uid) { + (None, None) => Err(ValidationError::new( + "Either camera address or uid must be given", + )), + _ => Ok(()), + } +} diff --git a/crates/mailnoti/src/main.rs b/crates/mailnoti/src/main.rs new file mode 100644 index 0000000..4ffc54e --- /dev/null +++ b/crates/mailnoti/src/main.rs @@ -0,0 +1,189 @@ +//! Main test app for mail + +use anyhow::{anyhow, Context, Result}; +use clap::Parser; +use neolink_core::{ + bc::xml::{xml_ver, Email}, + bc_protocol::BcCamera, +}; +use std::{ + fs, + net::{IpAddr, SocketAddr}, +}; +use validator::Validate; + +mod config; +mod opt; +mod utils; + +use config::Config; +use opt::Opt; +use utils::find_and_connect; + +#[tokio::main] +async fn main() -> Result<()> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + let opt = Opt::parse(); + + let conf_path = opt.config.context("Must supply --config file")?; + let config: Config = toml::from_str( + &fs::read_to_string(&conf_path) + .with_context(|| format!("Failed to read {:?}", conf_path))?, + ) + .with_context(|| format!("Failed to parse the {:?} config file", conf_path))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", conf_path))?; + + let name = opt.camera.clone(); + let camera = find_and_connect(&config, &opt.camera).await?; + + const MAIL_PORT: u16 = 22022; + // let addr = SocketAddr::from((get_local_ip()?, MAIL_PORT)); + let cam_addr = SocketAddr::from((IpAddr::from([192, 168, 1, 201]), MAIL_PORT)); + let post_addr = SocketAddr::from((IpAddr::from([127, 0, 0, 1]), MAIL_PORT)); + + tokio::select! { + v = cam_tasks(&name, camera, cam_addr) => v, + v = mail_server(&name, post_addr) => v, + }?; + + Ok(()) +} + +fn get_local_ip() -> Result { + get_if_addrs::get_if_addrs()? + .iter() + .find(|i| !i.is_loopback() && matches!(i.addr, get_if_addrs::IfAddr::V4(_))) + .map(|iface| Ok(iface.ip())) + .unwrap_or_else(|| Err(anyhow!("No Local Ip Address Found"))) +} + +async fn cam_tasks(name: &str, camera: BcCamera, addr: SocketAddr) -> Result<()> { + let support = camera.get_support().await?; + if support.email.is_some_and(|v| v > 0) { + let ip = addr.ip(); + let port = addr.port(); + log::info!("Telling camera to send the mail to {}:{}", ip, port); + let mail_settings = Email { + version: xml_ver(), + smtp_server: format!("{}", ip), + user_name: format!("{name}@neolink.neolink"), + password: "TestPass".to_owned(), + address1: "neolink@neolink.neolink".to_owned(), + address2: "".to_owned(), + address3: "".to_owned(), + smtp_port: addr.port(), + send_nickname: name.to_string(), + attachment: 1, + attachment_type: Some("picture".to_owned()), + text_type: "withText".to_owned(), + ssl: 0, + interval: 30, + sender_max_len: None, + }; + camera.set_email(mail_settings.clone()).await?; + camera.email_on_always().await?; + + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + log::info!("Sending test email"); + camera.test_email(mail_settings).await?; + + // Wait to give me time to wave at the camera please + tokio::time::sleep(tokio::time::Duration::from_secs(300)).await; + + Ok(()) + } else { + Err(anyhow::anyhow!( + "Camera does not support email notfications" + )) + } +} + +use mailin_embedded::{ + response::{self, Response}, + Handler, Server, SslConfig, +}; +use regex::Regex; + +#[derive(Clone)] +struct MailHandler { + name: String, +} +impl Handler for MailHandler { + fn helo(&mut self, _ip: IpAddr, _domain: &str) -> Response { + log::debug!("HELO"); + response::OK + } + + fn rcpt(&mut self, to: &str) -> Response { + log::debug!("rcpr:: {to}"); + let re = Regex::new(r"^(.*)@neolink.neolink$").unwrap(); + if re.is_match(to) { + response::OK + } else { + response::NO_MAILBOX + } + } + + fn mail(&mut self, ip: IpAddr, domain: &str, from: &str) -> Response { + log::debug!("mail:: ip: {ip:?}, domain: {domain}, from: {from}"); + response::OK + } + + fn data_start(&mut self, domain: &str, from: &str, is8bit: bool, to: &[String]) -> Response { + log::debug!("data_start:: domain: {domain}, from: {from}, is8bit: {is8bit}, to: {to:?}"); + response::OK + } + + fn data(&mut self, buf: &[u8]) -> std::io::Result<()> { + let text = String::from_utf8_lossy(buf); + log::debug!("data:: text: {text}"); + Ok(()) + } + + fn data_end(&mut self) -> Response { + log::debug!("data_end::"); + response::OK + } + + fn auth_login(&mut self, username: &str, password: &str) -> Response { + log::debug!("auth_login;: username: {username}, password: {password}"); + let correct_username = format!("{}@neolink.neolink", self.name); + let correct_password = "TestPass"; + if username == correct_username && password == correct_password { + response::AUTH_OK + } else { + response::INVALID_CREDENTIALS + } + } + + fn auth_plain( + &mut self, + authorization_id: &str, + authentication_id: &str, + password: &str, + ) -> Response { + log::debug!("auth_plain:: authorization_id: {authorization_id}, authentication_id: {authentication_id}, password: {password}"); + response::INVALID_CREDENTIALS + } +} + +async fn mail_server(name: &str, addr: SocketAddr) -> Result<()> { + let handler = MailHandler { + name: name.to_string(), + }; + let mut server = Server::new(handler); + + server + .with_name("neolink.neolink") + .with_ssl(SslConfig::None) + .map_err(|e| anyhow!("{e:?}"))? + .with_addr(addr) + .map_err(|e| anyhow!("{e:?}"))?; + + tokio::task::spawn_blocking(move || server.serve().map_err(|e| anyhow!("{e:?}"))).await??; + Ok(()) +} diff --git a/crates/mailnoti/src/opt.rs b/crates/mailnoti/src/opt.rs new file mode 100644 index 0000000..73b9c94 --- /dev/null +++ b/crates/mailnoti/src/opt.rs @@ -0,0 +1,16 @@ +use clap::{crate_authors, crate_version, Parser}; +use std::path::PathBuf; +use std::str::FromStr; + +/// A standards-compliant bridge to Reolink IP cameras +/// +/// Neolink is free software released under the GNU AGPL v3. +/// You can find its source code at https://github.com/thirtythreeforty/neolink +#[derive(Parser, Debug)] +#[command(name = "pushnoti", arg_required_else_help = true, version = crate_version!(), author = crate_authors!("\n"))] +pub struct Opt { + #[arg(short, long, value_parser = PathBuf::from_str)] + pub config: Option, + /// The name of the camera. Must be a name in the config + pub camera: String, +} diff --git a/crates/mailnoti/src/utils.rs b/crates/mailnoti/src/utils.rs new file mode 100644 index 0000000..d3aa47c --- /dev/null +++ b/crates/mailnoti/src/utils.rs @@ -0,0 +1,155 @@ +//! Contains code that is not specific to any of the subcommands +//! +use log::*; + +use super::config::{CameraConfig, Config}; +use anyhow::{anyhow, Context, Error, Result}; +use neolink_core::bc_protocol::{ + BcCamera, BcCameraOpt, ConnectionProtocol, Credentials, DiscoveryMethods, MaxEncryption, +}; +use std::{ + fmt::{Display, Error as FmtError, Formatter}, + net::{IpAddr, ToSocketAddrs}, + str::FromStr, +}; + +pub(crate) enum AddressOrUid { + Address(String), + #[allow(dead_code)] + Uid(String, DiscoveryMethods), + #[allow(dead_code)] + AddressWithUid(String, String, DiscoveryMethods), +} + +impl Display for AddressOrUid { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { + match self { + AddressOrUid::AddressWithUid(addr, uid, _) => { + write!(f, "Address: {}, UID: {}", addr, uid) + } + AddressOrUid::Address(host) => write!(f, "Address: {}", host), + AddressOrUid::Uid(host, _) => write!(f, "UID: {}", host), + } + } +} + +impl AddressOrUid { + // Created by translating the config fields directly + pub(crate) fn new( + address: &Option, + uid: &Option, + method: &DiscoveryMethods, + ) -> Result { + match (address, uid) { + (None, None) => Err(anyhow!("Neither address or uid given")), + (Some(host), Some(uid)) => Ok(AddressOrUid::AddressWithUid( + host.clone(), + uid.clone(), + *method, + )), + (Some(host), None) => Ok(AddressOrUid::Address(host.clone())), + (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone(), *method)), + } + } + + // Convience method to get the BcCamera with the appropiate method + // from a camera_config + pub(crate) async fn connect_camera( + &self, + camera_config: &CameraConfig, + ) -> Result { + let (port, addrs) = { + if let Some(addr_str) = camera_config.camera_addr.as_ref() { + match addr_str.to_socket_addrs() { + Ok(addr_iter) => { + let mut port = None; + let mut ipaddrs = vec![]; + for addr in addr_iter { + port = Some(addr.port()); + ipaddrs.push(addr.ip()); + } + Ok((port, ipaddrs)) + } + Err(_) => match IpAddr::from_str(addr_str) { + Ok(ip) => Ok((None, vec![ip])), + Err(_) => Err(anyhow!("Could not parse address in config")), + }, + } + } else { + Ok((None, vec![])) + } + }?; + + let options = BcCameraOpt { + name: camera_config.name.clone(), + channel_id: camera_config.channel_id, + addrs, + port, + uid: camera_config.camera_uid.clone(), + protocol: ConnectionProtocol::TcpUdp, + discovery: camera_config.discovery, + max_discovery_retries: 10, + credentials: Credentials { + username: camera_config.username.clone(), + password: camera_config.password.clone(), + }, + debug: false, + }; + + trace!("Camera Info: {:?}", options); + + Ok(BcCamera::new(&options).await?) + } +} + +pub(crate) async fn find_and_connect(config: &Config, name: &str) -> Result { + let camera_config = find_camera_by_name(config, name)?; + connect_and_login(camera_config).await +} + +pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result { + let camera_addr = AddressOrUid::new( + &camera_config.camera_addr, + &camera_config.camera_uid, + &camera_config.discovery, + ) + .unwrap(); + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_addr + ); + + let camera = camera_addr + .connect_camera(camera_config) + .await + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; + + let max_encryption = match camera_config.max_encryption.to_lowercase().as_str() { + "none" => MaxEncryption::None, + "bcencrypt" => MaxEncryption::BcEncrypt, + "aes" => MaxEncryption::Aes, + _ => MaxEncryption::Aes, + }; + info!("{}: Logging in", camera_config.name); + camera + .login_with_maxenc(max_encryption) + .await + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + Ok(camera) +} + +pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<&'a CameraConfig> { + config + .cameras + .iter() + .find(|c| c.name == name) + .ok_or_else(|| anyhow!("Camera {} not found in the config file", name)) +} diff --git a/crates/pushnoti/Cargo.toml b/crates/pushnoti/Cargo.toml index 7d0d128..47fa05c 100644 --- a/crates/pushnoti/Cargo.toml +++ b/crates/pushnoti/Cargo.toml @@ -9,13 +9,14 @@ edition = "2021" anyhow = "1.0.71" clap = { version = "4.2.2", features = ["derive", "cargo"] } env_logger = "0.10.0" -fcm-push-listener = "2.0.1" +# fcm-push-listener = { path = "../fcm-push-listener" } +fcm-push-listener = { version = "2.0.3" } lazy_static = "1.4.0" log = { version = "0.4.17", features = [ "release_max_level_debug" ] } neolink_core = { path = "../core", version = "0.6.3-rc.3" } +once_cell = "1.19.0" regex = "1.8.1" serde = "1.0.163" tokio = { version = "1.28.1", features = ["full"] } toml = "0.8.2" -validator = "0.16.0" -validator_derive = "0.16.0" +validator = {version="0.18.1", features = ["derive"] } diff --git a/crates/pushnoti/src/config.rs b/crates/pushnoti/src/config.rs index 19531a2..93f4fcf 100644 --- a/crates/pushnoti/src/config.rs +++ b/crates/pushnoti/src/config.rs @@ -1,23 +1,17 @@ -use lazy_static::lazy_static; use neolink_core::bc_protocol::DiscoveryMethods; +use once_cell::sync::Lazy; use regex::Regex; use serde::Deserialize; use std::clone::Clone; use validator::{Validate, ValidationError}; -use validator_derive::Validate; -lazy_static! { - static ref RE_STREAM_SRC: Regex = - Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap(); - static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap(); - static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap(); - static ref RE_MAXENC_SRC: Regex = - Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap(); -} +static RE_MAXENC_SRC: Lazy = Lazy::new(|| { + Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap() +}); #[derive(Debug, Deserialize, Validate, Clone)] pub(crate) struct Config { - #[validate] + #[validate(nested)] pub(crate) cameras: Vec, } @@ -36,7 +30,7 @@ pub(crate) struct CameraConfig { pub(crate) password: Option, #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] + #[serde(default = "default_channel_id", alias = "channel")] pub(crate) channel_id: u8, #[serde(default = "default_discovery")] @@ -44,7 +38,7 @@ pub(crate) struct CameraConfig { #[serde(default = "default_maxenc")] #[validate(regex( - path = "RE_MAXENC_SRC", + path = *RE_MAXENC_SRC, message = "Invalid maximum encryption method", code = "max_encryption" ))] diff --git a/crates/pushnoti/src/main.rs b/crates/pushnoti/src/main.rs index d9e5bfd..02a7d17 100644 --- a/crates/pushnoti/src/main.rs +++ b/crates/pushnoti/src/main.rs @@ -41,6 +41,11 @@ async fn main() -> Result<()> { // into this program // let registration = fcm_push_listener::register("263684512460").await?; + // let firebase_app_id = "1:743639030586:android:86f60a4fb7143876"; + // let firebase_project_id = "reolink-login"; + // let firebase_api_key = "AIzaSyBEUIuWHnnOEwFahxWgQB4Yt4NsgOmkPyE"; + // let vapid_key = ""; + let sender_id = "743639030586"; // andriod // let sender_id = "696841269229"; // ios @@ -56,6 +61,13 @@ async fn main() -> Result<()> { } else { info!("Registering new token"); let registration = fcm_push_listener::register(sender_id).await?; + // let registration = fcm_push_listener::register( + // firebase_app_id, + // firebase_project_id, + // firebase_api_key, + // vapid_key, + // ) + // .await?; let new_token = toml::to_string(®istration)?; fs::write(token_path, new_token)?; registration diff --git a/src/common/instance.rs b/src/common/instance.rs index 30a028f..f3ecfc6 100644 --- a/src/common/instance.rs +++ b/src/common/instance.rs @@ -435,7 +435,7 @@ impl NeoInstance { loop { let noti: Option = pn.borrow_and_update().clone(); if let Some(noti) = noti { - if noti.message.contains("MOTION") { + if noti.message.contains("Motion Alert from") { log::info!( "{thread_name}::{stream:?}: Push Notification Recieved" );