Skip to content

Commit

Permalink
fix: adjust for server change
Browse files Browse the repository at this point in the history
  • Loading branch information
Zxilly committed Jan 17, 2023
1 parent e0de762 commit f2a8858
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 92 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "znotify"
version = "0.1.1"
version = "0.2.0"
edition = "2021"
license = "Apache-2.0"
homepage = "https://github.com/ZNotify/rs-sdk"
Expand Down
64 changes: 28 additions & 36 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,8 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::constant::ENDPOINT;
use crate::entity::{Message, MessageOptions};
use crate::entity::{Channel, ClientResponse, Message, MessageOptions};

#[derive(Debug, Serialize, Deserialize)]
struct ClientResponse<T> {
code: i32,
body: T,
}

#[derive(Debug)]
pub enum ChannelType {
WebSocket,
FCM,
}

impl ChannelType {
fn as_str(&self) -> &'static str {
match self {
ChannelType::WebSocket => "websocket",
ChannelType::FCM => "fcm",
}
}
}

pub struct Client {
endpoint: String,
Expand All @@ -47,8 +27,8 @@ impl Client {
}
}

pub async fn create(user_id: String, endpoint: Option<String>) -> Result<Self, Box<dyn Error>> {
let client = Self::new(user_id, endpoint);
pub async fn create(user_secret: String, endpoint: Option<String>) -> Result<Self, Box<dyn Error>> {
let client = Self::new(user_secret, endpoint);
let ret = client.check().await;
if ret.is_ok() {
Ok(client)
Expand All @@ -61,13 +41,13 @@ impl Client {
let resp = self
.client
.get(format!("{}/check", self.endpoint))
.query(&[("user_id", self.user_id.clone())])
.query(&[("user_secret", self.user_id.clone())])
.send()
.await?;

let resp: ClientResponse<bool> = resp.json().await?;
if !resp.body {
Err("User ID not valid")?
Err("User secret not valid")?
}
Ok(())
}
Expand Down Expand Up @@ -107,41 +87,53 @@ impl Client {
}
}

pub async fn delete(&self, id: String) -> Result<(), Box<dyn Error>> {
pub async fn delete_message(&self, id: String) -> Result<bool, Box<dyn Error>> {
let client = ReqClient::new();
client
.delete(format!("{}/{}/{}", self.endpoint, self.user_id, id))
let resp = client
.delete(format!("{}/{}/message/{}", self.endpoint, self.user_id, id))
.send()
.await?;
Ok(())

if resp.status().is_success() {
let resp: ClientResponse<bool> = resp.json().await?;
Ok(resp.body)
} else {
let resp: ClientResponse<String> = resp.json().await?;
Err(resp.body)?
}
}

pub async fn register(
pub async fn create_device(
&self,
channel: ChannelType,
token: String,
channel: Channel,
device_id: String,
) -> Result<(), Box<dyn Error>> {
token: Option<String>,
device_name: Option<String>,
device_meta: Option<String>,
) -> Result<bool, Box<dyn Error>> {
if !Uuid::parse_str(&device_id).is_ok() {
Err("Device ID not valid, should be a UUID")?
}

let mut data = HashMap::new();
data.insert("channel", format!("{:?}", channel));
data.insert("token", token);
data.insert("token", token.unwrap_or_default());
data.insert("device_name", device_name.unwrap_or_default());
data.insert("device_meta", device_meta.unwrap_or_default());

let resp = self
.client
.put(format!(
"{}/{}/token/{}",
"{}/{}/device/{}",
self.endpoint, self.user_id, device_id
))
.form(&data)
.send()
.await?;

if resp.status().is_success() {
Ok(())
let resp: ClientResponse<bool> = resp.json().await?;
Ok(resp.body)
} else {
let resp: ClientResponse<String> = resp.json().await?;
Err(resp.body)?
Expand Down
60 changes: 52 additions & 8 deletions src/entity.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,58 @@
use std::fmt;
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Debug)]
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Priority {
#[serde(rename = "high")]
High,

#[serde(rename = "normal")]
Normal,

#[serde(rename = "low")]
Low,
}

impl Priority {
pub fn to_string(&self) -> String {
impl ToString for Priority {
fn to_string(&self) -> String {
match self {
Priority::High => "high",
Priority::Normal => "normal",
Priority::Low => "low",
}
.to_string()
}
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Channel {
#[serde(rename = "WebSocket")]
WebSocket,

#[serde(rename = "FCM")]
FCM,

#[serde(rename = "WebPush")]
WebPush,

#[serde(rename = "WNS")]
WNS,

#[serde(rename = "Telegram")]
Telegram,
}

impl ToString for Channel {
fn to_string(&self) -> String {
match self {
Priority::High => "high".to_string(),
Priority::Normal => "normal".to_string(),
Priority::Low => "low".to_string(),
Channel::WebSocket => "WebSocket",
Channel::FCM => "FCM",
Channel::WebPush => "WebPush",
Channel::WNS => "WNS",
Channel::Telegram => "Telegram",
}
.to_string()
}
}

Expand All @@ -30,8 +68,8 @@ pub struct Message {
pub title: String,
pub content: String,
pub long: String,
pub user_id: String,
pub created_at: String,
pub priority: Priority,
}

#[derive(Debug)]
Expand All @@ -48,7 +86,13 @@ impl Default for MessageOptions {
content: String::new(),
title: None,
long: None,
priority: Some(Priority::Normal),
priority: Some(Priority::default()),
}
}
}

#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct ClientResponse<T> {
pub(crate) code: i32,
pub(crate) body: T,
}
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

pub mod client;
pub mod entity;
pub mod send;

mod constant;

pub use self::client::Client;
pub use self::entity::{Message, MessageOptions};
pub use self::send::send;
21 changes: 0 additions & 21 deletions src/send.rs

This file was deleted.

56 changes: 52 additions & 4 deletions tests/client_test.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use znotify::{Client, MessageOptions};
use znotify::entity::{Channel, Priority};

#[tokio::test]
async fn test_client_create_err() {
let client = Client::create("error".to_string(), None).await;
assert!(client.is_err());
assert!(client
assert_eq!("User secret not valid", client
.err()
.unwrap()
.to_string()
.contains("User ID not valid"));
.to_string())
}

#[tokio::test]
Expand All @@ -28,14 +28,15 @@ async fn client_send() {
content: content.clone(),
title: title.clone(),
long: long.clone(),
priority: None,
priority: Some(Priority::High),
})
.await;
assert!(message.is_ok());
let message = message.unwrap();
assert_eq!(message.content, content);
assert_eq!(message.title, title.unwrap());
assert_eq!(message.long, long.unwrap());
assert_eq!(message.priority, Priority::High);
}

#[tokio::test]
Expand All @@ -59,3 +60,50 @@ async fn client_send_failed() {
.to_string()
.contains("Content is required"));
}

#[tokio::test]
async fn client_delete() {
let content = "test".to_string();
let title = Some("test_title".to_string());
let long = Some("test_long".to_string());
let client = Client::create("test".to_string(), None).await.unwrap();
let message = client
.send(MessageOptions {
content: content.clone(),
title: title.clone(),
long: long.clone(),
priority: Some(Priority::High),
})
.await;
assert!(message.is_ok());
let message = message.unwrap();
let id = message.id;

let ret = client.delete_message(id).await;
assert!(ret.is_ok());
assert!(ret.unwrap());
}

#[tokio::test]
async fn client_create_device() {
let client = Client::create("test".to_string(), None).await.unwrap();
let ret = client.create_device(
Channel::FCM,
"test".to_string(),
Some("test".to_string()),
Some("test".to_string()),
Some("test".to_string()),
).await;
assert!(ret.is_err());
assert_eq!(ret.unwrap_err().to_string(), "Device ID not valid, should be a UUID");

let ret2 = client.create_device(
Channel::FCM,
"9a31666d-1b9e-4d9b-ba63-53c9f381e52b".to_string(),
Some("test".to_string()),
Some("test".to_string()),
Some("test".to_string()),
).await;
assert!(ret2.is_ok());
assert!(ret2.unwrap());
}
20 changes: 0 additions & 20 deletions tests/send_test.rs

This file was deleted.

0 comments on commit f2a8858

Please sign in to comment.