nio-rust: Format the repo.

master
Damir Jelić 2019-11-10 18:33:06 +01:00
parent 9e474a5cc2
commit 8d58938b41
7 changed files with 68 additions and 36 deletions

View File

@ -18,4 +18,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,10 +1,11 @@
#![feature(async_closure)]
use std::{env, process::exit};
use std::pin::Pin;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{env, process::exit};
use url::Url;
use matrix_nio::{
self,
@ -13,7 +14,7 @@ use matrix_nio::{
room::message::{MessageEvent, MessageEventContent, TextMessageEventContent},
EventType,
},
AsyncClient, AsyncClientConfig, SyncSettings, Room
AsyncClient, AsyncClientConfig, Room, SyncSettings,
};
async fn async_helper(room: Arc<Mutex<Room>>, event: Arc<RoomEvent>) {
@ -25,11 +26,18 @@ async fn async_helper(room: Arc<Mutex<Room>>, event: Arc<RoomEvent>) {
}) = &*event
{
let user = room.members.get(&sender.to_string()).unwrap();
println!("{}: {}", user.display_name.as_ref().unwrap_or(&sender.to_string()), msg_body);
println!(
"{}: {}",
user.display_name.as_ref().unwrap_or(&sender.to_string()),
msg_body
);
}
}
fn async_callback(room: Arc<Mutex<Room>>, event: Arc<RoomEvent>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync >> {
fn async_callback(
room: Arc<Mutex<Room>>,
event: Arc<RoomEvent>,
) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
Box::pin(async_helper(room, event))
}
@ -41,9 +49,10 @@ async fn login(
let client_config = AsyncClientConfig::new()
.proxy("http://localhost:8080")?
.disable_ssl_verification();
let mut client = AsyncClient::new_with_config(&homeserver_url, None, client_config).unwrap();
let homeserver_url = Url::parse(&homeserver_url)?;
let mut client = AsyncClient::new_with_config(homeserver_url, None, client_config).unwrap();
client.add_event_future(EventType::RoomMessage, Box::new(async_callback));
// client.add_event_future(EventType::RoomMessage, Box::new(async_callback));
client.login(username, password, None).await?;
let response = client.sync(SyncSettings::new()).await?;

View File

@ -17,7 +17,21 @@ impl Account {
Account {
account: acc_ptr,
buffer: account_data
buffer: account_data,
}
}
pub fn identity_keys(&self) {
let keys_length = unsafe { nio_olm_sys::olm_account_identity_keys_length(self.account) };
let out_buffer: Vec<u8> = vec![0; keys_length];
}
}
impl Drop for Account {
fn drop(&mut self) {
unsafe {
nio_olm_sys::olm_clear_account(self.account);
}
}
}

View File

@ -2,8 +2,8 @@ use std::convert::{TryFrom, TryInto};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use http::Method as HttpMethod;
use http::Response as HttpResponse;
@ -16,8 +16,8 @@ use ruma_events::collections::all::RoomEvent;
use ruma_events::room::message::MessageEvent;
use ruma_events::room::message::MessageEventContent;
use ruma_events::Event;
use ruma_identifiers::RoomId;
pub use ruma_events::EventType;
use ruma_identifiers::RoomId;
use crate::api;
use crate::base_client::Client as BaseClient;
@ -25,8 +25,12 @@ use crate::base_client::Room;
use crate::error::{Error, InnerError};
use crate::session::Session;
type RoomEventCallback = Box::<dyn FnMut(&Room, &RoomEvent)>;
type RoomEventCallbackF = Box::<dyn FnMut(Arc<RwLock<Room>>, Arc<RoomEvent>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> + Send + Sync>;
type RoomEventCallback = Box<dyn FnMut(&Room, &RoomEvent)>;
type RoomEventCallbackF = Box<
dyn FnMut(Arc<RwLock<Room>>, Arc<RoomEvent>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>>
+ Send
+ Sync,
>;
#[derive(Clone)]
pub struct AsyncClient {
@ -120,13 +124,16 @@ impl SyncSettings {
}
}
use api::r0::send::send_message_event;
use api::r0::session::login;
use api::r0::sync::sync_events;
use api::r0::send::send_message_event;
impl AsyncClient {
/// Creates a new client for making HTTP requests to the given homeserver.
pub fn new<U: TryInto<Url>>(homeserver_url: U, session: Option<Session>) -> Result<Self, Error> {
pub fn new<U: TryInto<Url>>(
homeserver_url: U,
session: Option<Session>,
) -> Result<Self, Error> {
let config = AsyncClientConfig::new();
AsyncClient::new_with_config(homeserver_url, session, config)
}
@ -138,7 +145,7 @@ impl AsyncClient {
) -> Result<Self, Error> {
let homeserver: Url = match homeserver_url.try_into() {
Ok(u) => u,
Err(e) => panic!("Error parsing homeserver url")
Err(e) => panic!("Error parsing homeserver url"),
};
let http_client = reqwest::Client::builder();
@ -167,10 +174,7 @@ impl AsyncClient {
None => HeaderValue::from_static("nio-rust"),
};
headers.insert(
reqwest::header::USER_AGENT,
user_agent,
);
headers.insert(reqwest::header::USER_AGENT, user_agent);
let http_client = http_client.default_headers(headers).build().unwrap();
@ -244,7 +248,7 @@ impl AsyncClient {
for event in &room.state.events {
let event = match event.clone().into_result() {
Ok(e) => e,
Err(e) => continue
Err(e) => continue,
};
client.receive_joined_state_event(&room_id, &event);
@ -253,7 +257,7 @@ impl AsyncClient {
for event in &room.timeline.events {
let event = match event.clone().into_result() {
Ok(e) => e,
Err(e) => continue
Err(e) => continue,
};
client.receive_joined_timeline_event(&room_id, &event);
@ -276,7 +280,10 @@ impl AsyncClient {
async fn send<Request: Endpoint>(&self, request: Request) -> Result<Request::Response, Error> {
let request: http::Request<Vec<u8>> = request.try_into()?;
let url = request.uri();
let url = self.homeserver.join(url.path_and_query().unwrap().as_str()).unwrap();
let url = self
.homeserver
.join(url.path_and_query().unwrap().as_str())
.unwrap();
let request_builder = match Request::METADATA.method {
HttpMethod::GET => self.http_client.get(url),
@ -324,7 +331,11 @@ impl AsyncClient {
self.transaction_id.fetch_add(1, Ordering::SeqCst)
}
pub async fn room_send(&mut self, room_id: &str, data: MessageEventContent) -> Result<send_message_event::Response, Error> {
pub async fn room_send(
&mut self,
room_id: &str,
data: MessageEventContent,
) -> Result<send_message_event::Response, Error> {
let request = send_message_event::Request {
room_id: RoomId::try_from(room_id).unwrap(),
event_type: EventType::RoomMessage,

View File

@ -188,15 +188,14 @@ impl Client {
fn get_or_create_room(&mut self, room_id: &RoomId) -> &mut Arc<RwLock<Room>> {
self.joined_rooms
.entry(room_id.to_string())
.or_insert(
Arc::new(RwLock::new(Room::new(
room_id,
&self
.session
.as_ref()
.expect("Receiving events while not being logged in")
.user_id
.to_string(),
.or_insert(Arc::new(RwLock::new(Room::new(
room_id,
&self
.session
.as_ref()
.expect("Receiving events while not being logged in")
.user_id
.to_string(),
))))
}

View File

@ -3,11 +3,11 @@
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result as FmtResult};
use url::ParseError;
use reqwest::Error as ReqwestError;
use ruma_api::Error as RumaApiError;
use serde_json::Error as SerdeJsonError;
use serde_urlencoded::ser::Error as SerdeUrlEncodedSerializeError;
use url::ParseError;
/// An error that can occur during client operations.
#[derive(Debug)]

View File

@ -3,9 +3,9 @@
#![warn(missing_docs)]
pub use crate::{error::Error, session::Session};
pub use reqwest::header::InvalidHeaderValue;
pub use ruma_client_api as api;
pub use ruma_events as events;
pub use reqwest::header::InvalidHeaderValue;
mod async_client;
mod base_client;