Skip to content

Commit

Permalink
Make it build again
Browse files Browse the repository at this point in the history
  • Loading branch information
rumpelsepp committed Feb 2, 2024
1 parent 08e73e0 commit da47240
Show file tree
Hide file tree
Showing 9 changed files with 1,559 additions and 1,235 deletions.
2,578 changes: 1,459 additions & 1,119 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ futures = "0.3.26"
is-terminal = "0.4.4"
keyring = "2.0.1"
log = "0.4.17"
matrix-sdk-crypto = "0.7.0"
mime = "0.3.17"
prompts = "0.1.0"
reqwest = { version = "0.11.23", features = ["native-tls-vendored"] }
rpassword = "7.2.0"
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.96"
Expand All @@ -29,10 +31,9 @@ tracing-subscriber = "0.3.17"
xdg = "2.4.1"

[dependencies.matrix-sdk]
git = "https://github.com/matrix-org/matrix-rust-sdk"
branch = "main"
version = "0.7.0"
default-features = false
features = ["e2e-encryption", "sled", "markdown", "socks", "anyhow", "image-proc"]
features = ["e2e-encryption", "markdown", "socks", "anyhow", "image-proc", "experimental-sliding-sync", "sqlite", "bundled-sqlite"]

[dev-dependencies]
assert_cmd = "2.0.8"
Expand Down
20 changes: 0 additions & 20 deletions src/base64.rs

This file was deleted.

5 changes: 4 additions & 1 deletion src/client/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use anyhow::anyhow;
use matrix_sdk::ruma::OwnedUserId;
use matrix_sdk::Client as MatrixClient;

use super::session::state_db_path;
use super::{session, Client};
use crate::CRATE_NAME;

Expand Down Expand Up @@ -37,9 +38,11 @@ impl ClientBuilder {
panic!("no device name set");
};

let state_path = state_db_path(user_id.clone())?;

let mut builder = MatrixClient::builder()
.server_name(user_id.server_name())
.sled_store(session::state_db_path(&user_id)?, None);
.sqlite_store(state_path, None);

