[fractal] Remove HostAndPort



commit b32c86b6123d2a2acba821f3f6621ed81f3909e3
Author: Alejandro Domínguez <adomu net-c com>
Date:   Fri Oct 2 02:32:58 2020 +0200

    Remove HostAndPort

 fractal-gtk/src/api/r0.rs           | 56 ++-----------------------------------
 fractal-gtk/src/appop/login.rs      | 12 ++++++--
 fractal-gtk/src/appop/mod.rs        |  5 ++--
 fractal-gtk/src/backend/register.rs |  9 +++++-
 fractal-gtk/src/backend/user.rs     | 15 ++++------
 fractal-gtk/src/globals.rs          |  7 +++--
 fractal-gtk/src/passwd.rs           | 24 ++++++++++------
 fractal-gtk/src/widgets/login.rs    |  5 ++++
 8 files changed, 53 insertions(+), 80 deletions(-)
---
diff --git a/fractal-gtk/src/api/r0.rs b/fractal-gtk/src/api/r0.rs
index 76bd2dbe..5ea80832 100644
--- a/fractal-gtk/src/api/r0.rs
+++ b/fractal-gtk/src/api/r0.rs
@@ -2,12 +2,9 @@ pub mod account;
 pub mod contact;
 pub mod server;
 
-use serde::{Deserialize, Serialize, Serializer};
-use std::convert::TryFrom;
+use matrix_sdk::identifiers::ServerName;
+use serde::{Deserialize, Serialize};
 use std::fmt::{self, Display, Formatter};
-use url::Host;
-use url::ParseError;
-use url::Url;
 
 #[derive(Clone, Debug, Deserialize, Serialize)]
 #[serde(rename_all = "lowercase")]
@@ -19,57 +16,10 @@ pub enum Medium {
 #[derive(Clone, Debug, Serialize)]
 pub struct ThreePIDCredentials {
     pub client_secret: String,
-    pub id_server: HostAndPort<String>,
+    pub id_server: Box<ServerName>,
     pub sid: String,
 }
 
-#[derive(Clone, Debug)]
-pub struct HostAndPort<T> {
-    pub host: Host<T>,
-    pub port: Option<u16>,
-}
-
-impl TryFrom<&Url> for HostAndPort<String> {
-    type Error = ParseError;
-
-    fn try_from(url: &Url) -> Result<Self, Self::Error> {
-        Ok(Self {
-            host: url
-                .host()
-                .ok_or(ParseError::SetHostOnCannotBeABaseUrl)?
-                .to_owned(),
-            port: url.port(),
-        })
-    }
-}
-
-impl TryFrom<Url> for HostAndPort<String> {
-    type Error = ParseError;
-
-    fn try_from(url: Url) -> Result<Self, Self::Error> {
-        Self::try_from(&url)
-    }
-}
-
-impl<T: AsRef<str>> Display for HostAndPort<T> {
-    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
-        if let Some(port) = self.port {
-            write!(f, "{}:{}", self.host, port)
-        } else {
-            write!(f, "{}", self.host)
-        }
-    }
-}
-
-impl<T: AsRef<str>> Serialize for HostAndPort<T> {
-    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
-    where
-        S: Serializer,
-    {
-        ser.serialize_str(&self.to_string())
-    }
-}
-
 #[derive(Clone, Debug, Deserialize, Serialize)]
 pub struct AccessToken(String);
 
diff --git a/fractal-gtk/src/appop/login.rs b/fractal-gtk/src/appop/login.rs
index cce49b4f..c8310419 100644
--- a/fractal-gtk/src/appop/login.rs
+++ b/fractal-gtk/src/appop/login.rs
@@ -3,7 +3,7 @@ use log::error;
 use crate::api::r0::AccessToken;
 use crate::app::RUNTIME;
 use crate::backend::register;
-use matrix_sdk::identifiers::{DeviceId, UserId};
+use matrix_sdk::identifiers::{DeviceId, ServerName, UserId};
 use matrix_sdk::Session;
 use url::Url;
 
