1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
use ruma::events::*;
pub use ruma::{
api::client::sync::sync_events::v3::Response, OwnedEventId, OwnedRoomAliasId, OwnedRoomId,
OwnedRoomName, OwnedServerName, OwnedUserId, RoomAliasId, RoomId, RoomName, ServerName, UserId,
};
use serde::{Deserialize, Serialize};
//use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::time::Duration;
//use ureq::{Agent, AgentBuilder, OrAnyStatus};
//use uuid::Uuid;
const TIMEOUT: Duration = Duration::from_secs(3);
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct StorageData {
pub auth_token: String,
pub room_to_aliases: BTreeMap<OwnedRoomId, Vec<OwnedRoomAliasId>>,
pub alias_to_room: BTreeMap<OwnedRoomAliasId, OwnedRoomId>,
pub joined_rooms: Vec<OwnedRoomId>,
pub room_id_to_cananoical_alias: BTreeMap<OwnedRoomId, OwnedRoomAliasId>,
pub room_to_name: BTreeMap<OwnedRoomId, OwnedRoomName>,
pub room_to_direct_name: BTreeMap<OwnedRoomId, String>,
pub recent_event_ids: Vec<OwnedEventId>,
pub last_sent_messages: Vec<(OwnedRoomId, String)>,
}
/*
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Response {
/// The batch token to supply in the `since` param of the next `/sync` request.
pub next_batch: String,
/// Updates to rooms.
#[serde(default, skip_serializing_if = "Rooms::is_empty")]
pub rooms: Rooms,
/// Updates to the presence status of other users.
#[serde(default, skip_serializing_if = "Presence::is_empty")]
pub presence: Presence,
/// The global private data created by this user.
#[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
pub account_data: GlobalAccountData,
/// Messages sent directly between devices.
#[serde(default, skip_serializing_if = "ToDevice::is_empty")]
pub to_device: ToDevice,
/// Information on E2E device updates.
///
/// Only present on an incremental sync.
#[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
pub device_lists: DeviceLists,
/// For each key algorithm, the number of unclaimed one-time keys
/// currently held on the server for a device.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub device_one_time_keys_count: BTreeMap<DeviceKeyAlgorithm, UInt>,
/// For each key algorithm, the number of unclaimed one-time keys
/// currently held on the server for a device.
///
/// The presence of this field indicates that the server supports
/// fallback keys.
#[serde(rename = "org.matrix.msc2732.device_unused_fallback_key_types")]
pub device_unused_fallback_key_types: Option<Vec<DeviceKeyAlgorithm>>,
}*/
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Client {
client: ruma::Client<ruma::client::http_client::Reqwest>,
pub me: OwnedUserId,
since: Option<String>,
host: String,
pub data: StorageData,
room_list_updated: bool,
}
pub enum Authentication {
Password(String),
AuthToken(String),
}
impl Client {
pub async fn new(
host: impl Into<String>,
username: impl Into<String>,
server_name: impl Into<String>,
authentication: Authentication,
) -> Self {
let good_host = host.into().trim_end_matches("/").to_string();
let me = UserId::parse_with_server_name(
username.into(),
&ruma::ServerName::parse(server_name.into()).unwrap(),
)
.unwrap();
let client = match authentication {
Authentication::Password(x) => {
let c = ruma::Client::builder()
.homeserver_url(good_host.clone())
.build()
.await
.unwrap();
c.log_in(me.clone().as_str(), x.as_str(), None, None)
.await
.unwrap();
c
}
Authentication::AuthToken(x) => ruma::Client::builder()
.homeserver_url(good_host.clone())
.access_token(Some(x))
.build()
.await
.unwrap(),
};
Self {
client: client,
host: good_host, //host.into().trim_end_matches("/").to_string(),
me: me, /*UserId::parse_with_server_name(
username.into(),
&*ruma::ServerName::parse(server_name.into()).unwrap(),
)
.unwrap(),
agent: AgentBuilder::new()
.timeout_read(Duration::from_secs(3))
.build(),
*/
since: None,
data: StorageData::default(),
room_list_updated: false,
}
}
pub fn room_list_updated(&mut self) -> bool {
if self.room_list_updated {
self.room_list_updated = false;
return true;
}
false
}
/*
pub fn set_auth_token(&mut self, auth_token: String) {
let should_req_well_known = match self.host.split(":").last().unwrap().parse::<usize>() {
Ok(port) => {
if port != 443 {
false
} else {
true
}
}
Err(_) => true,
};
if should_req_well_known {
if let Ok(z) =
ureq::get(&format!("{}/.well-known/matrix/client", self.host.clone())).call()
{
let resp: Value = z.into_json().unwrap();
let base_url: String = resp["m.homeserver"]["base_url"]
.as_str()
.unwrap()
.to_string();
self.host = base_url.trim_end_matches("/").to_string();
}
}
self.data.auth_token = auth_token;
}
pub fn login(&mut self, password: String) -> Result<(), Value> {
let should_req_well_known = match self.host.split(":").last().unwrap().parse::<usize>() {
Ok(port) => {
if port != 443 {
false
} else {
true
}
}
Err(_) => true,
};
if should_req_well_known {
if let Ok(z) =
ureq::get(&format!("{}/.well-known/matrix/client", self.host.clone())).call()
{
let resp: Value = z.into_json().unwrap();
let base_url: String = resp["m.homeserver"]["base_url"]
.as_str()
.unwrap()
.to_string();
self.host = base_url.trim_end_matches("/").to_string();
}
}
let content = json!({
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": self.me.localpart()
},
"password": password
});
let val: Value = self
.post_r0("login", content, None)
.unwrap()
.into_json()
.unwrap();
//println!("{:#}", val);
if !val.clone().as_object().unwrap().contains_key("auth_token") {
return Err(val);
}
self.data.auth_token = val["access_token"].as_str().unwrap().to_string();
self.me = OwnedUserId::try_from(val["user_id"].as_str().unwrap()).unwrap();
Ok(())
}
*/
pub fn get_me(&self) -> OwnedUserId {
self.me.clone()
}
/*
fn post(
&self,
url_ext: impl Into<String>,
content: Value,
query_pairs: Option<Vec<(String, String)>>,
) -> Result<ureq::Response, ureq::Transport> {
let mut r = self
.agent
.post(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str())
.set(
"Authorization",
format!("Bearer {}", self.data.auth_token).as_str(),
);
if let Some(pairs) = query_pairs {
for pair in pairs {
r = r.query(pair.0.as_str(), pair.1.as_str());
}
}
//let x = r.send_json(content).or_any_status();
//println!("{:#?}", x);
//x
let mut resp = r.clone().send_json(content.clone()).or_any_status();
while let Err(_e) = resp {
resp = r.clone().send_json(content.clone()).or_any_status();
//eprintln!("{}", e);
}
resp
}
fn post_r0(
&self,
url_ext: impl Into<String>,
content: Value,
query_pairs: Option<Vec<(String, String)>>,
) -> Result<ureq::Response, ureq::Transport> {
let mut r = self
.agent
.post(
format!(
"{}{}{}",
self.host,
BASE.replace("v3", "r0"),
url_ext.into()
)
.as_str(),
)
.set(
"Authorization",
format!("Bearer {}", self.data.auth_token).as_str(),
);
if let Some(pairs) = query_pairs {
for pair in pairs {
r = r.query(pair.0.as_str(), pair.1.as_str());
}
}
//let x = r.send_json(content).or_any_status();
//println!("{:#?}", x);
//x
let mut resp = r.clone().send_json(content.clone()).or_any_status();
while let Err(_e) = resp {
resp = r.clone().send_json(content.clone()).or_any_status();
//eprintln!("{}", e);
}
resp
}
fn put(
&self,
url_ext: impl Into<String>,
content: Value,
query_pairs: Option<Vec<(String, String)>>,
) -> Result<ureq::Response, ureq::Transport> {
let mut r = self
.agent
.put(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str())
.set(
"Authorization",
format!("Bearer {}", self.data.auth_token).as_str(),
);
if let Some(pairs) = query_pairs {
for pair in pairs {
r = r.query(pair.0.as_str(), pair.1.as_str());
}
}
let mut resp = r.clone().send_json(content.clone()).or_any_status();
while let Err(_e) = resp {
resp = r.clone().send_json(content.clone()).or_any_status();
//eprintln!("{}", e);
}
resp
}
fn get(
&self,
url_ext: impl Into<String>,
query_pairs: Option<Vec<(String, String)>>,
) -> Result<ureq::Response, ureq::Transport> {
let mut r = self
.agent
.get(format!("{}{}{}", self.host, BASE, url_ext.into()).as_str())
.set(
"Authorization",
format!("Bearer {}", self.data.auth_token).as_str(),
);
if let Some(pairs) = query_pairs {
for pair in pairs {
r = r.query(pair.0.as_str(), pair.1.as_str());
}
}
let mut resp = r.clone().call().or_any_status();
while let Err(_e) = resp {
resp = r.clone().call().or_any_status();
//eprintln!("{}", e);
}
//println!("{:#?}", resp);
resp
}
pub fn join_room_id(&self, room_id: OwnedRoomId) -> Value {
let rid = room_id.to_string();
let room = urlencoding::encode(rid.as_str());
let content = json!({});
self.post(format!("rooms/{}/join", room).as_str(), content, None)
.unwrap()
.into_json()
.unwrap()
}
*/
pub async fn join_room_id(
&self,
room_id: OwnedRoomId,
) -> ruma::api::client::membership::join_room_by_id::v3::Response {
self.client
.send_request(
ruma::api::client::membership::join_room_by_id::v3::Request::new(&room_id),
)
.await
.unwrap()
}
pub async fn sync(&mut self) -> Result<Response, ()> {
//let since: Option<&'a str>;
//since = Some(self.since.unwrap().as_str())
/*
if let Some(start) = self.since.clone() {
since = Some(&start);
} else {
since = None;
}
*/
let mut req = ruma::api::client::sync::sync_events::v3::Request::new();
req.filter = None;
req.since = match self.since {
Some(ref x) => Some(x),
None => None,
};
req.full_state = self.since.clone().is_none();
//set_presence: &PresenceState::Online,
req.timeout = Some(TIMEOUT);
if let Ok(res) = self.client.send_request(req).await {
self.since = Some(res.clone().next_batch);
return Ok(res);
} else {
return Err(());
}
}
/*
pub fn sync(&mut self) -> Result<Response, Value> {
let req: ureq::Response;
if let Some(start) = self.since.clone() {
req = self
.get(
"sync",
Some(vec![
("since".to_string(), start),
("full_state".to_string(), "false".to_string()),
(
"set_presence".to_string(),
format!("{}", PresenceState::Online),
),
("timeout".to_string(), "3000".to_string()),
]),
)
.unwrap();
} else {
req = self
.get(
"sync",
Some(vec![
("full_state".to_string(), "true".to_string()),
(
"set_presence".to_string(),
format!("{}", PresenceState::Online),
),
("timeout".to_string(), "3000".to_string()),
]),
)
.unwrap();
}
let val: Value = req.into_json().unwrap();
if val.clone().as_object().unwrap().contains_key("error") {
Err(val)
} else {
let x: Response = serde_json::from_str::<Raw<Response>>(val.to_string().as_str())
.unwrap()
.deserialize()
.unwrap();
self.since = Some(x.clone().next_batch);
Ok(x)
}
}
*/
pub async fn join_with_alias(&self, alias: impl Into<String>) {
let room_alias = alias.into();
self.join_room_id(self.room_id_from_alias(room_alias).await)
.await;
}
/*
pub fn join_with_alias(&self, alias: impl Into<String>) {
let room_alias = alias.into();
let this_room_id_val: Value = self
.get(
format!(
"directory/room/{}",
urlencoding::encode(room_alias.as_str())
.to_string()
.as_str()
)
None,
)
.unwrap()
.into_json()
.unwrap();
let room_id =
OwnedRoomId::try_from(this_room_id_val["room_id"].as_str().unwrap()).unwrap();
self.join_room_id(room_id);
}
pub fn leave_room_id(&mut self, room_id: OwnedRoomId) -> Value {
let rid = room_id.to_string();
let room = urlencoding::encode(rid.as_str());
let content = json!({});
let output = self
.post(format!("rooms/{}/leave", room).as_str(), content, None)
.unwrap()
.into_json()
.unwrap();
self.data.joined_rooms.retain(|x| x != &room_id);
self.room_list_updated = true;
output
}
*/
pub async fn leave_room_id(
&mut self,
room_id: OwnedRoomId,
) -> ruma::api::client::membership::leave_room::v3::Response {
let resp = self
.client
.send_request(ruma::api::client::membership::leave_room::v3::Request::new(
&room_id,
))
.await
.unwrap();
self.data.joined_rooms.retain(|x| x != &room_id);
self.room_list_updated = true;
resp
}
/*
pub fn room_id_from_alias(&self, alias: impl Into<String>) -> OwnedRoomId {
let room_alias = alias.into();
let this_room_id_val: Value = self
.get(
format!(
"directory/room/{}",
urlencoding::encode(room_alias.as_str())
.to_string()
.as_str()
),
None,
)
.unwrap()
.into_json()
.unwrap();
OwnedRoomId::try_from(this_room_id_val["room_id"].as_str().unwrap()).unwrap()
}
*/
pub async fn room_id_from_alias(&self, alias: impl Into<String>) -> OwnedRoomId {
let room_alias_string = alias.into();
let room_alias = RoomAliasId::parse(room_alias_string.as_str()).unwrap();
self.client
.send_request(ruma::api::client::alias::get_alias::v3::Request::new(
&room_alias,
))
.await
.unwrap()
.room_id
}
/*
pub fn send_message(&mut self, room_id: OwnedRoomId, message: impl Into<String>) {
let msg = message.into();
let txid = Uuid::new_v4()
.to_simple()
.encode_lower(&mut Uuid::encode_buffer())
.to_string();
self.put(
format!("rooms/{}/send/m.room.message/{}", room_id.clone(), txid).as_str(),
json!({"body": msg, "msgtype": "m.text"}),
None,
)
.unwrap();
self.data.last_sent_messages.push((room_id.clone(), msg));
}
*/
pub async fn send_message(
&mut self,
room_id: OwnedRoomId,
message: impl Into<String>,
) -> ruma::api::client::message::send_message_event::v3::Response {
let msg = message.into();
let resp = self
.client
.send_request(
ruma::api::client::message::send_message_event::v3::Request::new(
&room_id,
&ruma::TransactionId::new(),
&ruma::events::room::message::RoomMessageEventContent::text_plain(msg.clone()),
)
.unwrap(),
)
.await
.unwrap();
self.data.last_sent_messages.push((room_id.clone(), msg));
resp
}
pub fn extract_data(&mut self, sync_results: Response) -> Vec<MessageInfo> {
let mut messages: Vec<MessageInfo> = Vec::new();
let x = sync_results.rooms.join;
for (room_id, joined_room) in x.iter() {
if !self.data.joined_rooms.contains(room_id) {
self.data.joined_rooms.push(room_id.clone());
self.room_list_updated = true;
}
let mut room_members: Vec<String> = Vec::new();
let mut is_direct = false;
for event in joined_room.state.events.clone() {
if let Ok(ev) = event.deserialize() {
if let ruma::events::AnySyncStateEvent::RoomAliases(SyncStateEvent::Original(
room_aliases_event,
)) = ev.clone()
{
let aliases = room_aliases_event.content.aliases;
for alias in aliases {
if !self.data.alias_to_room.contains_key(&alias) {
self.data
.alias_to_room
.insert(alias.clone(), room_id.clone())
.unwrap();
}
if !self.data.room_to_aliases.contains_key(room_id) {
self.data
.room_to_aliases
.insert(room_id.clone(), vec![alias])
.unwrap();
} else {
if !self.data.room_to_aliases[room_id].contains(&alias) {
let mut current = self.data.room_to_aliases[room_id].clone();
current.push(alias.clone());
self.data
.room_to_aliases
.insert(room_id.clone(), current)
.unwrap();
}
}
}
}
if let ruma::events::AnySyncStateEvent::RoomName(SyncStateEvent::Original(
room_name_event,
)) = ev.clone()
{
if let Some(room_name) = room_name_event.content.name {
self.data
.room_to_name
.insert(room_id.clone(), room_name.into());
}
} else if let ruma::events::AnySyncStateEvent::RoomCanonicalAlias(
SyncStateEvent::Original(room_canonical_alias_event),
) = ev.clone()
{
if let Some(alias) = room_canonical_alias_event.content.alias {
self.data
.room_id_to_cananoical_alias
.insert(room_id.clone(), alias);
}
} else if let ruma::events::AnySyncStateEvent::RoomMember(
SyncStateEvent::Original(room_member_event),
) = ev.clone()
{
if let Some(display_name) = room_member_event.content.displayname {
room_members.push(display_name);
}
if let Some(direct) = room_member_event.content.is_direct {
if !is_direct && direct == true {
room_members.pop();
is_direct = true;
}
}
}
}
}
if is_direct {
self.data
.room_to_direct_name
.insert(room_id.clone(), room_members[0].clone());
}
for message_info in joined_room.timeline.events.iter().filter_map(|m| {
if let Ok(ruma::events::AnySyncRoomEvent::MessageLike(message_event)) =
m.deserialize_as()
{
let msg_event_id = Box::new(message_event.event_id().to_owned());
if self.data.recent_event_ids.contains(&msg_event_id) {
return None;
}
if !self.data.recent_event_ids.contains(&msg_event_id) {
self.data.recent_event_ids.push(*msg_event_id);
}
if self.data.recent_event_ids.len() > 500 {
self.data.recent_event_ids.remove(0);
}
if let AnySyncMessageLikeEvent::RoomMessage(SyncMessageLikeEvent::Original(
room_message,
)) = message_event
{
let sender = room_message.sender;
let message: String;
let mut is_emote: bool = false;
if let room::message::MessageType::Text(text_message_event_content) =
room_message.content.msgtype
{
message = text_message_event_content.body;
//is_emote = false;
} else if let room::message::MessageType::Emote(
emote_message_event_content,
) = room_message.content.msgtype
{
message = emote_message_event_content.body;
is_emote = true;
} else if let room::message::MessageType::Notice(
notice_message_event_content,
) = room_message.content.msgtype
{
message = notice_message_event_content.body;
} else {
return None;
}
if sender == self.me {
//return None;
let look_for = &(room_id.clone(), message.clone());
if self.data.last_sent_messages.contains(&look_for) {
self.data.last_sent_messages.retain(|q| q != look_for);
return None;
}
}
return Some(MessageInfo {
message: message.clone(),
sender: sender,
room_id: room_id.clone(),
is_emote: is_emote,
});
}
}
None
}) {
messages.push(message_info);
}
}
messages
}
}
pub struct MessageInfo {
pub room_id: OwnedRoomId,
pub sender: OwnedUserId,
pub message: String,
pub is_emote: bool,
}