Compare commits
113 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7a292c429a | |||
| 095d2cea86 | |||
| 6eea194d52 | |||
| 4f7cc49b63 | |||
| 1d444684f7 | |||
| bc3e3b1e13 | |||
| fe68694932 | |||
| 58b55ef433 | |||
| cdcf80ab9a | |||
| 7360bf96f8 | |||
| 61f5559370 | |||
| f973a819b6 | |||
| 8506a231dd | |||
| 85c93ee01d | |||
| 4314a24e78 | |||
| 0256329f65 | |||
| 20b2aab209 | |||
| 69a4a2c07f | |||
| 276ff68512 | |||
| 97fe80bca1 | |||
| 37934b3af8 | |||
| 96743e26e2 | |||
| 2decee83e9 | |||
| fa6c8cdce9 | |||
| ebdbb52f0d | |||
| 09aed3181e | |||
| 34f33ff038 | |||
| 0f217a6279 | |||
| 0c135844a4 | |||
| c479cbd687 | |||
| 768a259f02 | |||
| 373a98c26c | |||
| 5005e56881 | |||
| 3aaef7ab11 | |||
| 4479126500 | |||
| a6331d50b8 | |||
| 1844cddcc0 | |||
| 7120e1d5b9 | |||
| d303dfbd0d | |||
| f60420afa5 | |||
| 480ea3bd82 | |||
| 23d3166c2d | |||
| f5c5043896 | |||
| 8b8d281f8a | |||
| 5b4bf87506 | |||
| aa6383c1cf | |||
| be9d43f8cc | |||
| 319de09c35 | |||
| bcbe2614ab | |||
| c5be90cd60 | |||
| 88bf1f7cf0 | |||
| a5a6f121bd | |||
| 632760cfb9 | |||
| f394ddc5a6 | |||
| de62727dc6 | |||
| 46d9367670 | |||
| 09a9620f8e | |||
| e6898cc9f7 | |||
| 3bc50dcf26 | |||
| ac2a3cdd9f | |||
| ff886efd78 | |||
| 2719ab3301 | |||
| dfacc05749 | |||
| a0d55482cc | |||
| 5655fa7c4a | |||
| ec9c4c9dd4 | |||
| 4dcc021f73 | |||
| 84b742ee6e | |||
| 9023de6509 | |||
| 63464fdc59 | |||
| 29b7d0ed7a | |||
| cd4b65d9cc | |||
| 6660313200 | |||
| 24e2da9fd3 | |||
| 9315e5798c | |||
| b34de07fe1 | |||
| d5b45ecb39 | |||
| 820da6db1b | |||
| 5d1d12522e | |||
| 3f14151feb | |||
| 0c7e8c1dff | |||
| 1ea5ede442 | |||
| 5a8ad6b40f | |||
| adcd17deae | |||
| eab230e796 | |||
| d02b9a2e76 | |||
| fb8bb33965 | |||
| 99893a1272 | |||
| 4365d14923 | |||
| f243e2243d | |||
| e5f1b21303 | |||
| 3f5ae51a41 | |||
| bd74931ecd | |||
| c1a970ae3c | |||
| 5805c25408 | |||
| 02019762e0 | |||
| 74423b6207 | |||
| 705ef90e98 | |||
| 7357435ee1 | |||
| 0ea72259f6 | |||
| 84af98b5aa | |||
| 90aa3fda31 | |||
| c15c05a64e | |||
| 94159e8cad | |||
| f47dff6ca8 | |||
| 72eb15543a | |||
| e151c721c4 | |||
| ebb40edd0e | |||
| 6916977a47 | |||
| 470f3455f7 | |||
| 142cdfab1c | |||
| fab7ac52f2 | |||
| 22e729289d |
34 changed files with 6995 additions and 548 deletions
8
.vscode/settings.json
vendored
Normal file
8
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"files.insertFinalNewline": true,
|
||||||
|
"rust-analyzer.cargo.features": "all",
|
||||||
|
"rust-analyzer.imports.granularity.enforce": true,
|
||||||
|
"rust-analyzer.imports.granularity.group": "module",
|
||||||
|
"rust-analyzer.imports.group.enable": true,
|
||||||
|
"evenBetterToml.formatter.columnWidth": 100,
|
||||||
|
}
|
||||||
139
CHANGELOG.md
139
CHANGELOG.md
|
|
@ -4,6 +4,7 @@ All notable changes to this project will be documented in this file.
|
||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
||||||
|
|
||||||
Procedure when bumping the version number:
|
Procedure when bumping the version number:
|
||||||
|
|
||||||
1. Update dependencies in a separate commit
|
1. Update dependencies in a separate commit
|
||||||
2. Set version number in `Cargo.toml`
|
2. Set version number in `Cargo.toml`
|
||||||
3. Add new section in this changelog
|
3. Add new section in this changelog
|
||||||
|
|
@ -13,13 +14,147 @@ Procedure when bumping the version number:
|
||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
## v0.6.1 - 2025-02-23
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated set of emoji names
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Nick hue hashing algorithm in some edge cases
|
||||||
|
|
||||||
|
## v0.6.0 - 2025-02-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `api::Time::from_timestamp`
|
||||||
|
- `api::Time::as_timestamp`
|
||||||
|
- `bot::botrulez::full_help`
|
||||||
|
- `bot::botrulez::ping`
|
||||||
|
- `bot::botrulez::short_help`
|
||||||
|
- `bot::botrulez::uptime`
|
||||||
|
- `bot::botrulez::format_relative_time`
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **(breaking)** Switched to `jiff` from `time`
|
||||||
|
- **(breaking)** `api::Time` contents are now an `i64`
|
||||||
|
- **(breaking)** Bumped `tokio-tungstenite` dependency from `0.18` to `0.24`. If
|
||||||
|
this causes a panic while using euphoxide, consider following the steps
|
||||||
|
mentioned in the [tokio-tungstenite README]. If I'm reading the [rustls docs]
|
||||||
|
correctly, it is on the users of the libraries to set the required features.
|
||||||
|
- `bot::botrulez::format_duration` now no longer mentions "since" or "ago", but
|
||||||
|
instead has a sign (`-`) if the duration is negative.
|
||||||
|
|
||||||
|
[tokio-tungstenite README]: https://github.com/snapview/tokio-tungstenite?tab=readme-ov-file#features
|
||||||
|
[rustls docs]: https://docs.rs/rustls/0.23.19/rustls/crypto/struct.CryptoProvider.html#using-the-per-process-default-cryptoprovider
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- `api::Time::new`
|
||||||
|
|
||||||
|
## v0.5.1 - 2024-05-20
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `Emoji::load_from_json`
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated set of emoji names
|
||||||
|
|
||||||
|
## v0.5.0 - 2023-12-27
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **(breaking)** `bot::instance::ServerConfig::default` now points to `euphoria.leet.nu`
|
||||||
|
- **(breaking)** Bumped `cookie` dependency from `0.17` to `0.18`
|
||||||
|
- **(breaking)** Bumped `tokio-tungstenite` dependency from `0.18` to `0.21`
|
||||||
|
- Updated set of emoji names
|
||||||
|
- Documentation now references `euphoria.leet.nu` instead of `euphoria.io`
|
||||||
|
|
||||||
|
## v0.4.0 - 2023-05-14
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `bot::botrulez::Uptime` now implements `bot::command::Command`
|
||||||
|
- `bot::command::parse_prefix_initiated`
|
||||||
|
- `bot::commands::Commands::fallthrough`
|
||||||
|
- `bot::commands::Commands::set_fallthrough`
|
||||||
|
- `conn::Error::ConnectionTimedOut`
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **(breaking)** `bot::command::ClapCommand::execute` now returns a `Result<bool, E>` instead of a `Result<(), E>`
|
||||||
|
- **(breaking)** `bot::command::Command::execute` now returns a `Result<bool, E>` instead of a `Result<(), E>`
|
||||||
|
- **(breaking)** `bot::commands::Commands::handle_packet` now returns a `Result<bool, E>` instead of a `Result<(), E>`
|
||||||
|
- **(breaking)** `bot::instance::Snapshot` renamed to `ConnSnapshot`
|
||||||
|
- **(breaking)** `conn::Conn::connect` now returns `conn::Result`
|
||||||
|
- `bot::instance::Instance` now implements `Clone`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **(breaking)** Deserializing empty events and replies by turning unit structs into empty structs
|
||||||
|
- `phone` and `mobile` emoji
|
||||||
|
- Instances getting stuck in "Connecting" state
|
||||||
|
- Euph errors always turning into `conn::Error`s
|
||||||
|
|
||||||
|
## v0.3.1 - 2023-02-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `bot::botrulez::FullHelp` now implements `bot::command::Command`
|
||||||
|
- `bot::botrulez::Ping` now implements `bot::command::Command`
|
||||||
|
- `bot::botrulez::ShortHelp` now implements `bot::command::Command`
|
||||||
|
- `bot::instances::Instances::is_from_known_instance`
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Instances log to target `euphoxide::live::<name>`
|
||||||
|
- Instances stay connected if auth is required but no password is set
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- `!uptime` minute count
|
||||||
|
- Instance reconnecting after encountering a 404 (it now stops and logs an error)
|
||||||
|
- Instance taking too long to stop when stopped during reconnect delay
|
||||||
|
|
||||||
|
## v0.3.0 - 2023-02-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `bot` feature
|
||||||
|
- `bot` module (enable the `bot` feature to use)
|
||||||
|
- `Emoji` for finding, replacing and removing colon-delimited emoji in text
|
||||||
|
- `api::Time::new`
|
||||||
|
- `nick::hue`
|
||||||
|
- `nick::mention`
|
||||||
|
- `nick::normalize`
|
||||||
|
- Debug logging using the `log` crate
|
||||||
|
- `testbot_instance` example using the new `bot::instance::Instance`
|
||||||
|
- VSCode project settings
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **(breaking)** `conn` module redesigned and rewritten
|
||||||
|
- **(breaking)** `nick_hue` moved to `nick::hue_without_removing_emoji`
|
||||||
|
- Renamed `testbot` example to `testbot_manual`
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- **(breaking)** `connect` (see `conn::Conn::connect`)
|
||||||
|
- **(breaking)** `wrap` (see `conn::Conn::wrap`)
|
||||||
|
|
||||||
## v0.2.0 - 2022-12-10
|
## v0.2.0 - 2022-12-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- `euphoxide::connect`
|
|
||||||
|
- `connect`
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Updated dependencies in backwards-incompatible way
|
|
||||||
|
- **(breaking)** Updated dependencies
|
||||||
|
|
||||||
## v0.1.0 - 2022-10-23
|
## v0.1.0 - 2022-10-23
|
||||||
|
|
||||||
|
|
|
||||||
68
Cargo.toml
68
Cargo.toml
|
|
@ -1,22 +1,64 @@
|
||||||
[package]
|
[package]
|
||||||
name = "euphoxide"
|
name = "euphoxide"
|
||||||
version = "0.2.0"
|
version = "0.6.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
bot = ["dep:async-trait", "dep:clap", "dep:cookie"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "1.0.149", features = ["derive"] }
|
async-trait = { version = "0.1.86", optional = true }
|
||||||
serde_json = "1.0.89"
|
caseless = "0.2.2"
|
||||||
time = { version = "0.3.17", features = ["serde"] }
|
cookie = { version = "0.18.1", optional = true }
|
||||||
tokio = { version = "1.23.0", features = ["time", "sync", "macros", "rt"] }
|
futures-util = { version = "0.3.31", default-features = false, features = ["sink"] }
|
||||||
|
jiff = { version = "0.2.1", features = ["serde"] }
|
||||||
|
log = "0.4.25"
|
||||||
|
serde = { version = "1.0.218", features = ["derive"] }
|
||||||
|
serde_json = "1.0.139"
|
||||||
|
tokio = { version = "1.43.0", features = ["time", "sync", "macros", "rt"] }
|
||||||
|
tokio-stream = "0.1.17"
|
||||||
|
tokio-tungstenite = { version = "0.26.2", features = ["rustls-tls-native-roots"] }
|
||||||
|
unicode-normalization = "0.1.24"
|
||||||
|
|
||||||
[dependencies.futures]
|
[dependencies.clap]
|
||||||
version = "0.3.25"
|
version = "4.5.30"
|
||||||
|
optional = true
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["std"]
|
features = ["std", "derive", "deprecated"]
|
||||||
|
|
||||||
[dependencies.tokio-tungstenite]
|
|
||||||
version = "0.18.0"
|
|
||||||
features = ["rustls-tls-native-roots"]
|
|
||||||
|
|
||||||
[dev-dependencies] # For example bot
|
[dev-dependencies] # For example bot
|
||||||
tokio = { version = "1.23.0", features = ["rt-multi-thread"] }
|
rustls = "0.23.23"
|
||||||
|
tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "testbot_instance"
|
||||||
|
required-features = ["bot"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "testbot_instances"
|
||||||
|
required-features = ["bot"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "testbot_commands"
|
||||||
|
required-features = ["bot"]
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
rust.unsafe_code = { level = "forbid", priority = 1 }
|
||||||
|
# Lint groups
|
||||||
|
rust.deprecated_safe = "warn"
|
||||||
|
rust.future_incompatible = "warn"
|
||||||
|
rust.keyword_idents = "warn"
|
||||||
|
rust.rust_2018_idioms = "warn"
|
||||||
|
rust.unused = "warn"
|
||||||
|
# Individual lints
|
||||||
|
rust.non_local_definitions = "warn"
|
||||||
|
rust.redundant_imports = "warn"
|
||||||
|
rust.redundant_lifetimes = "warn"
|
||||||
|
rust.single_use_lifetimes = "warn"
|
||||||
|
rust.unit_bindings = "warn"
|
||||||
|
rust.unnameable_types = "warn"
|
||||||
|
rust.unused_import_braces = "warn"
|
||||||
|
rust.unused_lifetimes = "warn"
|
||||||
|
rust.unused_qualifications = "warn"
|
||||||
|
# Clippy
|
||||||
|
clippy.use_self = "warn"
|
||||||
|
|
|
||||||
|
|
@ -1,145 +0,0 @@
|
||||||
use std::error::Error;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use euphoxide::api::{Data, Nick, Send};
|
|
||||||
|
|
||||||
const URI: &str = "wss://euphoria.io/room/test/ws";
|
|
||||||
const NICK: &str = "TestBot";
|
|
||||||
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
|
|
||||||
|
|
||||||
fn format_delta(delta: Duration) -> String {
|
|
||||||
const MINUTE: u64 = 60;
|
|
||||||
const HOUR: u64 = MINUTE * 60;
|
|
||||||
const DAY: u64 = HOUR * 24;
|
|
||||||
|
|
||||||
let mut seconds = delta.as_secs();
|
|
||||||
let mut parts = vec![];
|
|
||||||
|
|
||||||
let days = seconds / DAY;
|
|
||||||
if days > 0 {
|
|
||||||
parts.push(format!("{days}d"));
|
|
||||||
seconds -= days * DAY;
|
|
||||||
}
|
|
||||||
|
|
||||||
let hours = seconds / HOUR;
|
|
||||||
if hours > 0 {
|
|
||||||
parts.push(format!("{hours}h"));
|
|
||||||
seconds -= hours * HOUR;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mins = seconds / MINUTE;
|
|
||||||
if mins > 0 {
|
|
||||||
parts.push(format!("{mins}m"));
|
|
||||||
seconds -= mins * MINUTE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if parts.is_empty() || seconds > 0 {
|
|
||||||
parts.push(format!("{seconds}s"));
|
|
||||||
}
|
|
||||||
|
|
||||||
parts.join(" ")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() -> Result<(), Box<dyn Error>> {
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
let (ws, _) = tokio_tungstenite::connect_async(URI).await?;
|
|
||||||
let (tx, mut rx) = euphoxide::conn::wrap(ws, Duration::from_secs(30));
|
|
||||||
while let Some(packet) = rx.recv().await {
|
|
||||||
let data = match packet.content {
|
|
||||||
Ok(data) => data,
|
|
||||||
Err(err) => {
|
|
||||||
println!("Error for {}: {err}", packet.r#type);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
match data {
|
|
||||||
Data::HelloEvent(event) => println!("Connected with id {}", event.session.id),
|
|
||||||
Data::SnapshotEvent(event) => {
|
|
||||||
for session in event.listing {
|
|
||||||
println!("{:?} ({}) is already here", session.name, session.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Here, a new task is spawned so the main event loop can
|
|
||||||
// continue running immediately instead of waiting for a reply
|
|
||||||
// from the server.
|
|
||||||
let tx_clone = tx.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
// Awaiting the future returned by the send command lets you
|
|
||||||
// (type-safely) access the server's reply.
|
|
||||||
let reply = tx_clone
|
|
||||||
.send(Nick {
|
|
||||||
name: NICK.to_string(),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
match reply {
|
|
||||||
Ok(reply) => println!("Set nick to {:?}", reply.to),
|
|
||||||
Err(err) => println!("Failed to set nick: {err}"),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Data::BounceEvent(_) => {
|
|
||||||
println!("Received bounce event, stopping");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Data::DisconnectEvent(_) => {
|
|
||||||
println!("Received disconnect event, stopping");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Data::JoinEvent(event) => println!("{:?} ({}) joined", event.0.name, event.0.id),
|
|
||||||
Data::PartEvent(event) => println!("{:?} ({}) left", event.0.name, event.0.id),
|
|
||||||
Data::NickEvent(event) => println!(
|
|
||||||
"{:?} ({}) is now known as {:?}",
|
|
||||||
event.from, event.id, event.to
|
|
||||||
),
|
|
||||||
Data::SendEvent(event) => {
|
|
||||||
println!("Message {} was just sent", event.0.id.0);
|
|
||||||
|
|
||||||
let content = event.0.content.trim();
|
|
||||||
let mut reply = None;
|
|
||||||
|
|
||||||
if content == "!ping" || content == format!("!ping @{NICK}") {
|
|
||||||
reply = Some("Pong!".to_string());
|
|
||||||
} else if content == format!("!help @{NICK}") {
|
|
||||||
reply = Some(HELP.to_string());
|
|
||||||
} else if content == format!("!uptime @{NICK}") {
|
|
||||||
let delta = Instant::now().duration_since(start);
|
|
||||||
reply = Some(format!("/me has been up for {}", format_delta(delta)));
|
|
||||||
} else if content == "!test" {
|
|
||||||
reply = Some("Test successful!".to_string());
|
|
||||||
} else if content == format!("!kill @{NICK}") {
|
|
||||||
println!(
|
|
||||||
"I was killed by {:?} ({})",
|
|
||||||
event.0.sender.name, event.0.sender.id
|
|
||||||
);
|
|
||||||
// Awaiting the server reply in the main loop to ensure the
|
|
||||||
// message is sent before we exit the loop. Otherwise, there
|
|
||||||
// would be a race between sending the message and closing
|
|
||||||
// the connection as the send function can return before the
|
|
||||||
// message has actually been sent.
|
|
||||||
let _ = tx
|
|
||||||
.send(Send {
|
|
||||||
content: "/me dies".to_string(),
|
|
||||||
parent: Some(event.0.id),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(reply) = reply {
|
|
||||||
// If you are not interested in the result, you can just
|
|
||||||
// throw away the future returned by the send function.
|
|
||||||
println!("Sending reply...");
|
|
||||||
let _ = tx.send(Send {
|
|
||||||
content: reply,
|
|
||||||
parent: Some(event.0.id),
|
|
||||||
});
|
|
||||||
println!("Reply sent!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
150
examples/testbot_commands.rs
Normal file
150
examples/testbot_commands.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
// TODO Add description
|
||||||
|
// TODO Clean up and unify test bots
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::Parser;
|
||||||
|
use euphoxide::api::Message;
|
||||||
|
use euphoxide::bot::botrulez::{FullHelp, HasDescriptions, HasStartTime, Ping, ShortHelp, Uptime};
|
||||||
|
use euphoxide::bot::command::{Clap, ClapCommand, Context, General, Global, Hidden, Specific};
|
||||||
|
use euphoxide::bot::commands::Commands;
|
||||||
|
use euphoxide::bot::instance::{Event, ServerConfig};
|
||||||
|
use euphoxide::bot::instances::Instances;
|
||||||
|
use euphoxide::conn;
|
||||||
|
use jiff::Timestamp;
|
||||||
|
use log::error;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
|
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
|
||||||
|
|
||||||
|
/// Kill this bot.
|
||||||
|
#[derive(Parser)]
|
||||||
|
struct KillArgs;
|
||||||
|
|
||||||
|
struct Kill;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ClapCommand<Bot, conn::Error> for Kill {
|
||||||
|
type Args = KillArgs;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
_args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut Bot,
|
||||||
|
) -> Result<bool, conn::Error> {
|
||||||
|
bot.stop = true;
|
||||||
|
ctx.reply(msg.id, "/me dies").await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Do some testing.
|
||||||
|
#[derive(Parser)]
|
||||||
|
struct TestArgs {
|
||||||
|
/// How much testing to do.
|
||||||
|
#[arg(default_value_t = 1)]
|
||||||
|
amount: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Test;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ClapCommand<Bot, conn::Error> for Test {
|
||||||
|
type Args = TestArgs;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
_bot: &mut Bot,
|
||||||
|
) -> Result<bool, conn::Error> {
|
||||||
|
let content = if args.amount == 1 {
|
||||||
|
format!("/me did {} test", args.amount)
|
||||||
|
} else {
|
||||||
|
format!("/me did {} tests", args.amount)
|
||||||
|
};
|
||||||
|
ctx.reply(msg.id, content).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Bot {
|
||||||
|
commands: Arc<Commands<Self, conn::Error>>,
|
||||||
|
start_time: Timestamp,
|
||||||
|
stop: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasDescriptions for Bot {
|
||||||
|
fn descriptions(&self, ctx: &Context) -> Vec<String> {
|
||||||
|
self.commands.descriptions(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasStartTime for Bot {
|
||||||
|
fn start_time(&self) -> Timestamp {
|
||||||
|
self.start_time
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// https://github.com/snapview/tokio-tungstenite/issues/353#issuecomment-2455247837
|
||||||
|
rustls::crypto::aws_lc_rs::default_provider()
|
||||||
|
.install_default()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||||
|
let mut instances = Instances::new(ServerConfig::default());
|
||||||
|
|
||||||
|
let mut cmds = Commands::new();
|
||||||
|
cmds.add(Hidden(General::new("ping", Clap(Ping::default()))));
|
||||||
|
cmds.add(Specific::new("ping", Clap(Ping::default())));
|
||||||
|
cmds.add(Hidden(General::new("help", Clap(ShortHelp::new(HELP)))));
|
||||||
|
cmds.add(Specific::new("help", Clap(FullHelp::new(HELP, ""))));
|
||||||
|
cmds.add(Specific::new("uptime", Clap(Uptime)));
|
||||||
|
cmds.add(Specific::new("kill", Clap(Kill)));
|
||||||
|
cmds.add(Global::new("test", Clap(Test)));
|
||||||
|
let cmds = Arc::new(cmds);
|
||||||
|
|
||||||
|
let mut bot = Bot {
|
||||||
|
commands: cmds.clone(),
|
||||||
|
start_time: Timestamp::now(),
|
||||||
|
stop: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
for room in ["test", "test2", "testing"] {
|
||||||
|
let tx_clone = tx.clone();
|
||||||
|
let instance = instances
|
||||||
|
.server_config()
|
||||||
|
.clone()
|
||||||
|
.room(room)
|
||||||
|
.username(Some("TestBot"))
|
||||||
|
.build(move |e| {
|
||||||
|
let _ = tx_clone.send(e);
|
||||||
|
});
|
||||||
|
instances.add(instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(event) = rx.recv().await {
|
||||||
|
instances.purge();
|
||||||
|
if instances.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Event::Packet(config, packet, snapshot) = event {
|
||||||
|
let result = cmds
|
||||||
|
.handle_packet(&config, &packet, &snapshot, &mut bot)
|
||||||
|
.await;
|
||||||
|
if let Err(err) = result {
|
||||||
|
error!("{err}");
|
||||||
|
}
|
||||||
|
if bot.stop {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
146
examples/testbot_instance.rs
Normal file
146
examples/testbot_instance.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
//! Similar to the `testbot_manual` example, but using [`Instance`] to connect
|
||||||
|
//! to the room (and to reconnect).
|
||||||
|
|
||||||
|
use euphoxide::api::packet::ParsedPacket;
|
||||||
|
use euphoxide::api::{Data, Nick, Send};
|
||||||
|
use euphoxide::bot::botrulez;
|
||||||
|
use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig};
|
||||||
|
use jiff::Timestamp;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
|
const NICK: &str = "TestBot";
|
||||||
|
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
|
||||||
|
|
||||||
|
async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> {
|
||||||
|
let data = match packet.content {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(err) => {
|
||||||
|
println!("Error for {}: {err}", packet.r#type);
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match data {
|
||||||
|
Data::HelloEvent(ev) => println!("Connected with id {}", ev.session.id),
|
||||||
|
Data::SnapshotEvent(ev) => {
|
||||||
|
for session in ev.listing {
|
||||||
|
println!("{:?} ({}) is already here", session.name, session.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Here, a new task is spawned so the main event loop can
|
||||||
|
// continue running immediately instead of waiting for a reply
|
||||||
|
// from the server.
|
||||||
|
//
|
||||||
|
// We only need to do this because we want to log the result of
|
||||||
|
// the nick command. Otherwise, we could've just called
|
||||||
|
// tx.send() synchronously and ignored the returned Future.
|
||||||
|
let conn_tx_clone = snapshot.conn_tx.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Awaiting the future returned by the send command lets you
|
||||||
|
// (type-safely) access the server's reply.
|
||||||
|
let reply = conn_tx_clone
|
||||||
|
.send(Nick {
|
||||||
|
name: NICK.to_string(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match reply {
|
||||||
|
Ok(reply) => println!("Set nick to {:?}", reply.to),
|
||||||
|
Err(err) => println!("Failed to set nick: {err}"),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Data::BounceEvent(_) => {
|
||||||
|
println!("Received bounce event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::DisconnectEvent(_) => {
|
||||||
|
println!("Received disconnect event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::JoinEvent(event) => println!("{:?} ({}) joined", event.0.name, event.0.id),
|
||||||
|
Data::PartEvent(event) => println!("{:?} ({}) left", event.0.name, event.0.id),
|
||||||
|
Data::NickEvent(event) => println!(
|
||||||
|
"{:?} ({}) is now known as {:?}",
|
||||||
|
event.from, event.id, event.to
|
||||||
|
),
|
||||||
|
Data::SendEvent(event) => {
|
||||||
|
println!("Message {} was just sent", event.0.id.0);
|
||||||
|
|
||||||
|
let content = event.0.content.trim();
|
||||||
|
let mut reply = None;
|
||||||
|
|
||||||
|
if content == "!ping" || content == format!("!ping @{NICK}") {
|
||||||
|
reply = Some("Pong!".to_string());
|
||||||
|
} else if content == format!("!help @{NICK}") {
|
||||||
|
reply = Some(HELP.to_string());
|
||||||
|
} else if content == format!("!uptime @{NICK}") {
|
||||||
|
if let Some(joined) = snapshot.state.joined() {
|
||||||
|
let delta = Timestamp::now() - joined.since;
|
||||||
|
reply = Some(format!(
|
||||||
|
"/me has been up for {}",
|
||||||
|
botrulez::format_duration(delta)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if content == "!test" {
|
||||||
|
reply = Some("Test successful!".to_string());
|
||||||
|
} else if content == format!("!kill @{NICK}") {
|
||||||
|
println!(
|
||||||
|
"I was killed by {:?} ({})",
|
||||||
|
event.0.sender.name, event.0.sender.id
|
||||||
|
);
|
||||||
|
// Awaiting the server reply in the main loop to ensure the
|
||||||
|
// message is sent before we exit the loop. Otherwise, there
|
||||||
|
// would be a race between sending the message and closing
|
||||||
|
// the connection as the send function can return before the
|
||||||
|
// message has actually been sent.
|
||||||
|
let _ = snapshot
|
||||||
|
.conn_tx
|
||||||
|
.send(Send {
|
||||||
|
content: "/me dies".to_string(),
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(reply) = reply {
|
||||||
|
// If you are not interested in the result, you can just
|
||||||
|
// throw away the future returned by the send function.
|
||||||
|
println!("Sending reply...");
|
||||||
|
snapshot.conn_tx.send_only(Send {
|
||||||
|
content: reply,
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
});
|
||||||
|
println!("Reply sent!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// https://github.com/snapview/tokio-tungstenite/issues/353#issuecomment-2455247837
|
||||||
|
rustls::crypto::aws_lc_rs::default_provider()
|
||||||
|
.install_default()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||||
|
|
||||||
|
let _instance = ServerConfig::default()
|
||||||
|
.room("test")
|
||||||
|
.username(Some("TestBot"))
|
||||||
|
.build(move |e| {
|
||||||
|
let _ = tx.send(e);
|
||||||
|
});
|
||||||
|
|
||||||
|
while let Some(event) = rx.recv().await {
|
||||||
|
if let Event::Packet(_config, packet, snapshot) = event {
|
||||||
|
if on_packet(packet, snapshot).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
159
examples/testbot_instances.rs
Normal file
159
examples/testbot_instances.rs
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
//! Similar to the `testbot_manual` example, but using [`Instance`] to connect
|
||||||
|
//! to the room (and to reconnect).
|
||||||
|
|
||||||
|
use euphoxide::api::packet::ParsedPacket;
|
||||||
|
use euphoxide::api::{Data, Nick, Send};
|
||||||
|
use euphoxide::bot::botrulez;
|
||||||
|
use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig};
|
||||||
|
use euphoxide::bot::instances::Instances;
|
||||||
|
use jiff::Timestamp;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
|
const NICK: &str = "TestBot";
|
||||||
|
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
|
||||||
|
|
||||||
|
async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> {
|
||||||
|
let data = match packet.content {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(err) => {
|
||||||
|
println!("Error for {}: {err}", packet.r#type);
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match data {
|
||||||
|
Data::HelloEvent(ev) => println!("Connected with id {}", ev.session.id),
|
||||||
|
Data::SnapshotEvent(ev) => {
|
||||||
|
for session in ev.listing {
|
||||||
|
println!("{:?} ({}) is already here", session.name, session.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Here, a new task is spawned so the main event loop can
|
||||||
|
// continue running immediately instead of waiting for a reply
|
||||||
|
// from the server.
|
||||||
|
//
|
||||||
|
// We only need to do this because we want to log the result of
|
||||||
|
// the nick command. Otherwise, we could've just called
|
||||||
|
// tx.send() synchronously and ignored the returned Future.
|
||||||
|
let conn_tx_clone = snapshot.conn_tx.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Awaiting the future returned by the send command lets you
|
||||||
|
// (type-safely) access the server's reply.
|
||||||
|
let reply = conn_tx_clone
|
||||||
|
.send(Nick {
|
||||||
|
name: NICK.to_string(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match reply {
|
||||||
|
Ok(reply) => println!("Set nick to {:?}", reply.to),
|
||||||
|
Err(err) => println!("Failed to set nick: {err}"),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Data::BounceEvent(_) => {
|
||||||
|
println!("Received bounce event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::DisconnectEvent(_) => {
|
||||||
|
println!("Received disconnect event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::JoinEvent(event) => println!("{:?} ({}) joined", event.0.name, event.0.id),
|
||||||
|
Data::PartEvent(event) => println!("{:?} ({}) left", event.0.name, event.0.id),
|
||||||
|
Data::NickEvent(event) => println!(
|
||||||
|
"{:?} ({}) is now known as {:?}",
|
||||||
|
event.from, event.id, event.to
|
||||||
|
),
|
||||||
|
Data::SendEvent(event) => {
|
||||||
|
println!("Message {} was just sent", event.0.id.0);
|
||||||
|
|
||||||
|
let content = event.0.content.trim();
|
||||||
|
let mut reply = None;
|
||||||
|
|
||||||
|
if content == "!ping" || content == format!("!ping @{NICK}") {
|
||||||
|
reply = Some("Pong!".to_string());
|
||||||
|
} else if content == format!("!help @{NICK}") {
|
||||||
|
reply = Some(HELP.to_string());
|
||||||
|
} else if content == format!("!uptime @{NICK}") {
|
||||||
|
if let Some(joined) = snapshot.state.joined() {
|
||||||
|
let delta = Timestamp::now() - joined.since;
|
||||||
|
reply = Some(format!(
|
||||||
|
"/me has been up for {}",
|
||||||
|
botrulez::format_duration(delta)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if content == "!test" {
|
||||||
|
reply = Some("Test successful!".to_string());
|
||||||
|
} else if content == format!("!kill @{NICK}") {
|
||||||
|
println!(
|
||||||
|
"I was killed by {:?} ({})",
|
||||||
|
event.0.sender.name, event.0.sender.id
|
||||||
|
);
|
||||||
|
// Awaiting the server reply in the main loop to ensure the
|
||||||
|
// message is sent before we exit the loop. Otherwise, there
|
||||||
|
// would be a race between sending the message and closing
|
||||||
|
// the connection as the send function can return before the
|
||||||
|
// message has actually been sent.
|
||||||
|
let _ = snapshot
|
||||||
|
.conn_tx
|
||||||
|
.send(Send {
|
||||||
|
content: "/me dies".to_string(),
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(reply) = reply {
|
||||||
|
// If you are not interested in the result, you can just
|
||||||
|
// throw away the future returned by the send function.
|
||||||
|
println!("Sending reply...");
|
||||||
|
snapshot.conn_tx.send_only(Send {
|
||||||
|
content: reply,
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
});
|
||||||
|
println!("Reply sent!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// https://github.com/snapview/tokio-tungstenite/issues/353#issuecomment-2455247837
|
||||||
|
rustls::crypto::aws_lc_rs::default_provider()
|
||||||
|
.install_default()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||||
|
let mut instances = Instances::new(ServerConfig::default());
|
||||||
|
|
||||||
|
for room in ["test", "test2", "testing"] {
|
||||||
|
let tx_clone = tx.clone();
|
||||||
|
let instance = instances
|
||||||
|
.server_config()
|
||||||
|
.clone()
|
||||||
|
.room(room)
|
||||||
|
.username(Some("TestBot"))
|
||||||
|
.build(move |e| {
|
||||||
|
let _ = tx_clone.send(e);
|
||||||
|
});
|
||||||
|
instances.add(instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(event) = rx.recv().await {
|
||||||
|
instances.purge();
|
||||||
|
if instances.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Event::Packet(_config, packet, snapshot) = event {
|
||||||
|
if on_packet(packet, snapshot).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
142
examples/testbot_manual.rs
Normal file
142
examples/testbot_manual.rs
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
//! A small bot that doesn't use the `bot` submodule. Meant to show how the main
|
||||||
|
//! parts of the API fit together.
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use euphoxide::api::packet::ParsedPacket;
|
||||||
|
use euphoxide::api::{Data, Nick, Send};
|
||||||
|
use euphoxide::bot::botrulez;
|
||||||
|
use euphoxide::conn::{Conn, ConnTx, State};
|
||||||
|
use jiff::Timestamp;
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
const DOMAIN: &str = "euphoria.leet.nu";
|
||||||
|
const ROOM: &str = "test";
|
||||||
|
const NICK: &str = "TestBot";
|
||||||
|
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
|
||||||
|
|
||||||
|
async fn on_packet(packet: ParsedPacket, conn_tx: &ConnTx, state: &State) -> Result<(), ()> {
|
||||||
|
let data = match packet.content {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(err) => {
|
||||||
|
println!("Error for {}: {err}", packet.r#type);
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match data {
|
||||||
|
Data::HelloEvent(event) => println!("Connected with id {}", event.session.id),
|
||||||
|
Data::SnapshotEvent(event) => {
|
||||||
|
for session in event.listing {
|
||||||
|
println!("{:?} ({}) is already here", session.name, session.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Here, a new task is spawned so the main event loop can
|
||||||
|
// continue running immediately instead of waiting for a reply
|
||||||
|
// from the server.
|
||||||
|
//
|
||||||
|
// We only need to do this because we want to log the result of
|
||||||
|
// the nick command. Otherwise, we could've just called
|
||||||
|
// tx.send() synchronously and ignored the returned Future.
|
||||||
|
let conn_tx_clone = conn_tx.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Awaiting the future returned by the send command lets you
|
||||||
|
// (type-safely) access the server's reply.
|
||||||
|
let reply = conn_tx_clone
|
||||||
|
.send(Nick {
|
||||||
|
name: NICK.to_string(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match reply {
|
||||||
|
Ok(reply) => println!("Set nick to {:?}", reply.to),
|
||||||
|
Err(err) => println!("Failed to set nick: {err}"),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Data::BounceEvent(_) => {
|
||||||
|
println!("Received bounce event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::DisconnectEvent(_) => {
|
||||||
|
println!("Received disconnect event, stopping");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Data::JoinEvent(event) => println!("{:?} ({}) joined", event.0.name, event.0.id),
|
||||||
|
Data::PartEvent(event) => println!("{:?} ({}) left", event.0.name, event.0.id),
|
||||||
|
Data::NickEvent(event) => println!(
|
||||||
|
"{:?} ({}) is now known as {:?}",
|
||||||
|
event.from, event.id, event.to
|
||||||
|
),
|
||||||
|
Data::SendEvent(event) => {
|
||||||
|
println!("Message {} was just sent", event.0.id.0);
|
||||||
|
|
||||||
|
let content = event.0.content.trim();
|
||||||
|
let mut reply = None;
|
||||||
|
|
||||||
|
if content == "!ping" || content == format!("!ping @{NICK}") {
|
||||||
|
reply = Some("Pong!".to_string());
|
||||||
|
} else if content == format!("!help @{NICK}") {
|
||||||
|
reply = Some(HELP.to_string());
|
||||||
|
} else if content == format!("!uptime @{NICK}") {
|
||||||
|
if let Some(joined) = state.joined() {
|
||||||
|
let delta = Timestamp::now() - joined.since;
|
||||||
|
reply = Some(format!(
|
||||||
|
"/me has been up for {}",
|
||||||
|
botrulez::format_duration(delta)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if content == "!test" {
|
||||||
|
reply = Some("Test successful!".to_string());
|
||||||
|
} else if content == format!("!kill @{NICK}") {
|
||||||
|
println!(
|
||||||
|
"I was killed by {:?} ({})",
|
||||||
|
event.0.sender.name, event.0.sender.id
|
||||||
|
);
|
||||||
|
// Awaiting the server reply in the main loop to ensure the
|
||||||
|
// message is sent before we exit the loop. Otherwise, there
|
||||||
|
// would be a race between sending the message and closing
|
||||||
|
// the connection as the send function can return before the
|
||||||
|
// message has actually been sent.
|
||||||
|
let _ = conn_tx
|
||||||
|
.send(Send {
|
||||||
|
content: "/me dies".to_string(),
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(reply) = reply {
|
||||||
|
// If you are not interested in the result, you can just
|
||||||
|
// throw away the future returned by the send function.
|
||||||
|
println!("Sending reply...");
|
||||||
|
conn_tx.send_only(Send {
|
||||||
|
content: reply,
|
||||||
|
parent: Some(event.0.id),
|
||||||
|
});
|
||||||
|
println!("Reply sent!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
// https://github.com/snapview/tokio-tungstenite/issues/353#issuecomment-2455247837
|
||||||
|
rustls::crypto::aws_lc_rs::default_provider()
|
||||||
|
.install_default()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (mut conn, _) = Conn::connect(DOMAIN, ROOM, false, None, TIMEOUT).await?;
|
||||||
|
|
||||||
|
while let Ok(packet) = conn.recv().await {
|
||||||
|
if on_packet(packet, conn.tx(), conn.state()).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
//! Models the euphoria API at <http://api.euphoria.io/>.
|
//! Models the [euphoria API][0].
|
||||||
|
//!
|
||||||
|
//! [0]: https://euphoria.leet.nu/heim/api
|
||||||
|
|
||||||
mod account_cmds;
|
mod account_cmds;
|
||||||
mod events;
|
mod events;
|
||||||
|
|
|
||||||
|
|
@ -56,7 +56,7 @@ pub struct ChangePassword {
|
||||||
|
|
||||||
/// Return the outcome of changing the password.
|
/// Return the outcome of changing the password.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ChangePasswordReply;
|
pub struct ChangePasswordReply {}
|
||||||
|
|
||||||
/// Attempt to log an anonymous session into an account.
|
/// Attempt to log an anonymous session into an account.
|
||||||
///
|
///
|
||||||
|
|
@ -99,11 +99,11 @@ pub struct LoginReply {
|
||||||
/// [`DisconnectEvent`](super::DisconnectEvent) shortly after. The next
|
/// [`DisconnectEvent`](super::DisconnectEvent) shortly after. The next
|
||||||
/// connection the client makes will be a logged out session.
|
/// connection the client makes will be a logged out session.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Logout;
|
pub struct Logout {}
|
||||||
|
|
||||||
/// Confirm a logout.
|
/// Confirm a logout.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct LogoutReply;
|
pub struct LogoutReply {}
|
||||||
|
|
||||||
/// Create a new account and logs into it.
|
/// Create a new account and logs into it.
|
||||||
///
|
///
|
||||||
|
|
@ -146,11 +146,11 @@ pub struct RegisterAccountReply {
|
||||||
/// An error will be returned if the account has no unverified email addresses
|
/// An error will be returned if the account has no unverified email addresses
|
||||||
/// associated with it.
|
/// associated with it.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ResendVerificationEmail;
|
pub struct ResendVerificationEmail {}
|
||||||
|
|
||||||
/// Indicate that a verification email has been sent.
|
/// Indicate that a verification email has been sent.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ResendVerificationEmailReply;
|
pub struct ResendVerificationEmailReply {}
|
||||||
|
|
||||||
/// Generate a password reset request.
|
/// Generate a password reset request.
|
||||||
///
|
///
|
||||||
|
|
@ -164,4 +164,4 @@ pub struct ResetPassword {
|
||||||
|
|
||||||
/// Confirm that the password reset is in progress.
|
/// Confirm that the password reset is in progress.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ResetPasswordReply;
|
pub struct ResetPasswordReply {}
|
||||||
|
|
|
||||||
|
|
@ -68,7 +68,7 @@ pub struct LoginEvent {
|
||||||
/// Sent to all sessions of an agent when that agent is logged out (except for
|
/// Sent to all sessions of an agent when that agent is logged out (except for
|
||||||
/// the session that issued the logout command).
|
/// the session that issued the logout command).
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct LogoutEvent;
|
pub struct LogoutEvent {}
|
||||||
|
|
||||||
/// Indicates some server-side event that impacts the presence of sessions in a
|
/// Indicates some server-side event that impacts the presence of sessions in a
|
||||||
/// room.
|
/// room.
|
||||||
|
|
|
||||||
|
|
@ -110,7 +110,7 @@ pub struct SendReply(pub Message);
|
||||||
|
|
||||||
/// Request a list of sessions currently joined in the room.
|
/// Request a list of sessions currently joined in the room.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Who;
|
pub struct Who {}
|
||||||
|
|
||||||
/// Lists the sessions currently joined in the room.
|
/// Lists the sessions currently joined in the room.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,9 @@ use std::num::ParseIntError;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::{error, fmt};
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
use jiff::Timestamp;
|
||||||
use serde::{de, ser, Deserialize, Serialize};
|
use serde::{de, ser, Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use time::OffsetDateTime;
|
|
||||||
|
|
||||||
/// Describes an account and its preferred name.
|
/// Describes an account and its preferred name.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
|
@ -243,7 +243,7 @@ pub enum PacketType {
|
||||||
impl fmt::Display for PacketType {
|
impl fmt::Display for PacketType {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match serde_json::to_value(self) {
|
match serde_json::to_value(self) {
|
||||||
Ok(Value::String(s)) => write!(f, "{}", s),
|
Ok(Value::String(s)) => write!(f, "{s}"),
|
||||||
_ => Err(fmt::Error),
|
_ => Err(fmt::Error),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -371,7 +371,7 @@ impl FromStr for Snowflake {
|
||||||
|
|
||||||
impl Serialize for Snowflake {
|
impl Serialize for Snowflake {
|
||||||
fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||||
format!("{}", self).serialize(serializer)
|
format!("{self}").serialize(serializer)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -403,11 +403,19 @@ impl<'de> Deserialize<'de> for Snowflake {
|
||||||
/// Time is specified as a signed 64-bit integer, giving the number of seconds
|
/// Time is specified as a signed 64-bit integer, giving the number of seconds
|
||||||
/// since the Unix Epoch.
|
/// since the Unix Epoch.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Time(#[serde(with = "time::serde::timestamp")] pub OffsetDateTime);
|
pub struct Time(pub i64);
|
||||||
|
|
||||||
impl Time {
|
impl Time {
|
||||||
|
pub fn from_timestamp(time: Timestamp) -> Self {
|
||||||
|
Self(time.as_second())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_timestamp(&self) -> Timestamp {
|
||||||
|
Timestamp::from_second(self.0).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn now() -> Self {
|
pub fn now() -> Self {
|
||||||
Self(OffsetDateTime::now_utc().replace_millisecond(0).unwrap())
|
Self::from_timestamp(Timestamp::now())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
7
src/bot.rs
Normal file
7
src/bot.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
//! Building blocks for bots.
|
||||||
|
|
||||||
|
pub mod botrulez;
|
||||||
|
pub mod command;
|
||||||
|
pub mod commands;
|
||||||
|
pub mod instance;
|
||||||
|
pub mod instances;
|
||||||
10
src/bot/botrulez.rs
Normal file
10
src/bot/botrulez.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
//! The main [botrulez](https://github.com/jedevc/botrulez) commands.
|
||||||
|
pub mod full_help;
|
||||||
|
pub mod ping;
|
||||||
|
pub mod short_help;
|
||||||
|
pub mod uptime;
|
||||||
|
|
||||||
|
pub use self::full_help::{FullHelp, HasDescriptions};
|
||||||
|
pub use self::ping::Ping;
|
||||||
|
pub use self::short_help::ShortHelp;
|
||||||
|
pub use self::uptime::{format_duration, format_relative_time, format_time, HasStartTime, Uptime};
|
||||||
93
src/bot/botrulez/full_help.rs
Normal file
93
src/bot/botrulez/full_help.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::bot::command::{ClapCommand, Command, Context};
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
pub struct FullHelp {
|
||||||
|
pub before: String,
|
||||||
|
pub after: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasDescriptions {
|
||||||
|
fn descriptions(&self, ctx: &Context) -> Vec<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FullHelp {
|
||||||
|
pub fn new<S1: ToString, S2: ToString>(before: S1, after: S2) -> Self {
|
||||||
|
Self {
|
||||||
|
before: before.to_string(),
|
||||||
|
after: after.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn formulate_reply<B: HasDescriptions>(&self, ctx: &Context, bot: &B) -> String {
|
||||||
|
let mut result = String::new();
|
||||||
|
|
||||||
|
if !self.before.is_empty() {
|
||||||
|
result.push_str(&self.before);
|
||||||
|
result.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
for description in bot.descriptions(ctx) {
|
||||||
|
result.push_str(&description);
|
||||||
|
result.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.after.is_empty() {
|
||||||
|
result.push_str(&self.after);
|
||||||
|
result.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> Command<B, E> for FullHelp
|
||||||
|
where
|
||||||
|
B: HasDescriptions + Send,
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
if arg.trim().is_empty() {
|
||||||
|
let reply = self.formulate_reply(ctx, bot);
|
||||||
|
ctx.reply(msg.id, reply).await?;
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show full bot help.
|
||||||
|
#[derive(Parser)]
|
||||||
|
pub struct Args {}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> ClapCommand<B, E> for FullHelp
|
||||||
|
where
|
||||||
|
B: HasDescriptions + Send,
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
type Args = Args;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
_args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
let reply = self.formulate_reply(ctx, bot);
|
||||||
|
ctx.reply(msg.id, reply).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
64
src/bot/botrulez/ping.rs
Normal file
64
src/bot/botrulez/ping.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::bot::command::{ClapCommand, Command, Context};
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
pub struct Ping(pub String);
|
||||||
|
|
||||||
|
impl Ping {
|
||||||
|
pub fn new<S: ToString>(reply: S) -> Self {
|
||||||
|
Self(reply.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Ping {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new("Pong!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> Command<B, E> for Ping
|
||||||
|
where
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
_bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
if arg.trim().is_empty() {
|
||||||
|
ctx.reply(msg.id, &self.0).await?;
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trigger a short reply.
|
||||||
|
#[derive(Parser)]
|
||||||
|
pub struct Args {}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> ClapCommand<B, E> for Ping
|
||||||
|
where
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
type Args = Args;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
_args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
_bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
ctx.reply(msg.id, &self.0).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
58
src/bot/botrulez/short_help.rs
Normal file
58
src/bot/botrulez/short_help.rs
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::bot::command::{ClapCommand, Command, Context};
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
pub struct ShortHelp(pub String);
|
||||||
|
|
||||||
|
impl ShortHelp {
|
||||||
|
pub fn new<S: ToString>(text: S) -> Self {
|
||||||
|
Self(text.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> Command<B, E> for ShortHelp
|
||||||
|
where
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
_bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
if arg.trim().is_empty() {
|
||||||
|
ctx.reply(msg.id, &self.0).await?;
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show short bot help.
|
||||||
|
#[derive(Parser)]
|
||||||
|
pub struct Args {}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> ClapCommand<B, E> for ShortHelp
|
||||||
|
where
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
type Args = Args;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
_args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
_bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
ctx.reply(msg.id, &self.0).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
133
src/bot/botrulez/uptime.rs
Normal file
133
src/bot/botrulez/uptime.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::Parser;
|
||||||
|
use jiff::{Span, Timestamp, Unit};
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::bot::command::{ClapCommand, Command, Context};
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
pub fn format_time(t: Timestamp) -> String {
|
||||||
|
t.strftime("%Y-%m-%d %H:%M:%S UTC").to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn format_relative_time(d: Span) -> String {
|
||||||
|
if d.is_positive() {
|
||||||
|
format!("in {}", format_duration(d.abs()))
|
||||||
|
} else {
|
||||||
|
format!("{} ago", format_duration(d.abs()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn format_duration(d: Span) -> String {
|
||||||
|
let total = d.abs().total(Unit::Second).unwrap() as i64;
|
||||||
|
let secs = total % 60;
|
||||||
|
let mins = (total / 60) % 60;
|
||||||
|
let hours = (total / 60 / 60) % 24;
|
||||||
|
let days = total / 60 / 60 / 24;
|
||||||
|
|
||||||
|
let mut segments = vec![];
|
||||||
|
if days > 0 {
|
||||||
|
segments.push(format!("{days}d"));
|
||||||
|
}
|
||||||
|
if hours > 0 {
|
||||||
|
segments.push(format!("{hours}h"));
|
||||||
|
}
|
||||||
|
if mins > 0 {
|
||||||
|
segments.push(format!("{mins}m"));
|
||||||
|
}
|
||||||
|
if secs > 0 {
|
||||||
|
segments.push(format!("{secs}s"));
|
||||||
|
}
|
||||||
|
if segments.is_empty() {
|
||||||
|
segments.push("0s".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let segments = segments.join(" ");
|
||||||
|
if d.is_positive() {
|
||||||
|
segments
|
||||||
|
} else {
|
||||||
|
format!("-{segments}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Uptime;
|
||||||
|
|
||||||
|
pub trait HasStartTime {
|
||||||
|
fn start_time(&self) -> Timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Uptime {
|
||||||
|
fn formulate_reply<B: HasStartTime>(&self, ctx: &Context, bot: &B, connected: bool) -> String {
|
||||||
|
let start = bot.start_time();
|
||||||
|
let now = Timestamp::now();
|
||||||
|
|
||||||
|
let mut reply = format!(
|
||||||
|
"/me has been up since {} ({})",
|
||||||
|
format_time(start),
|
||||||
|
format_relative_time(start - now),
|
||||||
|
);
|
||||||
|
|
||||||
|
if connected {
|
||||||
|
let since = ctx.joined.since;
|
||||||
|
reply.push_str(&format!(
|
||||||
|
", connected since {} ({})",
|
||||||
|
format_time(since),
|
||||||
|
format_relative_time(since - now),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
reply
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> Command<B, E> for Uptime
|
||||||
|
where
|
||||||
|
B: HasStartTime + Send,
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
if arg.trim().is_empty() {
|
||||||
|
let reply = self.formulate_reply(ctx, bot, false);
|
||||||
|
ctx.reply(msg.id, reply).await?;
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show how long the bot has been online.
|
||||||
|
#[derive(Parser)]
|
||||||
|
pub struct Args {
|
||||||
|
/// Show how long the bot has been connected without interruption.
|
||||||
|
#[arg(long, short)]
|
||||||
|
pub connected: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E> ClapCommand<B, E> for Uptime
|
||||||
|
where
|
||||||
|
B: HasStartTime + Send,
|
||||||
|
E: From<conn::Error>,
|
||||||
|
{
|
||||||
|
type Args = Args;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
let reply = self.formulate_reply(ctx, bot, args.connected);
|
||||||
|
ctx.reply(msg.id, reply).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
64
src/bot/command.rs
Normal file
64
src/bot/command.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
mod bang;
|
||||||
|
mod clap;
|
||||||
|
mod hidden;
|
||||||
|
mod prefixed;
|
||||||
|
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::api::{self, Message, MessageId};
|
||||||
|
use crate::conn::{self, ConnTx, Joined};
|
||||||
|
|
||||||
|
pub use self::bang::*;
|
||||||
|
pub use self::clap::*;
|
||||||
|
pub use self::hidden::*;
|
||||||
|
pub use self::prefixed::*;
|
||||||
|
|
||||||
|
use super::instance::InstanceConfig;
|
||||||
|
|
||||||
|
pub struct Context {
|
||||||
|
pub config: InstanceConfig,
|
||||||
|
pub conn_tx: ConnTx,
|
||||||
|
pub joined: Joined,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Context {
|
||||||
|
pub fn send<S: ToString>(&self, content: S) -> impl Future<Output = conn::Result<Message>> {
|
||||||
|
let cmd = api::Send {
|
||||||
|
content: content.to_string(),
|
||||||
|
parent: None,
|
||||||
|
};
|
||||||
|
let reply = self.conn_tx.send(cmd);
|
||||||
|
async move { reply.await.map(|r| r.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reply<S: ToString>(
|
||||||
|
&self,
|
||||||
|
parent: MessageId,
|
||||||
|
content: S,
|
||||||
|
) -> impl Future<Output = conn::Result<Message>> {
|
||||||
|
let cmd = api::Send {
|
||||||
|
content: content.to_string(),
|
||||||
|
parent: Some(parent),
|
||||||
|
};
|
||||||
|
let reply = self.conn_tx.send(cmd);
|
||||||
|
async move { reply.await.map(|r| r.0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Command<B, E> {
|
||||||
|
fn description(&self, ctx: &Context) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E>;
|
||||||
|
}
|
||||||
235
src/bot/command/bang.rs
Normal file
235
src/bot/command/bang.rs
Normal file
|
|
@ -0,0 +1,235 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::nick;
|
||||||
|
|
||||||
|
use super::{Command, Context};
|
||||||
|
|
||||||
|
// TODO Don't ignore leading whitespace?
|
||||||
|
// I'm not entirely happy with how commands handle whitespace, and on euphoria,
|
||||||
|
// prefixing commands with whitespace is traditionally used to not trigger them.
|
||||||
|
|
||||||
|
/// Parse leading whitespace followed by an prefix-initiated command.
|
||||||
|
///
|
||||||
|
/// Returns the command name and the remaining text with one leading whitespace
|
||||||
|
/// removed. The remaining text may be the empty string.
|
||||||
|
pub fn parse_prefix_initiated<'a>(text: &'a str, prefix: &str) -> Option<(&'a str, &'a str)> {
|
||||||
|
let text = text.trim_start();
|
||||||
|
let text = text.strip_prefix(prefix)?;
|
||||||
|
let (name, rest) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
|
||||||
|
if name.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((name, rest))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Global<C> {
|
||||||
|
prefix: String,
|
||||||
|
name: String,
|
||||||
|
inner: C,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C> Global<C> {
|
||||||
|
pub fn new<S: ToString>(name: S, inner: C) -> Self {
|
||||||
|
Self {
|
||||||
|
prefix: "!".to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
inner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prefix<S: ToString>(mut self, prefix: S) -> Self {
|
||||||
|
self.prefix = prefix.to_string();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for Global<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
C: Command<B, E> + Send + Sync,
|
||||||
|
{
|
||||||
|
fn description(&self, ctx: &Context) -> Option<String> {
|
||||||
|
let inner = self.inner.description(ctx)?;
|
||||||
|
Some(format!("{}{} - {inner}", self.prefix, self.name))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
// TODO Replace with let-else
|
||||||
|
let (name, rest) = match parse_prefix_initiated(arg, &self.prefix) {
|
||||||
|
Some(parsed) => parsed,
|
||||||
|
None => return Ok(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
if name != self.name {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.inner.execute(rest, msg, ctx, bot).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct General<C> {
|
||||||
|
prefix: String,
|
||||||
|
name: String,
|
||||||
|
inner: C,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C> General<C> {
|
||||||
|
pub fn new<S: ToString>(name: S, inner: C) -> Self {
|
||||||
|
Self {
|
||||||
|
prefix: "!".to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
inner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prefix<S: ToString>(mut self, prefix: S) -> Self {
|
||||||
|
self.prefix = prefix.to_string();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for General<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
C: Command<B, E> + Send + Sync,
|
||||||
|
{
|
||||||
|
fn description(&self, ctx: &Context) -> Option<String> {
|
||||||
|
let inner = self.inner.description(ctx)?;
|
||||||
|
Some(format!("{}{} - {inner}", self.prefix, self.name))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
// TODO Replace with let-else
|
||||||
|
let (name, rest) = match parse_prefix_initiated(arg, &self.prefix) {
|
||||||
|
Some(parsed) => parsed,
|
||||||
|
None => return Ok(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
if name != self.name {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if parse_prefix_initiated(rest, "@").is_some() {
|
||||||
|
// The command looks like a specific command. If we treated it like
|
||||||
|
// a general command match, we would interpret other bots' specific
|
||||||
|
// commands as general commands.
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.inner.execute(rest, msg, ctx, bot).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Specific<C> {
|
||||||
|
prefix: String,
|
||||||
|
name: String,
|
||||||
|
inner: C,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C> Specific<C> {
|
||||||
|
pub fn new<S: ToString>(name: S, inner: C) -> Self {
|
||||||
|
Self {
|
||||||
|
prefix: "!".to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
inner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prefix<S: ToString>(mut self, prefix: S) -> Self {
|
||||||
|
self.prefix = prefix.to_string();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for Specific<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
C: Command<B, E> + Send + Sync,
|
||||||
|
{
|
||||||
|
fn description(&self, ctx: &Context) -> Option<String> {
|
||||||
|
let inner = self.inner.description(ctx)?;
|
||||||
|
let nick = nick::mention(&ctx.joined.session.name);
|
||||||
|
Some(format!("{}{} @{nick} - {inner}", self.prefix, self.name))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
// TODO Replace with let-else
|
||||||
|
let (name, rest) = match parse_prefix_initiated(arg, &self.prefix) {
|
||||||
|
Some(parsed) => parsed,
|
||||||
|
None => return Ok(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
if name != self.name {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO Replace with let-else
|
||||||
|
let (nick, rest) = match parse_prefix_initiated(rest, "@") {
|
||||||
|
Some(parsed) => parsed,
|
||||||
|
None => return Ok(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
if nick::normalize(nick) != nick::normalize(&ctx.joined.session.name) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.inner.execute(rest, msg, ctx, bot).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::parse_prefix_initiated;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_prefixed() {
|
||||||
|
assert_eq!(parse_prefix_initiated("!foo", "!"), Some(("foo", "")));
|
||||||
|
assert_eq!(parse_prefix_initiated(" !foo", "!"), Some(("foo", "")));
|
||||||
|
assert_eq!(
|
||||||
|
parse_prefix_initiated("!foo ", "!"),
|
||||||
|
Some(("foo", " "))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_prefix_initiated(" !foo ", "!"),
|
||||||
|
Some(("foo", " "))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_prefix_initiated("!foo @bar", "!"),
|
||||||
|
Some(("foo", "@bar"))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_prefix_initiated("!foo @bar", "!"),
|
||||||
|
Some(("foo", " @bar"))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_prefix_initiated("!foo @bar ", "!"),
|
||||||
|
Some(("foo", "@bar "))
|
||||||
|
);
|
||||||
|
assert_eq!(parse_prefix_initiated("! foo @bar", "!"), None);
|
||||||
|
assert_eq!(parse_prefix_initiated("!", "!"), None);
|
||||||
|
assert_eq!(parse_prefix_initiated("?foo", "!"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
182
src/bot/command/clap.rs
Normal file
182
src/bot/command/clap.rs
Normal file
|
|
@ -0,0 +1,182 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use clap::{CommandFactory, Parser};
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
use super::{Command, Context};
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ClapCommand<B, E> {
|
||||||
|
type Args;
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
args: Self::Args,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse bash-like quoted arguments separated by whitespace.
|
||||||
|
///
|
||||||
|
/// Outside of quotes, the backslash either escapes the next character or forms
|
||||||
|
/// an escape sequence. \n is a newline, \r a carriage return and \t a tab.
|
||||||
|
/// TODO Escape sequences
|
||||||
|
///
|
||||||
|
/// Special characters like the backslash and whitespace can also be quoted
|
||||||
|
/// using double quotes. Within double quotes, \" escapes a double quote and \\
|
||||||
|
/// escapes a backslash. Other occurrences of \ have no special meaning.
|
||||||
|
fn parse_quoted_args(text: &str) -> Result<Vec<String>, &'static str> {
|
||||||
|
let mut args = vec![];
|
||||||
|
let mut arg = String::new();
|
||||||
|
let mut arg_exists = false;
|
||||||
|
|
||||||
|
let mut quoted = false;
|
||||||
|
let mut escaped = false;
|
||||||
|
for c in text.chars() {
|
||||||
|
if quoted {
|
||||||
|
match c {
|
||||||
|
'\\' if escaped => {
|
||||||
|
arg.push('\\');
|
||||||
|
escaped = false;
|
||||||
|
}
|
||||||
|
'"' if escaped => {
|
||||||
|
arg.push('"');
|
||||||
|
escaped = false;
|
||||||
|
}
|
||||||
|
c if escaped => {
|
||||||
|
arg.push('\\');
|
||||||
|
arg.push(c);
|
||||||
|
escaped = false;
|
||||||
|
}
|
||||||
|
'\\' => escaped = true,
|
||||||
|
'"' => quoted = false,
|
||||||
|
c => arg.push(c),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match c {
|
||||||
|
c if escaped => {
|
||||||
|
arg.push(c);
|
||||||
|
arg_exists = true;
|
||||||
|
escaped = false;
|
||||||
|
}
|
||||||
|
c if c.is_whitespace() => {
|
||||||
|
if arg_exists {
|
||||||
|
args.push(arg);
|
||||||
|
arg = String::new();
|
||||||
|
arg_exists = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'\\' => escaped = true,
|
||||||
|
'"' => {
|
||||||
|
quoted = true;
|
||||||
|
arg_exists = true;
|
||||||
|
}
|
||||||
|
c => {
|
||||||
|
arg.push(c);
|
||||||
|
arg_exists = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if quoted {
|
||||||
|
return Err("Unclosed trailing quote");
|
||||||
|
}
|
||||||
|
if escaped {
|
||||||
|
return Err("Unfinished trailing escape");
|
||||||
|
}
|
||||||
|
|
||||||
|
if arg_exists {
|
||||||
|
args.push(arg);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(args)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Clap<C>(pub C);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for Clap<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
E: From<conn::Error>,
|
||||||
|
C: ClapCommand<B, E> + Send + Sync,
|
||||||
|
C::Args: Parser + Send,
|
||||||
|
{
|
||||||
|
fn description(&self, _ctx: &Context) -> Option<String> {
|
||||||
|
C::Args::command().get_about().map(|s| format!("{s}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
let mut args = match parse_quoted_args(arg) {
|
||||||
|
Ok(args) => args,
|
||||||
|
Err(err) => {
|
||||||
|
ctx.reply(msg.id, err).await?;
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Hacky, but it should work fine in most cases
|
||||||
|
let usage = msg.content.strip_suffix(arg).unwrap_or("<command>").trim();
|
||||||
|
args.insert(0, usage.to_string());
|
||||||
|
|
||||||
|
let args = match C::Args::try_parse_from(args) {
|
||||||
|
Ok(args) => args,
|
||||||
|
Err(err) => {
|
||||||
|
ctx.reply(msg.id, format!("{}", err.render())).await?;
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
self.0.execute(args, msg, ctx, bot).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::parse_quoted_args;
|
||||||
|
|
||||||
|
fn assert_quoted(raw: &str, parsed: &[&str]) {
|
||||||
|
let parsed = parsed.iter().map(|s| s.to_string()).collect();
|
||||||
|
assert_eq!(parse_quoted_args(raw), Ok(parsed))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_quoted_args() {
|
||||||
|
assert_quoted("foo bar baz", &["foo", "bar", "baz"]);
|
||||||
|
assert_quoted(" foo bar baz ", &["foo", "bar", "baz"]);
|
||||||
|
assert_quoted("foo\\ ba\"r ba\"z", &["foo bar baz"]);
|
||||||
|
assert_quoted(
|
||||||
|
"It's a nice day, isn't it?",
|
||||||
|
&["It's", "a", "nice", "day,", "isn't", "it?"],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Trailing whitespace
|
||||||
|
assert_quoted("a ", &["a"]);
|
||||||
|
assert_quoted("a\\ ", &["a "]);
|
||||||
|
assert_quoted("a\\ ", &["a "]);
|
||||||
|
|
||||||
|
// Zero-length arguments
|
||||||
|
assert_quoted("a \"\" b \"\"", &["a", "", "b", ""]);
|
||||||
|
assert_quoted("a \"\" b \"\" ", &["a", "", "b", ""]);
|
||||||
|
|
||||||
|
// Backslashes in quotes
|
||||||
|
assert_quoted("\"a \\b \\\" \\\\\"", &["a \\b \" \\"]);
|
||||||
|
|
||||||
|
// Unclosed quotes and unfinished escapes
|
||||||
|
assert!(parse_quoted_args("foo 'bar \"baz").is_err());
|
||||||
|
assert!(parse_quoted_args("foo \"bar baz").is_err());
|
||||||
|
assert!(parse_quoted_args("foo \"bar 'baz").is_err());
|
||||||
|
assert!(parse_quoted_args("foo \\").is_err());
|
||||||
|
assert!(parse_quoted_args("foo 'bar\\").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/bot/command/hidden.rs
Normal file
29
src/bot/command/hidden.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
|
||||||
|
use super::{Command, Context};
|
||||||
|
|
||||||
|
pub struct Hidden<C>(pub C);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for Hidden<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
C: Command<B, E> + Send + Sync,
|
||||||
|
{
|
||||||
|
fn description(&self, _ctx: &Context) -> Option<String> {
|
||||||
|
// Default implementation, repeated here for emphasis.
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
self.0.execute(arg, msg, ctx, bot).await
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/bot/command/prefixed.rs
Normal file
45
src/bot/command/prefixed.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::api::Message;
|
||||||
|
|
||||||
|
use super::{Command, Context};
|
||||||
|
|
||||||
|
pub struct Prefixed<C> {
|
||||||
|
prefix: String,
|
||||||
|
inner: C,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C> Prefixed<C> {
|
||||||
|
pub fn new<S: ToString>(prefix: S, inner: C) -> Self {
|
||||||
|
Self {
|
||||||
|
prefix: prefix.to_string(),
|
||||||
|
inner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<B, E, C> Command<B, E> for Prefixed<C>
|
||||||
|
where
|
||||||
|
B: Send,
|
||||||
|
C: Command<B, E> + Send + Sync,
|
||||||
|
{
|
||||||
|
fn description(&self, ctx: &Context) -> Option<String> {
|
||||||
|
let inner = self.inner.description(ctx)?;
|
||||||
|
Some(format!("{} - {inner}", self.prefix))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
arg: &str,
|
||||||
|
msg: &Message,
|
||||||
|
ctx: &Context,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
if let Some(rest) = arg.trim_start().strip_prefix(&self.prefix) {
|
||||||
|
self.inner.execute(rest, msg, ctx, bot).await
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
93
src/bot/commands.rs
Normal file
93
src/bot/commands.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
use crate::api::packet::ParsedPacket;
|
||||||
|
use crate::api::{Data, SendEvent};
|
||||||
|
use crate::conn;
|
||||||
|
|
||||||
|
use super::command::{Command, Context};
|
||||||
|
use super::instance::{ConnSnapshot, InstanceConfig};
|
||||||
|
|
||||||
|
pub struct Commands<B, E> {
|
||||||
|
commands: Vec<Box<dyn Command<B, E> + Send + Sync>>,
|
||||||
|
fallthrough: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B, E> Commands<B, E> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
commands: vec![],
|
||||||
|
fallthrough: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether further commands should be executed after a command returns
|
||||||
|
/// `true`.
|
||||||
|
///
|
||||||
|
/// If disabled, commands are run until the first command that returns
|
||||||
|
/// `true`. If enabled, all commands are run irrespective of their return
|
||||||
|
/// values.
|
||||||
|
pub fn fallthrough(&self) -> bool {
|
||||||
|
self.fallthrough
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set whether fallthrough is active.
|
||||||
|
///
|
||||||
|
/// See [`Self::fallthrough`] for more details.
|
||||||
|
pub fn set_fallthrough(&mut self, active: bool) {
|
||||||
|
self.fallthrough = active;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add<C>(&mut self, command: C)
|
||||||
|
where
|
||||||
|
C: Command<B, E> + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
self.commands.push(Box::new(command));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn descriptions(&self, ctx: &Context) -> Vec<String> {
|
||||||
|
self.commands
|
||||||
|
.iter()
|
||||||
|
.filter_map(|c| c.description(ctx))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `true` if one or more commands returned `true`, `false`
|
||||||
|
/// otherwise.
|
||||||
|
pub async fn handle_packet(
|
||||||
|
&self,
|
||||||
|
config: &InstanceConfig,
|
||||||
|
packet: &ParsedPacket,
|
||||||
|
snapshot: &ConnSnapshot,
|
||||||
|
bot: &mut B,
|
||||||
|
) -> Result<bool, E> {
|
||||||
|
let msg = match &packet.content {
|
||||||
|
Ok(Data::SendEvent(SendEvent(msg))) => msg,
|
||||||
|
_ => return Ok(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
let joined = match &snapshot.state {
|
||||||
|
conn::State::Joining(_) => return Ok(false),
|
||||||
|
conn::State::Joined(joined) => joined.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ctx = Context {
|
||||||
|
config: config.clone(),
|
||||||
|
conn_tx: snapshot.conn_tx.clone(),
|
||||||
|
joined,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut handled = false;
|
||||||
|
for command in &self.commands {
|
||||||
|
handled = handled || command.execute(&msg.content, msg, &ctx, bot).await?;
|
||||||
|
if !self.fallthrough && handled {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(handled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B, E> Default for Commands<B, E> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
534
src/bot/instance.rs
Normal file
534
src/bot/instance.rs
Normal file
|
|
@ -0,0 +1,534 @@
|
||||||
|
//! A single instance of a bot in a single room.
|
||||||
|
//!
|
||||||
|
//! See [`Instance`] for more details.
|
||||||
|
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::fmt;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use cookie::{Cookie, CookieJar};
|
||||||
|
use tokio::select;
|
||||||
|
use tokio::sync::{mpsc, oneshot};
|
||||||
|
use tokio_tungstenite::tungstenite;
|
||||||
|
use tokio_tungstenite::tungstenite::http::{HeaderValue, StatusCode};
|
||||||
|
|
||||||
|
use crate::api::packet::ParsedPacket;
|
||||||
|
use crate::api::{Auth, AuthOption, Data, Nick};
|
||||||
|
use crate::conn::{self, Conn, ConnTx, State};
|
||||||
|
|
||||||
|
macro_rules! ilog {
|
||||||
|
( $conf:expr, $target:expr, $($arg:tt)+ ) => {
|
||||||
|
::log::log!(
|
||||||
|
target: &format!("euphoxide::live::{}", $conf.name),
|
||||||
|
$target,
|
||||||
|
$($arg)+
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! idebug {
|
||||||
|
( $conf:expr, $($arg:tt)+ ) => {
|
||||||
|
ilog!($conf, ::log::Level::Debug, $($arg)+);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! iinfo {
|
||||||
|
( $conf:expr, $($arg:tt)+ ) => {
|
||||||
|
ilog!($conf, ::log::Level::Info, $($arg)+);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! iwarn {
|
||||||
|
( $conf:expr, $($arg:tt)+ ) => {
|
||||||
|
ilog!($conf, ::log::Level::Warn, $($arg)+);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settings that are usually shared between all instances connecting to a
|
||||||
|
/// specific server.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
/// How long to wait for the server until an operation is considered timed
|
||||||
|
/// out.
|
||||||
|
///
|
||||||
|
/// This timeout applies to waiting for reply packets to command packets
|
||||||
|
/// sent by the client, as well as operations like connecting or closing a
|
||||||
|
/// connection.
|
||||||
|
pub timeout: Duration,
|
||||||
|
/// How long to wait until reconnecting after an unsuccessful attempt to
|
||||||
|
/// connect.
|
||||||
|
pub reconnect_delay: Duration,
|
||||||
|
/// Domain name, to be used with [`Conn::connect`].
|
||||||
|
pub domain: String,
|
||||||
|
/// Cookies to use when connecting. They are updated with the server's reply
|
||||||
|
/// after successful connection attempts.
|
||||||
|
pub cookies: Arc<Mutex<CookieJar>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServerConfig {
|
||||||
|
pub fn timeout(mut self, timeout: Duration) -> Self {
|
||||||
|
self.timeout = timeout;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reconnect_delay(mut self, reconnect_delay: Duration) -> Self {
|
||||||
|
self.reconnect_delay = reconnect_delay;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn domain<S: ToString>(mut self, domain: S) -> Self {
|
||||||
|
self.domain = domain.to_string();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cookies(mut self, cookies: Arc<Mutex<CookieJar>>) -> Self {
|
||||||
|
self.cookies = cookies;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn room<S: ToString>(self, room: S) -> InstanceConfig {
|
||||||
|
InstanceConfig::new(self, room)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ServerConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
timeout: Duration::from_secs(30),
|
||||||
|
reconnect_delay: Duration::from_secs(30),
|
||||||
|
domain: "euphoria.leet.nu".to_string(),
|
||||||
|
cookies: Arc::new(Mutex::new(CookieJar::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Hidden;
|
||||||
|
|
||||||
|
impl fmt::Debug for Hidden {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "<hidden>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ServerConfig {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("ServerConfig")
|
||||||
|
.field("timeout", &self.timeout)
|
||||||
|
.field("reconnect_delay", &self.reconnect_delay)
|
||||||
|
.field("domain", &self.domain)
|
||||||
|
.field("cookies", &Hidden)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settings that are usually specific to a single instance.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct InstanceConfig {
|
||||||
|
pub server: ServerConfig,
|
||||||
|
/// Unique name of this instance.
|
||||||
|
pub name: String,
|
||||||
|
/// Room name, to be used with [`Conn::connect`].
|
||||||
|
pub room: String,
|
||||||
|
/// Whether the instance should connect as human or bot.
|
||||||
|
pub human: bool,
|
||||||
|
/// Username to set upon connecting.
|
||||||
|
pub username: Option<String>,
|
||||||
|
/// Whether to set the username even if the server reports that the session
|
||||||
|
/// already has a username set.
|
||||||
|
pub force_username: bool,
|
||||||
|
/// Password to use if room requires authentication.
|
||||||
|
pub password: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InstanceConfig {
|
||||||
|
pub fn new<S: ToString>(server: ServerConfig, room: S) -> Self {
|
||||||
|
Self {
|
||||||
|
server,
|
||||||
|
name: room.to_string(),
|
||||||
|
room: room.to_string(),
|
||||||
|
human: false,
|
||||||
|
username: None,
|
||||||
|
force_username: false,
|
||||||
|
password: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name<S: ToString>(mut self, name: S) -> Self {
|
||||||
|
self.name = name.to_string();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn human(mut self, human: bool) -> Self {
|
||||||
|
self.human = human;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn username<S: ToString>(mut self, username: Option<S>) -> Self {
|
||||||
|
self.username = username.map(|s| s.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn force_username(mut self, force_username: bool) -> Self {
|
||||||
|
self.force_username = force_username;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn password<S: ToString>(mut self, password: Option<S>) -> Self {
|
||||||
|
self.password = password.map(|s| s.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new instance using this config.
|
||||||
|
///
|
||||||
|
/// See [`Instance::new`] for more details.
|
||||||
|
pub fn build<F>(self, on_event: F) -> Instance
|
||||||
|
where
|
||||||
|
F: Fn(Event) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
Instance::new(self, on_event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot of a [`Conn`]'s state immediately after receiving a packet.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConnSnapshot {
|
||||||
|
pub conn_tx: ConnTx,
|
||||||
|
pub state: State,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnSnapshot {
|
||||||
|
fn from_conn(conn: &Conn) -> Self {
|
||||||
|
Self {
|
||||||
|
conn_tx: conn.tx().clone(),
|
||||||
|
state: conn.state().clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Most of the time, the largest variant (`Packet`) is sent. The size of this
|
||||||
|
// enum is not critical anyways since it's not constructed that often.
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
|
/// An event emitted by an [`Instance`].
|
||||||
|
///
|
||||||
|
/// Events are emitted by a single instance following this schema, written in
|
||||||
|
/// pseudo-regex syntax:
|
||||||
|
/// ```text
|
||||||
|
/// (Connecting (Connected Packet*)? Disconnected)* Stopped
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// In particular, this means that every [`Self::Connecting`] is always followed
|
||||||
|
/// by exactly one [`Self::Disconnected`], and that [`Self::Stopped`] is always
|
||||||
|
/// the last event and is always sent exactly once per instance.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Event {
|
||||||
|
Connecting(InstanceConfig),
|
||||||
|
Connected(InstanceConfig, ConnSnapshot),
|
||||||
|
Packet(InstanceConfig, ParsedPacket, ConnSnapshot),
|
||||||
|
Disconnected(InstanceConfig),
|
||||||
|
Stopped(InstanceConfig),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Event {
|
||||||
|
pub fn config(&self) -> &InstanceConfig {
|
||||||
|
match self {
|
||||||
|
Self::Connecting(config) => config,
|
||||||
|
Self::Connected(config, _) => config,
|
||||||
|
Self::Packet(config, _, _) => config,
|
||||||
|
Self::Disconnected(config) => config,
|
||||||
|
Self::Stopped(config) => config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Request {
|
||||||
|
GetConnTx(oneshot::Sender<ConnTx>),
|
||||||
|
Stop,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error that occurred inside an [`Instance`] while it was running.
|
||||||
|
enum RunError {
|
||||||
|
StoppedManually,
|
||||||
|
InstanceDropped,
|
||||||
|
CouldNotConnect(conn::Error),
|
||||||
|
Conn(conn::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single instance of a bot in a single room.
|
||||||
|
///
|
||||||
|
/// The instance automatically connects to its room once it is created, and it
|
||||||
|
/// reconnects when it loses connection. If the room requires authentication and
|
||||||
|
/// a password is given, the instance automatically authenticates. If a nick is
|
||||||
|
/// given, the instance sets its nick upon joining the room.
|
||||||
|
///
|
||||||
|
/// An instance has a unique name used for logging and identifying the instance.
|
||||||
|
/// The room name can be used as the instance name if there is never more than
|
||||||
|
/// one instance per room.
|
||||||
|
///
|
||||||
|
/// An instance can be created using [`Instance::new`] or using
|
||||||
|
/// [`InstanceConfig::build`].
|
||||||
|
///
|
||||||
|
/// An instance can be stopped using [`Instance::stop`] or by dropping it. In
|
||||||
|
/// either case, the last event the instance sends will be an
|
||||||
|
/// [`Event::Stopped`]. If it is not stopped using one of these two ways, it
|
||||||
|
/// will continue to run and reconnect indefinitely.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Instance {
|
||||||
|
config: InstanceConfig,
|
||||||
|
request_tx: mpsc::UnboundedSender<Request>,
|
||||||
|
// In theory, request_tx should be sufficient as canary, but I'm not sure
|
||||||
|
// exactly how to check it during the reconnect timeout.
|
||||||
|
_canary_tx: mpsc::UnboundedSender<Infallible>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Instance {
|
||||||
|
// Previously, the event callback was asynchronous and would return a result. It
|
||||||
|
// was called in-line to calling Conn::recv. The idea was that the instance
|
||||||
|
// would stop if the event handler returned Err. This was, however, not even
|
||||||
|
// implemented correctly and the instance would just reconnect.
|
||||||
|
//
|
||||||
|
// The new event handler is synchronous. This way, it becomes harder to
|
||||||
|
// accidentally block Conn::recv, for example by waiting for a channel with
|
||||||
|
// limited capacity. If async code must be executed upon receiving a command,
|
||||||
|
// the user can start a task from inside the handler.
|
||||||
|
//
|
||||||
|
// The new event handler does not return anything. This makes the code nicer. In
|
||||||
|
// the use cases I'm thinking of, it should not be a problem: If the event
|
||||||
|
// handler encounters errors, there's usually other ways to tell the same. Make
|
||||||
|
// the event handler ignore the errors and stop the instance in that other way.
|
||||||
|
|
||||||
|
/// Create a new instance based on an [`InstanceConfig`].
|
||||||
|
///
|
||||||
|
/// The `on_event` parameter is called whenever the instance wants to emit
|
||||||
|
/// an [`Event`]. It must not block for long. See [`Event`] for more details
|
||||||
|
/// on the events and the order in which they are emitted.
|
||||||
|
///
|
||||||
|
/// [`InstanceConfig::build`] can be used in place of this function.
|
||||||
|
pub fn new<F>(config: InstanceConfig, on_event: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(Event) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
idebug!(config, "Created with config {config:?}");
|
||||||
|
|
||||||
|
let (request_tx, request_rx) = mpsc::unbounded_channel();
|
||||||
|
let (canary_tx, canary_rx) = mpsc::unbounded_channel();
|
||||||
|
|
||||||
|
tokio::spawn(Self::run::<F>(
|
||||||
|
config.clone(),
|
||||||
|
on_event,
|
||||||
|
request_rx,
|
||||||
|
canary_rx,
|
||||||
|
));
|
||||||
|
|
||||||
|
Self {
|
||||||
|
config,
|
||||||
|
request_tx,
|
||||||
|
_canary_tx: canary_tx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config(&self) -> &InstanceConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve the instance's current connection.
|
||||||
|
///
|
||||||
|
/// Returns `None` if the instance is currently not connected, or has
|
||||||
|
/// stopped running.
|
||||||
|
pub async fn conn_tx(&self) -> Option<ConnTx> {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
let _ = self.request_tx.send(Request::GetConnTx(tx));
|
||||||
|
rx.await.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the instance.
|
||||||
|
///
|
||||||
|
/// For more info on stopping instances, see [`Instance`].
|
||||||
|
pub fn stop(&self) {
|
||||||
|
let _ = self.request_tx.send(Request::Stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this instance is stopped.
|
||||||
|
///
|
||||||
|
/// For more info on stopping instances, see [`Instance`].
|
||||||
|
pub fn stopped(&self) -> bool {
|
||||||
|
self.request_tx.is_closed()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run<F: Fn(Event)>(
|
||||||
|
config: InstanceConfig,
|
||||||
|
on_event: F,
|
||||||
|
request_rx: mpsc::UnboundedReceiver<Request>,
|
||||||
|
mut canary_rx: mpsc::UnboundedReceiver<Infallible>,
|
||||||
|
) {
|
||||||
|
select! {
|
||||||
|
_ = Self::stay_connected(&config, &on_event, request_rx) => (),
|
||||||
|
_ = canary_rx.recv() => { idebug!(config, "Instance dropped"); },
|
||||||
|
}
|
||||||
|
on_event(Event::Stopped(config))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn stay_connected<F: Fn(Event)>(
|
||||||
|
config: &InstanceConfig,
|
||||||
|
on_event: &F,
|
||||||
|
mut request_rx: mpsc::UnboundedReceiver<Request>,
|
||||||
|
) {
|
||||||
|
loop {
|
||||||
|
idebug!(config, "Connecting...");
|
||||||
|
|
||||||
|
on_event(Event::Connecting(config.clone()));
|
||||||
|
let result = Self::run_once::<F>(config, on_event, &mut request_rx).await;
|
||||||
|
on_event(Event::Disconnected(config.clone()));
|
||||||
|
|
||||||
|
let connected = match result {
|
||||||
|
Ok(()) => {
|
||||||
|
idebug!(config, "Connection closed normally");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(RunError::StoppedManually) => {
|
||||||
|
idebug!(config, "Instance stopped manually");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(RunError::InstanceDropped) => {
|
||||||
|
idebug!(config, "Instance dropped");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(RunError::CouldNotConnect(conn::Error::Tungstenite(
|
||||||
|
tungstenite::Error::Http(response),
|
||||||
|
))) if response.status() == StatusCode::NOT_FOUND => {
|
||||||
|
iwarn!(config, "Failed to connect: room does not exist");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(RunError::CouldNotConnect(err)) => {
|
||||||
|
iwarn!(config, "Failed to connect: {err}");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Err(RunError::Conn(err)) => {
|
||||||
|
iwarn!(config, "An error occurred: {err}");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !connected {
|
||||||
|
let s = config.server.reconnect_delay.as_secs();
|
||||||
|
idebug!(config, "Waiting {s} seconds before reconnecting");
|
||||||
|
tokio::time::sleep(config.server.reconnect_delay).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_cookies(config: &InstanceConfig) -> HeaderValue {
|
||||||
|
let guard = config.server.cookies.lock().unwrap();
|
||||||
|
let cookies = guard
|
||||||
|
.iter()
|
||||||
|
.map(|c| format!("{}", c.stripped()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("; ");
|
||||||
|
drop(guard);
|
||||||
|
cookies.try_into().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cookies(config: &InstanceConfig, cookies: Vec<HeaderValue>) {
|
||||||
|
idebug!(config, "Updating cookies");
|
||||||
|
let mut guard = config.server.cookies.lock().unwrap();
|
||||||
|
|
||||||
|
for cookie in cookies {
|
||||||
|
if let Ok(cookie) = cookie.to_str() {
|
||||||
|
if let Ok(cookie) = Cookie::from_str(cookie) {
|
||||||
|
guard.add(cookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_once<F: Fn(Event)>(
|
||||||
|
config: &InstanceConfig,
|
||||||
|
on_event: &F,
|
||||||
|
request_rx: &mut mpsc::UnboundedReceiver<Request>,
|
||||||
|
) -> Result<(), RunError> {
|
||||||
|
let (mut conn, cookies) = Conn::connect(
|
||||||
|
&config.server.domain,
|
||||||
|
&config.room,
|
||||||
|
config.human,
|
||||||
|
Some(Self::get_cookies(config)),
|
||||||
|
config.server.timeout,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(RunError::CouldNotConnect)?;
|
||||||
|
|
||||||
|
Self::set_cookies(config, cookies);
|
||||||
|
on_event(Event::Connected(
|
||||||
|
config.clone(),
|
||||||
|
ConnSnapshot::from_conn(&conn),
|
||||||
|
));
|
||||||
|
|
||||||
|
let conn_tx = conn.tx().clone();
|
||||||
|
select! {
|
||||||
|
r = Self::receive::<F>(config, &mut conn, on_event) => r,
|
||||||
|
r = Self::handle_requests(request_rx, &conn_tx) => Err(r),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive<F: Fn(Event)>(
|
||||||
|
config: &InstanceConfig,
|
||||||
|
conn: &mut Conn,
|
||||||
|
on_event: &F,
|
||||||
|
) -> Result<(), RunError> {
|
||||||
|
loop {
|
||||||
|
let packet = conn.recv().await.map_err(RunError::Conn)?;
|
||||||
|
let snapshot = ConnSnapshot::from_conn(conn);
|
||||||
|
|
||||||
|
match &packet.content {
|
||||||
|
Ok(Data::SnapshotEvent(snapshot)) => {
|
||||||
|
if let Some(username) = &config.username {
|
||||||
|
if config.force_username || snapshot.nick.is_none() {
|
||||||
|
idebug!(config, "Setting nick to username {username}");
|
||||||
|
let name = username.to_string();
|
||||||
|
conn.tx().send_only(Nick { name });
|
||||||
|
} else if let Some(nick) = &snapshot.nick {
|
||||||
|
idebug!(config, "Not setting nick, already set to {nick}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Data::BounceEvent(_)) => {
|
||||||
|
if let Some(password) = &config.password {
|
||||||
|
idebug!(config, "Authenticating with password");
|
||||||
|
let cmd = Auth {
|
||||||
|
r#type: AuthOption::Passcode,
|
||||||
|
passcode: Some(password.to_string()),
|
||||||
|
};
|
||||||
|
conn.tx().send_only(cmd);
|
||||||
|
} else {
|
||||||
|
iwarn!(config, "Auth required but no password configured");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Data::DisconnectEvent(ev)) => {
|
||||||
|
if ev.reason == "authentication changed" {
|
||||||
|
iinfo!(config, "Disconnected because {}", ev.reason);
|
||||||
|
} else {
|
||||||
|
iwarn!(config, "Disconnected because {}", ev.reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
on_event(Event::Packet(config.clone(), packet, snapshot));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_requests(
|
||||||
|
request_rx: &mut mpsc::UnboundedReceiver<Request>,
|
||||||
|
conn_tx: &ConnTx,
|
||||||
|
) -> RunError {
|
||||||
|
while let Some(request) = request_rx.recv().await {
|
||||||
|
match request {
|
||||||
|
Request::GetConnTx(tx) => {
|
||||||
|
let _ = tx.send(conn_tx.clone());
|
||||||
|
}
|
||||||
|
Request::Stop => return RunError::StoppedManually,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RunError::InstanceDropped
|
||||||
|
}
|
||||||
|
}
|
||||||
70
src/bot/instances.rs
Normal file
70
src/bot/instances.rs
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
//! A convenient way to keep a [`ServerConfig`] and some [`Instance`]s.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use super::instance::{self, Instance, ServerConfig};
|
||||||
|
|
||||||
|
/// A convenient way to keep a [`ServerConfig`] and some [`Instance`]s.
|
||||||
|
pub struct Instances {
|
||||||
|
server_config: ServerConfig,
|
||||||
|
instances: HashMap<String, Instance>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Instances {
|
||||||
|
pub fn new(server_config: ServerConfig) -> Self {
|
||||||
|
Self {
|
||||||
|
server_config,
|
||||||
|
instances: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn server_config(&self) -> &ServerConfig {
|
||||||
|
&self.server_config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn instances(&self) -> impl Iterator<Item = &Instance> {
|
||||||
|
self.instances.values()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if an event comes from an instance whose name is known.
|
||||||
|
///
|
||||||
|
/// Assuming every instance has a unique name, events from unknown instances
|
||||||
|
/// should be discarded. This helps prevent "ghost instances" that were
|
||||||
|
/// stopped but haven't yet disconnected properly from influencing your
|
||||||
|
/// bot's state.
|
||||||
|
///
|
||||||
|
/// The user is responsible for ensuring that instances' names are unique.
|
||||||
|
pub fn is_from_known_instance(&self, event: &instance::Event) -> bool {
|
||||||
|
self.instances.contains_key(&event.config().name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.instances.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get an instance by its name.
|
||||||
|
pub fn get(&self, name: &str) -> Option<&Instance> {
|
||||||
|
self.instances.get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a new instance.
|
||||||
|
///
|
||||||
|
/// If an instance with the same name exists already, it will be replaced by
|
||||||
|
/// the new instance.
|
||||||
|
pub fn add(&mut self, instance: Instance) {
|
||||||
|
self.instances
|
||||||
|
.insert(instance.config().name.clone(), instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove an instance by its name.
|
||||||
|
pub fn remove(&mut self, name: &str) -> Option<Instance> {
|
||||||
|
self.instances.remove(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove all stopped instances.
|
||||||
|
///
|
||||||
|
/// This function should be called regularly.
|
||||||
|
pub fn purge(&mut self) {
|
||||||
|
self.instances.retain(|_, i| !i.stopped());
|
||||||
|
}
|
||||||
|
}
|
||||||
693
src/conn.rs
693
src/conn.rs
|
|
@ -1,24 +1,23 @@
|
||||||
//! Connection state modeling.
|
//! Connection state modeling.
|
||||||
|
|
||||||
// TODO Catch errors differently when sending into mpsc/oneshot
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
use std::{error, fmt};
|
use std::{error, fmt, result};
|
||||||
|
|
||||||
use futures::channel::oneshot;
|
use futures_util::SinkExt;
|
||||||
use futures::stream::{SplitSink, SplitStream};
|
use jiff::Timestamp;
|
||||||
use futures::{SinkExt, StreamExt};
|
use log::debug;
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use tokio::sync::mpsc;
|
use tokio::select;
|
||||||
use tokio::{select, task, time};
|
use tokio::sync::{mpsc, oneshot};
|
||||||
|
use tokio_stream::StreamExt;
|
||||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||||
use tokio_tungstenite::tungstenite::http::{header, HeaderValue};
|
use tokio_tungstenite::tungstenite::http::{header, HeaderValue};
|
||||||
use tokio_tungstenite::{tungstenite, MaybeTlsStream, WebSocketStream};
|
use tokio_tungstenite::{tungstenite, MaybeTlsStream, WebSocketStream};
|
||||||
|
|
||||||
use crate::api::packet::{Command, Packet, ParsedPacket};
|
use crate::api::packet::{Command, ParsedPacket};
|
||||||
use crate::api::{
|
use crate::api::{
|
||||||
BounceEvent, Data, HelloEvent, LoginReply, NickEvent, PersonalAccountView, Ping, PingReply,
|
BounceEvent, Data, HelloEvent, LoginReply, NickEvent, PersonalAccountView, Ping, PingReply,
|
||||||
SessionId, SessionView, SnapshotEvent, Time, UserId,
|
SessionId, SessionView, SnapshotEvent, Time, UserId,
|
||||||
|
|
@ -29,66 +28,82 @@ pub type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
|
/// The connection is now closed.
|
||||||
ConnectionClosed,
|
ConnectionClosed,
|
||||||
TimedOut,
|
/// The connection was not opened in time.
|
||||||
IncorrectReplyType,
|
ConnectionTimedOut,
|
||||||
|
/// The server didn't reply to one of our commands in time.
|
||||||
|
CommandTimedOut,
|
||||||
|
/// The server did something that violated the api specification.
|
||||||
|
ProtocolViolation(&'static str),
|
||||||
|
/// An error returned by the euphoria server.
|
||||||
Euph(String),
|
Euph(String),
|
||||||
|
|
||||||
|
Tungstenite(tungstenite::Error),
|
||||||
|
SerdeJson(serde_json::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Error {
|
impl fmt::Display for Error {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::ConnectionClosed => write!(f, "connection closed"),
|
Self::ConnectionClosed => write!(f, "connection closed"),
|
||||||
Self::TimedOut => write!(f, "packet timed out"),
|
Self::ConnectionTimedOut => write!(f, "connection did not open in time"),
|
||||||
Self::IncorrectReplyType => write!(f, "incorrect reply type"),
|
Self::CommandTimedOut => write!(f, "server did not reply to command in time"),
|
||||||
Self::Euph(error_msg) => write!(f, "{error_msg}"),
|
Self::ProtocolViolation(msg) => write!(f, "{msg}"),
|
||||||
|
Self::Euph(msg) => write!(f, "{msg}"),
|
||||||
|
Self::Tungstenite(err) => write!(f, "{err}"),
|
||||||
|
Self::SerdeJson(err) => write!(f, "{err}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<tungstenite::Error> for Error {
|
||||||
|
fn from(err: tungstenite::Error) -> Self {
|
||||||
|
Self::Tungstenite(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<serde_json::Error> for Error {
|
||||||
|
fn from(err: serde_json::Error) -> Self {
|
||||||
|
Self::SerdeJson(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl error::Error for Error {}
|
impl error::Error for Error {}
|
||||||
|
|
||||||
type InternalResult<T> = Result<T, Box<dyn error::Error>>;
|
pub type Result<T> = result::Result<T, Error>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
enum Event {
|
|
||||||
Message(tungstenite::Message),
|
|
||||||
SendCmd(Data, oneshot::Sender<PendingReply<ParsedPacket>>),
|
|
||||||
SendRpl(Option<String>, Data),
|
|
||||||
Status(oneshot::Sender<Status>),
|
|
||||||
DoPings,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Event {
|
|
||||||
fn send_cmd<C: Into<Data>>(cmd: C, rpl: oneshot::Sender<PendingReply<ParsedPacket>>) -> Self {
|
|
||||||
Self::SendCmd(cmd.into(), rpl)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_rpl<C: Into<Data>>(id: Option<String>, rpl: C) -> Self {
|
|
||||||
Self::SendRpl(id, rpl.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct Joining {
|
pub struct Joining {
|
||||||
|
pub since: Timestamp,
|
||||||
pub hello: Option<HelloEvent>,
|
pub hello: Option<HelloEvent>,
|
||||||
pub snapshot: Option<SnapshotEvent>,
|
pub snapshot: Option<SnapshotEvent>,
|
||||||
pub bounce: Option<BounceEvent>,
|
pub bounce: Option<BounceEvent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Joining {
|
impl Joining {
|
||||||
fn on_data(&mut self, data: &Data) -> InternalResult<()> {
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
since: Timestamp::now(),
|
||||||
|
hello: None,
|
||||||
|
snapshot: None,
|
||||||
|
bounce: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_data(&mut self, data: &Data) -> Result<()> {
|
||||||
match data {
|
match data {
|
||||||
Data::BounceEvent(p) => self.bounce = Some(p.clone()),
|
Data::BounceEvent(p) => self.bounce = Some(p.clone()),
|
||||||
Data::HelloEvent(p) => self.hello = Some(p.clone()),
|
Data::HelloEvent(p) => self.hello = Some(p.clone()),
|
||||||
Data::SnapshotEvent(p) => self.snapshot = Some(p.clone()),
|
Data::SnapshotEvent(p) => self.snapshot = Some(p.clone()),
|
||||||
|
// TODO Check and maybe expand list of unexpected packet types
|
||||||
Data::JoinEvent(_)
|
Data::JoinEvent(_)
|
||||||
| Data::NetworkEvent(_)
|
| Data::NetworkEvent(_)
|
||||||
| Data::NickEvent(_)
|
| Data::NickEvent(_)
|
||||||
| Data::EditMessageEvent(_)
|
| Data::EditMessageEvent(_)
|
||||||
| Data::PartEvent(_)
|
| Data::PartEvent(_)
|
||||||
| Data::PmInitiateEvent(_)
|
| Data::PmInitiateEvent(_)
|
||||||
| Data::SendEvent(_) => return Err("unexpected packet type".into()),
|
| Data::SendEvent(_) => return Err(Error::ProtocolViolation("unexpected packet type")),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -107,6 +122,7 @@ impl Joining {
|
||||||
.map(|s| (s.session_id.clone(), SessionInfo::Full(s)))
|
.map(|s| (s.session_id.clone(), SessionInfo::Full(s)))
|
||||||
.collect::<HashMap<_, _>>();
|
.collect::<HashMap<_, _>>();
|
||||||
Some(Joined {
|
Some(Joined {
|
||||||
|
since: Timestamp::now(),
|
||||||
session,
|
session,
|
||||||
account: hello.account.clone(),
|
account: hello.account.clone(),
|
||||||
listing,
|
listing,
|
||||||
|
|
@ -148,6 +164,7 @@ impl SessionInfo {
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Joined {
|
pub struct Joined {
|
||||||
|
pub since: Timestamp,
|
||||||
pub session: SessionView,
|
pub session: SessionView,
|
||||||
pub account: Option<PersonalAccountView>,
|
pub account: Option<PersonalAccountView>,
|
||||||
pub listing: HashMap<SessionId, SessionInfo>,
|
pub listing: HashMap<SessionId, SessionInfo>,
|
||||||
|
|
@ -157,20 +174,24 @@ impl Joined {
|
||||||
fn on_data(&mut self, data: &Data) {
|
fn on_data(&mut self, data: &Data) {
|
||||||
match data {
|
match data {
|
||||||
Data::JoinEvent(p) => {
|
Data::JoinEvent(p) => {
|
||||||
|
debug!("Updating listing after join-event");
|
||||||
self.listing
|
self.listing
|
||||||
.insert(p.0.session_id.clone(), SessionInfo::Full(p.0.clone()));
|
.insert(p.0.session_id.clone(), SessionInfo::Full(p.0.clone()));
|
||||||
}
|
}
|
||||||
Data::SendEvent(p) => {
|
Data::SendEvent(p) => {
|
||||||
|
debug!("Updating listing after send-event");
|
||||||
self.listing.insert(
|
self.listing.insert(
|
||||||
p.0.sender.session_id.clone(),
|
p.0.sender.session_id.clone(),
|
||||||
SessionInfo::Full(p.0.sender.clone()),
|
SessionInfo::Full(p.0.sender.clone()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Data::PartEvent(p) => {
|
Data::PartEvent(p) => {
|
||||||
|
debug!("Updating listing after part-event");
|
||||||
self.listing.remove(&p.0.session_id);
|
self.listing.remove(&p.0.session_id);
|
||||||
}
|
}
|
||||||
Data::NetworkEvent(p) => {
|
Data::NetworkEvent(p) => {
|
||||||
if p.r#type == "partition" {
|
if p.r#type == "partition" {
|
||||||
|
debug!("Updating listing after network-event with type partition");
|
||||||
self.listing.retain(|_, s| match s {
|
self.listing.retain(|_, s| match s {
|
||||||
SessionInfo::Full(s) => {
|
SessionInfo::Full(s) => {
|
||||||
s.server_id != p.server_id && s.server_era != p.server_era
|
s.server_id != p.server_id && s.server_era != p.server_era
|
||||||
|
|
@ -190,6 +211,7 @@ impl Joined {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Data::NickEvent(p) => {
|
Data::NickEvent(p) => {
|
||||||
|
debug!("Updating listing after nick-event");
|
||||||
self.listing
|
self.listing
|
||||||
.entry(p.session_id.clone())
|
.entry(p.session_id.clone())
|
||||||
.and_modify(|s| match s {
|
.and_modify(|s| match s {
|
||||||
|
|
@ -199,6 +221,7 @@ impl Joined {
|
||||||
.or_insert_with(|| SessionInfo::Partial(p.clone()));
|
.or_insert_with(|| SessionInfo::Partial(p.clone()));
|
||||||
}
|
}
|
||||||
Data::NickReply(p) => {
|
Data::NickReply(p) => {
|
||||||
|
debug!("Updating own session after nick-reply");
|
||||||
assert_eq!(self.session.id, p.id);
|
assert_eq!(self.session.id, p.id);
|
||||||
self.session.name = p.to.clone();
|
self.session.name = p.to.clone();
|
||||||
}
|
}
|
||||||
|
|
@ -211,183 +234,322 @@ impl Joined {
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
#[allow(clippy::large_enum_variant)]
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum Status {
|
pub enum State {
|
||||||
Joining(Joining),
|
Joining(Joining),
|
||||||
Joined(Joined),
|
Joined(Joined),
|
||||||
}
|
}
|
||||||
|
|
||||||
struct State {
|
impl State {
|
||||||
ws_tx: SplitSink<WsStream, tungstenite::Message>,
|
pub fn into_joining(self) -> Option<Joining> {
|
||||||
|
match self {
|
||||||
|
Self::Joining(joining) => Some(joining),
|
||||||
|
Self::Joined(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_joined(self) -> Option<Joined> {
|
||||||
|
match self {
|
||||||
|
Self::Joining(_) => None,
|
||||||
|
Self::Joined(joined) => Some(joined),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn joining(&self) -> Option<&Joining> {
|
||||||
|
match self {
|
||||||
|
Self::Joining(joining) => Some(joining),
|
||||||
|
Self::Joined(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn joined(&self) -> Option<&Joined> {
|
||||||
|
match self {
|
||||||
|
Self::Joining(_) => None,
|
||||||
|
Self::Joined(joined) => Some(joined),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
|
enum ConnCommand {
|
||||||
|
SendCmd(Data, oneshot::Sender<PendingReply<ParsedPacket>>),
|
||||||
|
GetState(oneshot::Sender<State>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConnTx {
|
||||||
|
cmd_tx: mpsc::UnboundedSender<ConnCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnTx {
|
||||||
|
/// The async part of sending a command.
|
||||||
|
///
|
||||||
|
/// This is split into a separate function so that [`Self::send`] can be
|
||||||
|
/// fully synchronous (you can safely throw away the returned future) while
|
||||||
|
/// still guaranteeing that the packet was sent.
|
||||||
|
async fn finish_send<C>(rx: oneshot::Receiver<PendingReply<ParsedPacket>>) -> Result<C::Reply>
|
||||||
|
where
|
||||||
|
C: Command,
|
||||||
|
C::Reply: TryFrom<Data>,
|
||||||
|
{
|
||||||
|
let pending_reply = rx
|
||||||
|
.await
|
||||||
|
// This should only happen if something goes wrong during encoding
|
||||||
|
// of the packet or while sending it through the websocket. Assuming
|
||||||
|
// the first doesn't happen, the connection is probably closed.
|
||||||
|
.map_err(|_| Error::ConnectionClosed)?;
|
||||||
|
|
||||||
|
let data = pending_reply
|
||||||
|
.get()
|
||||||
|
.await
|
||||||
|
.map_err(|e| match e {
|
||||||
|
replies::Error::TimedOut => Error::CommandTimedOut,
|
||||||
|
replies::Error::Canceled => Error::ConnectionClosed,
|
||||||
|
})?
|
||||||
|
.content
|
||||||
|
.map_err(Error::Euph)?;
|
||||||
|
|
||||||
|
data.try_into()
|
||||||
|
.map_err(|_| Error::ProtocolViolation("incorrect command reply type"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a command to the server.
|
||||||
|
///
|
||||||
|
/// Returns a future containing the server's reply. This future does not
|
||||||
|
/// have to be awaited and can be safely ignored if you are not interested
|
||||||
|
/// in the reply.
|
||||||
|
///
|
||||||
|
/// This function may return before the command was sent. To ensure that it
|
||||||
|
/// was sent before doing something else, await the returned future first.
|
||||||
|
///
|
||||||
|
/// When called multiple times, this function guarantees that the commands
|
||||||
|
/// are sent in the order that the function is called.
|
||||||
|
pub fn send<C>(&self, cmd: C) -> impl Future<Output = Result<C::Reply>>
|
||||||
|
where
|
||||||
|
C: Command + Into<Data>,
|
||||||
|
C::Reply: TryFrom<Data>,
|
||||||
|
{
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
let _ = self.cmd_tx.send(ConnCommand::SendCmd(cmd.into(), tx));
|
||||||
|
Self::finish_send::<C>(rx)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`Self::send`] but ignoring the server's reply.
|
||||||
|
pub fn send_only<C: Into<Data>>(&self, cmd: C) {
|
||||||
|
let (tx, _) = oneshot::channel();
|
||||||
|
let _ = self.cmd_tx.send(ConnCommand::SendCmd(cmd.into(), tx));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn state(&self) -> Result<State> {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.cmd_tx
|
||||||
|
.send(ConnCommand::GetState(tx))
|
||||||
|
.map_err(|_| Error::ConnectionClosed)?;
|
||||||
|
rx.await.map_err(|_| Error::ConnectionClosed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Conn {
|
||||||
|
ws: WsStream,
|
||||||
last_id: usize,
|
last_id: usize,
|
||||||
replies: Replies<String, ParsedPacket>,
|
replies: Replies<String, ParsedPacket>,
|
||||||
|
|
||||||
packet_tx: mpsc::UnboundedSender<ParsedPacket>,
|
conn_tx: ConnTx,
|
||||||
|
cmd_rx: mpsc::UnboundedReceiver<ConnCommand>,
|
||||||
|
|
||||||
// The server may send a pong frame with arbitrary payload unprompted at any
|
// The websocket server may send a pong frame with arbitrary payload
|
||||||
// time (see RFC 6455 5.5.3). Because of this, we can't just remember the
|
// unprompted at any time (see RFC 6455 5.5.3). Because of this, we can't
|
||||||
// last pong payload.
|
// just remember the last pong payload.
|
||||||
ws_ping_counter: u64,
|
last_ping: Instant,
|
||||||
last_ws_ping: Option<Vec<u8>>,
|
last_ws_ping_payload: Option<Vec<u8>>,
|
||||||
last_ws_ping_replied_to: bool,
|
last_ws_ping_replied_to: bool,
|
||||||
|
last_euph_ping_payload: Option<Time>,
|
||||||
|
last_euph_ping_replied_to: bool,
|
||||||
|
|
||||||
last_euph_ping: Option<Time>,
|
state: State,
|
||||||
last_euph_pong: Option<Time>,
|
|
||||||
|
|
||||||
status: Status,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl State {
|
enum ConnEvent {
|
||||||
async fn run(
|
Ws(Option<tungstenite::Result<tungstenite::Message>>),
|
||||||
ws: WsStream,
|
Cmd(Option<ConnCommand>),
|
||||||
timeout: Duration,
|
Ping,
|
||||||
mut tx_canary: mpsc::UnboundedReceiver<Infallible>,
|
}
|
||||||
rx_canary: oneshot::Receiver<Infallible>,
|
|
||||||
event_tx: mpsc::UnboundedSender<Event>,
|
|
||||||
mut event_rx: mpsc::UnboundedReceiver<Event>,
|
|
||||||
packet_tx: mpsc::UnboundedSender<ParsedPacket>,
|
|
||||||
) {
|
|
||||||
let (ws_tx, mut ws_rx) = ws.split();
|
|
||||||
let mut state = Self {
|
|
||||||
ws_tx,
|
|
||||||
last_id: 0,
|
|
||||||
replies: Replies::new(timeout),
|
|
||||||
packet_tx,
|
|
||||||
ws_ping_counter: 0,
|
|
||||||
last_ws_ping: None,
|
|
||||||
last_ws_ping_replied_to: false,
|
|
||||||
last_euph_ping: None,
|
|
||||||
last_euph_pong: None,
|
|
||||||
status: Status::Joining(Joining::default()),
|
|
||||||
};
|
|
||||||
|
|
||||||
select! {
|
impl Conn {
|
||||||
_ = tx_canary.recv() => (),
|
pub fn tx(&self) -> &ConnTx {
|
||||||
_ = rx_canary => (),
|
&self.conn_tx
|
||||||
_ = Self::listen(&mut ws_rx, &event_tx) => (),
|
|
||||||
_ = Self::send_ping_events(&event_tx, timeout) => (),
|
|
||||||
_ = state.handle_events(&event_tx, &mut event_rx) => (),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn listen(
|
pub fn state(&self) -> &State {
|
||||||
ws_rx: &mut SplitStream<WsStream>,
|
&self.state
|
||||||
event_tx: &mpsc::UnboundedSender<Event>,
|
|
||||||
) -> InternalResult<()> {
|
|
||||||
while let Some(msg) = ws_rx.next().await {
|
|
||||||
event_tx.send(Event::Message(msg?))?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_ping_events(
|
pub async fn recv(&mut self) -> Result<ParsedPacket> {
|
||||||
event_tx: &mpsc::UnboundedSender<Event>,
|
|
||||||
timeout: Duration,
|
|
||||||
) -> InternalResult<()> {
|
|
||||||
loop {
|
loop {
|
||||||
event_tx.send(Event::DoPings)?;
|
|
||||||
time::sleep(timeout).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_events(
|
|
||||||
&mut self,
|
|
||||||
event_tx: &mpsc::UnboundedSender<Event>,
|
|
||||||
event_rx: &mut mpsc::UnboundedReceiver<Event>,
|
|
||||||
) -> InternalResult<()> {
|
|
||||||
while let Some(ev) = event_rx.recv().await {
|
|
||||||
self.replies.purge();
|
self.replies.purge();
|
||||||
match ev {
|
let timeout = self.replies.timeout();
|
||||||
Event::Message(msg) => self.on_msg(msg, event_tx)?,
|
|
||||||
Event::SendCmd(data, reply_tx) => self.on_send_cmd(data, reply_tx).await?,
|
// All of these functions are cancel-safe.
|
||||||
Event::SendRpl(id, data) => self.on_send_rpl(id, data).await?,
|
let event = select! {
|
||||||
Event::Status(reply_tx) => self.on_status(reply_tx),
|
msg = self.ws.next() => ConnEvent::Ws(msg),
|
||||||
Event::DoPings => self.do_pings(event_tx).await?,
|
cmd = self.cmd_rx.recv() => ConnEvent::Cmd(cmd),
|
||||||
|
_ = Self::await_next_ping(self.last_ping, timeout) => ConnEvent::Ping,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
ConnEvent::Ws(msg) => {
|
||||||
|
if let Some(packet) = self.on_ws(msg).await? {
|
||||||
|
break Ok(packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ConnEvent::Cmd(Some(cmd)) => self.on_cmd(cmd).await?,
|
||||||
|
ConnEvent::Cmd(None) => unreachable!("self contains a ConnTx"),
|
||||||
|
ConnEvent::Ping => self.on_ping().await?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_msg(
|
async fn on_ws(
|
||||||
&mut self,
|
&mut self,
|
||||||
msg: tungstenite::Message,
|
msg: Option<tungstenite::Result<tungstenite::Message>>,
|
||||||
event_tx: &mpsc::UnboundedSender<Event>,
|
) -> Result<Option<ParsedPacket>> {
|
||||||
) -> InternalResult<()> {
|
let msg = msg.ok_or(Error::ConnectionClosed)??;
|
||||||
match msg {
|
match msg {
|
||||||
tungstenite::Message::Text(t) => self.on_packet(serde_json::from_str(&t)?, event_tx)?,
|
tungstenite::Message::Text(text) => {
|
||||||
tungstenite::Message::Binary(_) => return Err("unexpected binary message".into()),
|
let packet = serde_json::from_str(&text)?;
|
||||||
|
debug!(target: "euphoxide::conn::full", "Received {packet:?}");
|
||||||
|
let packet = ParsedPacket::from_packet(packet)?;
|
||||||
|
self.on_packet(&packet).await?;
|
||||||
|
return Ok(Some(packet));
|
||||||
|
}
|
||||||
|
tungstenite::Message::Binary(_) => {
|
||||||
|
return Err(Error::ProtocolViolation("unexpected binary ws message"));
|
||||||
|
}
|
||||||
tungstenite::Message::Ping(_) => {}
|
tungstenite::Message::Ping(_) => {}
|
||||||
tungstenite::Message::Pong(p) => {
|
tungstenite::Message::Pong(payload) => {
|
||||||
if self.last_ws_ping == Some(p) {
|
if self.last_ws_ping_payload == Some(payload.to_vec()) {
|
||||||
self.last_ws_ping_replied_to = true;
|
self.last_ws_ping_replied_to = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tungstenite::Message::Close(_) => {}
|
tungstenite::Message::Close(_) => {}
|
||||||
tungstenite::Message::Frame(_) => {}
|
tungstenite::Message::Frame(_) => {}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_packet(
|
async fn on_packet(&mut self, packet: &ParsedPacket) -> Result<()> {
|
||||||
&mut self,
|
|
||||||
packet: Packet,
|
|
||||||
event_tx: &mpsc::UnboundedSender<Event>,
|
|
||||||
) -> InternalResult<()> {
|
|
||||||
let packet = ParsedPacket::from_packet(packet)?;
|
|
||||||
|
|
||||||
// Complete pending replies if the packet has an id
|
// Complete pending replies if the packet has an id
|
||||||
if let Some(id) = &packet.id {
|
if let Some(id) = &packet.id {
|
||||||
|
debug!("Resolving pending reply for id {id}");
|
||||||
self.replies.complete(id, packet.clone());
|
self.replies.complete(id, packet.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Ok(data) = &packet.content {
|
||||||
|
self.on_data(&packet.id, data).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_data(&mut self, id: &Option<String>, data: &Data) -> Result<()> {
|
||||||
// Play a game of table tennis
|
// Play a game of table tennis
|
||||||
match &packet.content {
|
match data {
|
||||||
Ok(Data::PingReply(p)) => self.last_euph_pong = p.time,
|
Data::PingReply(p) => {
|
||||||
Ok(Data::PingEvent(p)) => {
|
if self.last_euph_ping_payload.is_some() && self.last_euph_ping_payload == p.time {
|
||||||
|
self.last_euph_ping_replied_to = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Data::PingEvent(p) => {
|
||||||
let reply = PingReply { time: Some(p.time) };
|
let reply = PingReply { time: Some(p.time) };
|
||||||
event_tx.send(Event::send_rpl(packet.id.clone(), reply))?;
|
self.send_rpl(id.clone(), reply.into()).await?;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update internal state
|
// Update internal state
|
||||||
if let Ok(data) = &packet.content {
|
match &mut self.state {
|
||||||
match &mut self.status {
|
State::Joining(joining) => {
|
||||||
Status::Joining(joining) => {
|
joining.on_data(data)?;
|
||||||
joining.on_data(data)?;
|
if let Some(joined) = joining.joined() {
|
||||||
if let Some(joined) = joining.joined() {
|
self.state = State::Joined(joined);
|
||||||
self.status = Status::Joined(joined);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Status::Joined(joined) => joined.on_data(data),
|
|
||||||
}
|
|
||||||
|
|
||||||
// The euphoria server doesn't always disconnect the client
|
|
||||||
// when it would make sense to do so or when the API
|
|
||||||
// specifies it should. This ensures we always disconnect
|
|
||||||
// when it makes sense to do so.
|
|
||||||
match data {
|
|
||||||
Data::DisconnectEvent(_) => return Err("received disconnect-event".into()),
|
|
||||||
Data::LoginEvent(_) => return Err("received login-event".into()),
|
|
||||||
Data::LogoutEvent(_) => return Err("received logout-event".into()),
|
|
||||||
Data::LoginReply(LoginReply { success: true, .. }) => {
|
|
||||||
return Err("received successful login-reply".into())
|
|
||||||
}
|
|
||||||
Data::LogoutReply(_) => return Err("received logout-reply".into()),
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
State::Joined(joined) => joined.on_data(data),
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shovel packets into self.packet_tx
|
// The euphoria server doesn't always disconnect the client when it
|
||||||
self.packet_tx.send(packet)?;
|
// would make sense to do so or when the API specifies it should. This
|
||||||
|
// ensures we always disconnect when it makes sense to do so.
|
||||||
|
if matches!(
|
||||||
|
data,
|
||||||
|
Data::DisconnectEvent(_)
|
||||||
|
| Data::LoginEvent(_)
|
||||||
|
| Data::LogoutEvent(_)
|
||||||
|
| Data::LoginReply(LoginReply { success: true, .. })
|
||||||
|
| Data::LogoutReply(_)
|
||||||
|
) {
|
||||||
|
self.disconnect().await?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn on_send_cmd(
|
async fn on_cmd(&mut self, cmd: ConnCommand) -> Result<()> {
|
||||||
|
match cmd {
|
||||||
|
ConnCommand::SendCmd(data, reply_tx) => self.send_cmd(data, reply_tx).await?,
|
||||||
|
ConnCommand::GetState(reply_tx) => {
|
||||||
|
let _ = reply_tx.send(self.state.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn await_next_ping(last_ping: Instant, timeout: Duration) {
|
||||||
|
let next_ping = last_ping + timeout;
|
||||||
|
tokio::time::sleep_until(next_ping.into()).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_ping(&mut self) -> Result<()> {
|
||||||
|
debug!("Checking ping replies and sending new pings");
|
||||||
|
|
||||||
|
// Check previous pings
|
||||||
|
if self.last_ws_ping_payload.is_some() && !self.last_ws_ping_replied_to {
|
||||||
|
debug!("Server did not respond to websocket ping, disconnecting");
|
||||||
|
self.disconnect().await?;
|
||||||
|
}
|
||||||
|
if self.last_euph_ping_payload.is_some() && !self.last_euph_ping_replied_to {
|
||||||
|
debug!("Server did not respond to euph ping, disconnecting");
|
||||||
|
self.disconnect().await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = Timestamp::now();
|
||||||
|
|
||||||
|
// Send new ws ping
|
||||||
|
let ws_payload = now.as_millisecond().to_be_bytes().to_vec();
|
||||||
|
self.last_ws_ping_payload = Some(ws_payload.clone());
|
||||||
|
self.last_ws_ping_replied_to = false;
|
||||||
|
self.ws
|
||||||
|
.send(tungstenite::Message::Ping(ws_payload.into()))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Send new euph ping
|
||||||
|
let euph_payload = Time::from_timestamp(now);
|
||||||
|
self.last_euph_ping_payload = Some(euph_payload);
|
||||||
|
self.last_euph_ping_replied_to = false;
|
||||||
|
let (tx, _) = oneshot::channel();
|
||||||
|
self.send_cmd(Ping { time: euph_payload }.into(), tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
self.last_ping = Instant::now();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_cmd(
|
||||||
&mut self,
|
&mut self,
|
||||||
data: Data,
|
data: Data,
|
||||||
reply_tx: oneshot::Sender<PendingReply<ParsedPacket>>,
|
reply_tx: oneshot::Sender<PendingReply<ParsedPacket>>,
|
||||||
) -> InternalResult<()> {
|
) -> Result<()> {
|
||||||
// Overkill of universe-heat-death-like proportions
|
// Overkill of universe-heat-death-like proportions
|
||||||
self.last_id = self.last_id.wrapping_add(1);
|
self.last_id = self.last_id.wrapping_add(1);
|
||||||
let id = format!("{}", self.last_id);
|
let id = format!("{}", self.last_id);
|
||||||
|
|
@ -399,16 +561,17 @@ impl State {
|
||||||
throttled: None,
|
throttled: None,
|
||||||
}
|
}
|
||||||
.into_packet()?;
|
.into_packet()?;
|
||||||
|
debug!(target: "euphoxide::conn::full", "Sending {packet:?}");
|
||||||
|
|
||||||
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?);
|
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?.into());
|
||||||
self.ws_tx.send(msg).await?;
|
self.ws.send(msg).await?;
|
||||||
|
|
||||||
let _ = reply_tx.send(self.replies.wait_for(id));
|
let _ = reply_tx.send(self.replies.wait_for(id));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn on_send_rpl(&mut self, id: Option<String>, data: Data) -> InternalResult<()> {
|
async fn send_rpl(&mut self, id: Option<String>, data: Data) -> Result<()> {
|
||||||
let packet = ParsedPacket {
|
let packet = ParsedPacket {
|
||||||
id,
|
id,
|
||||||
r#type: data.packet_type(),
|
r#type: data.packet_type(),
|
||||||
|
|
@ -416,170 +579,66 @@ impl State {
|
||||||
throttled: None,
|
throttled: None,
|
||||||
}
|
}
|
||||||
.into_packet()?;
|
.into_packet()?;
|
||||||
|
debug!(target: "euphoxide::conn::full", "Sending {packet:?}");
|
||||||
|
|
||||||
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?);
|
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?.into());
|
||||||
self.ws_tx.send(msg).await?;
|
self.ws.send(msg).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_status(&mut self, reply_tx: oneshot::Sender<Status>) {
|
async fn disconnect(&mut self) -> Result<Infallible> {
|
||||||
let _ = reply_tx.send(self.status.clone());
|
let _ = tokio::time::timeout(self.replies.timeout(), self.ws.close(None)).await;
|
||||||
|
debug!("Closed connection");
|
||||||
|
Err(Error::ConnectionClosed)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn do_pings(&mut self, event_tx: &mpsc::UnboundedSender<Event>) -> InternalResult<()> {
|
pub fn wrap(ws: WsStream, timeout: Duration) -> Self {
|
||||||
// Check old ws ping
|
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||||
if self.last_ws_ping.is_some() && !self.last_ws_ping_replied_to {
|
Self {
|
||||||
return Err("server missed ws ping".into());
|
ws,
|
||||||
|
last_id: 0,
|
||||||
|
replies: Replies::new(timeout),
|
||||||
|
|
||||||
|
conn_tx: ConnTx { cmd_tx },
|
||||||
|
cmd_rx,
|
||||||
|
|
||||||
|
last_ping: Instant::now(), // Wait a bit before first pings
|
||||||
|
last_ws_ping_payload: None,
|
||||||
|
last_ws_ping_replied_to: false,
|
||||||
|
last_euph_ping_payload: None,
|
||||||
|
last_euph_ping_replied_to: false,
|
||||||
|
|
||||||
|
state: State::Joining(Joining::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn connect(
|
||||||
|
domain: &str,
|
||||||
|
room: &str,
|
||||||
|
human: bool,
|
||||||
|
cookies: Option<HeaderValue>,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> Result<(Self, Vec<HeaderValue>)> {
|
||||||
|
let human = if human { "?h=1" } else { "" };
|
||||||
|
let uri = format!("wss://{domain}/room/{room}/ws{human}");
|
||||||
|
debug!("Connecting to {uri} with cookies: {cookies:?}");
|
||||||
|
let mut request = uri.into_client_request().expect("valid request");
|
||||||
|
if let Some(cookies) = cookies {
|
||||||
|
request.headers_mut().append(header::COOKIE, cookies);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send new ws ping
|
let (ws, response) =
|
||||||
let ws_payload = self.ws_ping_counter.to_be_bytes().to_vec();
|
tokio::time::timeout(timeout, tokio_tungstenite::connect_async(request))
|
||||||
self.ws_ping_counter = self.ws_ping_counter.wrapping_add(1);
|
.await
|
||||||
self.last_ws_ping = Some(ws_payload.clone());
|
.map_err(|_| Error::ConnectionTimedOut)??;
|
||||||
self.last_ws_ping_replied_to = false;
|
let (mut parts, _) = response.into_parts();
|
||||||
self.ws_tx
|
let cookies_set = match parts.headers.entry(header::SET_COOKIE) {
|
||||||
.send(tungstenite::Message::Ping(ws_payload))
|
header::Entry::Occupied(entry) => entry.remove_entry_mult().1.collect(),
|
||||||
.await?;
|
header::Entry::Vacant(_) => vec![],
|
||||||
|
};
|
||||||
// Check old euph ping
|
debug!("Received cookies {cookies_set:?}");
|
||||||
if self.last_euph_ping.is_some() && self.last_euph_ping != self.last_euph_pong {
|
let rx = Self::wrap(ws, timeout);
|
||||||
return Err("server missed euph ping".into());
|
Ok((rx, cookies_set))
|
||||||
}
|
|
||||||
|
|
||||||
// Send new euph ping
|
|
||||||
let euph_payload = Time::now();
|
|
||||||
self.last_euph_ping = Some(euph_payload);
|
|
||||||
let (tx, _) = oneshot::channel();
|
|
||||||
event_tx.send(Event::send_cmd(Ping { time: euph_payload }, tx))?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ConnTx {
|
|
||||||
#[allow(dead_code)]
|
|
||||||
canary: mpsc::UnboundedSender<Infallible>,
|
|
||||||
event_tx: mpsc::UnboundedSender<Event>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ConnTx {
|
|
||||||
async fn finish_send<C>(
|
|
||||||
rx: oneshot::Receiver<PendingReply<ParsedPacket>>,
|
|
||||||
) -> Result<C::Reply, Error>
|
|
||||||
where
|
|
||||||
C: Command,
|
|
||||||
C::Reply: TryFrom<Data>,
|
|
||||||
{
|
|
||||||
let pending_reply = rx
|
|
||||||
.await
|
|
||||||
// This should only happen if something goes wrong during encoding
|
|
||||||
// of the packet or while sending it through the websocket. Assuming
|
|
||||||
// the first doesn't happen, the connection is probably closed.
|
|
||||||
.map_err(|_| Error::ConnectionClosed)?;
|
|
||||||
let data = pending_reply
|
|
||||||
.get()
|
|
||||||
.await
|
|
||||||
.map_err(|e| match e {
|
|
||||||
replies::Error::TimedOut => Error::TimedOut,
|
|
||||||
replies::Error::Canceled => Error::ConnectionClosed,
|
|
||||||
})?
|
|
||||||
.content
|
|
||||||
.map_err(Error::Euph)?;
|
|
||||||
data.try_into().map_err(|_| Error::IncorrectReplyType)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send a command to the server.
|
|
||||||
///
|
|
||||||
/// Returns a future containing the server's reply. This future does not
|
|
||||||
/// have to be awaited and can be safely ignored if you are not interested
|
|
||||||
/// in the reply.
|
|
||||||
///
|
|
||||||
/// This function may return before the command was sent. To ensure that it
|
|
||||||
/// was sent, await the returned future first.
|
|
||||||
///
|
|
||||||
/// When called multiple times, this function guarantees that the commands
|
|
||||||
/// are sent in the order that the function is called.
|
|
||||||
pub fn send<C>(&self, cmd: C) -> impl Future<Output = Result<C::Reply, Error>>
|
|
||||||
where
|
|
||||||
C: Command + Into<Data>,
|
|
||||||
C::Reply: TryFrom<Data>,
|
|
||||||
{
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
let _ = self.event_tx.send(Event::SendCmd(cmd.into(), tx));
|
|
||||||
Self::finish_send::<C>(rx)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn status(&self) -> Result<Status, Error> {
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
self.event_tx
|
|
||||||
.send(Event::Status(tx))
|
|
||||||
.map_err(|_| Error::ConnectionClosed)?;
|
|
||||||
rx.await.map_err(|_| Error::ConnectionClosed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ConnRx {
|
|
||||||
#[allow(dead_code)]
|
|
||||||
canary: oneshot::Sender<Infallible>,
|
|
||||||
packet_rx: mpsc::UnboundedReceiver<ParsedPacket>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ConnRx {
|
|
||||||
pub async fn recv(&mut self) -> Option<ParsedPacket> {
|
|
||||||
self.packet_rx.recv().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn wrap(ws: WsStream, timeout: Duration) -> (ConnTx, ConnRx) {
|
|
||||||
let (tx_canary_tx, tx_canary_rx) = mpsc::unbounded_channel();
|
|
||||||
let (rx_canary_tx, rx_canary_rx) = oneshot::channel();
|
|
||||||
let (event_tx, event_rx) = mpsc::unbounded_channel();
|
|
||||||
let (packet_tx, packet_rx) = mpsc::unbounded_channel();
|
|
||||||
|
|
||||||
task::spawn(State::run(
|
|
||||||
ws,
|
|
||||||
timeout,
|
|
||||||
tx_canary_rx,
|
|
||||||
rx_canary_rx,
|
|
||||||
event_tx.clone(),
|
|
||||||
event_rx,
|
|
||||||
packet_tx,
|
|
||||||
));
|
|
||||||
|
|
||||||
let tx = ConnTx {
|
|
||||||
canary: tx_canary_tx,
|
|
||||||
event_tx,
|
|
||||||
};
|
|
||||||
let rx = ConnRx {
|
|
||||||
canary: rx_canary_tx,
|
|
||||||
packet_rx,
|
|
||||||
};
|
|
||||||
(tx, rx)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn connect(
|
|
||||||
domain: &str,
|
|
||||||
room: &str,
|
|
||||||
human: bool,
|
|
||||||
cookies: Option<HeaderValue>,
|
|
||||||
timeout: Duration,
|
|
||||||
) -> tungstenite::Result<(ConnTx, ConnRx, Vec<HeaderValue>)> {
|
|
||||||
let human = if human { "?h=1" } else { "" };
|
|
||||||
let uri = format!("wss://{domain}/room/{room}/ws{human}");
|
|
||||||
let mut request = uri.into_client_request().expect("valid request");
|
|
||||||
if let Some(cookies) = cookies {
|
|
||||||
request.headers_mut().append(header::COOKIE, cookies);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (ws, response) = tokio_tungstenite::connect_async(request).await?;
|
|
||||||
let (mut parts, _) = response.into_parts();
|
|
||||||
let set_cookies = match parts.headers.entry(header::SET_COOKIE) {
|
|
||||||
header::Entry::Occupied(entry) => entry.remove_entry_mult().1.collect(),
|
|
||||||
header::Entry::Vacant(_) => vec![],
|
|
||||||
};
|
|
||||||
let (tx, rx) = wrap(ws, timeout);
|
|
||||||
Ok((tx, rx, set_cookies))
|
|
||||||
}
|
|
||||||
|
|
|
||||||
3840
src/emoji.json
Normal file
3840
src/emoji.json
Normal file
File diff suppressed because it is too large
Load diff
195
src/emoji.rs
Normal file
195
src/emoji.rs
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
//! All emoji the euphoria.leet.nu client knows.
|
||||||
|
|
||||||
|
use std::borrow::Cow;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::RangeInclusive;
|
||||||
|
|
||||||
|
/// Euphoria.leet.nu emoji list, obtainable via shell command:
|
||||||
|
///
|
||||||
|
/// ```bash
|
||||||
|
/// curl 'https://euphoria.leet.nu/static/emoji.json' \
|
||||||
|
/// | jq 'to_entries | sort_by(.key) | from_entries' \
|
||||||
|
/// > emoji.json
|
||||||
|
/// ```
|
||||||
|
const EMOJI_JSON: &str = include_str!("emoji.json");
|
||||||
|
|
||||||
|
/// A map from emoji names to their unicode representation. Not all emojis have
|
||||||
|
/// such a representation.
|
||||||
|
pub struct Emoji(pub HashMap<String, Option<String>>);
|
||||||
|
|
||||||
|
fn parse_hex_to_char(hex: &str) -> Option<char> {
|
||||||
|
u32::from_str_radix(hex, 16).ok()?.try_into().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_code_points(code_points: &str) -> Option<String> {
|
||||||
|
code_points
|
||||||
|
.split('-')
|
||||||
|
.map(parse_hex_to_char)
|
||||||
|
.collect::<Option<String>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Emoji {
|
||||||
|
/// Load a list of emoji compiled into the library.
|
||||||
|
pub fn load() -> Self {
|
||||||
|
Self::load_from_json(EMOJI_JSON).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a list of emoji from a string containing a JSON object.
|
||||||
|
///
|
||||||
|
/// The object keys are the emoji names (without colons `:`). The object
|
||||||
|
/// values are the emoji code points encoded as hexadecimal numbers and
|
||||||
|
/// separated by a dash `-` (e.g. `"34-fe0f-20e3"`). Emojis whose values
|
||||||
|
/// don't match this schema are interpreted as emojis without unicode
|
||||||
|
/// representation.
|
||||||
|
pub fn load_from_json(json: &str) -> Option<Self> {
|
||||||
|
let map = serde_json::from_str::<HashMap<String, String>>(json)
|
||||||
|
.ok()?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k, parse_code_points(&v)))
|
||||||
|
.collect::<HashMap<_, _>>();
|
||||||
|
|
||||||
|
Some(Self(map))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, name: &str) -> Option<Option<&str>> {
|
||||||
|
match self.0.get(name) {
|
||||||
|
Some(Some(replace)) => Some(Some(replace)),
|
||||||
|
Some(None) => Some(None),
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, text: &str) -> Vec<(RangeInclusive<usize>, Option<&str>)> {
|
||||||
|
let mut result = vec![];
|
||||||
|
|
||||||
|
let mut prev_colon_idx = None;
|
||||||
|
for (colon_idx, _) in text.match_indices(':') {
|
||||||
|
if let Some(prev_idx) = prev_colon_idx {
|
||||||
|
let name = &text[prev_idx + 1..colon_idx];
|
||||||
|
if let Some(replace) = self.get(name) {
|
||||||
|
let range = prev_idx..=colon_idx;
|
||||||
|
result.push((range, replace));
|
||||||
|
prev_colon_idx = None;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prev_colon_idx = Some(colon_idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace<'a>(&self, text: &'a str) -> Cow<'a, str> {
|
||||||
|
let emoji = self.find(text);
|
||||||
|
if emoji.is_empty() {
|
||||||
|
return Cow::Borrowed(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = String::new();
|
||||||
|
|
||||||
|
let mut after_last_emoji = 0;
|
||||||
|
for (range, replace) in emoji {
|
||||||
|
// Only replace emoji with a replacement
|
||||||
|
if let Some(replace) = replace {
|
||||||
|
if *range.start() > after_last_emoji {
|
||||||
|
// There were non-emoji characters between the last and the
|
||||||
|
// current emoji.
|
||||||
|
result.push_str(&text[after_last_emoji..*range.start()]);
|
||||||
|
}
|
||||||
|
result.push_str(replace);
|
||||||
|
after_last_emoji = range.end() + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if after_last_emoji < text.len() {
|
||||||
|
result.push_str(&text[after_last_emoji..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cow::Owned(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove<'a>(&self, text: &'a str) -> Cow<'a, str> {
|
||||||
|
let emoji = self.find(text);
|
||||||
|
if emoji.is_empty() {
|
||||||
|
return Cow::Borrowed(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = String::new();
|
||||||
|
|
||||||
|
let mut after_last_emoji = 0;
|
||||||
|
for (range, _) in emoji {
|
||||||
|
if *range.start() > after_last_emoji {
|
||||||
|
// There were non-emoji characters between the last and the
|
||||||
|
// current emoji.
|
||||||
|
result.push_str(&text[after_last_emoji..*range.start()]);
|
||||||
|
}
|
||||||
|
after_last_emoji = range.end() + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if after_last_emoji < text.len() {
|
||||||
|
result.push_str(&text[after_last_emoji..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cow::Owned(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::Emoji;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_without_panic() {
|
||||||
|
Emoji::load();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn find() {
|
||||||
|
let emoji = Emoji::load();
|
||||||
|
|
||||||
|
// :bad: does not exist, while :x: and :o: do.
|
||||||
|
|
||||||
|
assert_eq!(emoji.find(":bad:x:o:"), vec![(4..=6, Some("❌"))]);
|
||||||
|
assert_eq!(
|
||||||
|
emoji.find(":x:bad:o:"),
|
||||||
|
vec![(0..=2, Some("❌")), (6..=8, Some("⭕"))]
|
||||||
|
);
|
||||||
|
assert_eq!(emoji.find("ab:bad:x:o:cd"), vec![(6..=8, Some("❌"))]);
|
||||||
|
assert_eq!(
|
||||||
|
emoji.find("ab:x:bad:o:cd"),
|
||||||
|
vec![(2..=4, Some("❌")), (8..=10, Some("⭕"))]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replace() {
|
||||||
|
let emoji = Emoji::load();
|
||||||
|
assert_eq!(emoji.replace("no:emo:ji:here"), "no:emo:ji:here");
|
||||||
|
assert_eq!(emoji.replace(":bad:x:o:"), ":bad❌o:");
|
||||||
|
assert_eq!(emoji.replace(":x:bad:o:"), "❌bad⭕");
|
||||||
|
assert_eq!(emoji.replace("ab:bad:x:o:cd"), "ab:bad❌o:cd");
|
||||||
|
assert_eq!(emoji.replace("ab:x:bad:o:cd"), "ab❌bad⭕cd");
|
||||||
|
assert_eq!(emoji.replace("chᴜm:crown::ant:"), "chᴜm👑🐜");
|
||||||
|
assert_eq!(
|
||||||
|
emoji.replace(":waning_crescent_moon: (2% full)"),
|
||||||
|
"🌘 (2% full)"
|
||||||
|
);
|
||||||
|
assert_eq!(emoji.replace("Jan-20 17:58 Z"), "Jan-20 17:58 Z");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remove() {
|
||||||
|
let emoji = Emoji::load();
|
||||||
|
assert_eq!(emoji.remove("no:emo:ji:here"), "no:emo:ji:here");
|
||||||
|
assert_eq!(emoji.remove(":bad:x:o:"), ":bado:");
|
||||||
|
assert_eq!(emoji.remove(":x:bad:o:"), "bad");
|
||||||
|
assert_eq!(emoji.remove("ab:bad:x:o:cd"), "ab:bado:cd");
|
||||||
|
assert_eq!(emoji.remove("ab:x:bad:o:cd"), "abbadcd");
|
||||||
|
assert_eq!(emoji.remove("chᴜm:crown::ant:"), "chᴜm");
|
||||||
|
assert_eq!(
|
||||||
|
emoji.remove(":waning_crescent_moon: (2% full)"),
|
||||||
|
" (2% full)"
|
||||||
|
);
|
||||||
|
assert_eq!(emoji.remove("Jan-20 17:58 Z"), "Jan-20 17:58 Z");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
fn normalize(text: &str) -> String {
|
|
||||||
// TODO Remove emoji names?
|
|
||||||
text.chars()
|
|
||||||
.filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
|
||||||
.map(|c| c.to_ascii_lowercase())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A re-implementation of [euphoria's nick hue hashing algorithm][0].
|
|
||||||
///
|
|
||||||
/// [0]: https://github.com/euphoria-io/heim/blob/master/client/lib/hueHash.js
|
|
||||||
fn hue_hash(text: &str, offset: i64) -> u8 {
|
|
||||||
let mut val = 0_i32;
|
|
||||||
for bibyte in text.encode_utf16() {
|
|
||||||
let char_val = (bibyte as i32).wrapping_mul(439) % 256;
|
|
||||||
val = val.wrapping_mul(33).wrapping_add(char_val);
|
|
||||||
}
|
|
||||||
|
|
||||||
let val: i64 = val as i64 + 2_i64.pow(31);
|
|
||||||
((val + offset) % 255) as u8
|
|
||||||
}
|
|
||||||
|
|
||||||
const GREENIE_OFFSET: i64 = 148 - 192; // 148 - hue_hash("greenie", 0)
|
|
||||||
|
|
||||||
pub fn nick_hue(nick: &str) -> u8 {
|
|
||||||
let normalized = normalize(nick);
|
|
||||||
if normalized.is_empty() {
|
|
||||||
hue_hash(nick, GREENIE_OFFSET)
|
|
||||||
} else {
|
|
||||||
hue_hash(&normalized, GREENIE_OFFSET)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
24
src/lib.rs
24
src/lib.rs
|
|
@ -1,23 +1,9 @@
|
||||||
#![deny(unsafe_code)]
|
|
||||||
// Rustc lint groups
|
|
||||||
#![warn(future_incompatible)]
|
|
||||||
#![warn(rust_2018_idioms)]
|
|
||||||
// Rustc lints
|
|
||||||
#![warn(noop_method_call)]
|
|
||||||
#![warn(single_use_lifetimes)]
|
|
||||||
#![warn(trivial_numeric_casts)]
|
|
||||||
#![warn(unused_crate_dependencies)]
|
|
||||||
#![warn(unused_extern_crates)]
|
|
||||||
#![warn(unused_import_braces)]
|
|
||||||
#![warn(unused_lifetimes)]
|
|
||||||
#![warn(unused_qualifications)]
|
|
||||||
// Clippy lints
|
|
||||||
#![warn(clippy::use_self)]
|
|
||||||
|
|
||||||
pub mod api;
|
pub mod api;
|
||||||
|
#[cfg(feature = "bot")]
|
||||||
|
pub mod bot;
|
||||||
pub mod conn;
|
pub mod conn;
|
||||||
mod huehash;
|
mod emoji;
|
||||||
|
pub mod nick;
|
||||||
mod replies;
|
mod replies;
|
||||||
|
|
||||||
pub use conn::{connect, wrap};
|
pub use emoji::Emoji;
|
||||||
pub use huehash::nick_hue;
|
|
||||||
|
|
|
||||||
127
src/nick.rs
Normal file
127
src/nick.rs
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
//! Nick-related utility functions.
|
||||||
|
|
||||||
|
use caseless::Caseless;
|
||||||
|
use unicode_normalization::UnicodeNormalization;
|
||||||
|
|
||||||
|
use crate::emoji::Emoji;
|
||||||
|
|
||||||
|
fn hue_normalize(emoji: &Emoji, text: &str) -> String {
|
||||||
|
emoji
|
||||||
|
.remove(text)
|
||||||
|
.chars()
|
||||||
|
.filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
||||||
|
.map(|c| c.to_ascii_lowercase())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A re-implementation of [euphoria's nick hue hashing algorithm][0].
|
||||||
|
///
|
||||||
|
/// [0]: https://github.com/CylonicRaider/heim/blob/097a1fde89ada53de2b70e51e635257f27956e4e/client/lib/heim/hueHash.js
|
||||||
|
fn hue_hash(text: &str, offset: i64) -> u8 {
|
||||||
|
let mut val = 0_i32;
|
||||||
|
for bibyte in text.encode_utf16() {
|
||||||
|
let char_val = (bibyte as i32).wrapping_mul(439) % 256;
|
||||||
|
val = val.wrapping_mul(33).wrapping_add(char_val);
|
||||||
|
}
|
||||||
|
|
||||||
|
let val: i64 = val as i64 + 2_i64.pow(31);
|
||||||
|
((val + offset) % 255) as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
const GREENIE_OFFSET: i64 = 148 - 192; // 148 - hue_hash("greenie", 0)
|
||||||
|
|
||||||
|
/// Calculate a nick's hue like [`hue`] but without removing colon-delimited
|
||||||
|
/// emoji as part of normalization.
|
||||||
|
///
|
||||||
|
/// This should be slightly faster than [`hue`] but produces incorrect results
|
||||||
|
/// if any colon-delimited emoji are present.
|
||||||
|
pub fn hue_without_removing_emoji(nick: &str) -> u8 {
|
||||||
|
// An emoji-less version of hue_normalize
|
||||||
|
let normalized = nick
|
||||||
|
.chars()
|
||||||
|
.filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
||||||
|
.map(|c| c.to_ascii_lowercase())
|
||||||
|
.collect::<String>();
|
||||||
|
|
||||||
|
if normalized.is_empty() {
|
||||||
|
hue_hash(nick, GREENIE_OFFSET)
|
||||||
|
} else {
|
||||||
|
hue_hash(&normalized, GREENIE_OFFSET)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calculate a nick's hue.
|
||||||
|
///
|
||||||
|
/// This is a reimplementation of [euphoria's nick hue hashing algorithm][0]. It
|
||||||
|
/// should always return the same value as the official client's implementation.
|
||||||
|
///
|
||||||
|
/// [0]: https://github.com/CylonicRaider/heim/blob/097a1fde89ada53de2b70e51e635257f27956e4e/client/lib/heim/hueHash.js
|
||||||
|
pub fn hue(emoji: &Emoji, nick: &str) -> u8 {
|
||||||
|
let normalized = hue_normalize(emoji, nick);
|
||||||
|
if normalized.is_empty() {
|
||||||
|
hue_hash(nick, GREENIE_OFFSET)
|
||||||
|
} else {
|
||||||
|
hue_hash(&normalized, GREENIE_OFFSET)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalize a nick to a form that can be compared against other nicks.
|
||||||
|
///
|
||||||
|
/// This normalization is less aggressive than the nick hue normalization. It is
|
||||||
|
/// also less aggressive than the normalization used by the euphoria client to
|
||||||
|
/// determine who is pinged by a mention. This means that it will not compute
|
||||||
|
/// the same normal form for all pairs of nicks that ping each other in the
|
||||||
|
/// euphoria client.
|
||||||
|
///
|
||||||
|
/// A nick and its mention form calculated via [`mention`] will always evaluate
|
||||||
|
/// to the same normal form.
|
||||||
|
///
|
||||||
|
/// The steps performed are as follows:
|
||||||
|
///
|
||||||
|
/// 1. Apply [`mention`]
|
||||||
|
/// 2. Convert to NFKC
|
||||||
|
/// 3. Case fold
|
||||||
|
///
|
||||||
|
/// Steps 2 and 3 are meant to be an alternative to the NKFC_Casefold derived
|
||||||
|
/// property that's easier to implement, even though it may be incorrect in some
|
||||||
|
/// edge cases.
|
||||||
|
///
|
||||||
|
/// [0]: https://github.com/CylonicRaider/heim/blob/978c921063e6b06012fc8d16d9fbf1b3a0be1191/client/lib/stores/chat.js#L14
|
||||||
|
pub fn normalize(nick: &str) -> String {
|
||||||
|
mention(nick) // Step 1
|
||||||
|
.nfkc() // Step 2
|
||||||
|
.default_case_fold() // Step 3
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_non_whitespace_delimiter(c: char) -> bool {
|
||||||
|
matches!(
|
||||||
|
c,
|
||||||
|
',' | '.' | '!' | '?' | ';' | '&' | '<' | '>' | '\'' | '"'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute a mentionable version of a nick while remaining as close to the
|
||||||
|
/// original as possible.
|
||||||
|
///
|
||||||
|
/// The return value of this function appended to an `@` character will
|
||||||
|
/// highlight as a mention in the official euphoria client. It should ping any
|
||||||
|
/// people using the original nick. It might also ping other people.
|
||||||
|
///
|
||||||
|
/// In the official euphoria client, mentions are non-whitespace characters
|
||||||
|
/// delimited by whitespace and any of the following characters:
|
||||||
|
///
|
||||||
|
/// `,`, `.`, `!`, `?`, `;`, `&`, `<`, `>`, `'`, `"`.
|
||||||
|
///
|
||||||
|
/// The first character of a mention may be a delimiting character.
|
||||||
|
pub fn mention(nick: &str) -> String {
|
||||||
|
let mut nick = nick.chars().filter(|c| !c.is_whitespace());
|
||||||
|
let mut result = String::new();
|
||||||
|
if let Some(c) = nick.next() {
|
||||||
|
result.push(c);
|
||||||
|
}
|
||||||
|
for c in nick.filter(|c| !is_non_whitespace_delimiter(*c)) {
|
||||||
|
result.push(c);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
@ -5,7 +5,6 @@ use std::time::Duration;
|
||||||
use std::{error, result};
|
use std::{error, result};
|
||||||
|
|
||||||
use tokio::sync::oneshot::{self, Receiver, Sender};
|
use tokio::sync::oneshot::{self, Receiver, Sender};
|
||||||
use tokio::time;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
|
|
@ -34,8 +33,7 @@ pub struct PendingReply<R> {
|
||||||
|
|
||||||
impl<R> PendingReply<R> {
|
impl<R> PendingReply<R> {
|
||||||
pub async fn get(self) -> Result<R> {
|
pub async fn get(self) -> Result<R> {
|
||||||
let result = time::timeout(self.timeout, self.result).await;
|
match tokio::time::timeout(self.timeout, self.result).await {
|
||||||
match result {
|
|
||||||
Err(_) => Err(Error::TimedOut),
|
Err(_) => Err(Error::TimedOut),
|
||||||
Ok(Err(_)) => Err(Error::Canceled),
|
Ok(Err(_)) => Err(Error::Canceled),
|
||||||
Ok(Ok(value)) => Ok(value),
|
Ok(Ok(value)) => Ok(value),
|
||||||
|
|
@ -49,7 +47,7 @@ pub struct Replies<I, R> {
|
||||||
pending: HashMap<I, Sender<R>>,
|
pending: HashMap<I, Sender<R>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<I: Eq + Hash, R> Replies<I, R> {
|
impl<I, R> Replies<I, R> {
|
||||||
pub fn new(timeout: Duration) -> Self {
|
pub fn new(timeout: Duration) -> Self {
|
||||||
Self {
|
Self {
|
||||||
timeout,
|
timeout,
|
||||||
|
|
@ -57,7 +55,14 @@ impl<I: Eq + Hash, R> Replies<I, R> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wait_for(&mut self, id: I) -> PendingReply<R> {
|
pub fn timeout(&self) -> Duration {
|
||||||
|
self.timeout
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wait_for(&mut self, id: I) -> PendingReply<R>
|
||||||
|
where
|
||||||
|
I: Eq + Hash,
|
||||||
|
{
|
||||||
let (tx, rx) = oneshot::channel();
|
let (tx, rx) = oneshot::channel();
|
||||||
self.pending.insert(id, tx);
|
self.pending.insert(id, tx);
|
||||||
PendingReply {
|
PendingReply {
|
||||||
|
|
@ -66,7 +71,10 @@ impl<I: Eq + Hash, R> Replies<I, R> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn complete(&mut self, id: &I, result: R) {
|
pub fn complete(&mut self, id: &I, result: R)
|
||||||
|
where
|
||||||
|
I: Eq + Hash,
|
||||||
|
{
|
||||||
if let Some(tx) = self.pending.remove(id) {
|
if let Some(tx) = self.pending.remove(id) {
|
||||||
let _ = tx.send(result);
|
let _ = tx.send(result);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue