Browse Source

use anyhow to replace new_io_error

pull/18/head
Sun 4 years ago
parent
commit
d8fdbaaa8d
  1. 6
      Cargo.toml
  2. 22
      src/account.rs
  3. 4
      src/apps/assistant/models.rs
  4. 12
      src/apps/chat/layer.rs
  5. 11
      src/apps/device/rpc.rs
  6. 78
      src/apps/group_chat/layer.rs
  7. 18
      src/apps/group_chat/models.rs
  8. 3
      src/daemon.rs
  9. 4
      src/event.rs
  10. 26
      src/group.rs
  11. 6
      src/group/running.rs
  12. 16
      src/layer.rs
  13. 3
      src/lib.rs
  14. 5
      src/migrate.rs
  15. 4
      src/rpc.rs
  16. 6
      src/server.rs
  17. 10
      src/session.rs
  18. 27
      src/storage.rs

6
Cargo.toml

@ -20,18 +20,18 @@ codegen-units = 1 @@ -20,18 +20,18 @@ codegen-units = 1
panic = 'abort'
[dependencies]
anyhow = "1.0"
log = "0.4"
rand = "0.8"
once_cell = "1.7"
simplelog = "0.10"
image = "0.23"
base64 = "0.13"
sha2 = "0.9"
blake3 = "0.3"
aes-gcm = "0.8"
bincode = "1.3"
serde = { version = "1", features = ["derive"] }
aes-gcm = "0.8"
sysinfo = "0.16"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
tdn = { version = "0.5", default-features = false, features = ["full"] }
tdn_did = { git = "https://github.com/cypherlink/tdn_did", branch="main" }

22
src/account.rs

@ -3,7 +3,7 @@ use aes_gcm::Aes256Gcm; @@ -3,7 +3,7 @@ use aes_gcm::Aes256Gcm;
use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::{EventId, GroupId},
primitive::{new_io_error, Result},
primitive::Result,
};
use tdn_did::{genereate_id, Keypair};
use tdn_storage::local::{DStorage, DsValue};
@ -65,11 +65,11 @@ impl Account { @@ -65,11 +65,11 @@ impl Account {
let mnemonic_bytes = cipher
.encrypt(nonce, mnemonic.as_bytes())
.map_err(|_e| new_io_error("mnemonic lock invalid."))?;
.map_err(|_e| anyhow!("mnemonic lock invalid."))?;
let sk_bytes = cipher
.encrypt(nonce, sk.to_bytes().as_ref())
.map_err(|_e| new_io_error("secret lock invalid."))?;
.map_err(|_e| anyhow!("secret lock invalid."))?;
Ok((
Account::new(
@ -101,19 +101,19 @@ impl Account { @@ -101,19 +101,19 @@ impl Account {
let mnemonic = cipher
.decrypt(old_nonce, self.mnemonic.as_ref())
.map_err(|_e| new_io_error("mnemonic unlock invalid."))?;
.map_err(|_e| anyhow!("mnemonic unlock invalid."))?;
self.mnemonic = cipher
.encrypt(new_nonce, mnemonic.as_ref())
.map_err(|_e| new_io_error("mnemonic lock invalid."))?;
.map_err(|_e| anyhow!("mnemonic lock invalid."))?;
let secret = cipher
.decrypt(old_nonce, self.secret.as_ref())
.map_err(|_e| new_io_error("secret unlock invalid."))?;
.map_err(|_e| anyhow!("secret unlock invalid."))?;
self.secret = cipher
.encrypt(new_nonce, secret.as_ref())
.map_err(|_e| new_io_error("secret lock invalid."))?;
.map_err(|_e| anyhow!("secret lock invalid."))?;
Ok(())
}
@ -125,9 +125,9 @@ impl Account { @@ -125,9 +125,9 @@ impl Account {
let plaintext = cipher
.decrypt(nonce, self.mnemonic.as_ref())
.map_err(|_e| new_io_error("mnemonic unlock invalid."))?;
.map_err(|_e| anyhow!("mnemonic unlock invalid."))?;
String::from_utf8(plaintext).map_err(|_e| new_io_error("mnemonic unlock invalid."))
String::from_utf8(plaintext).map_err(|_e| anyhow!("mnemonic unlock invalid."))
}
pub fn secret(&self, skey: &[u8], lock: &str) -> Result<Keypair> {
@ -137,9 +137,9 @@ impl Account { @@ -137,9 +137,9 @@ impl Account {
let plaintext = cipher
.decrypt(nonce, self.secret.as_ref())
.map_err(|_e| new_io_error("secret unlock invalid."))?;
.map_err(|_e| anyhow!("secret unlock invalid."))?;
Keypair::from_bytes(&plaintext).map_err(|_e| new_io_error("secret unlock invalid."))
Keypair::from_bytes(&plaintext).map_err(|_e| anyhow!("secret unlock invalid."))
}
/// here is zero-copy and unwrap is safe. checked.

4
src/apps/assistant/models.rs

@ -3,7 +3,7 @@ use std::path::PathBuf; @@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::GroupId,
primitive::{new_io_error, Result},
primitive::Result,
rpc::{json, RpcError, RpcParam},
};
use tdn_storage::local::{DStorage, DsValue};
@ -72,7 +72,7 @@ impl MessageType { @@ -72,7 +72,7 @@ impl MessageType {
(self, filename.clone(), MessageType::File, filename)
}
MessageType::Contact => {
let cid: i64 = content.parse().map_err(|_e| new_io_error("id error"))?;
let cid: i64 = content.parse().map_err(|_| anyhow!("parse i64 failure!"))?;
let db = chat_db(base, mgid)?;
let contact = Friend::get_id(&db, cid)?.ok_or(RpcError::ParseError)?;
db.close()?;

12
src/apps/chat/layer.rs

@ -4,7 +4,7 @@ use std::sync::Arc; @@ -4,7 +4,7 @@ use std::sync::Arc;
use tdn::types::{
group::{EventId, GroupId},
message::{RecvType, SendType},
primitive::{new_io_error, DeliveryType, HandleResult, PeerAddr, Result},
primitive::{DeliveryType, HandleResult, PeerAddr, Result},
rpc::RpcError,
};
use tdn_did::{user::User, Proof};
@ -139,8 +139,7 @@ fn handle_connect( @@ -139,8 +139,7 @@ fn handle_connect(
results: &mut HandleResult,
) -> Result<bool> {
// 0. deserialize connect data.
let proof: Proof = bincode::deserialize(&data)
.map_err(|_e| new_io_error("Deseralize chat layer connect failure"))?;
let proof: Proof = bincode::deserialize(&data)?;
// 1. check verify.
proof.verify(fgid, addr, &layer.addr)?;
@ -177,8 +176,7 @@ impl LayerEvent { @@ -177,8 +176,7 @@ impl LayerEvent {
addr: PeerAddr,
bytes: Vec<u8>,
) -> Result<HandleResult> {
let event: LayerEvent =
bincode::deserialize(&bytes).map_err(|_| new_io_error("serialize event error."))?;
let event: LayerEvent = bincode::deserialize(&bytes)?;
let mut results = HandleResult::new();
@ -330,7 +328,7 @@ impl LayerEvent { @@ -330,7 +328,7 @@ impl LayerEvent {
let (_sid, fid) = layer.get_running_remote_id(&mgid, &fgid)?;
let avatar = remote.avatar.clone();
let db = chat_db(&layer.base, &mgid)?;
let mut f = Friend::get_id(&db, fid)?.ok_or(new_io_error(""))?;
let mut f = Friend::get_id(&db, fid)?.ok_or(anyhow!("friend not found"))?;
f.name = remote.name;
f.addr = remote.addr;
f.remote_update(&db)?;
@ -400,7 +398,7 @@ impl LayerEvent { @@ -400,7 +398,7 @@ impl LayerEvent {
(NetworkMessage::File(filename.clone(), bytes), filename)
}
MessageType::Contact => {
let cid: i64 = content.parse().map_err(|_e| new_io_error("id error"))?;
let cid: i64 = content.parse().map_err(|_| anyhow!("parse i64 failure!"))?;
let contact = Friend::get_id(&db, cid)?.ok_or(RpcError::ParseError)?;
let avatar_bytes = read_avatar(base, &mgid, &contact.gid).await?;
let tmp_name = contact.name.replace(";", "-;");

11
src/apps/device/rpc.rs

@ -1,7 +1,7 @@ @@ -1,7 +1,7 @@
use std::sync::Arc;
use tdn::types::{
group::GroupId,
primitive::{new_io_error, HandleResult, PeerAddr},
primitive::{HandleResult, PeerAddr},
rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam},
};
@ -81,8 +81,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) { @@ -81,8 +81,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) {
handler.add_method(
"device-status",
|gid: GroupId, params: Vec<RpcParam>, state: Arc<RpcState>| async move {
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)
.map_err(|_e| new_io_error("PeerAddr invalid!"))?;
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)?;
let group_lock = state.group.read().await;
if &addr == group_lock.addr() {
@ -108,8 +107,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) { @@ -108,8 +107,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) {
handler.add_method(
"device-create",
|gid: GroupId, params: Vec<RpcParam>, state: Arc<RpcState>| async move {
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)
.map_err(|_e| new_io_error("PeerAddr invalid!"))?;
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)?;
let msg = state.group.read().await.create_message(&gid, addr)?;
Ok(HandleResult::group(gid, msg))
@ -119,8 +117,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) { @@ -119,8 +117,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<RpcState>) {
handler.add_method(
"device-connect",
|gid: GroupId, params: Vec<RpcParam>, state: Arc<RpcState>| async move {
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)
.map_err(|_e| new_io_error("PeerAddr invalid!"))?;
let addr = PeerAddr::from_hex(params[0].as_str().ok_or(RpcError::ParseError)?)?;
let msg = state.group.read().await.connect_message(&gid, addr)?;
Ok(HandleResult::group(gid, msg))

78
src/apps/group_chat/layer.rs

@ -4,7 +4,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; @@ -4,7 +4,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::GroupId,
message::{RecvType, SendType},
primitive::{new_io_error, HandleResult, PeerAddr, Result},
primitive::{HandleResult, PeerAddr, Result},
};
use tokio::sync::RwLock;
@ -43,9 +43,7 @@ pub(crate) async fn handle( @@ -43,9 +43,7 @@ pub(crate) async fn handle(
return Ok(results);
}
let LayerConnect(gcd, connect) = bincode::deserialize(&data)
.map_err(|_e| new_io_error("deserialize group chat connect failure"))?;
let LayerConnect(gcd, connect) = bincode::deserialize(&data)?;
let (ogid, height, id) = layer.read().await.running(&gcd)?.owner_height_id();
match connect {
@ -70,8 +68,7 @@ pub(crate) async fn handle( @@ -70,8 +68,7 @@ pub(crate) async fn handle(
results.rpcs.push(rpc::member_online(mgid, id, fgid, addr));
let new_data =
bincode::serialize(&LayerEvent::MemberOnline(gcd, fgid, addr))
.map_err(|_| new_io_error("serialize event error."))?;
bincode::serialize(&LayerEvent::MemberOnline(gcd, fgid, addr))?;
for (mid, maddr) in layer.read().await.running(&gcd)?.onlines() {
let s = SendType::Event(0, *maddr, new_data.clone());
@ -116,8 +113,7 @@ pub(crate) async fn handle( @@ -116,8 +113,7 @@ pub(crate) async fn handle(
}
RecvType::Event(addr, bytes) => {
// server & client handle it.
let event: LayerEvent =
bincode::deserialize(&bytes).map_err(|_| new_io_error("serialize event error."))?;
let event: LayerEvent = bincode::deserialize(&bytes)?;
handle_event(fgid, mgid, is_server, addr, event, layer, &mut results).await?;
}
RecvType::Stream(_uid, _stream, _bytes) => {
@ -139,11 +135,11 @@ fn handle_connect( @@ -139,11 +135,11 @@ fn handle_connect(
results: &mut HandleResult,
) -> Result<bool> {
// 0. deserialize result.
let LayerResult(gcd, height) =
bincode::deserialize(&data).map_err(|_e| new_io_error("Deseralize result failure"))?;
let LayerResult(gcd, height) = bincode::deserialize(&data)?;
// 1. check group.
if let Some(group) = load_group(layer.base(), &mgid, &gcd)? {
let db = group_chat_db(layer.base(), &mgid)?;
if let Some(group) = GroupChat::get(&db, &gcd)? {
// 1.0 check address.
if group.g_addr != addr {
return Ok(false);
@ -202,8 +198,7 @@ async fn handle_event( @@ -202,8 +198,7 @@ async fn handle_event(
results.rpcs.push(rpc::member_offline(ogid, id, fgid));
// 3. broadcast offline event.
let new_data = bincode::serialize(&LayerEvent::MemberOffline(gcd, fgid))
.map_err(|_| new_io_error("serialize event error."))?;
let new_data = bincode::serialize(&LayerEvent::MemberOffline(gcd, fgid))?;
for (mid, maddr) in layer.read().await.running(&gcd)?.onlines() {
let s = SendType::Event(0, *maddr, new_data.clone());
@ -426,20 +421,15 @@ async fn handle_event( @@ -426,20 +421,15 @@ async fn handle_event(
let (ogid, height, id) = layer.read().await.running(&gcd)?.owner_height_id();
let base = layer.read().await.base.clone();
let db = group_chat_db(&base, &ogid)?;
let group = GroupChat::get_id(&db, &id)?.ok_or(new_io_error("missing group"))?;
let group = GroupChat::get_id(&db, &id)?.ok_or(anyhow!("missing group"))?;
// 1. check account is online, if not online, nothing.
match join_proof {
JoinProof::Open(mname, mavatar) => {
// check is member.
if let Ok(mid) = Member::get_id(&db, &id, &fgid) {
let gavatar = read_avatar(&base, &ogid, &gcd).await?;
let group_info = group.to_group_info("".to_owned(), gavatar, vec![]);
let res = LayerEvent::Agree(gcd, group_info);
let d = bincode::serialize(&res).unwrap_or(vec![]);
let s = SendType::Event(0, addr, d);
if Member::get_id(&db, &id, &fgid).is_ok() {
let s = agree(&base, &ogid, &gcd, group, addr).await;
add_server_layer(results, fgid, s);
return Ok(());
}
@ -461,24 +451,16 @@ async fn handle_event( @@ -461,24 +451,16 @@ async fn handle_event(
// self.broadcast_join(&gcd, m, mavatar, results).await?;
// return join result.
let gavatar = read_avatar(&base, &ogid, &gcd).await?;
let group_info = group.to_group_info("".to_owned(), gavatar, vec![]);
let res = LayerEvent::Agree(gcd, group_info);
let d = bincode::serialize(&res).unwrap_or(vec![]);
let s = SendType::Event(0, addr, d);
let s = agree(&base, &ogid, &gcd, group, addr).await;
add_server_layer(results, fgid, s);
} else {
// Self::reject(gcd, fmid, addr, false, results);
add_server_layer(results, fgid, reject(gcd, addr, false));
}
}
JoinProof::Invite(invite_gid, proof, mname, mavatar) => {
// check is member.
if let Ok(mid) = Member::get_id(&db, &id, &fgid) {
let gavatar = read_avatar(&base, &ogid, &gcd).await?;
let group_info = group.to_group_info("".to_owned(), gavatar, vec![]);
let res = LayerEvent::Agree(gcd, group_info);
let d = bincode::serialize(&res).unwrap_or(vec![]);
let s = SendType::Event(0, addr, d);
if Member::get_id(&db, &id, &fgid).is_ok() {
let s = agree(&base, &ogid, &gcd, group, addr).await;
add_server_layer(results, fgid, s);
return Ok(());
}
@ -487,7 +469,7 @@ async fn handle_event( @@ -487,7 +469,7 @@ async fn handle_event(
// check if inviter is member.
if Member::get_id(&db, &id, &invite_gid).is_err() {
//Self::reject(gcd, fmid, addr, true, results);
add_server_layer(results, fgid, reject(gcd, addr, false));
return Ok(());
}
@ -518,7 +500,8 @@ async fn handle_event( @@ -518,7 +500,8 @@ async fn handle_event(
//self.broadcast_join(&gcd, m, mavatar, results).await?;
// return join result.
//self.agree(gcd, fmid, addr, group, results).await?;
let s = agree(&base, &ogid, &gcd, group, addr).await;
add_server_layer(results, fgid, s);
}
JoinProof::Zkp(_proof) => {
// TOOD zkp join.
@ -535,12 +518,6 @@ async fn handle_event( @@ -535,12 +518,6 @@ async fn handle_event(
Ok(())
}
#[inline]
fn load_group(base: &PathBuf, mgid: &GroupId, gcd: &GroupId) -> Result<Option<GroupChat>> {
let db = group_chat_db(base, mgid)?;
GroupChat::get(&db, gcd)
}
pub(crate) fn group_chat_conn(proof: Proof, addr: PeerAddr, gid: GroupId) -> SendType {
let data =
bincode::serialize(&LayerConnect(gid, ConnectProof::Common(proof))).unwrap_or(vec![]);
@ -558,6 +535,25 @@ fn sync_online(gcd: GroupId, addr: PeerAddr) -> SendType { @@ -558,6 +535,25 @@ fn sync_online(gcd: GroupId, addr: PeerAddr) -> SendType {
SendType::Event(0, addr, data)
}
async fn agree(
base: &PathBuf,
ogid: &GroupId,
gcd: &GroupId,
group: GroupChat,
addr: PeerAddr,
) -> SendType {
let gavatar = read_avatar(base, ogid, gcd).await.unwrap_or(vec![]);
let group_info = group.to_group_info("".to_owned(), gavatar, vec![]);
let res = LayerEvent::Agree(*gcd, group_info);
let d = bincode::serialize(&res).unwrap_or(vec![]);
SendType::Event(0, addr, d)
}
fn reject(gcd: GroupId, addr: PeerAddr, lost: bool) -> SendType {
let d = bincode::serialize(&LayerEvent::Reject(gcd, lost)).unwrap_or(vec![]);
SendType::Event(0, addr, d)
}
// fn broadcast_join(
// gcd: &GroupId,
// member: Member,

18
src/apps/group_chat/models.rs

@ -3,7 +3,7 @@ use std::path::PathBuf; @@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::GroupId,
primitive::{new_io_error, PeerAddr, Result},
primitive::{PeerAddr, Result},
rpc::{json, RpcParam},
};
use tdn_storage::local::{DStorage, DsValue};
@ -35,13 +35,13 @@ impl GroupChatKey { @@ -35,13 +35,13 @@ impl GroupChatKey {
pub fn from_hex(s: impl ToString) -> Result<Self> {
let s = s.to_string();
if s.len() % 2 != 0 {
return Err(new_io_error("Hex is invalid"));
return Err(anyhow!("Hex is invalid"));
}
let mut value = vec![];
for i in 0..(s.len() / 2) {
let res = u8::from_str_radix(&s[2 * i..2 * i + 2], 16)
.map_err(|_e| new_io_error("Hex is invalid"))?;
.map_err(|_e| anyhow!("Hex is invalid"))?;
value.push(res);
}
@ -576,7 +576,7 @@ impl Request { @@ -576,7 +576,7 @@ impl Request {
rid
))?;
if matrix.len() == 0 {
return Err(new_io_error("request is missing"));
return Err(anyhow!("request is missing"));
}
let id = matrix.pop().unwrap().pop().unwrap().as_i64(); // safe.
let sql = format!(
@ -610,7 +610,7 @@ impl Request { @@ -610,7 +610,7 @@ impl Request {
if requests.len() > 0 {
Ok(requests.pop().unwrap()) // safe.
} else {
Err(new_io_error("no requests"))
Err(anyhow!("no requests"))
}
}
}
@ -743,7 +743,7 @@ impl Member { @@ -743,7 +743,7 @@ impl Member {
if matrix.len() > 0 {
Ok(matrix.pop().unwrap().pop().unwrap().as_i64()) // safe unwrap.
} else {
Err(new_io_error("missing member"))
Err(anyhow!("missing member"))
}
}
@ -757,7 +757,7 @@ impl Member { @@ -757,7 +757,7 @@ impl Member {
if matrix.len() > 0 {
Ok(matrix.pop().unwrap().pop().unwrap().as_i64()) // safe unwrap.
} else {
Err(new_io_error("missing member"))
Err(anyhow!("missing member"))
}
}
@ -945,9 +945,9 @@ pub(super) async fn to_network_message( @@ -945,9 +945,9 @@ pub(super) async fn to_network_message(
NetworkMessage::File(old_name, bytes)
}
MessageType::Contact => {
let cid: i64 = content.parse().map_err(|_e| new_io_error("id error"))?;
let cid: i64 = content.parse()?;
let db = chat_db(base, gid)?;
let contact = Friend::get_id(&db, cid)?.ok_or(new_io_error("contact missind"))?;
let contact = Friend::get_id(&db, cid)?.ok_or(anyhow!("contact missind"))?;
drop(db);
let avatar_bytes = read_avatar(base, &gid, &contact.gid).await?;
NetworkMessage::Contact(contact.name, contact.gid, contact.addr, avatar_bytes)

3
src/daemon.rs

@ -1,6 +1,9 @@ @@ -1,6 +1,9 @@
#[macro_use]
extern crate log;
#[macro_use]
extern crate anyhow;
use std::env::args;
mod account;

4
src/event.rs

@ -6,7 +6,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; @@ -6,7 +6,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::{EventId, GroupId},
message::{SendMessage, SendType},
primitive::{new_io_error, HandleResult, PeerAddr, Result},
primitive::{HandleResult, PeerAddr, Result},
};
use tdn_did::user::User;
use tdn_storage::local::DStorage;
@ -655,7 +655,7 @@ impl SyncEvent { @@ -655,7 +655,7 @@ impl SyncEvent {
}
if events.len() as u64 != to + 1 - from {
return Err(new_io_error("events number not matching."));
return Err(anyhow!("events number not matching."));
}
Ok(events)

26
src/group.rs

@ -5,7 +5,7 @@ use std::sync::Arc; @@ -5,7 +5,7 @@ use std::sync::Arc;
use tdn::types::{
group::{EventId, GroupId},
message::{RecvType, SendMessage, SendType},
primitive::{new_io_error, HandleResult, PeerAddr, Result},
primitive::{HandleResult, PeerAddr, Result},
};
use tdn_did::{user::User, Proof};
use tokio::sync::{mpsc::Sender, RwLock};
@ -111,8 +111,7 @@ impl Group { @@ -111,8 +111,7 @@ impl Group {
self.hanlde_connect(&mut results, &gid, addr, data, true)?;
}
RecvType::Event(addr, bytes) => {
let event: GroupEvent = bincode::deserialize(&bytes)
.map_err(|_| new_io_error("serialize event error."))?;
let event: GroupEvent = bincode::deserialize(&bytes)?;
return GroupEvent::handle(self, event, gid, addr, layer, uid);
}
RecvType::Stream(_uid, _stream, _bytes) => {
@ -133,8 +132,7 @@ impl Group { @@ -133,8 +132,7 @@ impl Group {
data: Vec<u8>,
is_connect: bool,
) -> Result<()> {
let connect = bincode::deserialize(&data)
.map_err(|_e| new_io_error("Deserialize group connect failure"))?;
let connect = bincode::deserialize(&data)?;
let (remote_height, remote_event, others) = match connect {
GroupConnect::Create(
@ -148,7 +146,7 @@ impl Group { @@ -148,7 +146,7 @@ impl Group {
) => {
// check remote addr is receive addr.
if remote.addr != addr {
return Err(new_io_error("Address is invalid."));
return Err(anyhow!("Address is invalid."));
}
proof.verify(gid, &addr, &self.addr)?;
if is_connect {
@ -273,7 +271,7 @@ impl Group { @@ -273,7 +271,7 @@ impl Group {
if let Some(account) = self.accounts.get(gid) {
Ok(account)
} else {
Err(new_io_error("user missing"))
Err(anyhow!("user missing"))
}
}
@ -281,7 +279,7 @@ impl Group { @@ -281,7 +279,7 @@ impl Group {
if let Some(account) = self.accounts.get_mut(gid) {
Ok(account)
} else {
Err(new_io_error("user missing"))
Err(anyhow!("user missing"))
}
}
@ -289,7 +287,7 @@ impl Group { @@ -289,7 +287,7 @@ impl Group {
if let Some(running) = self.runnings.get(gid) {
Ok(running)
} else {
Err(new_io_error("user missing"))
Err(anyhow!("user missing"))
}
}
@ -297,7 +295,7 @@ impl Group { @@ -297,7 +295,7 @@ impl Group {
if let Some(running) = self.runnings.get_mut(gid) {
Ok(running)
} else {
Err(new_io_error("user missing"))
Err(anyhow!("user missing"))
}
}
@ -406,14 +404,14 @@ impl Group { @@ -406,14 +404,14 @@ impl Group {
}
}
Err(new_io_error("user missing."))
Err(anyhow!("user missing."))
}
pub fn clone_user(&self, gid: &GroupId) -> Result<User> {
if let Some(u) = self.accounts.get(gid) {
User::new(u.gid, self.addr, u.name.clone(), u.avatar.clone())
} else {
Err(new_io_error("user missing."))
Err(anyhow!("user missing."))
}
}
@ -476,7 +474,7 @@ impl Group { @@ -476,7 +474,7 @@ impl Group {
if let Some(u) = self.accounts.get(gid) {
u.mnemonic(&self.secret, lock)
} else {
Err(new_io_error("user missing."))
Err(anyhow!("user missing."))
}
}
@ -487,7 +485,7 @@ impl Group { @@ -487,7 +485,7 @@ impl Group {
u.update(&account_db)?;
account_db.close()
} else {
Err(new_io_error("user missing."))
Err(anyhow!("user missing."))
}
}

6
src/group/running.rs

@ -3,7 +3,7 @@ use std::path::PathBuf; @@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use tdn::types::{
group::GroupId,
primitive::{new_io_error, PeerAddr, Result},
primitive::{PeerAddr, Result},
};
use tdn_did::Keypair;
@ -52,7 +52,7 @@ impl RunningAccount { @@ -52,7 +52,7 @@ impl RunningAccount {
v.1 = true;
Ok(v.0)
} else {
Err(new_io_error("device missing"))
Err(anyhow!("device missing"))
}
}
@ -61,7 +61,7 @@ impl RunningAccount { @@ -61,7 +61,7 @@ impl RunningAccount {
v.1 = false;
Ok(v.0)
} else {
Err(new_io_error("device missing"))
Err(anyhow!("device missing"))
}
}
}

16
src/layer.rs

@ -5,7 +5,7 @@ use std::sync::Arc; @@ -5,7 +5,7 @@ use std::sync::Arc;
use tdn::types::{
group::GroupId,
message::SendType,
primitive::{new_io_error, PeerAddr, Result},
primitive::{PeerAddr, Result},
};
use tokio::sync::RwLock;
@ -57,11 +57,11 @@ impl Layer { @@ -57,11 +57,11 @@ impl Layer {
}
pub fn running(&self, gid: &GroupId) -> Result<&RunningLayer> {
self.runnings.get(gid).ok_or(new_io_error("not online"))
self.runnings.get(gid).ok_or(anyhow!("not online"))
}
pub fn running_mut(&mut self, gid: &GroupId) -> Result<&mut RunningLayer> {
self.runnings.get_mut(gid).ok_or(new_io_error("not online"))
self.runnings.get_mut(gid).ok_or(anyhow!("not online"))
}
pub fn add_running(
@ -276,7 +276,7 @@ impl RunningLayer { @@ -276,7 +276,7 @@ impl RunningLayer {
Ok(false)
}
} else {
Err(new_io_error("remote not online"))
Err(anyhow!("remote not online"))
}
}
@ -284,7 +284,7 @@ impl RunningLayer { @@ -284,7 +284,7 @@ impl RunningLayer {
self.sessions
.get(gid)
.map(|online| (online.db_id, online.db_fid))
.ok_or(new_io_error("remote not online"))
.ok_or(anyhow!("remote not online"))
}
/// get online peer's addr.
@ -292,7 +292,7 @@ impl RunningLayer { @@ -292,7 +292,7 @@ impl RunningLayer {
self.sessions
.get(gid)
.map(|online| *online.online.addr())
.ok_or(new_io_error("remote not online"))
.ok_or(anyhow!("remote not online"))
}
pub fn online_direct(&self, gid: &GroupId) -> Result<PeerAddr> {
@ -302,7 +302,7 @@ impl RunningLayer { @@ -302,7 +302,7 @@ impl RunningLayer {
_ => {}
}
}
Err(new_io_error("no direct online"))
Err(anyhow!("no direct online"))
}
/// get all online peer.
@ -328,7 +328,7 @@ impl RunningLayer { @@ -328,7 +328,7 @@ impl RunningLayer {
.insert(gid, OnlineSession::new(online, id, fid));
Ok(())
}
_ => Err(new_io_error("remote had online")),
_ => Err(anyhow!("remote had online")),
}
} else {
self.sessions

3
src/lib.rs

@ -1,6 +1,9 @@ @@ -1,6 +1,9 @@
#[macro_use]
extern crate log;
#[macro_use]
extern crate anyhow;
use std::ffi::CStr;
use std::os::raw::c_char;

5
src/migrate.rs

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
use std::path::PathBuf;
use tdn::types::primitive::Result;
use tdn_storage::local::DStorage;
pub mod consensus;
@ -44,7 +45,7 @@ pub(crate) const ASSISTANT_DB: &'static str = "assistant.db"; @@ -44,7 +45,7 @@ pub(crate) const ASSISTANT_DB: &'static str = "assistant.db";
/// Account's assistant database name
pub(crate) const GROUP_CHAT_DB: &'static str = "group_chat.db";
pub(crate) fn main_migrate(path: &PathBuf) -> std::io::Result<()> {
pub(crate) fn main_migrate(path: &PathBuf) -> Result<()> {
let mut db_path = path.clone();
db_path.push(ACCOUNT_DB);
@ -200,7 +201,7 @@ pub(crate) fn main_migrate(path: &PathBuf) -> std::io::Result<()> { @@ -200,7 +201,7 @@ pub(crate) fn main_migrate(path: &PathBuf) -> std::io::Result<()> {
Ok(())
}
pub(crate) fn account_init_migrate(path: &PathBuf) -> std::io::Result<()> {
pub(crate) fn account_init_migrate(path: &PathBuf) -> Result<()> {
let mut db_path = path.clone();
db_path.push(CONSENSUS_DB);
let db = DStorage::open(db_path)?;

4
src/rpc.rs

@ -4,7 +4,7 @@ use std::sync::Arc; @@ -4,7 +4,7 @@ use std::sync::Arc;
use tdn::types::{
group::GroupId,
message::{NetworkType, SendMessage, SendType, StateRequest, StateResponse},
primitive::{new_io_error, HandleResult, PeerAddr, Result},
primitive::{HandleResult, PeerAddr, Result},
rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam},
};
use tokio::sync::{
@ -195,7 +195,7 @@ pub(crate) async fn inner_rpc(uid: u64, method: &str, sender: &Sender<SendMessag @@ -195,7 +195,7 @@ pub(crate) async fn inner_rpc(uid: u64, method: &str, sender: &Sender<SendMessag
return Ok(());
}
Err(new_io_error("not found"))
Err(anyhow!("not found"))
}
fn new_rpc_handler(

6
src/server.rs

@ -3,9 +3,11 @@ use simplelog::{CombinedLogger, Config as LogConfig, LevelFilter}; @@ -3,9 +3,11 @@ use simplelog::{CombinedLogger, Config as LogConfig, LevelFilter};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tdn::{prelude::*, types::primitive::HandleResult};
use tdn::{
prelude::*,
types::primitive::{HandleResult, Result},
};
use tokio::{
io::Result,
sync::mpsc::{error::SendError, Sender},
sync::RwLock,
};

10
src/session.rs

@ -1,7 +1,7 @@ @@ -1,7 +1,7 @@
use std::path::PathBuf;
use tdn::types::{
group::GroupId,
primitive::{new_io_error, PeerAddr, Result},
primitive::{PeerAddr, Result},
rpc::{json, RpcParam},
};
use tdn_storage::local::{DStorage, DsValue};
@ -159,7 +159,7 @@ impl Session { @@ -159,7 +159,7 @@ impl Session {
if matrix.len() > 0 {
Ok(Session::from_values(matrix.pop().unwrap())) // safe unwrap()
} else {
Err(new_io_error("session missing."))
Err(anyhow!("session missing."))
}
}
@ -191,7 +191,7 @@ impl Session { @@ -191,7 +191,7 @@ impl Session {
db.delete(&format!("DELETE FROM sessions WHERE id = {}", id))?;
Ok(id)
} else {
Err(new_io_error("session missing"))
Err(anyhow!("session missing"))
}
}
@ -208,7 +208,7 @@ impl Session { @@ -208,7 +208,7 @@ impl Session {
db.update(&s)?;
Ok(id)
} else {
Err(new_io_error("session missing"))
Err(anyhow!("session missing"))
}
}
@ -232,7 +232,7 @@ impl Session { @@ -232,7 +232,7 @@ impl Session {
db.update(&format!("UPDATE sessions SET is_close = false, last_datetime = {}, last_content = '{}', last_readed = {} WHERE id = {}", datetime, content, if readed { 1 } else { 0 }, id))?;
Ok(id)
} else {
Err(new_io_error("session missing"))
Err(anyhow!("session missing"))
}
}

27
src/storage.rs

@ -4,10 +4,7 @@ use std::path::PathBuf; @@ -4,10 +4,7 @@ use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::fs;
use tdn::types::{
group::GroupId,
primitive::{new_io_error, Result},
};
use tdn::types::{group::GroupId, primitive::Result};
use tdn_storage::local::DStorage;
use crate::migrate::{
@ -57,7 +54,7 @@ pub(crate) async fn init_local_files(base: &PathBuf) -> Result<()> { @@ -57,7 +54,7 @@ pub(crate) async fn init_local_files(base: &PathBuf) -> Result<()> {
}
pub(crate) async fn read_file(base: &PathBuf) -> Result<Vec<u8>> {
fs::read(base).await
Ok(fs::read(base).await?)
}
pub(crate) async fn write_file(
@ -94,7 +91,7 @@ pub(crate) fn read_file_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Resul @@ -94,7 +91,7 @@ pub(crate) fn read_file_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Resul
path.push(gid.to_hex());
path.push(FILES_DIR);
path.push(name);
std::fs::read(base)
Ok(std::fs::read(base)?)
}
#[inline]
@ -111,7 +108,7 @@ fn image_name() -> String { @@ -111,7 +108,7 @@ fn image_name() -> String {
#[inline]
fn image_thumb(bytes: &[u8]) -> Result<DynamicImage> {
// thumbnail image. 120*800
let img = load_from_memory(&bytes).map_err(|_e| new_io_error("image invalid format."))?;
let img = load_from_memory(&bytes)?;
let (x, _) = img.dimensions();
if x > 100 {
Ok(img.thumbnail(120, 800))
@ -167,7 +164,7 @@ pub(crate) fn read_image_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Resu @@ -167,7 +164,7 @@ pub(crate) fn read_image_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Resu
path.push(gid.to_hex());
path.push(IMAGE_DIR);
path.push(name);
std::fs::read(base)
Ok(std::fs::read(base)?)
}
#[inline]
@ -187,7 +184,7 @@ pub(crate) async fn read_avatar( @@ -187,7 +184,7 @@ pub(crate) async fn read_avatar(
path.push(AVATAR_DIR);
path.push(avatar_png(remote));
if path.exists() {
fs::read(path).await
Ok(fs::read(path).await?)
} else {
Ok(vec![])
}
@ -199,7 +196,7 @@ pub(crate) fn read_avatar_sync(base: &PathBuf, gid: &GroupId, remote: &GroupId) @@ -199,7 +196,7 @@ pub(crate) fn read_avatar_sync(base: &PathBuf, gid: &GroupId, remote: &GroupId)
path.push(AVATAR_DIR);
path.push(avatar_png(remote));
if path.exists() {
std::fs::read(path)
Ok(std::fs::read(path)?)
} else {
Ok(vec![])
}
@ -218,7 +215,7 @@ pub(crate) async fn write_avatar( @@ -218,7 +215,7 @@ pub(crate) async fn write_avatar(
path.push(gid.to_hex());
path.push(AVATAR_DIR);
path.push(avatar_png(remote));
fs::write(path, bytes).await
Ok(fs::write(path, bytes).await?)
}
pub(crate) fn write_avatar_sync(
@ -244,7 +241,7 @@ pub(crate) async fn delete_avatar(base: &PathBuf, gid: &GroupId, remote: &GroupI @@ -244,7 +241,7 @@ pub(crate) async fn delete_avatar(base: &PathBuf, gid: &GroupId, remote: &GroupI
path.push(AVATAR_DIR);
path.push(avatar_png(remote));
if path.exists() {
fs::remove_file(path).await
Ok(fs::remove_file(path).await?)
} else {
Ok(())
}
@ -267,7 +264,7 @@ pub(crate) async fn read_record(base: &PathBuf, gid: &GroupId, name: &str) -> Re @@ -267,7 +264,7 @@ pub(crate) async fn read_record(base: &PathBuf, gid: &GroupId, name: &str) -> Re
path.push(RECORD_DIR);
path.push(name);
if path.exists() {
fs::read(path).await
Ok(fs::read(path).await?)
} else {
Ok(vec![])
}
@ -278,7 +275,7 @@ pub(crate) fn read_record_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Res @@ -278,7 +275,7 @@ pub(crate) fn read_record_sync(base: &PathBuf, gid: &GroupId, name: &str) -> Res
path.push(gid.to_hex());
path.push(RECORD_DIR);
path.push(name);
std::fs::read(path)
Ok(std::fs::read(path)?)
}
pub(crate) fn write_record_sync(
@ -308,7 +305,7 @@ pub(crate) async fn _delete_record(base: &PathBuf, gid: &GroupId, name: &str) -> @@ -308,7 +305,7 @@ pub(crate) async fn _delete_record(base: &PathBuf, gid: &GroupId, name: &str) ->
path.push(gid.to_hex());
path.push(RECORD_DIR);
path.push(name);
fs::remove_file(path).await
Ok(fs::remove_file(path).await?)
}
pub(crate) fn _write_emoji(base: &PathBuf, gid: &GroupId) -> Result<()> {

Loading…
Cancel
Save