Browse Source

chore: Upgrade crate dependencies

merge-requests/1579/head
Kévin Commaille 2 years ago
parent
commit
1cc441a718
No known key found for this signature in database
GPG Key ID: 29A48C1F03620416
  1. 712
      Cargo.lock
  2. 12
      Cargo.toml
  3. 79
      src/session/model/notifications/mod.rs
  4. 32
      src/session/model/room/permissions.rs
  5. 4
      src/session/model/session.rs
  6. 9
      src/system_settings/linux.rs
  7. 106
      src/utils/matrix.rs

712
Cargo.lock generated

File diff suppressed because it is too large Load Diff

12
Cargo.toml

@ -36,7 +36,7 @@ mime = "0.3"
mime_guess = "2"
once_cell = "1"
pulldown-cmark = "0.9"
qrcode = "0.12"
qrcode = "0.13"
rand = "0.8"
regex = "1"
rmp-serde = "1"
@ -65,7 +65,7 @@ sourceview = { package = "sourceview5", version = "0.7" }
[dependencies.matrix-sdk]
git = "https://github.com/matrix-org/matrix-rust-sdk.git"
rev = "19526cea6bce133fc48904838956846aeb966dc6"
rev = "eec52d7977c6122879a2d25f6ea81d76ea754280"
features = [
"socks",
"sso-login",
@ -76,14 +76,14 @@ features = [
[dependencies.matrix-sdk-ui]
git = "https://github.com/matrix-org/matrix-rust-sdk.git"
rev = "19526cea6bce133fc48904838956846aeb966dc6"
rev = "eec52d7977c6122879a2d25f6ea81d76ea754280"
default-features = false
features = ["e2e-encryption", "native-tls"]
[dependencies.ruma]
version = "0.9.4"
# git = "https://github.com/ruma/ruma.git"
# rev = "4ef6d1641bdd7d1c1586d2356c183798f3900bf1"
# version = "0.9.4"
git = "https://github.com/ruma/ruma.git"
rev = "684ffc789877355bd25269451b2356817c17cc3f"
features = [
"unstable-unspecified",
"client-api-c",

79
src/session/model/notifications/mod.rs

@ -1,13 +1,6 @@
use gtk::{
gio,
glib::{self, clone},
prelude::*,
subclass::prelude::*,
};
use ruma::{
api::client::push::get_notifications::v3::Notification, EventId, OwnedEventId, OwnedRoomId,
RoomId,
};
use gtk::{gio, glib, prelude::*, subclass::prelude::*};
use matrix_sdk::{sync::Notification, Room as MatrixRoom};
use ruma::{EventId, OwnedRoomId, RoomId};
use tracing::{debug, error, warn};
mod notifications_settings;
@ -17,7 +10,11 @@ pub use self::notifications_settings::{
};
use super::{Room, Session};
use crate::{
intent, prelude::*, spawn, spawn_tokio, utils::matrix::get_event_body, Application, Window,
intent,
prelude::*,
spawn_tokio,
utils::matrix::{get_event_body, AnySyncOrStrippedTimelineEvent},
Application, Window,
};
mod imp {
@ -31,9 +28,8 @@ mod imp {
/// The current session.
#[property(get, set = Self::set_session, explicit_notify, nullable)]
pub session: glib::WeakRef<Session>,
/// A map of room ID to list of event IDs for which a notification was
/// sent to the system.
pub list: RefCell<HashMap<OwnedRoomId, Vec<OwnedEventId>>>,
/// A map of room ID to list of notification IDs.
pub list: RefCell<HashMap<OwnedRoomId, Vec<String>>>,
/// The notifications settings for this session.
#[property(get)]
pub settings: NotificationsSettings,
@ -77,13 +73,7 @@ impl Notifications {
///
/// The notification won't be shown if the application is active and this
/// session is displayed.
pub fn show(&self, matrix_notification: Notification) {
spawn!(clone!(@weak self as obj => async move {
obj.show_inner(matrix_notification).await;
}));
}
async fn show_inner(&self, matrix_notification: Notification) {
pub async fn show(&self, matrix_notification: Notification, matrix_room: MatrixRoom) {
let Some(session) = self.session() else {
return;
};
@ -96,6 +86,7 @@ impl Notifications {
let app = Application::default();
let window = app.active_window().and_downcast::<Window>();
let session_id = session.session_id();
let room_id = matrix_room.room_id();
// Don't show notifications for the current room in the current session if the
// window is active.
@ -104,32 +95,27 @@ impl Notifications {
&& w.current_session_id().as_deref() == Some(session_id)
&& w.session_view()
.selected_room()
.is_some_and(|r| r.room_id() == matrix_notification.room_id)
.is_some_and(|r| r.room_id() == room_id)
}) {
return;
}
let Some(room) = session.room_list().get(&matrix_notification.room_id) else {
warn!(
"Could not display notification for missing room {}",
matrix_notification.room_id
);
let Some(room) = session.room_list().get(room_id) else {
warn!("Could not display notification for missing room {room_id}",);
return;
};
let event = match matrix_notification.event.deserialize() {
let event = match AnySyncOrStrippedTimelineEvent::from_raw(&matrix_notification.event) {
Ok(event) => event,
Err(error) => {
warn!(
"Could not display notification for unrecognized event in room {}: {error}",
matrix_notification.room_id
"Could not display notification for unrecognized event in room {room_id}: {error}",
);
return;
}
};
let is_direct = room.direct_member().is_some();
let matrix_room = room.matrix_room().clone();
let sender_id = event.sender();
let owned_sender_id = sender_id.to_owned();
let handle =
@ -148,7 +134,7 @@ impl Notifications {
.and_then(|m| m.display_name())
.unwrap_or_else(|| sender_id.localpart());
let body = match get_event_body(&event, sender_name, !is_direct) {
let body = match get_event_body(&event, sender_name, session.user_id(), !is_direct) {
Some(body) => body,
None => {
debug!("Received notification for event of unexpected type {event:?}",);
@ -183,7 +169,7 @@ impl Notifications {
.borrow_mut()
.entry(room_id)
.or_default()
.push(event_id.to_owned());
.push(id);
}
/// Ask the system to remove the known notifications for the given room.
@ -191,16 +177,11 @@ impl Notifications {
/// Only the notifications that were shown since the application's startup
/// are known, older ones might still be present.
pub fn withdraw_all_for_room(&self, room: &Room) {
let Some(session) = self.session() else {
return;
};
let room_id = room.room_id();
if let Some(notifications) = self.imp().list.borrow_mut().remove(room_id) {
let app = Application::default();
for event_id in notifications {
let id = notification_id(session.session_id(), room_id, &event_id);
for id in notifications {
app.withdraw_notification(&id);
}
}
@ -211,17 +192,10 @@ impl Notifications {
/// Only the notifications that were shown since the application's startup
/// are known, older ones might still be present.
pub fn clear(&self) {
let Some(session) = self.session() else {
return;
};
let app = Application::default();
for (room_id, notifications) in self.imp().list.take() {
for event_id in notifications {
let id = notification_id(session.session_id(), &room_id, &event_id);
app.withdraw_notification(&id);
}
for id in self.imp().list.take().values().flatten() {
app.withdraw_notification(id);
}
}
}
@ -232,6 +206,11 @@ impl Default for Notifications {
}
}
fn notification_id(session_id: &str, room_id: &RoomId, event_id: &EventId) -> String {
format!("{session_id}//{room_id}//{event_id}")
fn notification_id(session_id: &str, room_id: &RoomId, event_id: Option<&EventId>) -> String {
if let Some(event_id) = event_id {
format!("{session_id}//{room_id}//{event_id}")
} else {
let random_id = glib::uuid_string_random();
format!("{session_id}//{room_id}//{random_id}")
}
}

32
src/session/model/room/permissions.rs

@ -318,37 +318,9 @@ mod imp {
self.obj().notify_can_send_reaction();
}
/// Whether our own member can redact an event.
// TODO: use Ruma's method when it is fixed.
fn can_redact(&self, is_own: bool) -> bool {
if !self.is_joined.get() {
// We cannot do anything if the member is not joined.
return false;
}
let Some(own_member) = self.own_member() else {
return false;
};
let power_levels = self.power_levels.borrow();
let own_user_id = own_member.user_id();
if !power_levels.user_can_send_message(own_user_id, MessageLikeEventType::RoomRedaction)
{
return false;
}
if is_own {
// No more checks needed.
return true;
}
power_levels.user_can_redact(own_user_id)
}
/// Update whether our own member can redact their own event.
fn update_can_redact_own(&self) {
let can_redact_own = self.can_redact(true);
let can_redact_own = self.is_allowed_to(PowerLevelAction::RedactOwn);
if self.can_redact_own.get() == can_redact_own {
return;
@ -360,7 +332,7 @@ mod imp {
/// Whether our own member can redact the event of another user.
fn update_can_redact_other(&self) {
let can_redact_other = self.can_redact(false);
let can_redact_other = self.is_allowed_to(PowerLevelAction::RedactOther);
if self.can_redact_other.get() == can_redact_other {
return;

4
src/session/model/session.rs

@ -297,14 +297,14 @@ impl Session {
let client = self.client();
spawn_tokio!(async move {
client
.register_notification_handler(move |notification, _, _| {
.register_notification_handler(move |notification, room, _| {
let obj_weak = obj_weak.clone();
async move {
let ctx = glib::MainContext::default();
ctx.spawn(async move {
spawn!(async move {
if let Some(obj) = obj_weak.upgrade() {
obj.notifications().show(notification);
obj.notifications().show(notification, room).await;
}
});
});

9
src/system_settings/linux.rs

@ -83,7 +83,10 @@ impl LinuxSystemSettings {
let clock_format_changed_stream = match spawn_tokio!(async move {
proxy
.receive_setting_changed_with_args(GNOME_DESKTOP_NAMESPACE, CLOCK_FORMAT_KEY)
.receive_setting_changed_with_args::<ClockFormat>(
GNOME_DESKTOP_NAMESPACE,
CLOCK_FORMAT_KEY,
)
.await
})
.await
@ -97,10 +100,10 @@ impl LinuxSystemSettings {
};
let obj_weak = self.downgrade();
clock_format_changed_stream.for_each(move |setting| {
clock_format_changed_stream.for_each(move |value| {
let obj_weak = obj_weak.clone();
async move {
let clock_format = match ClockFormat::try_from(setting.value()) {
let clock_format = match value {
Ok(clock_format) => clock_format,
Err(error) => {
error!("Could not update clock format setting: {error}");

106
src/utils/matrix.rs

@ -7,14 +7,21 @@ use std::{
use html2pango::html_escape;
use html5gum::{HtmlString, Token, Tokenizer};
use matrix_sdk::{config::RequestConfig, Client, ClientBuildError};
use matrix_sdk::{
config::RequestConfig, deserialized_responses::RawAnySyncOrStrippedTimelineEvent, Client,
ClientBuildError,
};
use ruma::{
events::{room::message::MessageType, AnyMessageLikeEventContent, AnySyncTimelineEvent},
events::{
room::{member::MembershipState, message::MessageType},
AnyMessageLikeEventContent, AnyStrippedStateEvent, AnySyncMessageLikeEvent,
AnySyncTimelineEvent,
},
html::{HtmlSanitizerMode, RemoveReplyFallback},
matrix_uri::MatrixId,
serde::Raw,
IdParseError, MatrixToUri, MatrixUri, OwnedEventId, OwnedRoomAliasId, OwnedRoomId,
OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomOrAliasId,
EventId, IdParseError, MatrixToUri, MatrixUri, OwnedEventId, OwnedRoomAliasId, OwnedRoomId,
OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomOrAliasId, UserId,
};
use thiserror::Error;
@ -97,20 +104,76 @@ pub fn validate_password(password: &str) -> PasswordValidity {
validity
}
/// An deserialized event received in a sync response.
#[derive(Debug, Clone)]
pub enum AnySyncOrStrippedTimelineEvent {
/// An event from a joined or left room.
Sync(AnySyncTimelineEvent),
/// An event from an invited room.
Stripped(AnyStrippedStateEvent),
}
impl AnySyncOrStrippedTimelineEvent {
/// Deserialize the given raw event.
pub fn from_raw(raw: &RawAnySyncOrStrippedTimelineEvent) -> Result<Self, serde_json::Error> {
let ev = match raw {
RawAnySyncOrStrippedTimelineEvent::Sync(ev) => Self::Sync(ev.deserialize()?),
RawAnySyncOrStrippedTimelineEvent::Stripped(ev) => Self::Stripped(ev.deserialize()?),
};
Ok(ev)
}
/// The sender of the event.
pub fn sender(&self) -> &UserId {
match self {
AnySyncOrStrippedTimelineEvent::Sync(ev) => ev.sender(),
AnySyncOrStrippedTimelineEvent::Stripped(ev) => ev.sender(),
}
}
/// The ID of the event, if it's not a stripped state event.
pub fn event_id(&self) -> Option<&EventId> {
match self {
AnySyncOrStrippedTimelineEvent::Sync(ev) => Some(ev.event_id()),
AnySyncOrStrippedTimelineEvent::Stripped(_) => None,
}
}
}
/// Extract the body from the given event.
///
/// Only returns the body for messages.
/// If the event does not have a body but is supported, this will return a
/// localized string.
///
/// If it's a media message, this will return a localized body.
/// Returns `None` if the event type is not supported.
pub fn get_event_body(
event: &AnySyncTimelineEvent,
event: &AnySyncOrStrippedTimelineEvent,
sender_name: &str,
own_user: &UserId,
show_sender: bool,
) -> Option<String> {
let AnySyncTimelineEvent::MessageLike(event) = event else {
return None;
};
match event {
AnySyncOrStrippedTimelineEvent::Sync(AnySyncTimelineEvent::MessageLike(message)) => {
get_message_event_body(message, sender_name, show_sender)
}
AnySyncOrStrippedTimelineEvent::Stripped(state) => {
get_stripped_state_event_body(state, sender_name, own_user)
}
_ => None,
}
}
/// Extract the body from the given message event.
///
/// If it's a media message, this will return a localized body.
///
/// Returns `None` if the message type is not supported.
pub fn get_message_event_body(
event: &AnySyncMessageLikeEvent,
sender_name: &str,
show_sender: bool,
) -> Option<String> {
match event.original_content()? {
AnyMessageLikeEventContent::RoomMessage(mut message) => {
message.sanitize(HtmlSanitizerMode::Compat, RemoveReplyFallback::Yes);
@ -166,6 +229,29 @@ fn text_event_body(message: String, sender_name: &str, show_sender: bool) -> Str
}
}
/// Extract the body from the given state event.
///
/// This will return a localized body.
///
/// Returns `None` if the state event type is not supported.
pub fn get_stripped_state_event_body(
event: &AnyStrippedStateEvent,
sender_name: &str,
own_user: &UserId,
) -> Option<String> {
if let AnyStrippedStateEvent::RoomMember(member_event) = event {
if member_event.content.membership == MembershipState::Invite
&& member_event.state_key == own_user
{
// Translators: Do NOT translate the content between '{' and '}', this is a
// variable name.
return Some(gettext_f("{user} invited you", &[("user", sender_name)]));
}
}
None
}
/// All errors that can occur when setting up the Matrix client.
#[derive(Error, Debug)]
pub enum ClientSetupError {

Loading…
Cancel
Save