use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeMessage {
pub topic: String,
pub event: ChannelEvent, pub payload: serde_json::Value, #[serde(rename = "ref")]
pub message_ref: serde_json::Value, }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] pub enum ChannelEvent {
Insert, Update,
Delete,
All, PostgresChanges,
#[serde(rename = "phx_join")] PhoenixJoin,
#[serde(rename = "phx_reply")]
PhoenixReply,
#[serde(rename = "phx_error")]
PhoenixError,
#[serde(rename = "phx_close")]
PhoenixClose,
Heartbeat,
Presence,
Broadcast,
}
impl std::fmt::Display for ChannelEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
serde_json::to_string(self).unwrap_or_else(|_| format!("{:?}", self))
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Payload {
pub data: serde_json::Value,
#[serde(rename = "type")] pub event_type: Option<String>,
pub timestamp: Option<String>, }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PresenceChange {
pub joins: HashMap<String, serde_json::Value>,
pub leaves: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PresenceState {
pub state: HashMap<String, serde_json::Value>,
}
impl PresenceState {
pub fn new() -> Self {
Self {
state: HashMap::new(),
}
}
pub fn sync(&mut self, presence_diff: &PresenceChange) {
for (key, value) in &presence_diff.joins {
self.state.insert(key.clone(), value.clone());
}
for key in presence_diff.leaves.keys() {
self.state.remove(key);
}
}
pub fn list(&self) -> Vec<(String, serde_json::Value)> {
self.state
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
self.state.get(key)
}
}
impl Default for PresenceState {
fn default() -> Self {
Self::new()
}
}