if let Ok(proxy) = env::var("HTTPS_PROXY") {
builder = builder.proxy(proxy);
Expand Down
1 change: 1 addition & 0 deletions src/client/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ impl super::Client {

pub(crate) async fn login_password(&self, password: &str) -> anyhow::Result<()> {
self.inner
.matrix_auth()
.login_username(&self.user_id, password)
.initial_device_display_name(&self.device_name)
.send()
Expand Down
86 changes: 44 additions & 42 deletions src/client/room.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ use anyhow::{anyhow, bail};
use matrix_sdk::attachment::AttachmentConfig;
use matrix_sdk::room::{self, Messages, MessagesOptions, Room};
use matrix_sdk::ruma::events::room::message::{
EmoteMessageEventContent, MessageType, RoomMessageEventContent,
AddMentions, EmoteMessageEventContent, MessageType, RoomMessageEventContent,
};
use matrix_sdk::ruma::events::room::message::{ForwardThread, RoomMessageEvent};
use matrix_sdk::ruma::OwnedEventId;
use matrix_sdk::ruma::RoomId;
use matrix_sdk::ruma::{OwnedEventId, OwnedMxcUri};
use matrix_sdk::RoomMemberships;

impl super::Client {
pub(crate) fn get_joined_room(
&self,
room_id: impl AsRef<RoomId>,
) -> anyhow::Result<room::Joined> {
) -> anyhow::Result<room::Room> {
self.inner
.get_joined_room(room_id.as_ref())
.get_room(room_id.as_ref())
.ok_or_else(|| anyhow!("no such room: {}", room_id.as_ref()))
}

Expand All @@ -27,7 +28,7 @@ impl super::Client {
content: RoomMessageEventContent,
) -> anyhow::Result<()> {
let room = self.get_joined_room(room_id)?;
room.send(content, None).await?;
room.send(content).await?;
Ok(())
}

Expand Down Expand Up @@ -62,7 +63,7 @@ impl super::Client {
} else {
RoomMessageEventContent::text_plain(body)
}
.make_reply_to(original_message, ForwardThread::Yes);
.make_reply_to(original_message, ForwardThread::Yes, AddMentions::No);

self.send_message_raw(room_id, content).await
}
Expand Down Expand Up @@ -103,7 +104,7 @@ impl super::Client {
path: impl AsRef<Path>,
) -> anyhow::Result<()> {
let path = path.as_ref();
let Some(file_name) = path.file_name().map(|s|s.to_str().unwrap()) else {
let Some(file_name) = path.file_name().map(|s| s.to_str().unwrap()) else {
bail!("invalid file: {:?}", path);
};

Expand All @@ -117,57 +118,58 @@ impl super::Client {
Ok(())
}

pub(crate) async fn query_room(
&self,
room: Room,
query_avatars: bool,
query_members: bool,
) -> anyhow::Result<crate::outputs::Room> {
let room_avatar = if query_avatars {
room.avatar(matrix_sdk::media::MediaFormat::File).await?
} else {
None
};
pub(crate) fn mxc_to_http(&self, mxc: OwnedMxcUri) -> String {
if !mxc.is_valid() {
return String::from("");
}
format!(
"{}_matrix/media/v3/thumbnail/{}/{}?width=50&height=50&method=scale",
self.inner.homeserver().as_str(),
mxc.server_name().unwrap(),
mxc.media_id().unwrap(),
)
}

let mut room_out = crate::outputs::Room {
pub(crate) async fn query_room(&self, room: Room) -> anyhow::Result<crate::outputs::Room> {
let mut members_out = Vec::new();
for member in room.members(RoomMemberships::empty()).await? {
let avatar = match member.avatar_url() {
Some(uri) => self.mxc_to_http(OwnedMxcUri::from(uri)),
None => String::from(""),
};
members_out.push(crate::outputs::RoomMember {
avatar,
name: member.name().to_string(),
display_name: member.display_name().map(|s| s.to_string()),
user_id: member.user_id().to_string(),
})
}

let mut opts = MessagesOptions::backward();
opts.limit = (1).try_into().unwrap();

let room_out = crate::outputs::Room {
name: room.name(),
topic: room.topic(),
display_name: room.display_name().await?.to_string(),
room_id: room.room_id().to_string(),
is_encrypted: room.is_encrypted().await?,
is_direct: room.is_direct(),
is_direct: room.is_direct().await?,
is_tombstoned: room.is_tombstoned(),
is_public: room.is_public(),
is_space: room.is_space(),
history_visibility: room.history_visibility().to_string(),
guest_access: room.guest_access().to_string(),
avatar: room_avatar,
avatar: match room.avatar_url() {
Some(url) => self.mxc_to_http(url.clone()),
None => String::from(""),
},
matrix_uri: room.matrix_permalink(false).await?.to_string(),
matrix_to_uri: room.matrix_to_permalink().await?.to_string(),
unread_notifications: room.unread_notification_counts(),
members: None,
members: Some(members_out),
};

if query_members {
let mut members_out = vec![];
for member in room.members().await? {
let member_avatar = if query_avatars {
member.avatar(matrix_sdk::media::MediaFormat::File).await?
} else {
None
};

members_out.push(crate::outputs::RoomMember {
avatar: member_avatar,
name: member.name().to_string(),
display_name: member.display_name().map(|s| s.to_string()),
user_id: member.user_id().to_string(),
})
}

room_out.members = Some(members_out);
}

Ok(room_out)
}

Expand Down
18 changes: 9 additions & 9 deletions src/client/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};

use anyhow::bail;
use matrix_sdk::ruma::{OwnedUserId, UserId};
use matrix_sdk::Session;
use matrix_sdk::matrix_auth::MatrixSession;
use serde::{Deserialize, Serialize};
use tracing::error;

Expand All @@ -26,28 +26,28 @@ pub(crate) fn state_db_path(user_id: impl AsRef<UserId>) -> anyhow::Result<PathB
Ok(xdg_dirs.place_state_file(Path::new(&user_id.to_string()).join("state.sled"))?)
}

fn load_session_json(path: impl AsRef<Path>) -> anyhow::Result<Option<Session>> {
fn load_session_json(path: impl AsRef<Path>) -> anyhow::Result<Option<MatrixSession>> {
let raw = fs::read_to_string(path)?;
// TODO: Handle None case.
Ok(Some(serde_json::from_str(&raw)?))
}

fn load_session_keyring(user_id: impl AsRef<UserId>) -> anyhow::Result<Option<Session>> {
fn load_session_keyring(user_id: impl AsRef<UserId>) -> anyhow::Result<Option<MatrixSession>> {
let entry = keyring::Entry::new(CRATE_NAME, user_id.as_ref().as_str())?;
// TODO: Handle None case.
let raw = entry.get_password()?;
Ok(Some(serde_json::from_str(&raw)?))
}

pub(crate) fn load_session(user_id: impl AsRef<UserId>) -> anyhow::Result<Option<Session>> {
pub(crate) fn load_session(user_id: impl AsRef<UserId>) -> anyhow::Result<Option<MatrixSession>> {
if env::var("MN_NO_KEYRING").is_ok() {
load_session_json(session_json_path(user_id)?)
} else {
load_session_keyring(user_id)
}
}

fn persist_session_json(path: impl AsRef<Path>, session: &Session) -> anyhow::Result<()> {
fn persist_session_json(path: impl AsRef<Path>, session: &MatrixSession) -> anyhow::Result<()> {
let mut out = serde_json::to_string(session)?;
if !out.ends_with('\n') {
out.push('\n');
Expand All @@ -65,15 +65,15 @@ fn persist_session_json(path: impl AsRef<Path>, session: &Session) -> anyhow::Re
Ok(())
}

fn persist_session_keyring(user_id: impl AsRef<UserId>, session: &Session) -> anyhow::Result<()> {
fn persist_session_keyring(user_id: impl AsRef<UserId>, session: &MatrixSession) -> anyhow::Result<()> {
let entry = keyring::Entry::new(CRATE_NAME, user_id.as_ref().as_str())?;
entry.set_password(&serde_json::to_string(session)?)?;
Ok(())
}

pub(crate) fn persist_session(
user_id: impl AsRef<UserId>,
session: &Session,
session: &MatrixSession,
) -> anyhow::Result<()> {
if env::var("MN_NO_KEYRING").is_ok() {
persist_session_json(session_json_path(user_id)?, session)
Expand Down Expand Up @@ -135,12 +135,12 @@ impl super::Client {
}

pub(super) fn persist_session(&self) -> anyhow::Result<()> {
let session = self.inner.session().unwrap();
let session = self.inner.matrix_auth().session().unwrap();
persist_session(&self.user_id, &session)
}

pub(crate) async fn logout(&self) -> anyhow::Result<()> {
self.inner.logout().await?;
self.inner.matrix_auth().logout().await?;
self.clean()
}
}
Expand Down
27 changes: 9 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ use matrix_sdk::ruma::events::receipt::ReceiptThread;
use matrix_sdk::ruma::presence::PresenceState;
use matrix_sdk::ruma::{events::AnySyncTimelineEvent, serde::Raw};
use matrix_sdk::ruma::{OwnedEventId, OwnedRoomId, OwnedUserId};
use matrix_sdk::RoomState;
use serde::Serialize;
use serde_json::value::RawValue;

mod base64;
mod client;
mod mime;
mod outputs;
Expand Down Expand Up @@ -101,14 +101,6 @@ enum Command {
/// Only query this room
#[arg(long)]
room_id: Option<OwnedRoomId>,

/// Query room members
#[arg(long = "members")]
query_members: bool,

/// Query avatars
#[arg(long = "avatars")]
query_avatars: bool,
},
/// Send a message to a room
Send {
Expand Down Expand Up @@ -180,7 +172,10 @@ async fn on_room_message(
room: Room,
receipt: bool,
) -> anyhow::Result<()> {
let Room::Joined(room) = room else {return Ok(())};
match room.state() {
RoomState::Joined => {},
_ => return Ok(())
}

let raw_json = event.clone().into_json();
let parsed_event: SyncTimelineEvent = event.into();
Expand Down Expand Up @@ -240,7 +235,7 @@ async fn main() -> anyhow::Result<()> {
force,
include_token,
} => {
let home_server = client.homeserver().await.to_string();
let home_server = client.homeserver().to_string();
let user_id = client.user_id().unwrap().to_string();

#[derive(Serialize)]
Expand Down Expand Up @@ -315,18 +310,14 @@ async fn main() -> anyhow::Result<()> {

println!("{}", serde_json::to_string(&events)?);
}
Command::Rooms {
room_id,
query_members,
query_avatars,
} => {
Command::Rooms { room_id} => {
let out = match room_id {
Some(room_id) => {
let Some(room) = client.get_room(&room_id) else {
bail!("no such room: {}", room_id);
};
let output = client
.query_room(room, query_avatars, query_members)
.query_room(room)
.await?;
serde_json::to_string(&output)?
}
Expand All @@ -335,7 +326,7 @@ async fn main() -> anyhow::Result<()> {
for room in client.rooms() {
output.push(
client
.query_room(room, query_avatars, query_members)
.query_room(room)
.await?,
);
}
Expand Down
Loading

0 comments on commit da47240

Please sign in to comment.