1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Sent from client to server, this shared model is used for all server communication
#[derive(Debug, Serialize, Deserialize)]
pub enum RequestMessage {
  Ping { v: i64 },
  GetVersion,

  // Session messages
  JoinSession { id: Uuid },
  UpdateSession { name: String, choices: Vec<String> },
  UpdateSelf { name: String },
  SetPollTitle { id: Uuid, title: String },
  SetPollStatus { poll: Uuid, status: crate::poll::PollStatus },
  SubmitVote { poll: Uuid, vote: String }
}

impl RequestMessage {
  pub fn from_json(s: &str) -> Result<Self> {
    serde_json::from_str(s).with_context(|| format!("Can't decode JSON RequestMessage from [{}]", s))
  }

  pub fn to_json(&self) -> Result<String> {
    serde_json::to_string_pretty(&self).with_context(|| "Can't encode JSON RequestMessage")
  }

  pub fn from_binary(b: &[u8]) -> Result<Self> {
    bincode::deserialize(b).with_context(|| "Can't decode binary RequestMessage".to_string())
  }

  pub fn to_binary(&self) -> Result<Vec<u8>> {
    bincode::serialize(&self).with_context(|| "Can't encode binary RequestMessage")
  }
}