Compare commits

..

No commits in common. "master" and "v0.5.0" have entirely different histories.

16 changed files with 1750 additions and 4078 deletions

View file

@ -14,56 +14,6 @@ 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 ## v0.5.0 - 2023-12-27
### Changed ### Changed

View file

@ -1,34 +1,33 @@
[package] [package]
name = "euphoxide" name = "euphoxide"
version = "0.6.1" version = "0.5.0"
edition = "2021" edition = "2021"
[features] [features]
bot = ["dep:async-trait", "dep:clap", "dep:cookie"] bot = ["dep:async-trait", "dep:clap", "dep:cookie"]
[dependencies] [dependencies]
async-trait = { version = "0.1.86", optional = true } async-trait = { version = "0.1.75", optional = true }
caseless = "0.2.2" caseless = "0.2.1"
cookie = { version = "0.18.1", optional = true } cookie = { version = "0.18.0", optional = true }
futures-util = { version = "0.3.31", default-features = false, features = ["sink"] } futures-util = { version = "0.3.30", default-features = false, features = ["sink"] }
jiff = { version = "0.2.1", features = ["serde"] } log = "0.4.20"
log = "0.4.25" serde = { version = "1.0.193", features = ["derive"] }
serde = { version = "1.0.218", features = ["derive"] } serde_json = "1.0.108"
serde_json = "1.0.139" time = { version = "0.3.31", features = ["serde"] }
tokio = { version = "1.43.0", features = ["time", "sync", "macros", "rt"] } tokio = { version = "1.35.1", features = ["time", "sync", "macros", "rt"] }
tokio-stream = "0.1.17" tokio-stream = "0.1.14"
tokio-tungstenite = { version = "0.26.2", features = ["rustls-tls-native-roots"] } tokio-tungstenite = { version = "0.21.0", features = ["rustls-tls-native-roots"] }
unicode-normalization = "0.1.24" unicode-normalization = "0.1.22"
[dependencies.clap] [dependencies.clap]
version = "4.5.30" version = "4.4.11"
optional = true optional = true
default-features = false default-features = false
features = ["std", "derive", "deprecated"] features = ["std", "derive", "deprecated"]
[dev-dependencies] # For example bot [dev-dependencies] # For example bot
rustls = "0.23.23" tokio = { version = "1.35.1", features = ["rt-multi-thread"] }
tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
[[example]] [[example]]
name = "testbot_instance" name = "testbot_instance"
@ -41,24 +40,3 @@ required-features = ["bot"]
[[example]] [[example]]
name = "testbot_commands" name = "testbot_commands"
required-features = ["bot"] 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"

View file

