Make identifier parsing easier to read

… by using `Id::parse` instead of `Box::<Id>::try_from`.
This commit is contained in:
Jonas Platte
2022-02-12 04:20:37 +01:00
parent a7dcd26588
commit c3d9c73d00
10 changed files with 27 additions and 44 deletions

View File

@@ -1,4 +1,4 @@
use std::{convert::TryFrom, env};
use std::env;
use matrix_sdk_appservice::{
matrix_sdk::{
@@ -21,7 +21,7 @@ pub async fn handle_room_member(
if !appservice.user_id_is_in_namespace(&event.state_key)? {
trace!("not an appservice user: {}", event.state_key);
} else if let MembershipState::Invite = event.content.membership {
let user_id = Box::<UserId>::try_from(event.state_key.as_str())?;
let user_id = UserId::parse(event.state_key.as_str())?;
appservice.register_virtual_user(user_id.localpart()).await?;
let client = appservice.virtual_user_client(user_id.localpart()).await?;

View File

@@ -222,24 +222,24 @@ impl Inspector {
async fn run(&self, matches: ArgMatches) {
match matches.subcommand() {
Some(("get-profiles", args)) => {
let room_id = Box::<RoomId>::try_from(args.value_of("room-id").unwrap()).unwrap();
let room_id = RoomId::parse(args.value_of("room-id").unwrap()).unwrap();
self.get_profiles(room_id).await;
}
Some(("get-members", args)) => {
let room_id = Box::<RoomId>::try_from(args.value_of("room-id").unwrap()).unwrap();
let room_id = RoomId::parse(args.value_of("room-id").unwrap()).unwrap();
self.get_members(room_id).await;
}
Some(("list-rooms", _)) => self.list_rooms().await,
Some(("get-display-names", args)) => {
let room_id = Box::<RoomId>::try_from(args.value_of("room-id").unwrap()).unwrap();
let room_id = RoomId::parse(args.value_of("room-id").unwrap()).unwrap();
let display_name = args.value_of("display-name").unwrap().to_string();
self.get_display_name_owners(room_id, display_name).await;
}
Some(("get-state", args)) => {
let room_id = Box::<RoomId>::try_from(args.value_of("room-id").unwrap()).unwrap();
let room_id = RoomId::parse(args.value_of("room-id").unwrap()).unwrap();
let event_type = EventType::try_from(args.value_of("event-type").unwrap()).unwrap();
self.get_state(room_id, event_type).await;
}
@@ -285,27 +285,19 @@ impl Inspector {
vec![
Argparse::new("list-rooms"),
Argparse::new("get-members").arg(Arg::new("room-id").required(true).validator(|r| {
Box::<RoomId>::try_from(r)
.map(|_| ())
.map_err(|_| "Invalid room id given".to_owned())
RoomId::parse(r).map(|_| ()).map_err(|_| "Invalid room id given".to_owned())
})),
Argparse::new("get-profiles").arg(Arg::new("room-id").required(true).validator(|r| {
Box::<RoomId>::try_from(r)
.map(|_| ())
.map_err(|_| "Invalid room id given".to_owned())
RoomId::parse(r).map(|_| ()).map_err(|_| "Invalid room id given".to_owned())
})),
Argparse::new("get-display-names")
.arg(Arg::new("room-id").required(true).validator(|r| {
Box::<RoomId>::try_from(r)
.map(|_| ())
.map_err(|_| "Invalid room id given".to_owned())
RoomId::parse(r).map(|_| ()).map_err(|_| "Invalid room id given".to_owned())
}))
.arg(Arg::new("display-name").required(true)),
Argparse::new("get-state")
.arg(Arg::new("room-id").required(true).validator(|r| {
Box::<RoomId>::try_from(r)
.map(|_| ())
.map_err(|_| "Invalid room id given".to_owned())
RoomId::parse(r).map(|_| ()).map_err(|_| "Invalid room id given".to_owned())
}))
.arg(Arg::new("event-type").required(true).validator(|e| {
EventType::try_from(e).map(|_| ()).map_err(|_| "Invalid event type".to_string())

View File

@@ -12,10 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{
convert::TryFrom,
sync::{Arc, RwLock as SyncRwLock},
};
use std::sync::{Arc, RwLock as SyncRwLock};
use futures_util::stream::{self, StreamExt};
use ruma::{
@@ -346,7 +343,7 @@ impl Room {
let members: Vec<_> =
stream::iter(summary.heroes.iter().filter(|u| !is_own_user_id(u)))
.filter_map(|u| async move {
let user_id = Box::<UserId>::try_from(u.as_str()).ok()?;
let user_id = UserId::parse(u.as_str()).ok()?;
self.get_member(&user_id).await.transpose()
})
.collect()

View File

@@ -556,7 +556,7 @@ impl IndexeddbStore {
.await?
.iter()
.filter_map(|key| match key.as_string() {
Some(k) => Box::<UserId>::try_from(&k[skip..]).ok(),
Some(k) => UserId::parse(&k[skip..]).ok(),
_ => None,
})
.collect::<Vec<_>>())
@@ -701,7 +701,7 @@ impl IndexeddbStore {
let res =
store.get(&k)?.await?.ok_or(StoreError::Codec(format!("no data at {:?}", k)))?;
let u = if let Some(k_str) = k.as_string() {
Box::<UserId>::try_from(&k_str[prefix_len..])
UserId::parse(&k_str[prefix_len..])
.map_err(|e| StoreError::Codec(format!("{:?}", e)))?
} else {
return Err(StoreError::Codec(format!("{:?}", k)));

View File

@@ -14,7 +14,7 @@
use std::{
collections::BTreeSet,
convert::{TryFrom, TryInto},
convert::TryInto,
path::{Path, PathBuf},
sync::Arc,
time::Instant,
@@ -660,7 +660,7 @@ impl SledStore {
let user_id = iter.next().expect("User ids weren't properly encoded");
Ok(Box::<UserId>::try_from(String::from_utf8_lossy(user_id).to_string())?)
Ok(UserId::parse(String::from_utf8_lossy(user_id).to_string())?)
};
let members = self.members.clone();
@@ -679,7 +679,7 @@ impl SledStore {
let key = room_id.encode();
spawn_blocking(move || {
stream::iter(db.invited_user_ids.scan_prefix(key).map(|u| {
Box::<UserId>::try_from(String::from_utf8_lossy(&u?.1).to_string())
UserId::parse(String::from_utf8_lossy(&u?.1).to_string())
.map_err(StoreError::Identifier)
}))
})
@@ -695,7 +695,7 @@ impl SledStore {
let key = room_id.encode();
spawn_blocking(move || {
stream::iter(db.joined_user_ids.scan_prefix(key).map(|u| {
Box::<UserId>::try_from(String::from_utf8_lossy(&u?.1).to_string())
UserId::parse(String::from_utf8_lossy(&u?.1).to_string())
.map_err(StoreError::Identifier)
}))
})

View File

@@ -366,7 +366,7 @@ impl InboundGroupSession {
let room_id = decrypted_object
.get("room_id")
.and_then(|r| r.as_str().and_then(|r| Box::<RoomId>::try_from(r).ok()));
.and_then(|r| r.as_str().and_then(|r| RoomId::parse(r).ok()));
// Check that we have a room id and that the event wasn't forwarded from
// another room.

View File

@@ -386,7 +386,7 @@ impl IndexeddbStore {
Some(Ok(false)) => false,
_ => true,
};
let user = match user_id.as_string().map(|u| Box::<UserId>::try_from(u)) {
let user = match user_id.as_string().map(|u| UserId::parse(u)) {
Some(Ok(user)) => user,
_ => continue,
};

View File

@@ -443,7 +443,7 @@ impl SledStore {
async fn load_tracked_users(&self) -> Result<()> {
for value in &self.tracked_users {
let (user, dirty) = value?;
let user = Box::<UserId>::try_from(String::from_utf8_lossy(&user).to_string())?;
let user = UserId::parse(String::from_utf8_lossy(&user).to_string())?;
let dirty = dirty.get(0).map(|d| *d == 1).unwrap_or(true);
self.tracked_users_cache.insert(user.to_owned());

View File

@@ -1,4 +1,4 @@
use std::{convert::TryFrom, env, process::exit};
use std::{env, process::exit};
use matrix_sdk::{
ruma::{api::client::r0::profile, MxcUri, UserId},
@@ -62,7 +62,7 @@ async fn main() -> Result<(), matrix_sdk::Error> {
let client = login(homeserver_url, &username, &password).await?;
let user_id = Box::<UserId>::try_from(username).expect("Couldn't parse the MXID");
let user_id = UserId::parse(username).expect("Couldn't parse the MXID");
let profile = get_profile(client, &user_id).await?;
println!("{:#?}", profile);
Ok(())

View File

@@ -231,7 +231,7 @@ impl Client {
/// use matrix_sdk::{Client, ruma::UserId};
///
/// // First let's try to construct an user id, presumably from user input.
/// let alice = Box::<UserId>::try_from("@alice:example.org")?;
/// let alice = UserId::parse("@alice:example.org")?;
///
/// // Now let's try to discover the homeserver and create a client object.
/// let client = Client::new_from_user_id(&alice).await?;
@@ -2367,13 +2367,7 @@ pub(crate) mod test {
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
use std::{
collections::BTreeMap,
convert::{TryFrom, TryInto},
io::Cursor,
str::FromStr,
time::Duration,
};
use std::{collections::BTreeMap, convert::TryInto, io::Cursor, str::FromStr, time::Duration};
use matrix_sdk_base::media::{MediaFormat, MediaRequest, MediaThumbnailSize, MediaType};
use matrix_sdk_test::{test_json, EventBuilder, EventsJson};
@@ -2447,7 +2441,7 @@ pub(crate) mod test {
async fn successful_discovery() {
let server_url = mockito::server_url();
let domain = server_url.strip_prefix("http://").unwrap();
let alice = Box::<UserId>::try_from("@alice:".to_string() + domain).unwrap();
let alice = UserId::parse("@alice:".to_string() + domain).unwrap();
let _m_well_known = mock("GET", "/.well-known/matrix/client")
.with_status(200)
@@ -2469,7 +2463,7 @@ pub(crate) mod test {
async fn discovery_broken_server() {
let server_url = mockito::server_url();
let domain = server_url.strip_prefix("http://").unwrap();
let alice = Box::<UserId>::try_from("@alice:".to_string() + domain).unwrap();
let alice = UserId::parse("@alice:".to_string() + domain).unwrap();
let _m = mock("GET", "/.well-known/matrix/client")
.with_status(200)