use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, FixedOffset};
use chrono::prelude::*;
use std::convert::From;
use crate::structs::{ACL, ConnectionState, CwtchEvent, MessageWrapper, Profile, Settings};
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct ProfileIdentity(String);
impl From<String> for ProfileIdentity {
fn from(x: String) -> Self {
ProfileIdentity(x)
}
}
impl From<ProfileIdentity> for String {
fn from(x: ProfileIdentity) -> Self {
x.into()
}
}
impl From<&str> for ProfileIdentity {
fn from(x: &str) -> Self {
ProfileIdentity(x.to_string())
}
}
impl From<&ProfileIdentity> for String {
fn from(x: &ProfileIdentity) -> Self {
x.0.clone()
}
}
impl ProfileIdentity {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct ContactIdentity(String);
impl From<String> for ContactIdentity {
fn from(x: String) -> Self {
ContactIdentity(x)
}
}
impl ContactIdentity {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct ConversationID(pub i32) ;
impl From<i32> for ConversationID {
fn from(x: i32) -> Self {
ConversationID(x)
}
}
impl From<ConversationID> for i32 {
fn from(x: ConversationID) -> Self {
x.0
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct GroupID(String) ;
impl From<String> for GroupID {
fn from(x: String) -> Self {
GroupID(x)
}
}
impl GroupID {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct ServerIdentity(String);
impl From<String> for ServerIdentity {
fn from(x: String) -> Self {
ServerIdentity(x)
}
}
impl From<&str> for ServerIdentity {
fn from(x: &str) -> Self {
ServerIdentity(x.to_string())
}
}
impl From<ServerIdentity> for String {
fn from(x: ServerIdentity) -> Self {
x.into()
}
}
impl ServerIdentity {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub struct FileKey(String);
impl From<String> for FileKey {
fn from(x: String) -> Self {
FileKey(x)
}
}
impl From<FileKey> for String {
fn from(x: FileKey) -> Self {
x.into()
}
}
impl From<&FileKey> for String {
fn from(x: &FileKey) -> Self {
x.into()
}
}
impl FileKey {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Clone)]
pub enum MessageNotification {
None,
SimpleEvent,
ContactInfo,
}
impl From<String> for MessageNotification {
fn from(str: String) -> MessageNotification {
match str.as_str() {
"None" => MessageNotification::None,
"SimpleEvent" => MessageNotification::SimpleEvent,
"ContactInfo" => MessageNotification::ContactInfo,
_ => MessageNotification::None,
}
}
}
#[derive(Debug, Clone)]
pub enum NetworkCheckStatus {
Error,
Success
}
impl From<String> for NetworkCheckStatus {
fn from(str: String) -> NetworkCheckStatus {
match str.as_str() {
"Error" => NetworkCheckStatus::Error,
"Success" => NetworkCheckStatus::Success,
_ => NetworkCheckStatus::Error,
}
}
}
#[derive(Debug, Clone)]
pub enum ServerStorageType {
DefaultPassword,
Password,
NoPassword
}
impl From<String> for ServerStorageType {
fn from(str: String) -> ServerStorageType {
match str.as_str() {
"storage-default-password" => ServerStorageType::DefaultPassword,
"storage-password" => ServerStorageType::Password,
"storage-no-password" => ServerStorageType::NoPassword,
_ => ServerStorageType::DefaultPassword,
}
}
}
#[derive(Debug, Clone)]
pub enum ServerIntent {
Running,
Stopped
}
impl From<String> for ServerIntent {
fn from(str: String) -> ServerIntent {
match str.as_str() {
"running" => ServerIntent::Running,
"stopped" => ServerIntent::Stopped,
_ => ServerIntent::Stopped,
}
}
}
#[derive(Debug, Clone)]
pub enum Event {
CwtchStarted,
NewPeer {
profile_id: ProfileIdentity,
tag: String,
created: bool,
name: String,
default_picture: String,
picture: String,
online: String,
profile_data: Result<Profile, String>,
},
AppError {
error: String,
data: String
},
UpdateGlobalSettings {
settings: Settings,
},
PeerError {
error: String
},
PeerDeleted {
profile_id: ProfileIdentity
},
Shutdown,
ACNStatus {
progress: i8,
status: String,
},
ACNVersion {
version: String,
},
StartingStorageMiragtion,
DoneStorageMigration,
NewServer {
server: ServerIdentity,
server_bundle: String,
description: String,
storage_type: ServerStorageType,
autostart: bool,
running: bool,
},
ServerIntentUpdate {
server: ServerIdentity,
intent: ServerIntent,
},
ServerDeleted {
server: ServerIdentity,
success: bool,
error: Option<String>,
},
ServerStatsUpdate {
server: ServerIdentity,
total_messages: i32,
connections: i32,
},
NewMessageFromPeer {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
contact_id: ContactIdentity,
nick: String,
timestamp_received: DateTime<FixedOffset>,
message: MessageWrapper,
notification: MessageNotification,
picture: String,
},
ContactCreated {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
contact_id: ContactIdentity,
nick: String,
status: ConnectionState,
unread: i32,
picture: String,
default_picture: String,
num_messages: i32,
accepted: bool,
access_control_list: ACL,
blocked: bool,
loading: bool,
last_msg_time: DateTime<FixedOffset>,
},
PeerStateChange {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
connection_state: ConnectionState,
},
NetworkStatus {
profile_id: ProfileIdentity,
error: String,
status: NetworkCheckStatus,
},
ACNInfo {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
key: String,
data: String,
},
UpdatedProfileAttribute {
profile_id: ProfileIdentity,
key: String,
value: String,
},
IndexedAcknowledgement {
profile_id: ProfileIdentity,
conversation_id: i32,
index: i32,
},
IndexedFailure {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
index: i32,
contact_id: ContactIdentity,
error: String,
},
PeerAcknowledgement {
profile_id: ProfileIdentity,
event_id: String,
contact_id: ContactIdentity,
conversation_id: i32,
},
NewMessageFromGroup {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
timestamp_sent: DateTime<FixedOffset>,
contact_id: ContactIdentity,
index: i32,
message: MessageWrapper,
content_hash: String,
picture: String,
notification: MessageNotification,
},
GroupCreated {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
group_id: GroupID,
group_server: String,
group_name: String,
picture: String,
access_control_list: ACL,
},
NewGroup {
profile_id: ProfileIdentity,
conversation_id: ConversationID,
group_server: String,
group_invite: String,
group_name: String,
},
ServerStateChange {
profile_id: ProfileIdentity,
group_server: String,
state: ConnectionState,
},
NewRetValMessageFromPeer {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
scope: String,
path: String,
exists: bool,
data: String,
file_path: Option<String>,
},
ShareManifest {
profile_id: ProfileIdentity,
filekey: FileKey,
serialized_manifest: String,
},
ManifestSizeReceived {
profile_id: ProfileIdentity,
filekey: FileKey,
manifest_size: i32,
contact_id: ContactIdentity,
},
ManifestError {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
filekey: FileKey,
},
ManifestReceived {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
filekey: FileKey,
serialized_manifest: String,
},
ManifestSaved {
profile_id: ProfileIdentity,
contact_id: ContactIdentity,
filekey: FileKey,
serialized_manifest: String,
temp_file: String,
name_suggestion: String,
},
FileDownloadProgressUpdate {
profile_id: ProfileIdentity,
filekey: FileKey,
progress: i32,
filesize_in_chunks: i32,
name_suggestion: String,
},
ErrUnhandled {
name: String,
data: HashMap<String, String>,
},
}
impl From<&CwtchEvent> for Event {
fn from(cwtch_event: &CwtchEvent) -> Self {
println!("EVENT: {:?}", cwtch_event);
match cwtch_event.event_type.as_str() {
"CwtchStarted" => Event::CwtchStarted,
"NewPeer" => Event::NewPeer {
profile_id: cwtch_event.data["Identity"].clone().into(),
tag: cwtch_event.data["tag"].clone(),
created: cwtch_event.data["Created"] == "true",
name: cwtch_event.data["name"].clone(),
default_picture: cwtch_event.data["defaultPicture"].clone(),
picture: cwtch_event.data["picture"].clone(),
online: cwtch_event.data["Online"].clone(),
profile_data: Profile::new(
cwtch_event.data["Identity"].clone().into(),
&cwtch_event.data["name"],
&cwtch_event.data["picture"],
&cwtch_event.data["ContactsJson"],
&cwtch_event.data["ServerList"],
)
},
"NewMessageFromPeer" => Event::NewMessageFromPeer {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
conversation_id: cwtch_event.data["ConversationID"].parse().unwrap_or(-2).into(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
nick: cwtch_event.data["Nick"].clone(),
timestamp_received: DateTime::parse_from_rfc3339(cwtch_event.data["TimestampReceived"].as_str()).unwrap_or( DateTime::from(Utc::now())),
message: MessageWrapper::from_json(&cwtch_event.data["Data"]),
notification: MessageNotification::from(cwtch_event.data["notification"].clone()),
picture: cwtch_event.data["picture"].clone(),
},
"PeerError" => Event::PeerError { error: cwtch_event.data["Error"].clone() },
"AppError" => Event::AppError {
error: match cwtch_event.data.contains_key("Error") {
true => cwtch_event.data["Error"].clone(),
false => "".to_string()
},
data: match cwtch_event.data.contains_key("Data") {
true => cwtch_event.data["Data"].clone(),
false => "".to_string()
}
},
"ContactCreated" => Event::ContactCreated {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
conversation_id: cwtch_event.data["ConversationID"].clone().parse().unwrap_or(-2).into(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
unread: cwtch_event.data["unread"].clone().parse().unwrap_or(0),
picture: cwtch_event.data["picture"].clone(),
default_picture: cwtch_event.data["defaultPicture"].clone(),
num_messages: cwtch_event.data["numMessages"].clone().parse().unwrap_or(0),
nick: cwtch_event.data["nick"].clone(),
accepted: cwtch_event.data["accepted"].clone().parse().unwrap_or(false),
status: ConnectionState::from(cwtch_event.data["status"].as_str()),
access_control_list: serde_json::from_str(cwtch_event.data["accessControlList"].as_str()).unwrap_or(ACL::new()),
blocked: cwtch_event.data["blocked"].clone().parse().unwrap_or(false),
loading: cwtch_event.data["loading"].clone().parse().unwrap_or(false),
last_msg_time: DateTime::parse_from_rfc3339(cwtch_event.data["lastMsgTime"].as_str()).unwrap_or(DateTime::from(Utc::now())),
},
"PeerStateChange" => Event::PeerStateChange {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
connection_state: ConnectionState::from(cwtch_event.data["ConnectionState"].as_str()),
},
"UpdateGlobalSettings" => Event::UpdateGlobalSettings {
settings: serde_json::from_str(cwtch_event.data["Data"].as_str()).expect("could not parse settings from libCwtch-go"),
},
"PeerDeleted" => Event::PeerDeleted { profile_id: cwtch_event.data["Identity"].clone().into() },
"ACNStatus" => Event::ACNStatus {
progress: cwtch_event.data["Progress"].parse().unwrap_or(0),
status: cwtch_event.data["Status"].clone(),
},
"ACNVersion" => Event::ACNVersion { version: cwtch_event.data["Data"].clone()},
"NetworkError" => Event::NetworkStatus {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
error: cwtch_event.data["Error"].clone(),
status: NetworkCheckStatus::from(cwtch_event.data["Status"].clone())
},
"ACNInfo" => Event::ACNInfo {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["Handle"].clone().into(),
key: cwtch_event.data["Key"].clone(),
data: cwtch_event.data["Data"].clone(),
},
"UpdatedProfileAttribute" => Event::UpdatedProfileAttribute {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
key: cwtch_event.data["Key"].clone(),
value: cwtch_event.data["Data"].clone(),
},
"IndexedAcknowledgement" => Event::IndexedAcknowledgement {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
conversation_id: cwtch_event.data["ConversationID"].parse().unwrap_or(-1).into(),
index: cwtch_event.data["Index"].parse().unwrap_or(-1),
},
"ShareManifest" => Event::ShareManifest {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
serialized_manifest: cwtch_event.data["SerializedManifest"].clone(),
},
"NewServer" => Event::NewServer {
server: cwtch_event.data["Onion"].clone().into(),
server_bundle: cwtch_event.data["ServerBundle"].clone(),
description: cwtch_event.data["Description"].clone(),
storage_type: ServerStorageType::from(cwtch_event.data["StorageType"].clone()),
autostart: cwtch_event.data["Autostart"].parse().unwrap_or(false),
running: cwtch_event.data["Running"].parse().unwrap_or(false),
},
"ServerIntentUpdate" => Event::ServerIntentUpdate {
server: cwtch_event.data["Identity"].clone().into(),
intent: ServerIntent::from(cwtch_event.data["Intent"].clone())
},
"ServerDeleted" => Event::ServerDeleted {
server: cwtch_event.data["Identity"].clone().into(),
success: cwtch_event.data["Status"].clone() == "success",
error: match cwtch_event.data.get("Error") {
Some(e) => Some(e.clone()),
None => None,
}
},
"ServerStatsUpdate" => Event::ServerStatsUpdate {
server: cwtch_event.data["Identity"].clone().into(),
total_messages: cwtch_event.data["TotalMessages"].parse().unwrap_or(0),
connections: cwtch_event.data["Connections"].parse().unwrap_or(0),
},
"ManifestSizeReceived" => Event::ManifestSizeReceived {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
manifest_size: cwtch_event.data["ManifestSize"].parse().unwrap_or(0),
contact_id: cwtch_event.data["Handle"].clone().into(),
},
"ManifestError" => Event::ManifestError {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["Handle"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
},
"ManifestReceived" => Event::ManifestReceived {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["Handle"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
serialized_manifest: cwtch_event.data["SerializedManifest"].clone(),
},
"ManifestSaved" => Event::ManifestSaved {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["Handle"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
serialized_manifest: cwtch_event.data["SerializedManifest"].clone(),
temp_file: cwtch_event.data["TempFile"].clone(),
name_suggestion: cwtch_event.data["NameSuggestion"].clone(),
},
"FileDownloadProgressUpdate" => Event::FileDownloadProgressUpdate {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
filekey: cwtch_event.data["FileKey"].clone().into(),
progress: cwtch_event.data["Progress"].parse().unwrap_or(0),
filesize_in_chunks: cwtch_event.data["FileSizeInChunks"].parse().unwrap_or(0),
name_suggestion: cwtch_event.data["NameSuggestion"].clone(),
},
"PeerAcknowledgement" => Event::PeerAcknowledgement {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
event_id: cwtch_event.data["EventID"].clone(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
conversation_id: cwtch_event.data.get("ConversationID").unwrap_or(&"0".to_string()).parse().unwrap_or(0)
},
"NewMessageFromGroup" => Event::NewMessageFromGroup {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
timestamp_sent: DateTime::parse_from_rfc3339(cwtch_event.data["TimestampSent"].as_str()).unwrap_or( DateTime::from(Utc::now())),
index: cwtch_event.data["RemotePeer"].parse().unwrap_or(-1),
content_hash: cwtch_event.data["ContentHash"].clone(),
conversation_id: cwtch_event.data["ConversationID"].parse().unwrap_or(-2).into(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
message: MessageWrapper::from_json(&cwtch_event.data["Data"]),
notification: MessageNotification::from(cwtch_event.data["notification"].clone()),
picture: cwtch_event.data["picture"].clone(),
},
"GroupCreated" => Event::GroupCreated {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
conversation_id: cwtch_event.data["ConversationID"].parse().unwrap_or(-2).into(),
group_id: cwtch_event.data["GroupID"].clone().into(),
group_server: cwtch_event.data["GroupServer"].clone(),
group_name: cwtch_event.data["GroupName"].clone(),
picture: cwtch_event.data["picture"].clone(),
access_control_list: serde_json::from_str(cwtch_event.data["accessControlList"].as_str()).unwrap_or(ACL::new()),
},
"NewGroup" => Event::NewGroup {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
conversation_id: cwtch_event.data["ConversationID"].parse().unwrap_or(-2).into(),
group_server: cwtch_event.data["GroupServer"].clone(),
group_name: cwtch_event.data["GroupName"].clone(),
group_invite: cwtch_event.data["GroupInvite"].clone(),
},
"ServerStateChange" => Event::ServerStateChange {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
group_server: cwtch_event.data["GroupServer"].clone(),
state: ConnectionState::from(cwtch_event.data["ConnectionState"].as_str()),
},
"NewRetValMessageFromPeer" => Event::NewRetValMessageFromPeer {
profile_id: cwtch_event.data["ProfileOnion"].clone().into(),
contact_id: cwtch_event.data["RemotePeer"].clone().into(),
scope: cwtch_event.data["Scope"].clone(),
path: cwtch_event.data["Path"].clone(),
exists: cwtch_event.data["Exists"].parse().unwrap_or(false),
data: cwtch_event.data["Data"].clone(),
file_path: match cwtch_event.data.get("FilePath") {
Some(fp) => Some(fp.to_string()),
None => None,
},
},
_ => Event::ErrUnhandled {
name: cwtch_event.event_type.to_string(),
data: cwtch_event.data.clone(),
},
}
}
}