[fractal] AppOp: Change server_url field type to Url



commit cfa70a3396d5739e21f2d6e164bf14f665292f7e
Author: Alejandro Domínguez <adomu net-c com>
Date:   Fri Sep 20 06:53:42 2019 +0200

    AppOp: Change server_url field type to Url

 fractal-gtk/src/appop/account.rs    |  2 +-
 fractal-gtk/src/appop/login.rs      | 55 +++++++++++++++++++------------------
 fractal-gtk/src/appop/mod.rs        | 10 ++++---
 fractal-gtk/src/appop/room.rs       |  2 +-
 fractal-gtk/src/globals.rs          |  9 +++++-
 fractal-gtk/src/passwd.rs           | 16 +++++++++--
 fractal-gtk/src/widgets/login.rs    | 20 ++++++++++++--
 fractal-gtk/src/widgets/roomlist.rs | 17 +++---------
 8 files changed, 78 insertions(+), 53 deletions(-)
---
diff --git a/fractal-gtk/src/appop/account.rs b/fractal-gtk/src/appop/account.rs
index 5a4533a2..77a56496 100644
--- a/fractal-gtk/src/appop/account.rs
+++ b/fractal-gtk/src/appop/account.rs
@@ -273,7 +273,7 @@ impl AppOp {
         self.get_three_pid();
         uid.set_text(&self.uid.clone().unwrap_or_default());
         device_id.set_text(&self.device_id.clone().unwrap_or_default());
-        homeserver.set_text(&self.server_url);
+        homeserver.set_text(self.server_url.as_str());
         name.set_text(&self.username.clone().unwrap_or_default());
         name.grab_focus_without_selecting();
         name.set_position(-1);
diff --git a/fractal-gtk/src/appop/login.rs b/fractal-gtk/src/appop/login.rs
index a3a1cea1..a6482c38 100644
--- a/fractal-gtk/src/appop/login.rs
+++ b/fractal-gtk/src/appop/login.rs
@@ -5,6 +5,8 @@ use crate::globals;
 use gtk;
 use gtk::prelude::*;
 
+use url::Url;
+
 use crate::appop::AppOp;
 
 use crate::backend::BKCommand;
@@ -118,10 +120,18 @@ impl AppOp {
             return;
         }
 
-        self.server_url = match server_entry.get_text() {
-            Some(s) => s.to_string(),
-            None => String::from(globals::DEFAULT_HOMESERVER),
-        };
+        if let Some(s) = server_entry.get_text() {
+            match Url::parse(&s) {
+                Ok(u) => {
+                    self.server_url = u;
+                }
+                Err(_) => {
+                    let msg = i18n("Malformed server URL");
+                    ErrorDialog::new(false, &msg);
+                    return;
+                }
+            }
+        }
         /* FIXME ask also for the identity server */
 
         //self.store_pass(username.clone(), password.clone(), server_url.clone())
@@ -132,9 +142,9 @@ impl AppOp {
 
         let uname = username.clone();
         let pass = password.clone();
-        let ser = self.server_url.clone();
+        let ser = self.server_url.to_string();
         self.backend
-            .send(BKCommand::Register(uname, pass, ser))
+            .send(BKCommand::Register(uname, pass, ser))  // TODO: Change command type to url
             .unwrap();
     }
 
@@ -142,13 +152,10 @@ impl AppOp {
         &mut self,
         username: Option<String>,
         password: Option<String>,
-        server: Option<String>,
+        server: Url,
         identity: Option<String>,
     ) -> Option<()> {
-        self.server_url = match server {
-            Some(s) => s,
-            None => String::from(globals::DEFAULT_HOMESERVER),
-        };
+        self.server_url = server;
 
         self.identity_url = match identity {
             Some(u) => u,
@@ -158,7 +165,7 @@ impl AppOp {
         self.store_pass(
             username.clone()?,
             password.clone()?,
-            self.server_url.clone(),
+            self.server_url.to_string(),
             self.identity_url.clone(),
         )
         .unwrap_or_else(|_| {
@@ -168,9 +175,9 @@ impl AppOp {
 
         let uname = username?;
         let pass = password?;
-        let ser = self.server_url.clone();
+        let ser = self.server_url.to_string();
         self.backend
-            .send(BKCommand::Login(uname, pass, ser))
+            .send(BKCommand::Login(uname, pass, ser))  // TODO: Change command type to url
             .unwrap();
         Some(())
     }
@@ -179,29 +186,23 @@ impl AppOp {
         &mut self,
         token: Option<String>,
         uid: Option<String>,
-        server: Option<String>,
+        server: Url,
     ) -> Option<()> {
-        self.server_url = match server {
-            Some(s) => s,
-            None => String::from(globals::DEFAULT_HOMESERVER),
-        };
+        self.server_url = server;
 
-        let ser = self.server_url.clone();
+        let ser = self.server_url.to_string();
         self.backend
-            .send(BKCommand::SetToken(token?, uid?, ser))
+            .send(BKCommand::SetToken(token?, uid?, ser))  // TODO: Change command type to url
             .unwrap();
         Some(())
     }
 
     #[allow(dead_code)]
-    pub fn connect_guest(&mut self, server: Option<String>) {
-        self.server_url = match server {
-            Some(s) => s,
-            None => String::from(globals::DEFAULT_HOMESERVER),
-        };
+    pub fn connect_guest(&mut self, server: Url) {
+        self.server_url = server;
 
         self.backend
-            .send(BKCommand::Guest(self.server_url.clone()))
+            .send(BKCommand::Guest(self.server_url.to_string()))  // TODO: Change command type to url
             .unwrap();
     }
 
diff --git a/fractal-gtk/src/appop/mod.rs b/fractal-gtk/src/appop/mod.rs
index 7553db6b..fed05602 100644
--- a/fractal-gtk/src/appop/mod.rs
+++ b/fractal-gtk/src/appop/mod.rs
@@ -4,6 +4,8 @@ use std::sync::mpsc::Sender;
 use gtk;
 use gtk::prelude::*;
 
+use url::Url;
+
 use crate::backend;
 use crate::backend::BKCommand;
 use crate::globals;
@@ -52,7 +54,7 @@ pub struct AppOp {
     pub uid: Option<String>,
     pub device_id: Option<String>,
     pub avatar: Option<String>,
-    pub server_url: String,
+    pub server_url: Url,
     pub identity_url: String,
 
     pub active_room: Option<String>,
@@ -96,7 +98,7 @@ impl AppOp {
             uid: None,
             device_id: None,
             avatar: None,
-            server_url: String::from(globals::DEFAULT_HOMESERVER),
+            server_url: globals::DEFAULT_HOMESERVER.clone(),
             identity_url: String::from(globals::DEFAULT_IDENTITYSERVER),
             syncing: false,
             msg_queue: vec![],
@@ -133,9 +135,9 @@ impl AppOp {
 
         if let Ok(pass) = self.get_pass() {
             if let Ok((token, uid)) = self.get_token() {
-                self.set_token(Some(token), Some(uid), Some(pass.2));
+                self.set_token(Some(token), Some(uid), pass.2);
             } else {
-                self.connect(Some(pass.0), Some(pass.1), Some(pass.2), Some(pass.3));
+                self.connect(Some(pass.0), Some(pass.1), pass.2, Some(pass.3));
             }
         } else {
             self.set_state(AppState::Login);
diff --git a/fractal-gtk/src/appop/room.rs b/fractal-gtk/src/appop/room.rs
index 46fe86a1..e1a3410a 100644
--- a/fractal-gtk/src/appop/room.rs
+++ b/fractal-gtk/src/appop/room.rs
@@ -110,7 +110,7 @@ impl AppOp {
                 });
             });
 
-            self.roomlist = widgets::RoomList::new(adj, Some(self.server_url.clone()));
+            self.roomlist = widgets::RoomList::new(adj, Some(self.server_url.to_string()));
             self.roomlist.add_rooms(roomlist);
             container.add(self.roomlist.widget());
 
diff --git a/fractal-gtk/src/globals.rs b/fractal-gtk/src/globals.rs
index 40cd2318..2165c63a 100644
--- a/fractal-gtk/src/globals.rs
+++ b/fractal-gtk/src/globals.rs
@@ -1,12 +1,19 @@
+use lazy_static::lazy_static;
+use url::Url;
+
 pub static CACHE_SIZE: usize = 40;
 pub static MSG_ICON_SIZE: i32 = 40;
 pub static USERLIST_ICON_SIZE: i32 = 30;
 pub static PILL_ICON_SIZE: i32 = 18;
 pub static MINUTES_TO_SPLIT_MSGS: i64 = 30;
-pub static DEFAULT_HOMESERVER: &'static str = "https://matrix.org";;
 pub static DEFAULT_IDENTITYSERVER: &'static str = "https://vector.im";;
 pub static PLACEHOLDER_TEXT: &'static str = "Matrix username, email or phone number";
 pub static RIOT_REGISTER_URL: &'static str = "https://riot.im/app/#/register";;
 
 pub static MAX_IMAGE_SIZE: (i32, i32) = (600, 400);
 pub static 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");
+}
diff --git a/fractal-gtk/src/passwd.rs b/fractal-gtk/src/passwd.rs
index ab4b856b..095b5f5a 100644
--- a/fractal-gtk/src/passwd.rs
+++ b/fractal-gtk/src/passwd.rs
@@ -1,9 +1,18 @@
 use fractal_api::derror;
 use secret_service;
+use url::ParseError;
+use url::Url;
 
 #[derive(Debug)]
 pub enum Error {
     SecretServiceError,
+    UrlParseError(ParseError),
+}
+
+impl From<ParseError> for Error {
+    fn from(err: ParseError) -> Error {
+        Error::UrlParseError(err)
+    }
 }
 
 derror!(secret_service::SsError, Error::SecretServiceError);
@@ -23,7 +32,7 @@ pub trait PasswordStorage {
         ss_storage::store_pass(username, password, server, identity)
     }
 
-    fn get_pass(&self) -> Result<(String, String, String, String), Error> {
+    fn get_pass(&self) -> Result<(String, String, Url, String), Error> {
         ss_storage::get_pass()
     }
 
@@ -38,6 +47,7 @@ pub trait PasswordStorage {
 
 mod ss_storage {
     use super::Error;
+    use url::Url;
 
     use super::secret_service::EncryptionType;
     use super::secret_service::SecretService;
@@ -184,7 +194,7 @@ mod ss_storage {
         Ok(())
     }
 
-    pub fn get_pass() -> Result<(String, String, String, String), Error> {
+    pub fn get_pass() -> Result<(String, String, Url, String), Error> {
         migrate_old_passwd()?;
 
         let ss = SecretService::new(EncryptionType::Dh)?;
@@ -214,7 +224,7 @@ mod ss_storage {
             .iter()
             .find(|&ref x| x.0 == "server")
             .ok_or(Error::SecretServiceError)?;
-        let server = attr.1.clone();
+        let server = Url::parse(&attr.1)?;
 
         let attr = attrs.iter().find(|&ref x| x.0 == "identity");
 
diff --git a/fractal-gtk/src/widgets/login.rs b/fractal-gtk/src/widgets/login.rs
index 7289a7c1..5aafb6dd 100644
--- a/fractal-gtk/src/widgets/login.rs
+++ b/fractal-gtk/src/widgets/login.rs
@@ -1,11 +1,14 @@
 use gio::prelude::*;
 use gtk::prelude::*;
 use log::info;
+use url::Url;
 
 use crate::actions;
 use crate::actions::global::AppState;
 use crate::actions::login::LoginState;
 use crate::appop::AppOp;
+use crate::i18n::i18n;
+use crate::widgets::ErrorDialog;
 
 use fractal_api::backend::register::get_well_known;
 
@@ -90,12 +93,23 @@ impl LoginWidget {
                 if !password.is_empty() && !username.is_empty() {
                     // take the user's homeserver value if the
                     // well-known request fails
-                    let mut homeserver_url = txt.clone();
+                    let hs_url = Url::parse(&txt);
+
+                    if hs_url.is_err() {
+                        let msg = i18n("Malformed server URL");
+                        ErrorDialog::new(false, &msg);
+                        return;
+                    };
+
+                    let mut homeserver_url =
+                        hs_url.expect("hs_url must return earlier if it's Err");
                     let mut idserver = None;
                     match get_well_known(&txt) {
+                        // TODO: Use Url everywhere
                         Ok(response) => {
                             info!("Got well-known response from {}: {:#?}", &txt, response);
-                            homeserver_url = response.homeserver.base_url;
+                            homeserver_url =
+                                Url::parse(&response.homeserver.base_url).unwrap_or(homeserver_url);
                             idserver = response.identity_server.map(|ids| ids.base_url);
                         }
                         Err(e) => info!("Failed to .well-known request: {:#?}", e),
@@ -107,7 +121,7 @@ impl LoginWidget {
                     op.lock().unwrap().connect(
                         Some(username),
                         Some(password),
-                        Some(homeserver_url),
+                        homeserver_url,
                         idserver,
                     );
                 } else {
diff --git a/fractal-gtk/src/widgets/roomlist.rs b/fractal-gtk/src/widgets/roomlist.rs
index a1ad0043..6d4080ee 100644
--- a/fractal-gtk/src/widgets/roomlist.rs
+++ b/fractal-gtk/src/widgets/roomlist.rs
@@ -17,18 +17,6 @@ use std::sync::{Arc, Mutex, MutexGuard};
 
 use chrono::prelude::*;
 
-fn get_url(url: Option<String>) -> Url {
-    let defurl = Url::parse(globals::DEFAULT_HOMESERVER).unwrap();
-
-    match url {
-        Some(u) => match Url::parse(&u) {
-            Ok(url) => url,
-            Err(_) => defurl,
-        },
-        None => defurl,
-    }
-}
-
 pub struct RoomUpdated {
     pub room: Room,
     pub updated: DateTime<Local>,
@@ -478,9 +466,12 @@ macro_rules! run_in_group {
 }
 
 impl RoomList {
+    // TODO: Change url to Url
     pub fn new(adj: Option<gtk::Adjustment>, url: Option<String>) -> RoomList {
         let widget = gtk::Box::new(gtk::Orientation::Vertical, 6);
-        let baseu = get_url(url);
+        let baseu = url
+            .and_then(|u| Url::parse(&u).ok())
+            .unwrap_or(globals::DEFAULT_HOMESERVER.clone());
 
         let inv = RGroup::new(
             &baseu,


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