@@ -27,7 +27,7 @@ impl AppOp {
         access_token: AccessToken,
         device_id: Box<DeviceId>,
         server_url: Url,
-        identity_url: Url,
+        identity_url: Box<ServerName>,
     ) {
         if self.store_token(uid.clone(), access_token.clone()).is_err() {
             error!("Can't store the token using libsecret");
@@ -76,7 +76,13 @@ impl AppOp {
         self.login_data = None;
     }
 
-    pub fn connect(&mut self, username: String, password: String, server: Url, identity: Url) {
+    pub fn connect(
+        &mut self,
+        username: String,
+        password: String,
+        server: Url,
+        identity: Box<ServerName>,
+    ) {
         self.store_pass(
             username.clone(),
             password.clone(),
diff --git a/fractal-gtk/src/appop/mod.rs b/fractal-gtk/src/appop/mod.rs
index 4c158441..59b77d5f 100644
--- a/fractal-gtk/src/appop/mod.rs
+++ b/fractal-gtk/src/appop/mod.rs
@@ -6,13 +6,12 @@ use std::sync::{Arc, Mutex};
 use std::time::Duration;
 
 use crate::api::r0::AccessToken;
-use matrix_sdk::identifiers::{DeviceId, RoomId, UserId};
+use matrix_sdk::identifiers::{DeviceId, RoomId, ServerName, UserId};
 
 use gtk::prelude::*;
 use matrix_sdk::Client as MatrixClient;
 
 use crate::cache::CacheMap;
-use url::Url;
 
 use crate::util::i18n;
 
@@ -80,7 +79,7 @@ pub struct LoginData {
     pub device_id: Box<DeviceId>,
     pub username: Option<String>,
     pub avatar: Option<PathBuf>,
-    pub identity_url: Url,
+    pub identity_url: Box<ServerName>,
 }
 
 pub struct AppOp {
diff --git a/fractal-gtk/src/backend/register.rs b/fractal-gtk/src/backend/register.rs
index b5cd3e7f..387c2e99 100644
--- a/fractal-gtk/src/backend/register.rs
+++ b/fractal-gtk/src/backend/register.rs
@@ -1,4 +1,4 @@
-use matrix_sdk::identifiers::{DeviceId, UserId};
+use matrix_sdk::identifiers::{DeviceId, Error as IdError, UserId};
 use matrix_sdk::reqwest::Error as ReqwestError;
 use url::{ParseError as UrlError, Url};
 
@@ -113,6 +113,7 @@ pub async fn logout(server: Url, access_token: AccessToken) -> Result<(), Logout
 pub enum GetWellKnownError {
     Reqwest(ReqwestError),
     Json(serde_json::Error),
+    IdParseError(IdError),
     ParseUrl(UrlError),
 }
 
@@ -128,6 +129,12 @@ impl From<serde_json::Error> for GetWellKnownError {
     }
 }
 
+impl From<IdError> for GetWellKnownError {
+    fn from(err: IdError) -> Self {
+        Self::IdParseError(err)
+    }
+}
+
 impl From<UrlError> for GetWellKnownError {
     fn from(err: UrlError) -> Self {
         Self::ParseUrl(err)
diff --git a/fractal-gtk/src/backend/user.rs b/fractal-gtk/src/backend/user.rs
index 3e91621c..c84b6fa1 100644
--- a/fractal-gtk/src/backend/user.rs
+++ b/fractal-gtk/src/backend/user.rs
@@ -1,5 +1,5 @@
 use matrix_sdk::api::error::ErrorKind as RumaErrorKind;
-use matrix_sdk::identifiers::UserId;
+use matrix_sdk::identifiers::{ServerName, UserId};
 use matrix_sdk::reqwest::Error as ReqwestError;
 use matrix_sdk::{Client as MatrixClient, Error as MatrixError};
 use std::collections::BTreeMap;
@@ -218,14 +218,11 @@ pub async fn get_phone_token(
 }
 
 #[derive(Debug)]
-pub enum AddedToFavError {
-    IdentityServerUrl(UrlError),
-    Reqwest(ReqwestError),
-}
+pub struct AddedToFavError(ReqwestError);
 
 impl From<ReqwestError> for AddedToFavError {
     fn from(err: ReqwestError) -> Self {
-        Self::Reqwest(err)
+        Self(err)
     }
 }
 
@@ -234,16 +231,14 @@ impl HandleError for AddedToFavError {}
 pub async fn add_threepid(
     base: Url,
     access_token: AccessToken,
-    identity: Url,
+    id_server: Box<ServerName>,
     client_secret: String,
     sid: String,
 ) -> Result<(), AddedToFavError> {
     let params = AddThreePIDParameters { access_token };
     let body = AddThreePIDBody {
         three_pid_creds: ThreePIDCredentials {
-            id_server: identity
-                .try_into()
-                .map_err(AddedToFavError::IdentityServerUrl)?,
+            id_server,
             sid,
             client_secret,
         },
diff --git a/fractal-gtk/src/globals.rs b/fractal-gtk/src/globals.rs
index 60668b91..3124a46f 100644
--- a/fractal-gtk/src/globals.rs
+++ b/fractal-gtk/src/globals.rs
@@ -1,6 +1,8 @@
 use directories::ProjectDirs;
 use lazy_static::lazy_static;
+use matrix_sdk::identifiers::ServerName;
 use regex::Regex;
+use std::convert::TryInto;
 use std::{path::PathBuf, time::Duration};
 use url::Url;
 
@@ -22,8 +24,9 @@ pub const MAX_STICKER_SIZE: (i32, i32) = (200, 130);
 lazy_static! {
     pub static ref DEFAULT_HOMESERVER: Url =
         Url::parse("https://matrix.org";).expect("Malformed DEFAULT_HOMESERVER value");
-    pub static ref DEFAULT_IDENTITYSERVER: Url =
-        Url::parse("https://vector.im";).expect("Malformed DEFAULT_IDENTITYSERVER value");
+    pub static ref DEFAULT_IDENTITYSERVER: Box<ServerName> = "vector.im"
+        .try_into()
+        .expect("Malformed DEFAULT_IDENTITYSERVER value");
     pub static ref EMAIL_RE: Regex = Regex::new(
         r"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])+@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"
     )
diff --git a/fractal-gtk/src/passwd.rs b/fractal-gtk/src/passwd.rs
index 668cc290..caadcf00 100644
--- a/fractal-gtk/src/passwd.rs
+++ b/fractal-gtk/src/passwd.rs
@@ -1,5 +1,5 @@
 use crate::api::r0::AccessToken;
-use matrix_sdk::identifiers::{Error as IdError, UserId};
+use matrix_sdk::identifiers::{Error as IdError, ServerName, UserId};
 use url::ParseError;
 use url::Url;
 
@@ -38,12 +38,12 @@ pub trait PasswordStorage {
         username: String,
         password: String,
         server: Url,
-        identity: Url,
+        identity: Box<ServerName>,
     ) -> Result<(), Error> {
         ss_storage::store_pass(username, password, server, identity)
     }
 
-    fn get_pass(&self) -> Result<(String, String, Url, Url), Error> {
+    fn get_pass(&self) -> Result<(String, String, Url, Box<ServerName>), Error> {
         ss_storage::get_pass()
     }
 
@@ -59,8 +59,8 @@ pub trait PasswordStorage {
 mod ss_storage {
     use super::Error;
     use crate::api::r0::AccessToken;
-    use matrix_sdk::identifiers::UserId;
-    use std::convert::TryFrom;
+    use matrix_sdk::identifiers::{ServerName, UserId};
+    use std::convert::{TryFrom, TryInto};
     use url::Url;
 
     use secret_service::{Collection, EncryptionType, SecretService, SsError};
@@ -139,7 +139,7 @@ mod ss_storage {
         username: String,
         password: String,
         server: Url,
-        identity: Url,
+        identity: Box<ServerName>,
     ) -> Result<(), Error> {
         let ss = SecretService::new(EncryptionType::Dh)?;
         let collection = get_default_collection_unlocked(&ss)?;
@@ -207,7 +207,7 @@ mod ss_storage {
         Ok(())
     }
 
-    pub fn get_pass() -> Result<(String, String, Url, Url), Error> {
+    pub fn get_pass() -> Result<(String, String, Url, Box<ServerName>), Error> {
         migrate_old_passwd()?;
 
         let ss = SecretService::new(EncryptionType::Dh)?;
@@ -243,7 +243,15 @@ mod ss_storage {
 
         /* Fallback to the vector identity server when there is none */
         let identity = match attr {
-            Some(a) => Url::parse(&a.1)?,
+            Some(ref a) => Url::parse(a.1.as_str())
+                .map_err(Error::from)
+                .and_then(|u| {
+                    u.host_str()
+                        .unwrap_or_default()
+                        .try_into()
+                        .map_err(Error::from)
+                })
+                .or_else(|_| a.1.as_str().try_into().map_err(Error::from))?,
             None => globals::DEFAULT_IDENTITYSERVER.clone(),
         };
 
diff --git a/fractal-gtk/src/widgets/login.rs b/fractal-gtk/src/widgets/login.rs
index 7292d708..cbd59caa 100644
--- a/fractal-gtk/src/widgets/login.rs
+++ b/fractal-gtk/src/widgets/login.rs
@@ -16,6 +16,7 @@ use crate::widgets::ErrorDialog;
 
 use crate::backend::register::get_well_known;
 
+use std::convert::TryInto;
 use std::sync::{Arc, Mutex};
 
 #[derive(Debug, Clone)]
@@ -109,6 +110,10 @@ impl LoginWidget {
                             .as_ref()
                             .map(|ids| Url::parse(&ids.base_url))
                             .transpose()?
+                            .as_ref()
+                            .and_then(Url::host_str)
+                            .map(TryInto::try_into)
+                            .transpose()?
                             .unwrap_or(globals::DEFAULT_IDENTITYSERVER.clone());
                         info!("Got well-known response from {}: {:#?}", &txt, response);
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]