Reduced backend resposibility to emmit game events, whole addon logic implemented in python side

This commit is contained in:
Wiktor Mazur
2020-02-18 16:55:33 +01:00
parent d73f34a33b
commit 133975cd77
78 changed files with 3203 additions and 1331 deletions
+4
View File
@@ -0,0 +1,4 @@
&.rs.bk
/target
*.so
.vscode
+48
View File
@@ -0,0 +1,48 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "byteorder"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "bytes"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "iovec"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libc"
version = "0.2.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "photon_decode"
version = "0.2.1"
dependencies = [
"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5"
"checksum bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)" = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c"
"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08"
"checksum libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "d44e80633f007889c7eff624b709ab43c92d708caad982295768a7b13ca3b5eb"
"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "photon_decode"
version = "0.2.1"
authors = ["Wiktor Mazur <wiktormazur1@gmail.com>"]
edition = "2018"
description = "Set of utilities for decoding messages generated by photon framework."
repository = "https://github.com/mazurwiktor/photon_decode"
license = "MIT/Apache-2.0"
readme = "README.md"
documentation = "https://docs.rs/photon_decode/*/photon_decode/"
categories = ["network-programming", "encoding"]
keywords = ["games", "multiplayer", "photon", "unity", "unrealengine"]
[dependencies]
bytes = "0.4"
+59
View File
@@ -0,0 +1,59 @@
Photon decode
=============
Set of utilities for decoding messages generated by *photon framework.
*Photon is a development framework for multiplayer games. More on https://www.photonengine.com/.
[![Documentation](https://docs.rs/photon_decode/badge.svg)](https://docs.rs/photon_decode/*/photon_decode/)
## Usage
To use `photon_decode`, first add this to your `Cargo.toml`:
```toml
[dependencies]
photon_decode = "0.1"
```
```rust
use photon_decode::{Photon, Message};
let mut photon = Photon::new();
let photon_packet = vec![
0x00, 0x01, // PeerID
0x01, // CrcEnabled
0x00, // CommandCount
0x00, 0x00, 0x00, 0x01, // Timestamp
0x00, 0x00, 0x00, 0x01, // Challenge
];
for message in photon.decode(&photon_packet).iter() {
match message {
Message::Event(_) => {
// use event
},
Message::Request(_) => {
// use request
},
Message::Response(_) => {
// use response
}
}
}
```
# Projects using photon decode
https://github.com/mazurwiktor/albion-online-stats - Albion online stats is an extension to MMORPG game - Albion Online. It tracks network traffic and displays various statistics, such as damage and DPS meter calculated from in-game actions.
# License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
+472
View File
@@ -0,0 +1,472 @@
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::mem::size_of;
use bytes::Buf;
use crate::error::*;
use crate::layout::*;
pub type PhotonCursor<'a> = Cursor<&'a [u8]>;
pub trait Decode<T> {
fn decode(&mut self) -> PhotonDecodeResult<T>;
}
trait TypedDecode {
fn typed_decode(&mut self, type_code: u8) -> PhotonDecodeResult<Value>;
}
macro_rules! impl_decode {
($type:ty, $decode_func:ident, $bytes_to_consume:expr) => {
impl Decode<$type> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<$type> {
let v = if self.remaining() >= $bytes_to_consume {
self.$decode_func()
} else {
return Err(PhotonDecodeError::from(concat!(
"Failed to decode ",
stringify!($type),
", not enough bytes"
)));
};
Ok(v)
}
}
};
}
impl_decode!(u8, get_u8, 1);
impl_decode!(f32, get_f32_be, 4);
impl_decode!(u32, get_u32_be, 4);
impl_decode!(i64, get_i64_be, 8);
impl_decode!(i16, get_i16_be, 2);
impl_decode!(f64, get_f64_be, 8);
impl Decode<bool> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<bool> {
let v = if self.remaining() >= 1 {
self.get_u8()
} else {
return Err(PhotonDecodeError::from(
"Failed to decode bool, not enough bytes",
));
};
Ok(v != 0)
}
}
impl Decode<String> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<String> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode String, unreasonable size",
));
}
let mut local_buffer = vec![0; size as usize];
if let Ok(_) = self.read_exact(&mut local_buffer[..]) {
if let Ok(s) = String::from_utf8(local_buffer) {
return Ok(s);
}
}
Err(PhotonDecodeError::from(
"Failed to decode String, not enough bytes",
))
}
}
impl Decode<Vec<String>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Vec<String>> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode String, unreasonable size",
));
}
let mut value: Vec<String> = vec![];
for _ in 0..size {
value.push(self.decode()?);
}
Ok(value)
}
}
impl Decode<Vec<u8>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Vec<u8>> {
let size: u32 = self.decode()?;
let mut value: Vec<u8> = vec![];
for _ in 0..size {
value.push(self.decode()?);
}
Ok(value)
}
}
impl Decode<Vec<Value>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Vec<Value>> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode Vec<Value>, unreasonable size",
));
}
let type_code: u8 = self.decode()?;
let mut value: Vec<Value> = vec![];
for _ in 0..size {
if let Ok(v) = self.typed_decode(type_code) {
value.push(v);
} else {
break;
}
}
Ok(value)
}
}
impl Decode<HashMap<String, Value>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<HashMap<String, Value>> {
let key_type_code: u8 = self.decode()?;
let value_type_code: u8 = self.decode()?;
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode HashMap<String, Value>, unreasonable size",
));
}
let mut value: HashMap<String, Value> = HashMap::new();
for _ in 0..size {
let key_code: u8 = if key_type_code == 0 || key_type_code == 42 {
self.decode()?
} else {
key_type_code
};
let key = self.typed_decode(key_code);
let value_code: u8 = if value_type_code == 0 || value_type_code == 42 {
self.decode()?
} else {
value_type_code
};
let val = self.typed_decode(value_code);
if let (Ok(key), Ok(val)) = (key, val) {
value.insert(format!("{}", key), val);
}
}
Ok(value)
}
}
impl Decode<HashMap<u8, Value>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<HashMap<u8, Value>> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode HashMap<u8, Value>, unreasonable size",
));
}
let mut value: HashMap<u8, Value> = HashMap::new();
for _ in 0..size {
let key_type_code: u8 = if let Ok(v) = self.decode() {
v
} else {
break;
};
let val: Value = if let Ok(v) = self.decode() {
v
} else {
break;
};
value.insert(key_type_code, val);
}
Ok(value)
}
}
impl Decode<EventData> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<EventData> {
let code: u8 = self.decode()?;
let parameters: HashMap<u8, Value> = self.decode()?;
Ok(EventData { code, parameters })
}
}
impl Decode<OperationResponse> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<OperationResponse> {
let code: u8 = self.decode()?;
let return_code: i16 = self.decode()?;
let maybe_debug_message: Value = self.decode()?;
let debug_message = if let Value::String(s) = maybe_debug_message {
s
} else {
"None".to_owned()
};
let parameters: HashMap<u8, Value> = self.decode()?;
Ok(OperationResponse {
code,
return_code,
debug_message,
parameters,
})
}
}
impl Decode<OperationRequest> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<OperationRequest> {
let code: u8 = self.decode()?;
let parameters: HashMap<u8, Value> = self.decode()?;
Ok(OperationRequest { code, parameters })
}
}
impl Decode<Vec<Box<Value>>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Vec<Box<Value>>> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode Vec<Box<Value>>, unreasonable size",
));
}
let mut value = vec![];
for _ in 0..size {
let type_code: u8 = if let Ok(v) = self.decode() {
v
} else {
break;
};
if let Ok(val) = self.typed_decode(type_code) {
value.push(Box::new(val));
}
}
Ok(value)
}
}
impl Decode<Vec<bool>> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Vec<bool>> {
let size: i16 = self.decode()?;
if size < 0 {
return Err(PhotonDecodeError::from(
"Failed to decode Vec<bool>, unreasonable size",
));
}
let mut value = vec![];
for _ in 0..size {
value.push(self.decode()?);
}
Ok(value)
}
}
impl TypedDecode for PhotonCursor<'_> {
fn typed_decode(&mut self, type_code: u8) -> PhotonDecodeResult<Value> {
match TypeCode::from(type_code) {
TypeCode::None => Ok(Value::None),
TypeCode::Null => Ok(Value::None),
TypeCode::Boolean => Ok(Value::Boolean(self.decode()?)),
TypeCode::Byte => Ok(Value::Byte(self.decode()?)),
TypeCode::Double => Ok(Value::Double(self.decode()?)),
TypeCode::Float => Ok(Value::Float(self.decode()?)),
TypeCode::Integer => Ok(Value::Integer(self.decode()?)),
TypeCode::Long => Ok(Value::Long(self.decode()?)),
TypeCode::Short => Ok(Value::Short(self.decode()?)),
TypeCode::String => Ok(Value::String(self.decode()?)),
TypeCode::StringArray => Ok(Value::StringArray(self.decode()?)),
TypeCode::ByteArray => Ok(Value::ByteArray(self.decode()?)),
TypeCode::Dictionary => Ok(Value::Dictionary(self.decode()?)),
TypeCode::EventData => Ok(Value::EventData(self.decode()?)),
TypeCode::OperationRequest => Ok(Value::OperationRequest(self.decode()?)),
TypeCode::OperationResponse => Ok(Value::OperationResponse(self.decode()?)),
TypeCode::BooleanArray => Ok(Value::BooleanArray(self.decode()?)),
TypeCode::Array => Ok(Value::Array(self.decode()?)),
TypeCode::ObjectArray => Ok(Value::ObjectArray(self.decode()?)),
_ => Err(PhotonDecodeError::from(format!(
"Failed to decode Value, unknown type code ({:#X})",
type_code
))),
}
}
}
impl Decode<Value> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Value> {
let type_code: u8 = self.decode()?;
self.typed_decode(type_code)
}
}
impl Decode<PhotonHeader> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<PhotonHeader> {
let peer_id = self.decode()?;
let crc_enabled = self.decode()?;
let command_count = self.decode()?;
let timestamp = self.decode()?;
let challenge = self.decode()?;
Ok(PhotonHeader {
peer_id,
crc_enabled,
command_count,
timestamp,
challenge,
})
}
}
impl Decode<ReliableCommand> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<ReliableCommand> {
let channel_id = self.decode()?;
let flags = self.decode()?;
let reserved_byte = self.decode()?;
let length: u32 = self.decode()?;
let reliable_sequence_number = self.decode()?;
let msg_len = length.checked_sub(size_of::<ReliableCommand>() as u32)
.map_or(Err(PhotonDecodeError::from("Invalid ReliableCommand length")), |v| Ok(v))?;
Ok(ReliableCommand {
channel_id,
flags,
reserved_byte,
msg_len,
reliable_sequence_number,
})
}
}
impl Decode<UnreliableCommand> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<UnreliableCommand> {
let mut reliable_command: ReliableCommand = self.decode()?;
let unknown = self.decode()?;
reliable_command.msg_len = reliable_command.msg_len.checked_sub(size_of::<u32>() as u32)
.map_or(Err(PhotonDecodeError::from("Invalid UnreliableCommand length")), |v| Ok(v))?;
Ok(UnreliableCommand {
reliable_command,
unknown,
})
}
}
impl Decode<ReliableFragment> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<ReliableFragment> {
let mut reliable_command: ReliableCommand = self.decode()?;
let sequence_number = self.decode()?;
let fragment_count = self.decode()?;
let fragment_number = self.decode()?;
let total_length = self.decode()?;
let operation_length = self.decode()?;
reliable_command.msg_len = reliable_command.msg_len.checked_sub((size_of::<u32>() * 5) as u32)
.map_or(Err(PhotonDecodeError::from("Invalid ReliableFragment length")), |v| Ok(v))?;
let mut payload = vec![0u8; reliable_command.msg_len as usize];
self.read_exact(&mut payload)
.map_err(|e| PhotonDecodeError::from(format!("{}", e)))?;
Ok(ReliableFragment {
reliable_command,
sequence_number,
fragment_count,
fragment_number,
total_length,
operation_length,
payload,
})
}
}
impl Decode<Command> for PhotonCursor<'_> {
fn decode(&mut self) -> PhotonDecodeResult<Command> {
let cmd_type_id: u8 = self.decode()?;
match cmd_type_id {
4 => Ok(Command::LogOut),
6 => Ok(Command::SendReliable(self.decode()?)),
7 => Ok(Command::SendUnreliable(
Decode::<UnreliableCommand>::decode(self)?.reliable_command,
)),
8 => Ok(Command::SendReliableFragment(self.decode()?)),
_ => Ok(Command::SendReliable(self.decode()?)),
}
}
}
pub enum TypeCode {
None = 0x00,
Null = 0x2A,
Dictionary = 0x44,
StringArray = 0x61,
Byte = 0x62,
Double = 0x64,
EventData = 0x65,
Float = 0x66,
Integer = 0x69,
Short = 0x6B,
Long = 0x6C,
BooleanArray = 0x6E,
Boolean = 0x6F,
OperationResponse = 0x70,
OperationRequest = 0x71,
String = 0x73,
ByteArray = 0x78,
Array = 0x79,
ObjectArray = 0x7A,
Unknown,
}
impl From<u8> for TypeCode {
fn from(v: u8) -> Self {
match v {
0x00 => TypeCode::None,
0x2A => TypeCode::Null,
0x44 => TypeCode::Dictionary,
0x61 => TypeCode::StringArray,
0x62 => TypeCode::Byte,
0x64 => TypeCode::Double,
0x65 => TypeCode::EventData,
0x66 => TypeCode::Float,
0x69 => TypeCode::Integer,
0x6B => TypeCode::Short,
0x6C => TypeCode::Long,
0x6E => TypeCode::BooleanArray,
0x6F => TypeCode::Boolean,
0x70 => TypeCode::OperationResponse,
0x71 => TypeCode::OperationRequest,
0x73 => TypeCode::String,
0x78 => TypeCode::ByteArray,
0x79 => TypeCode::Array,
0x7A => TypeCode::ObjectArray,
_ => TypeCode::Unknown,
}
}
}
impl std::ops::Index<usize> for Value {
type Output = Value;
fn index(&self, index: usize) -> &Self::Output {
match self {
Value::Array(v) => &v[index],
_ => panic!("Non indexable type"),
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::String(v) => write!(f, "{}", v),
Value::Byte(v) => write!(f, "{}", v),
Value::Integer(v) => write!(f, "{}", v),
v => write!(f, "{:?}", v),
}
}
}
+36
View File
@@ -0,0 +1,36 @@
use core::fmt::{self, Display};
#[derive(Debug)]
pub struct PhotonDecodeError {
cause: String,
}
impl PhotonDecodeError {
pub fn extend(self, cause: String) -> Self {
Self {
cause: format!("{} {}", cause, self.cause),
}
}
}
pub type PhotonDecodeResult<T> = std::result::Result<T, PhotonDecodeError>;
impl Display for PhotonDecodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.cause, f)
}
}
// Allows writing `PhotonDecodeError::from("oops"))?`
impl From<&'static str> for PhotonDecodeError {
fn from(msg: &'static str) -> PhotonDecodeError {
PhotonDecodeError { cause: msg.into() }
}
}
// Allows writing `PhotonDecodeError::from("oops".into()))?`
impl From<String> for PhotonDecodeError {
fn from(msg: String) -> PhotonDecodeError {
PhotonDecodeError { cause: msg }
}
}
+94
View File
@@ -0,0 +1,94 @@
use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
None,
Dictionary(HashMap<String, Value>),
StringArray(Vec<String>),
Byte(u8),
Double(f64),
EventData(EventData),
Float(f32),
Integer(u32),
Short(i16),
Long(i64),
BooleanArray(Vec<bool>),
Boolean(bool),
OperationResponse(OperationResponse),
OperationRequest(OperationRequest),
String(String),
ByteArray(Vec<u8>),
Array(Vec<Value>),
Object(Box<Value>),
ObjectArray(Vec<Box<Value>>),
}
pub type Parameters = HashMap<u8, Value>;
#[derive(Clone, Debug, PartialEq)]
pub struct EventData {
pub code: u8,
pub parameters: Parameters,
}
#[derive(Clone, Debug, PartialEq)]
pub struct OperationResponse {
pub code: u8,
pub return_code: i16,
pub debug_message: String,
pub parameters: Parameters,
}
#[derive(Clone, Debug, PartialEq)]
pub struct OperationRequest {
pub code: u8,
pub parameters: Parameters,
}
#[derive(Debug, PartialEq)]
pub enum Message {
Request(OperationRequest),
Response(OperationResponse),
Event(EventData),
}
#[derive(Debug)]
pub struct PhotonHeader {
pub peer_id: i16,
pub crc_enabled: bool,
pub command_count: u8,
pub timestamp: u32,
pub challenge: u32,
}
#[derive(Debug, Clone)]
pub struct ReliableCommand {
pub channel_id: u8,
pub flags: u8,
pub reserved_byte: u8,
pub msg_len: u32,
pub reliable_sequence_number: u32,
}
pub struct UnreliableCommand {
pub reliable_command: ReliableCommand,
pub unknown: u32,
}
#[derive(Debug, Clone)]
pub struct ReliableFragment {
pub reliable_command: ReliableCommand,
pub sequence_number: u32,
pub fragment_count: u32,
pub fragment_number: u32,
pub total_length: u32,
pub operation_length: u32,
pub payload: Vec<u8>,
}
pub enum Command {
LogOut,
SendUnreliable(ReliableCommand),
SendReliable(ReliableCommand),
SendReliableFragment(ReliableFragment),
}
+114
View File
@@ -0,0 +1,114 @@
mod decode;
mod error;
mod layout;
pub use decode::*;
use error::*;
pub use layout::*;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::io::Cursor;
impl TryFrom<(&ReliableCommand, &mut Cursor<&[u8]>)> for Message {
type Error = PhotonDecodeError;
fn try_from(message: (&ReliableCommand, &mut Cursor<&[u8]>)) -> Result<Self, Self::Error> {
let (command, cursor) = message;
let _: u8 = cursor.decode()?;
let msg_type: u8 = cursor.decode()?;
match msg_type {
2 => {
let v = cursor.decode().map_err(|e| e.extend("Request".into()))?;
Ok(Message::Request(v))
}
3 => {
let v = cursor.decode().map_err(|e| e.extend("Response".into()))?;
Ok(Message::Response(v))
}
4 => {
let v = cursor.decode().map_err(|e| e.extend("Event".into()))?;
Ok(Message::Event(v))
}
_ => {
let msg_header_len = 2;
cursor.set_position(cursor.position() + command.msg_len as u64 - msg_header_len);
Err(PhotonDecodeError::from(format!(
"Unknown message ({:#X})",
msg_type
)))
}
}
}
}
pub struct Photon {
fragments: HashMap<u32, Vec<ReliableFragment>>,
}
impl Photon {
pub fn new() -> Self {
Self {
fragments: HashMap::new(),
}
}
pub fn try_decode(
&mut self,
payload: &[u8],
) -> PhotonDecodeResult<Vec<PhotonDecodeResult<Message>>> {
let mut cursor = Cursor::new(payload);
Ok(
(0..Decode::<PhotonHeader>::decode(&mut cursor)?.command_count)
.into_iter()
.map(|_| {
Decode::<Command>::decode(&mut cursor).map_or_else(
|e| Some(Err(e)),
|command| match command {
Command::SendReliable(c) | Command::SendUnreliable(c) => Some(
Message::try_from((&c, &mut cursor))
.map_err(|e| e.extend("SendReliable".into())),
),
Command::SendReliableFragment(fragment) => {
self.fragments
.entry(fragment.sequence_number)
.or_insert(vec![])
.push(fragment.clone());
self.decode_reliable_fragment(&fragment).map(|msg| {
self.fragments.remove(&fragment.sequence_number).unwrap();
msg.map_err(|e| e.extend("Fragment".into()))
})
}
_ => None,
},
)
})
.filter_map(|v| v)
.collect(),
)
}
pub fn decode(&mut self, payload: &[u8]) -> Vec<Message> {
if let Ok(messages) = self.try_decode(payload) {
return messages.into_iter().filter_map(Result::ok).collect();
}
vec![]
}
fn decode_reliable_fragment(
&mut self,
fragment: &ReliableFragment,
) -> Option<PhotonDecodeResult<Message>> {
if let Some(fragments) = self.fragments.get(&fragment.sequence_number) {
if fragments.len() == fragment.fragment_count as usize {
let mut buf = Vec::<u8>::new();
for fragment in fragments {
buf.extend(fragment.payload.iter());
}
let mut c = Cursor::new(&buf[..]);
return Some(Message::try_from((&fragment.reliable_command, &mut c)));
}
}
None
}
}
@@ -0,0 +1,361 @@
use photon_decode::*;
use std::io::Cursor;
#[test]
fn deserialize_dictionary() {
let value = vec![
68, 115, 115, 0, 2, 0, 8, 116, 101, 115, 116, 75, 101, 121, 49, 0, 10, 116, 101, 115,
116, 86, 97, 108, 117, 101, 49, 0, 8, 116, 101, 115, 116, 75, 101, 121, 50, 0, 10, 116,
101, 115, 116, 86, 97, 108, 117, 101, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Dictionary(v) => {
return assert_eq!(
v.get("testKey1"),
Some(&Value::String("testValue1".to_owned()))
)
}
_ => assert!(false),
}
}
#[test]
fn deserialize_string_array() {
let value = vec![
121, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 0, 5, 116, 101, 115, 116, 50, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Array(v) => {
if let Value::String(val) = &v[0] {
assert_eq!(val, &"test1".to_owned());
}
if let Value::String(val) = &v[1] {
assert_eq!(val, &"test2".to_owned());
}
return;
}
Value::StringArray(v) => {
return assert_eq!(vec!["test1".to_owned(), "test2".to_owned()], v)
}
_ => assert!(false),
}
}
#[test]
fn test_deserialize_byte() {
let value = vec![98, 6];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Byte(v) => return assert_eq!(v, 6),
_ => assert!(false),
}
}
#[test]
fn deserialize_double() {
let value = vec![100, 64, 147, 74, 51, 51, 51, 51, 51, 0, 0, 0, 0, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Double(v) => return assert_eq!(v, 1234.55),
_ => assert!(false),
}
}
#[test]
fn deserialize_event_data() {
let value = vec![
101, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116,
50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::EventData(v) => {
assert_eq!(v.code, 100);
assert_eq!(
v.parameters.get(&0).unwrap(),
&Value::String("test1".to_owned())
);
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_float() {
let value = vec![102, 68, 154, 81, 154, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Float(v) => return assert_eq!(v, 1234.55),
_ => assert!(false),
}
}
#[test]
fn deserialize_integer() {
let value = vec![105, 0, 0, 4, 210, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Integer(v) => return assert_eq!(v, 1234),
_ => assert!(false),
}
}
#[test]
fn deserialize_short() {
let value = vec![107, 4, 210, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Short(v) => return assert_eq!(v, 1234),
_ => assert!(false),
}
}
#[test]
fn deserialize_long() {
let value = vec![108, 0, 0, 0, 0, 0, 0, 4, 210, 0, 0, 0, 0, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Long(v) => return assert_eq!(v, 1234),
_ => assert!(false),
}
}
#[test]
fn deserialize_integer_array() {
let value = vec![121, 0, 2, 105, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Array(v) => {
if let Value::Integer(val) = v[0] {
assert_eq!(val, 0);
}
if let Value::Integer(val) = v[1] {
assert_eq!(val, 1);
}
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_boolean() {
let value = vec![111, 1];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Boolean(v) => return assert_eq!(v, true),
_ => assert!(false),
}
}
#[test]
fn deserialize_operation_response() {
let value = vec![
112, 100, 0, 100, 42, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116,
101, 115, 116, 50, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::OperationResponse(v) => {
assert_eq!(v.code, 100);
assert_eq!(v.return_code, 100);
assert_eq!(
v.parameters.get(&1).unwrap(),
&Value::String("test2".to_owned())
);
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_operation_request() {
let value = vec![
113, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116,
50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::OperationRequest(v) => {
assert_eq!(v.code, 100);
assert_eq!(
v.parameters.get(&1).unwrap(),
&Value::String("test2".to_owned())
);
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_string() {
let value = vec![
115, 0, 12, 116, 101, 115, 116, 95, 109, 101, 115, 115, 97, 103, 101, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::String(v) => return assert_eq!(&v, "test_message"),
_ => assert!(false),
}
}
#[test]
fn deserialize_byte_array() {
let value = vec![120, 0, 0, 0, 2, 6, 7, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::ByteArray(v) => {
assert_eq!(&v[0], &6);
assert_eq!(&v[1], &7);
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_array_dictionary() {
let value = vec![
121, 0, 1, 68, 105, 115, 0, 1, 0, 0, 0, 0, 0, 5, 116, 101, 115, 116, 49, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Array(v) => {
if let Value::Dictionary(val) = &v[0] {
assert_eq!(val.get("0").unwrap(), &Value::String("test1".to_owned()));
}
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_array_byte_array() {
let value = vec![121, 0, 1, 120, 0, 0, 0, 4, 0, 2, 4, 8, 0, 0, 0, 0];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Array(v) => {
if let Value::ByteArray(val) = &v[0] {
assert_eq!(val[0], 0);
assert_eq!(val[1], 2);
assert_eq!(val[2], 4);
assert_eq!(val[3], 8);
return;
}
}
_ => assert!(false),
}
}
#[test]
fn deserialize_array_array() {
let value = vec![
121, 0, 1, 121, 0, 3, 105, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::Array(v) => {
if let Value::Integer(val) = &v[0][0] {
assert_eq!(val, &1);
}
if let Value::Integer(val) = &v[0][1] {
assert_eq!(val, &2);
}
if let Value::Integer(val) = &v[0][2] {
assert_eq!(val, &3);
}
return;
}
_ => assert!(false),
}
}
#[test]
fn deserialize_object_array() {
let value = vec![
122, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 115, 0, 5, 116, 101, 115, 116, 50, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let mut buf = Cursor::new(&value[..]);
let result = buf.decode();
assert!(result.is_ok(), "Unimplemented!");
let value = result.unwrap();
match value {
Value::ObjectArray(v) => {
if let Value::Object(val) = &*v[0] {
assert_eq!(**val, Value::String("test1".to_owned()));
}
if let Value::Object(val) = &*v[1] {
assert_eq!(**val, Value::String("test2".to_owned()));
}
}
_ => assert!(false),
};
}
@@ -0,0 +1,311 @@
use photon_decode;
use photon_decode::Message;
use photon_decode::EventData;
use photon_decode::OperationRequest;
use photon_decode::OperationResponse;
use photon_decode::Value;
use photon_decode::Parameters;
#[test]
fn test_single_event_message()
{
let header = vec![
0x00, 0x01, // PeerID
0x01, // CrcEnabled
0x01, // CommandCount
0x00, 0x00, 0x00, 0x01, // Timestamp
0x00, 0x00, 0x00, 0x01, // Challenge
];
let photon_command = vec![
0x06, // Type
0x01, // ChannelID
0x01, // Flags
0x04, // ReservedByte
0x00, 0x00, 0x00, 0x1a, // Length
0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber
];
let message = vec![
0x01, // ??
0x04, // MsgType (Event)
// Payload
0x64, 0x00, 0x02, // Key
0x00, 0x73, // String type
0x00, 0x05, // String length
0x74, 0x65, 0x73, 0x74, 0x31 //test1
];
let mut photon = photon_decode::Photon::new();
let mut decoded = photon.try_decode(
&[&header[..], &photon_command[..], &message[..]].concat()).expect("Shold works").into_iter();
let msg = decoded.next().expect("Shold contain one msg").expect("Should decode event");
let parameters: Parameters =
[(0, Value::String("test1".to_owned()))]
.iter().cloned().collect();
assert_eq!(msg, Message::Event(EventData{ code: 100, parameters}));
}
#[test]
fn test_fragmented_event_message()
{
let header = vec![
0x00, 0x01, // PeerID
0x01, // CrcEnabled
0x01, // CommandCount
0x00, 0x00, 0x00, 0x01, // Timestamp
0x00, 0x00, 0x00, 0x01, // Challenge
];
let mut photon = photon_decode::Photon::new();
let photon_command = vec![
0x08, // Type
0x01, // ChannelID
0x01, // Flags
0x04, // ReservedByte
0x00, 0x00, 0x00, 0x22, // Length
0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber
0x00, 0x00, 0x00, 0x01, // SequenceNumber
0x00, 0x00, 0x00, 0x03, // FragmentCount
0x00, 0x00, 0x00, 0x01, // FragmentNumber
0x00, 0x00, 0x00, 0x1a, // TotalLength
0x00, 0x00, 0x00, 0x01, // OperationLength
];
let message = vec![
0x01, // ??
0x04, // MsgType (Event)
// Payload
];
let decoded = photon.decode(
&[&header[..], &photon_command[..], &message[..]].concat());
assert!(decoded.len() == 0);
let photon_command = vec![
0x08, // Type
0x01, // ChannelID
0x01, // Flags
0x04, // ReservedByte
0x00, 0x00, 0x00, 0x27, // Length
0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber
0x00, 0x00, 0x00, 0x01, // SequenceNumber
0x00, 0x00, 0x00, 0x03, // FragmentCount
0x00, 0x00, 0x00, 0x02, // FragmentNumber
0x00, 0x00, 0x00, 0x1a, // TotalLength
0x00, 0x00, 0x00, 0x01, // OperationLength
];
let message = vec![
// Payload
0x64, 0x00, 0x02, // Key
0x00, 0x73, // String type
0x00, 0x05, // String length
];
let decoded = photon.decode(
&[&header[..], &photon_command[..], &message[..]].concat());
assert!(decoded.len() == 0);
let photon_command = vec![
0x08, // Type
0x01, // ChannelID
0x01, // Flags
0x04, // ReservedByte
0x00, 0x00, 0x00, 0x25, // Length
0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber
0x00, 0x00, 0x00, 0x01, // SequenceNumber
0x00, 0x00, 0x00, 0x03, // FragmentCount
0x00, 0x00, 0x00, 0x03, // FragmentNumber
0x00, 0x00, 0x00, 0x1a, // TotalLength
0x00, 0x00, 0x00, 0x01, // OperationLength
];
let message = vec![
0x74, 0x65, 0x73, 0x74, 0x31 //test1
];
let decoded = photon.decode(
&[&header[..], &photon_command[..], &message[..]].concat());
assert_eq!(decoded.len(), 1);
let parameters: Parameters =
[(0, Value::String("test1".to_owned()))]
.iter().cloned().collect();
assert_eq!(decoded[0], Message::Event(EventData{ code: 100, parameters}));
}
#[test]
fn test_two_event_messages()
{
let payload = vec![
0x00, 0x00,
0x00,
0x02,
0x72, 0xe9, 0xe2, 0x84,
0x11, 0x63, 0x88, 0x88,
0x07,
0x00,
0x00,
0x00,
0x00, 0x00, 0x00, 0x45,
0x00, 0x00, 0x16, 0x8e,
0x00, 0x00, 0x45, 0x2b,
0xf3, 0x04, 0x02, 0x00, 0x02, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa, 0xb7, 0x36, 0x01, 0x78, 0x00, 0x00, 0x00, 0x20, 0x03, 0x6b, 0xc9, 0x04, 0xc1, 0xe2, 0x62, 0xd7, 0x08, 0x6b, 0xb0, 0x91, 0xc1, 0x2a, 0x80, 0x1b, 0xc2, 0x26, 0x00, 0x00, 0xb0, 0x40, 0xd8, 0xe6, 0x53, 0xc1, 0x8f, 0xcd, 0xc, 0xc2, 0x00, 0x00,
0x06,
0x00,
0x01,
0x00,
0x00, 0x00, 0x00, 0x1b,
0x00, 0x00, 0x16, 0x8f,
0xf3, 0x04, 0x01, 0x00, 0x02, 0x00, 0x69, 0x00, 0xa, 0xf6, 0xdf, 0xfc, 0x6b, 0x00, 0x01
];
let mut photon = photon_decode::Photon::new();
let decoded = photon.decode(&payload);
assert!(decoded.len() == 2);
let parameters: Parameters =
[
(0x01, Value::ByteArray(vec![
3, 107, 201, 4, 193, 226, 98, 215, 8, 107, 176, 145, 193,
42, 128, 27, 194, 38, 0, 0, 176, 64, 216, 230, 83, 193,
143, 205, 12, 194, 0, 0])),
(0x00, Value::Long(702262))
]
.iter().cloned().collect();
assert_eq!(decoded[0], Message::Event(EventData{ code: 2, parameters}));
let parameters: Parameters =
[
(0x00, Value::Integer(718559)),
(0xfc, Value::Short(1))
]
.iter().cloned().collect();
assert_eq!(decoded[1], Message::Event(EventData{ code: 1, parameters}));
}
#[test]
fn test_request_message()
{
let payload = vec![
0x7d, 0xd3,
0x00,
0x01,
0x00, 0x04, 0xcc, 0xb6,
0x11, 0x63, 0x88, 0x88,
0x06,
0x00,
0x01,
0x04,
0x00, 0x00, 0x00, 0x2a,
0x00, 0x00, 0x00, 0x19,
0xf3, 0x02, 0x01, 0x00, 0x03, 0x00,
0x79, 0x00, 0x02, 0x66, 0xc1, 0xd3, 0x61, 0x20, 0xc2, 0x27, 0xc, 0xcd, 0x01, 0x62,
0x00, 0xfd, // key
0x73, // String type
0x00, 0x05, // String length
0x74, 0x65, 0x73, 0x74, 0x31 // test1
];
let mut photon = photon_decode::Photon::new();
let decoded = photon.decode(&payload);
assert!(decoded.len() == 1);
let parameters: Parameters =
[
(0x00, Value::Array(vec![Value::Float(-26.422424), Value::Float(-41.7625)])),
(0x01, Value::Byte(0)),
(0xfd, Value::String("test1".to_owned()))
]
.iter().cloned().collect();
assert_eq!(decoded[0], Message::Request(OperationRequest { code: 1, parameters}));
}
#[test]
fn test_response_message()
{
let payload = vec![
0x00, 0x00,
0x00,
0x02,
0x72, 0xea, 0x1d, 0x6a,
0x11, 0x63, 0x88, 0x88,
0x01,
0x00,
0x00,
0x00,
0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x24, 0x00, 0x04, 0xd7, 0x1a,
0x06,
0x00,
0x01,
0x00,
0x00, 0x00, 0x00, 0xb2,
0x00, 0x00, 0x17, 0x71,
0xf3, 0x03, 0x01, 0x00, 0x00, 0x2a, 0x00, 0xa, 0x00, 0x69, 0x18, 0xf2, 0x79, 0x68, 0x01, 0x73, 0x00, 0x5d, 0x40, 0x49, 0x53, 0x4c, 0x41, 0x4e, 0x44, 0x40, 0x65, 0x66, 0x33, 0x37, 0x39, 0x34, 0x64, 0x61, 0x2d, 0x38, 0x66, 0x38, 0x33, 0x2d, 0x34, 0x33, 0x34, 0x30, 0x2d, 0x62, 0x66, 0x35, 0x32, 0x2d, 0x36, 0x38, 0x31, 0x31, 0x37, 0x61, 0x30, 0x36, 0x37, 0x32, 0x65, 0x34, 0x7c, 0x57, 0x65, 0x64, 0x72, 0x6f, 0x77, 0x79, 0x63, 0x7a, 0x4a, 0x61, 0x6b, 0x75, 0x62, 0x7c, 0x36, 0x33, 0x37, 0x30, 0x37, 0x35, 0x33, 0x37, 0x38, 0x38, 0x30, 0x33, 0x31, 0x38, 0x33, 0x39, 0x33, 0x35, 0x7c, 0x57, 0x65, 0x64, 0x72, 0x6f, 0x77, 0x79, 0x63, 0x7a, 0x4a, 0x61, 0x6b, 0x75, 0x62, 0x02, 0x79, 0x00, 0x00, 0x78, 0x03, 0x79, 0x00, 0x00, 0x73, 0x04, 0x79, 0x00, 0x00, 0x73, 0x05, 0x78, 0x00, 0x00, 0x00, 0x00, 0x06, 0x79, 0x00, 0x01, 0x79, 0x00, 0x01, 0x69, 0xff, 0xff, 0xff, 0xff, 0x07, 0x79, 0x00, 0x01, 0x79, 0x00, 0x01, 0x69, 0xff, 0xff, 0xff, 0xff, 0x08, 0x78, 0x00, 0x00, 0x00, 0x00, 0xfd, 0x6b, 0x00, 0xa6
];
let mut photon = photon_decode::Photon::new();
let decoded = photon.decode(&payload);
assert_eq!(decoded.len(), 1);
let parameters: Parameters =
[
(0x00, Value::Integer(418543976)),
(0x01, Value::String("@ISLAND@ef3794da-8f83-4340-bf52-68117a0672e4|WedrowyczJakub|637075378803183935|WedrowyczJakub".to_owned())),
(0x02, Value::Array(vec![])),
(0x03, Value::Array(vec![])),
(0x04, Value::Array(vec![])),
(0x05, Value::ByteArray(vec![])),
(0x06, Value::Array(vec![Value::Array(vec![Value::Integer(4294967295)])])),
(0x07, Value::Array(vec![Value::Array(vec![Value::Integer(4294967295)])])),
(0x08, Value::ByteArray(vec![])),
(0xFD, Value::Short(166)),
]
.iter().cloned().collect();
assert_eq!(decoded[0], Message::Response(OperationResponse { code: 1, return_code: 0, debug_message: "None".to_owned(), parameters}));
}
#[test]
fn test_example(){
use photon_decode::{Photon, Message};
let mut photon = Photon::new();
let photon_packet = vec![
0x00, 0x01, // PeerID
0x01, // CrcEnabled
0x00, // CommandCount
0x00, 0x00, 0x00, 0x01, // Timestamp
0x00, 0x00, 0x00, 0x01, // Challenge
];
for message in photon.decode(&photon_packet).iter() {
match message {
Message::Event(_) => {
// use event
},
Message::Request(_) => {
// use request
},
Message::Response(_) => {
// use response
}
}
}
}