@ -12,8 +12,8 @@ use euphoxide::bot::commands::Commands;
use euphoxide::bot::instance::{Event, ServerConfig}; use euphoxide::bot::instance::{Event, ServerConfig};
use euphoxide::bot::instances::Instances; use euphoxide::bot::instances::Instances;
use euphoxide::conn; use euphoxide::conn;
use jiff::Timestamp;
use log::error; use log::error;
use time::OffsetDateTime;
use tokio::sync::mpsc; use tokio::sync::mpsc;
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide"; const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
@ -74,7 +74,7 @@ impl ClapCommand<Bot, conn::Error> for Test {
struct Bot { struct Bot {
commands: Arc<Commands<Self, conn::Error>>, commands: Arc<Commands<Self, conn::Error>>,
start_time: Timestamp, start_time: OffsetDateTime,
stop: bool, stop: bool,
} }
@ -85,18 +85,13 @@ impl HasDescriptions for Bot {
} }
impl HasStartTime for Bot { impl HasStartTime for Bot {
fn start_time(&self) -> Timestamp { fn start_time(&self) -> OffsetDateTime {
self.start_time self.start_time
} }
} }
#[tokio::main] #[tokio::main]
async fn 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 (tx, mut rx) = mpsc::unbounded_channel();
let mut instances = Instances::new(ServerConfig::default()); let mut instances = Instances::new(ServerConfig::default());
@ -112,7 +107,7 @@ async fn main() {
let mut bot = Bot { let mut bot = Bot {
commands: cmds.clone(), commands: cmds.clone(),
start_time: Timestamp::now(), start_time: OffsetDateTime::now_utc(),
stop: false, stop: false,
}; };

View file

@ -3,14 +3,46 @@
use euphoxide::api::packet::ParsedPacket; use euphoxide::api::packet::ParsedPacket;
use euphoxide::api::{Data, Nick, Send}; use euphoxide::api::{Data, Nick, Send};
use euphoxide::bot::botrulez;
use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig}; use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig};
use jiff::Timestamp; use time::OffsetDateTime;
use tokio::sync::mpsc; use tokio::sync::mpsc;
const NICK: &str = "TestBot"; const NICK: &str = "TestBot";
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide"; const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
fn format_delta(delta: time::Duration) -> String {
const MINUTE: u64 = 60;
const HOUR: u64 = MINUTE * 60;
const DAY: u64 = HOUR * 24;
let mut seconds: u64 = delta.whole_seconds().try_into().unwrap();
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(" ")
}
async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> { async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> {
let data = match packet.content { let data = match packet.content {
Ok(data) => data, Ok(data) => data,
@ -75,11 +107,8 @@ async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), (
reply = Some(HELP.to_string()); reply = Some(HELP.to_string());
} else if content == format!("!uptime @{NICK}") { } else if content == format!("!uptime @{NICK}") {
if let Some(joined) = snapshot.state.joined() { if let Some(joined) = snapshot.state.joined() {
let delta = Timestamp::now() - joined.since; let delta = OffsetDateTime::now_utc() - joined.since;
reply = Some(format!( reply = Some(format!("/me has been up for {}", format_delta(delta)));
"/me has been up for {}",
botrulez::format_duration(delta)
));
} }
} else if content == "!test" { } else if content == "!test" {
reply = Some("Test successful!".to_string()); reply = Some("Test successful!".to_string());
@ -122,11 +151,6 @@ async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), (
#[tokio::main] #[tokio::main]
async fn 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 (tx, mut rx) = mpsc::unbounded_channel();
let _instance = ServerConfig::default() let _instance = ServerConfig::default()

View file

@ -3,15 +3,47 @@
use euphoxide::api::packet::ParsedPacket; use euphoxide::api::packet::ParsedPacket;
use euphoxide::api::{Data, Nick, Send}; use euphoxide::api::{Data, Nick, Send};
use euphoxide::bot::botrulez;
use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig}; use euphoxide::bot::instance::{ConnSnapshot, Event, ServerConfig};
use euphoxide::bot::instances::Instances; use euphoxide::bot::instances::Instances;
use jiff::Timestamp; use time::OffsetDateTime;
use tokio::sync::mpsc; use tokio::sync::mpsc;
const NICK: &str = "TestBot"; const NICK: &str = "TestBot";
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide"; const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
fn format_delta(delta: time::Duration) -> String {
const MINUTE: u64 = 60;
const HOUR: u64 = MINUTE * 60;
const DAY: u64 = HOUR * 24;
let mut seconds: u64 = delta.whole_seconds().try_into().unwrap();
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(" ")
}
async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> { async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), ()> {
let data = match packet.content { let data = match packet.content {
Ok(data) => data, Ok(data) => data,
@ -76,11 +108,8 @@ async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), (
reply = Some(HELP.to_string()); reply = Some(HELP.to_string());
} else if content == format!("!uptime @{NICK}") { } else if content == format!("!uptime @{NICK}") {
if let Some(joined) = snapshot.state.joined() { if let Some(joined) = snapshot.state.joined() {
let delta = Timestamp::now() - joined.since; let delta = OffsetDateTime::now_utc() - joined.since;
reply = Some(format!( reply = Some(format!("/me has been up for {}", format_delta(delta)));
"/me has been up for {}",
botrulez::format_duration(delta)
));
} }
} else if content == "!test" { } else if content == "!test" {
reply = Some("Test successful!".to_string()); reply = Some("Test successful!".to_string());
@ -123,11 +152,6 @@ async fn on_packet(packet: ParsedPacket, snapshot: ConnSnapshot) -> Result<(), (
#[tokio::main] #[tokio::main]
async fn 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 (tx, mut rx) = mpsc::unbounded_channel();
let mut instances = Instances::new(ServerConfig::default()); let mut instances = Instances::new(ServerConfig::default());

View file

@ -6,9 +6,8 @@ use std::time::Duration;
use euphoxide::api::packet::ParsedPacket; use euphoxide::api::packet::ParsedPacket;
use euphoxide::api::{Data, Nick, Send}; use euphoxide::api::{Data, Nick, Send};
use euphoxide::bot::botrulez;
use euphoxide::conn::{Conn, ConnTx, State}; use euphoxide::conn::{Conn, ConnTx, State};
use jiff::Timestamp; use time::OffsetDateTime;
const TIMEOUT: Duration = Duration::from_secs(10); const TIMEOUT: Duration = Duration::from_secs(10);
const DOMAIN: &str = "euphoria.leet.nu"; const DOMAIN: &str = "euphoria.leet.nu";
@ -16,6 +15,39 @@ const ROOM: &str = "test";
const NICK: &str = "TestBot"; const NICK: &str = "TestBot";
const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide"; const HELP: &str = "I'm an example bot for https://github.com/Garmelon/euphoxide";
fn format_delta(delta: time::Duration) -> String {
const MINUTE: u64 = 60;
const HOUR: u64 = MINUTE * 60;
const DAY: u64 = HOUR * 24;
let mut seconds: u64 = delta.whole_seconds().try_into().unwrap();
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(" ")
}
async fn on_packet(packet: ParsedPacket, conn_tx: &ConnTx, state: &State) -> Result<(), ()> { async fn on_packet(packet: ParsedPacket, conn_tx: &ConnTx, state: &State) -> Result<(), ()> {
let data = match packet.content { let data = match packet.content {
Ok(data) => data, Ok(data) => data,
@ -80,11 +112,8 @@ async fn on_packet(packet: ParsedPacket, conn_tx: &ConnTx, state: &State) -> Res
reply = Some(HELP.to_string()); reply = Some(HELP.to_string());
} else if content == format!("!uptime @{NICK}") { } else if content == format!("!uptime @{NICK}") {
if let Some(joined) = state.joined() { if let Some(joined) = state.joined() {
let delta = Timestamp::now() - joined.since; let delta = OffsetDateTime::now_utc() - joined.since;
reply = Some(format!( reply = Some(format!("/me has been up for {}", format_delta(delta)));
"/me has been up for {}",
botrulez::format_duration(delta)
));
} }
} else if content == "!test" { } else if content == "!test" {
reply = Some("Test successful!".to_string()); reply = Some("Test successful!".to_string());
@ -126,11 +155,6 @@ async fn on_packet(packet: ParsedPacket, conn_tx: &ConnTx, state: &State) -> Res
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { 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?; let (mut conn, _) = Conn::connect(DOMAIN, ROOM, false, None, TIMEOUT).await?;
while let Ok(packet) = conn.recv().await { while let Ok(packet) = conn.recv().await {

View file

@ -1,6 +1,6 @@
//! Models the [euphoria API][0]. //! Models the [euphoria API][0].
//! //!
//! [0]: https://euphoria.leet.nu/heim/api //! [0](https://github.com/CylonicRaider/heim/blob/master/doc/api.md)
mod account_cmds; mod account_cmds;
mod events; mod events;

View file

@ -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, UtcOffset};
/// Describes an account and its preferred name. /// Describes an account and its preferred name.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@ -403,19 +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(pub i64); pub struct Time(#[serde(with = "time::serde::timestamp")] pub OffsetDateTime);
impl Time { impl Time {
pub fn from_timestamp(time: Timestamp) -> Self { pub fn new(time: OffsetDateTime) -> Self {
Self(time.as_second()) let time = time
} .to_offset(UtcOffset::UTC)
.replace_millisecond(0)
pub fn as_timestamp(&self) -> Timestamp { .unwrap();
Timestamp::from_second(self.0).unwrap() Self(time)
} }
pub fn now() -> Self { pub fn now() -> Self {
Self::from_timestamp(Timestamp::now()) Self::new(OffsetDateTime::now_utc())
} }
} }

View file

@ -1,10 +1,10 @@
//! The main [botrulez](https://github.com/jedevc/botrulez) commands. //! The main [botrulez](https://github.com/jedevc/botrulez) commands.
pub mod full_help; mod full_help;
pub mod ping; mod ping;
pub mod short_help; mod short_help;
pub mod uptime; mod uptime;
pub use self::full_help::{FullHelp, HasDescriptions}; pub use self::full_help::{FullHelp, HasDescriptions};
pub use self::ping::Ping; pub use self::ping::Ping;
pub use self::short_help::ShortHelp; pub use self::short_help::ShortHelp;
pub use self::uptime::{format_duration, format_relative_time, format_time, HasStartTime, Uptime}; pub use self::uptime::{format_duration, format_time, HasStartTime, Uptime};

View file

@ -1,29 +1,24 @@
use async_trait::async_trait; use async_trait::async_trait;
use clap::Parser; use clap::Parser;
use jiff::{Span, Timestamp, Unit}; use time::macros::format_description;
use time::{Duration, OffsetDateTime, UtcOffset};
use crate::api::Message; use crate::api::Message;
use crate::bot::command::{ClapCommand, Command, Context}; use crate::bot::command::{ClapCommand, Command, Context};
use crate::conn; use crate::conn;
pub fn format_time(t: Timestamp) -> String { pub fn format_time(t: OffsetDateTime) -> String {
t.strftime("%Y-%m-%d %H:%M:%S UTC").to_string() let t = t.to_offset(UtcOffset::UTC);
let format = format_description!("[year]-[month]-[day] [hour]:[minute]:[second] UTC");
t.format(format).unwrap()
} }
pub fn format_relative_time(d: Span) -> String { pub fn format_duration(d: Duration) -> String {
if d.is_positive() { let d_abs = d.abs();
format!("in {}", format_duration(d.abs())) let days = d_abs.whole_days();
} else { let hours = d_abs.whole_hours() % 24;
format!("{} ago", format_duration(d.abs())) let mins = d_abs.whole_minutes() % 60;
} let secs = d_abs.whole_seconds() % 60;
}
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![]; let mut segments = vec![];
if days > 0 { if days > 0 {
@ -44,27 +39,27 @@ pub fn format_duration(d: Span) -> String {
let segments = segments.join(" "); let segments = segments.join(" ");
if d.is_positive() { if d.is_positive() {
segments format!("in {segments}")
} else { } else {
format!("-{segments}") format!("{segments} ago")
} }
} }
pub struct Uptime; pub struct Uptime;
pub trait HasStartTime { pub trait HasStartTime {
fn start_time(&self) -> Timestamp; fn start_time(&self) -> OffsetDateTime;
} }
impl Uptime { impl Uptime {
fn formulate_reply<B: HasStartTime>(&self, ctx: &Context, bot: &B, connected: bool) -> String { fn formulate_reply<B: HasStartTime>(&self, ctx: &Context, bot: &B, connected: bool) -> String {
let start = bot.start_time(); let start = bot.start_time();
let now = Timestamp::now(); let now = OffsetDateTime::now_utc();
let mut reply = format!( let mut reply = format!(
"/me has been up since {} ({})", "/me has been up since {} ({})",
format_time(start), format_time(start),
format_relative_time(start - now), format_duration(start - now),
); );
if connected { if connected {
@ -72,7 +67,7 @@ impl Uptime {
reply.push_str(&format!( reply.push_str(&format!(
", connected since {} ({})", ", connected since {} ({})",
format_time(since), format_time(since),
format_relative_time(since - now), format_duration(since - now),
)); ));
} }
@ -108,7 +103,7 @@ where
pub struct Args { pub struct Args {
/// Show how long the bot has been connected without interruption. /// Show how long the bot has been connected without interruption.
#[arg(long, short)] #[arg(long, short)]
pub connected: bool, connected: bool,
} }
#[async_trait] #[async_trait]

View file

@ -6,8 +6,8 @@ use std::future::Future;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::{error, fmt, result}; use std::{error, fmt, result};
use ::time::OffsetDateTime;
use futures_util::SinkExt; use futures_util::SinkExt;
use jiff::Timestamp;
use log::debug; use log::debug;
use tokio::net::TcpStream; use tokio::net::TcpStream;
use tokio::select; use tokio::select;
@ -75,7 +75,7 @@ pub type Result<T> = result::Result<T, Error>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Joining { pub struct Joining {
pub since: Timestamp, pub since: OffsetDateTime,
pub hello: Option<HelloEvent>, pub hello: Option<HelloEvent>,
pub snapshot: Option<SnapshotEvent>, pub snapshot: Option<SnapshotEvent>,
pub bounce: Option<BounceEvent>, pub bounce: Option<BounceEvent>,
@ -84,7 +84,7 @@ pub struct Joining {
impl Joining { impl Joining {
fn new() -> Self { fn new() -> Self {
Self { Self {
since: Timestamp::now(), since: OffsetDateTime::now_utc(),
hello: None, hello: None,
snapshot: None, snapshot: None,
bounce: None, bounce: None,
@ -122,7 +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(), since: OffsetDateTime::now_utc(),
session, session,
account: hello.account.clone(), account: hello.account.clone(),
listing, listing,
@ -164,7 +164,7 @@ impl SessionInfo {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Joined { pub struct Joined {
pub since: Timestamp, pub since: OffsetDateTime,
pub session: SessionView, pub session: SessionView,
pub account: Option<PersonalAccountView>, pub account: Option<PersonalAccountView>,
pub listing: HashMap<SessionId, SessionInfo>, pub listing: HashMap<SessionId, SessionInfo>,
@ -427,7 +427,7 @@ impl Conn {
} }
tungstenite::Message::Ping(_) => {} tungstenite::Message::Ping(_) => {}
tungstenite::Message::Pong(payload) => { tungstenite::Message::Pong(payload) => {
if self.last_ws_ping_payload == Some(payload.to_vec()) { if self.last_ws_ping_payload == Some(payload) {
self.last_ws_ping_replied_to = true; self.last_ws_ping_replied_to = true;
} }
} }
@ -522,18 +522,16 @@ impl Conn {
self.disconnect().await?; self.disconnect().await?;
} }
let now = Timestamp::now(); let now = OffsetDateTime::now_utc();
// Send new ws ping // Send new ws ping
let ws_payload = now.as_millisecond().to_be_bytes().to_vec(); let ws_payload = now.unix_timestamp_nanos().to_be_bytes().to_vec();
self.last_ws_ping_payload = Some(ws_payload.clone()); self.last_ws_ping_payload = Some(ws_payload.clone());
self.last_ws_ping_replied_to = false; self.last_ws_ping_replied_to = false;
self.ws self.ws.send(tungstenite::Message::Ping(ws_payload)).await?;
.send(tungstenite::Message::Ping(ws_payload.into()))
.await?;
// Send new euph ping // Send new euph ping
let euph_payload = Time::from_timestamp(now); let euph_payload = Time::new(now);
self.last_euph_ping_payload = Some(euph_payload); self.last_euph_ping_payload = Some(euph_payload);
self.last_euph_ping_replied_to = false; self.last_euph_ping_replied_to = false;
let (tx, _) = oneshot::channel(); let (tx, _) = oneshot::channel();
@ -563,7 +561,7 @@ impl Conn {
.into_packet()?; .into_packet()?;
debug!(target: "euphoxide::conn::full", "Sending {packet:?}"); debug!(target: "euphoxide::conn::full", "Sending {packet:?}");
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?.into()); let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?);
self.ws.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));
@ -581,7 +579,7 @@ impl Conn {
.into_packet()?; .into_packet()?;
debug!(target: "euphoxide::conn::full", "Sending {packet:?}"); debug!(target: "euphoxide::conn::full", "Sending {packet:?}");
let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?.into()); let msg = tungstenite::Message::Text(serde_json::to_string(&packet)?);
self.ws.send(msg).await?; self.ws.send(msg).await?;
Ok(()) Ok(())

File diff suppressed because it is too large Load diff

View file

@ -4,51 +4,33 @@ use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
/// Euphoria.leet.nu emoji list, obtainable via shell command: const EMOJI_RAW: &str = include_str!("emoji.txt");
///
/// ```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 /// A map from emoji names to their unicode representation. Not all emojis have
/// such a representation. /// such a representation.
pub struct Emoji(pub HashMap<String, Option<String>>); pub struct Emoji(pub HashMap<String, Option<String>>);
fn parse_hex_to_char(hex: &str) -> Option<char> { fn parse_hex_to_char(hex: &str) -> char {
u32::from_str_radix(hex, 16).ok()?.try_into().ok() u32::from_str_radix(hex, 16).unwrap().try_into().unwrap()
} }
fn parse_code_points(code_points: &str) -> Option<String> { fn parse_line(line: &str) -> (String, Option<String>) {
code_points let mut line = line.split_ascii_whitespace();
.split('-') let name = line.next().unwrap().to_string();
.map(parse_hex_to_char) let unicode = line.map(parse_hex_to_char).collect::<String>();
.collect::<Option<String>>() let unicode = Some(unicode).filter(|u| !u.is_empty());
(name, unicode)
} }
impl Emoji { impl Emoji {
/// Load a list of emoji compiled into the library.
pub fn load() -> Self { pub fn load() -> Self {
Self::load_from_json(EMOJI_JSON).unwrap() let map = EMOJI_RAW
} .lines()
.map(|l| l.trim())
/// Load a list of emoji from a string containing a JSON object. .filter(|l| !l.is_empty() && !l.starts_with('#'))
/// .map(parse_line)
/// The object keys are the emoji names (without colons `:`). The object .collect();
/// values are the emoji code points encoded as hexadecimal numbers and Self(map)
/// 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>> { pub fn get(&self, name: &str) -> Option<Option<&str>> {

1543
src/emoji.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,14 @@
#![forbid(unsafe_code)]
// Rustc lint groups
#![warn(future_incompatible)]
#![warn(rust_2018_idioms)]
#![warn(unused)]
// Rustc lints
#![warn(noop_method_call)]
#![warn(single_use_lifetimes)]
// Clippy lints
#![warn(clippy::use_self)]
pub mod api; pub mod api;
#[cfg(feature = "bot")] #[cfg(feature = "bot")]
pub mod bot; pub mod bot;

View file

@ -5,10 +5,9 @@ use unicode_normalization::UnicodeNormalization;
use crate::emoji::Emoji; use crate::emoji::Emoji;
fn hue_normalize(emoji: &Emoji, text: &str) -> String { /// Does not remove emoji.
emoji fn hue_normalize(text: &str) -> String {
.remove(text) text.chars()
.chars()
.filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-') .filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
.map(|c| c.to_ascii_lowercase()) .map(|c| c.to_ascii_lowercase())
.collect() .collect()
@ -16,7 +15,7 @@ fn hue_normalize(emoji: &Emoji, text: &str) -> String {
/// A re-implementation of [euphoria's nick hue hashing algorithm][0]. /// A re-implementation of [euphoria's nick hue hashing algorithm][0].
/// ///
/// [0]: https://github.com/CylonicRaider/heim/blob/097a1fde89ada53de2b70e51e635257f27956e4e/client/lib/heim/hueHash.js /// [0]: https://github.com/CylonicRaider/heim/blob/master/client/lib/hueHash.js
fn hue_hash(text: &str, offset: i64) -> u8 { fn hue_hash(text: &str, offset: i64) -> u8 {
let mut val = 0_i32; let mut val = 0_i32;
for bibyte in text.encode_utf16() { for bibyte in text.encode_utf16() {
@ -36,13 +35,7 @@ const GREENIE_OFFSET: i64 = 148 - 192; // 148 - hue_hash("greenie", 0)
/// This should be slightly faster than [`hue`] but produces incorrect results /// This should be slightly faster than [`hue`] but produces incorrect results
/// if any colon-delimited emoji are present. /// if any colon-delimited emoji are present.
pub fn hue_without_removing_emoji(nick: &str) -> u8 { pub fn hue_without_removing_emoji(nick: &str) -> u8 {
// An emoji-less version of hue_normalize let normalized = hue_normalize(nick);
let normalized = nick
.chars()
.filter(|&c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
.map(|c| c.to_ascii_lowercase())
.collect::<String>();
if normalized.is_empty() { if normalized.is_empty() {
hue_hash(nick, GREENIE_OFFSET) hue_hash(nick, GREENIE_OFFSET)
} else { } else {
@ -55,14 +48,9 @@ pub fn hue_without_removing_emoji(nick: &str) -> u8 {
/// This is a reimplementation of [euphoria's nick hue hashing algorithm][0]. It /// 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. /// 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 /// [0]: https://github.com/CylonicRaider/heim/blob/978c921063e6b06012fc8d16d9fbf1b3a0be1191/client/lib/hueHash.js
pub fn hue(emoji: &Emoji, nick: &str) -> u8 { pub fn hue(emoji: &Emoji, nick: &str) -> u8 {
let normalized = hue_normalize(emoji, nick); hue_without_removing_emoji(&emoji.remove(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. /// Normalize a nick to a form that can be compared against other nicks.