Commit 9101aa43 authored by Alejandro Domínguez's avatar Alejandro Domínguez

Use Url where possible

parent 1b183d34
Pipeline #129606 passed with stages
in 31 minutes and 5 seconds
......@@ -40,7 +40,7 @@ impl AppOp {
let _ = self.backend.send(BKCommand::AddThreePID(
self.server_url.clone(),
access_token,
self.identity_url.to_string(), // TODO: Change type to Url
self.identity_url.clone(),
secret.clone(),
sid.clone(),
));
......@@ -133,7 +133,7 @@ impl AppOp {
&msg,
);
let backend = self.backend.clone();
let id_server = self.identity_url.to_string();
let id_server = self.identity_url.clone();
let server_url = self.server_url.clone();
dialog.add_button(&i18n("Cancel"), gtk::ResponseType::Cancel.into());
dialog.add_button(&i18n("Continue"), gtk::ResponseType::Ok.into());
......@@ -143,7 +143,7 @@ impl AppOp {
let _ = backend.send(BKCommand::AddThreePID(
server_url.clone(),
access_token.clone(),
id_server.clone(), // TODO: Change type to Url
id_server.clone(),
secret.clone(),
sid.clone(),
));
......
......@@ -145,9 +145,9 @@ impl AppOp {
let uname = username.clone();
let pass = password.clone();
let ser = self.server_url.to_string();
let ser = self.server_url.clone();
self.backend
.send(BKCommand::Register(uname, pass, ser)) // TODO: Change command type to url
.send(BKCommand::Register(uname, pass, ser))
.unwrap();
}
......@@ -164,8 +164,8 @@ impl AppOp {
self.store_pass(
username.clone()?,
password.clone()?,
self.server_url.to_string(),
self.identity_url.to_string(),
self.server_url.clone(),
self.identity_url.clone(),
)
.unwrap_or_else(|_| {
// TODO: show an error
......@@ -174,9 +174,9 @@ impl AppOp {
let uname = username?;
let pass = password?;
let ser = self.server_url.to_string();
let ser = self.server_url.clone();
self.backend
.send(BKCommand::Login(uname, pass, ser)) // TODO: Change command type to url
.send(BKCommand::Login(uname, pass, ser))
.unwrap();
Some(())
}
......@@ -198,7 +198,7 @@ impl AppOp {
self.server_url = server;
self.backend
.send(BKCommand::Guest(self.server_url.to_string())) // TODO: Change command type to url
.send(BKCommand::Guest(self.server_url.clone()))
.unwrap();
}
......
......@@ -121,7 +121,7 @@ impl AppOp {
});
});
self.roomlist = widgets::RoomList::new(adj, Some(self.server_url.to_string()));
self.roomlist = widgets::RoomList::new(adj, Some(self.server_url.clone()));
self.roomlist.add_rooms(roomlist);
container.add(self.roomlist.widget());
......
......@@ -27,8 +27,8 @@ pub trait PasswordStorage {
&self,
username: String,
password: String,
server: String,
identity: String,
server: Url,
identity: Url,
) -> Result<(), Error> {
ss_storage::store_pass(username, password, server, identity)
}
......@@ -133,8 +133,8 @@ mod ss_storage {
pub fn store_pass(
username: String,
password: String,
server: String,
identity: String,
server: Url,
identity: Url,
) -> Result<(), Error> {
let ss = SecretService::new(EncryptionType::Dh)?;
let collection = ss.get_default_collection()?;
......@@ -149,8 +149,8 @@ mod ss_storage {
key, // label
vec![
("username", &username),
("server", &server),
("identity", &identity),
("server", server.as_str()),
("identity", identity.as_str()),
], // properties
password.as_bytes(), //secret
true, // replace item with same attributes
......@@ -188,7 +188,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 pwd = String::from_utf8(secret).unwrap();
// removing old
......@@ -196,7 +196,7 @@ mod ss_storage {
p.delete()?;
}
/* Fallback to default identity server if there is none */
let identity = globals::DEFAULT_IDENTITYSERVER.to_string();
let identity = globals::DEFAULT_IDENTITYSERVER.clone();
store_pass(username, pwd, server, identity)?;
......
......@@ -163,7 +163,7 @@ impl<'a> Address<'a> {
let entry = self.entry.clone();
let address = self.address.clone();
let server_url = self.op.server_url.clone();
let id_server = self.op.identity_url.to_string();
let id_server = self.op.identity_url.clone();
let backend = self.op.backend.clone();
self.signal_id = Some(self.button.clone().connect_clicked(move |w| {
if !w.get_sensitive() || !w.is_visible() {
......@@ -195,7 +195,7 @@ impl<'a> Address<'a> {
add_address(
&backend,
medium,
id_server.clone(), // TODO: Change type to Url
id_server.clone(),
entry.get_text().map_or(None, |gstr| Some(gstr.to_string())),
server_url.clone(),
access_token.clone(),
......@@ -228,7 +228,7 @@ fn delete_address(
fn add_address(
backend: &Sender<BKCommand>,
medium: Medium,
id_server: String,
id_server: Url,
address: Option<String>,
server_url: Url,
access_token: AccessToken,
......
......@@ -103,8 +103,7 @@ impl LoginWidget {
};
let mut idserver = globals::DEFAULT_IDENTITYSERVER.clone();
match get_well_known(&txt) {
// TODO: Use Url everywhere
match get_well_known(homeserver_url.clone()) {
Ok(response) => {
info!("Got well-known response from {}: {:#?}", &txt, response);
homeserver_url = response.homeserver.base_url;
......
......@@ -466,12 +466,9 @@ macro_rules! run_in_group {
}
impl RoomList {
// TODO: Change url to Url
pub fn new(adj: Option<gtk::Adjustment>, url: Option<String>) -> RoomList {
pub fn new(adj: Option<gtk::Adjustment>, url: Option<Url>) -> RoomList {
let widget = gtk::Box::new(gtk::Orientation::Vertical, 6);
let baseu = url
.and_then(|u| Url::parse(&u).ok())
.unwrap_or(globals::DEFAULT_HOMESERVER.clone());
let baseu = url.unwrap_or(globals::DEFAULT_HOMESERVER.clone());
let inv = RGroup::new(
&baseu,
......
......@@ -50,7 +50,7 @@ pub fn room_search(
bk: &Backend,
base: Url,
access_token: AccessToken,
homeserver: Option<String>, // TODO: Use Url or HostAndPort?
homeserver: Option<String>, // TODO: Use HostAndPort?
generic_search_term: Option<String>,
third_party: Option<String>,
more: bool,
......
......@@ -2,6 +2,7 @@ use crate::backend::types::Backend;
use crate::error::Error;
use crate::globals;
use serde_json::json;
use std::str::Split;
use std::sync::mpsc::Sender;
use std::thread;
use url::Url;
......@@ -68,12 +69,15 @@ pub fn get_media_url(bk: &Backend, baseu: Url, media: String, tx: Sender<String>
});
}
pub fn get_file_async(url: String, tx: Sender<String>) -> Result<(), Error> {
let name = url.split('/').last().unwrap_or_default();
pub fn get_file_async(url: Url, tx: Sender<String>) -> Result<(), Error> {
let name = url
.path_segments()
.and_then(Split::last)
.unwrap_or_default();
let fname = cache_dir_path(Some("files"), name)?;
thread::spawn(move || {
let fname = download_file(&url, fname, None).unwrap_or_default();
let fname = download_file(url, fname, None).unwrap_or_default();
tx.send(fname).expect_log("Connection closed");
});
......@@ -115,7 +119,7 @@ fn get_room_media_list(
let path = format!("rooms/{}/messages", roomid);
let url = client_url(baseu, &path, &params)?;
let r = json_q("get", &url, &json!(null))?;
let r = json_q("get", url, &json!(null))?;
let array = r["chunk"].as_array();
let prev_batch = r["end"].to_string().trim_matches('"').to_string();
if array.is_none() || array.unwrap().is_empty() {
......
......@@ -88,20 +88,15 @@ impl Backend {
match cmd {
// Register module
Ok(BKCommand::Login(user, passwd, server)) => {
let r = register::login(self, user, passwd, &server);
bkerror!(r, tx, BKResponse::LoginError);
register::login(self, user, passwd, server)
}
Ok(BKCommand::Logout(server, access_token)) => {
register::logout(self, server, access_token)
}
Ok(BKCommand::Register(user, passwd, server)) => {
let r = register::register(self, user, passwd, &server);
bkerror!(r, tx, BKResponse::LoginError);
}
Ok(BKCommand::Guest(server)) => {
let r = register::guest(self, &server);
bkerror!(r, tx, BKResponse::GuestLoginError);
register::register(self, user, passwd, server)
}
Ok(BKCommand::Guest(server)) => register::guest(self, server),
Ok(BKCommand::SetToken(token, uid)) => register::set_token(self, token, uid),
// User module
......
......@@ -27,12 +27,10 @@ use crate::util::HTTP_CLIENT;
use crate::backend::types::BKResponse;
use crate::backend::types::Backend;
pub fn guest(bk: &Backend, server: &str) -> Result<(), Error> {
pub fn guest(bk: &Backend, base: Url) {
let tx = bk.tx.clone();
let data = bk.data.clone();
let base = Url::parse(server)?;
let params = RegisterParameters {
kind: RegistrationKind::Guest,
};
......@@ -68,16 +66,12 @@ pub fn guest(bk: &Backend, server: &str) -> Result<(), Error> {
}
}
});
Ok(())
}
pub fn login(bk: &Backend, user: String, password: String, server: &str) -> Result<(), Error> {
pub fn login(bk: &Backend, user: String, password: String, base: Url) {
let tx = bk.tx.clone();
let data = bk.data.clone();
let base = Url::parse(server)?;
let body = if globals::EMAIL_RE.is_match(&user) {
LoginBody {
auth: Auth::Password { password },
......@@ -134,8 +128,6 @@ pub fn login(bk: &Backend, user: String, password: String, server: &str) -> Resu
}
}
});
Ok(())
}
pub fn set_token(bk: &Backend, token: AccessToken, uid: String) {
......@@ -173,11 +165,10 @@ pub fn logout(bk: &Backend, server: Url, access_token: AccessToken) {
});
}
pub fn register(bk: &Backend, user: String, password: String, server: &str) -> Result<(), Error> {
pub fn register(bk: &Backend, user: String, password: String, base: Url) {
let data = bk.data.clone();
let tx = bk.tx.clone();
let base = Url::parse(server)?;
let params = Default::default();
let body = RegisterBody {
username: Some(user),
......@@ -213,18 +204,14 @@ pub fn register(bk: &Backend, user: String, password: String, server: &str) -> R
}
}
});
Ok(())
}
pub fn get_well_known(domain: &str) -> Result<DomainInfoResponse, Error> {
domain_info(Url::parse(domain)?)
.map_err(Into::into)
.and_then(|request| {
HTTP_CLIENT
.get_client()?
.execute(request)?
.json::<DomainInfoResponse>()
.map_err(Into::into)
})
pub fn get_well_known(domain: Url) -> Result<DomainInfoResponse, Error> {
domain_info(domain).map_err(Into::into).and_then(|request| {
HTTP_CLIENT
.get_client()?
.execute(request)?
.json::<DomainInfoResponse>()
.map_err(Into::into)
})
}
......@@ -70,7 +70,7 @@ pub fn get_room_detail(
let tx = bk.tx.clone();
let keys = key.clone();
get!(
&url,
url,
|r: JsonValue| {
let k = keys.split('.').last().unwrap();
......@@ -101,7 +101,7 @@ pub fn get_room_avatar(
)?;
let tx = bk.tx.clone();
get!(
&url,
url,
|r: JsonValue| {
let avatar = r["url"].as_str().and_then(|s| Url::parse(s).ok());
let dest = cache_dir_path(None, &roomid).ok();
......@@ -148,7 +148,7 @@ pub fn get_room_members(
let tx = bk.tx.clone();
get!(
&url,
url,
|r: JsonValue| {
let joined = r["joined"].as_object().unwrap();
let ms: Vec<Member> = joined
......@@ -202,7 +202,7 @@ pub fn get_room_messages(
)?;
let tx = bk.tx.clone();
get!(
&url,
url,
|r: JsonValue| {
let array = r["chunk"].as_array();
let evs = array.unwrap().iter().rev();
......@@ -259,7 +259,7 @@ fn parse_context(
)?;
get!(
&url,
url,
|r: JsonValue| {
let mut id: Option<String> = None;
......@@ -354,7 +354,7 @@ pub fn send_msg(
let tx = bk.tx.clone();
query!(
"put",
&url,
url,
&attrs,
move |js: JsonValue| {
let evid = js["event_id"].as_str().unwrap_or_default();
......@@ -390,7 +390,7 @@ pub fn send_typing(
});
let tx = bk.tx.clone();
query!("put", &url, &attrs, move |_| {}, |err| {
query!("put", url, &attrs, move |_| {}, |err| {
tx.send(BKResponse::SendTypingError(err))
.expect_log("Connection closed");
});
......@@ -422,7 +422,7 @@ pub fn redact_msg(
let tx = bk.tx.clone();
query!(
"put",
&url,
url,
&attrs,
move |js: JsonValue| {
let evid = js["event_id"].as_str().unwrap_or_default();
......@@ -456,7 +456,7 @@ pub fn join_room(
let tx = bk.tx.clone();
let data = bk.data.clone();
post!(
&url,
url,
move |_: JsonValue| {
data.lock().unwrap().join_to_room = roomid.clone();
tx.send(BKResponse::JoinRoom(Ok(())))
......@@ -486,7 +486,7 @@ pub fn leave_room(
let tx = bk.tx.clone();
post!(
&url,
url,
move |_: JsonValue| {
tx.send(BKResponse::LeaveRoom(Ok(())))
.expect_log("Connection closed");
......@@ -518,7 +518,7 @@ pub fn mark_as_read(
let e = eventid.clone();
let tx = bk.tx.clone();
post!(
&url,
url,
move |_: JsonValue| {
tx.send(BKResponse::MarkedAsRead(Ok((r, e))))
.expect_log("Connection closed");
......@@ -543,7 +543,7 @@ pub fn mark_as_read(
"m.fully_read": eventid,
"m.read": json!(null),
});
post!(&url, &attrs, |_| {}, |_| {});
post!(url, &attrs, |_| {}, |_| {});
Ok(())
}
......@@ -569,7 +569,7 @@ pub fn set_room_name(
let tx = bk.tx.clone();
query!(
"put",
&url,
url,
&attrs,
|_| {
tx.send(BKResponse::SetRoomName(Ok(())))
......@@ -605,7 +605,7 @@ pub fn set_room_topic(
let tx = bk.tx.clone();
query!(
"put",
&url,
url,
&attrs,
|_| {
tx.send(BKResponse::SetRoomTopic(Ok(())))
......@@ -651,7 +651,7 @@ pub fn set_room_avatar(
let uri = js["content_uri"].as_str().unwrap_or_default();
let attrs = json!({ "url": uri });
put!(
&roomurl,
roomurl,
&attrs,
|_| {
tx.send(BKResponse::SetRoomAvatar(Ok(())))
......@@ -771,7 +771,7 @@ pub fn new_room(
let tx = bk.tx.clone();
post!(
&url,
url,
&attrs,
move |r: JsonValue| {
let id = String::from(r["room_id"].as_str().unwrap_or_default());
......@@ -790,7 +790,7 @@ pub fn new_room(
pub fn update_direct_chats(url: Url, data: Arc<Mutex<BackendData>>, user: String, room: String) {
get!(
&url,
url.clone(),
|r: JsonValue| {
let mut directs: HashMap<String, Vec<String>> = HashMap::new();
let direct_obj = r.as_object().unwrap();
......@@ -815,7 +815,7 @@ pub fn update_direct_chats(url: Url, data: Arc<Mutex<BackendData>>, user: String
data.lock().unwrap().m_direct = directs.clone();
let attrs = json!(directs.clone());
put!(&url, &attrs, |_| {}, |err| error!("{:?}", err));
put!(url, &attrs, |_| {}, |err| error!("{:?}", err));
},
|err| {
error!("Can't set m.direct: {:?}", err);
......@@ -856,7 +856,7 @@ pub fn direct_chat(
let tx = bk.tx.clone();
let data = bk.data.clone();
post!(
&url,
url,
&attrs,
move |r: JsonValue| {
let id = String::from(r["room_id"].as_str().unwrap_or_default());
......@@ -900,7 +900,7 @@ pub fn add_to_fav(
let method = if tofav { "put" } else { "delete" };
query!(
method,
&url,
url,
&attrs,
|_| {
tx.send(BKResponse::AddedToFav(Ok((roomid.clone(), tofav))))
......@@ -934,7 +934,7 @@ pub fn invite(
});
let tx = bk.tx.clone();
post!(&url, &attrs, |_| {}, |err| {
post!(url, &attrs, |_| {}, |err| {
tx.send(BKResponse::InviteError(err))
.expect_log("Connection closed");
});
......
......@@ -41,7 +41,7 @@ pub fn list(bk: &Backend, access_token: AccessToken) -> Result<(), Error> {
let tx = bk.tx.clone();
get!(
&url,
url,
|r: JsonValue| {
let mut stickers = vec![];
for sticker_group in r["assets"].as_array().unwrap_or(&vec![]).iter() {
......@@ -74,7 +74,7 @@ pub fn get_sticker_widget_id(
let url = vurl(&d, &access_token, "widgets/request", vec![]).unwrap();
post!(
&url,
url,
&data,
|r: JsonValue| {
let mut id = String::new();
......@@ -145,7 +145,7 @@ pub fn send(
let tx = bk.tx.clone();
query!(
"put",
&url,
url,
&attrs,
move |js: JsonValue| {
let evid = js["event_id"].as_str().unwrap_or_default();
......@@ -183,7 +183,7 @@ pub fn purchase(bk: &Backend, access_token: AccessToken, group: StickerGroup) ->
let tx = bk.tx.clone();
let itx = bk.internal_tx.clone();
get!(
&url,
url,
|_| if let Some(t) = itx {
t.send(BKCommand::ListStickers(access_token))
.expect_log("Connection closed");
......@@ -207,12 +207,12 @@ fn get_scalar_token(
let params = &[("access_token", access_token.to_string())];
let path = &format!("user/{}/openid/request_token", uid);
let url = client_url(&base, path, params)?;
let js = json_q("post", &url, &json!({}))?;
let js = json_q("post", url, &json!({}))?;
let vurl = base
.join("/api/register")
.expect("Wrong URL in get_scalar_token()");
let js = json_q("post", &vurl, &js)?;
let js = json_q("post", vurl, &js)?;
match js["scalar_token"].as_str() {
Some(st) => {
......
......@@ -20,20 +20,20 @@ use url::Url;
#[derive(Debug)]
pub enum BKCommand {
Login(String, String, String),
Login(String, String, Url),
SetToken(AccessToken, String),
Logout(Url, AccessToken),
#[allow(dead_code)]
Register(String, String, String),
Register(String, String, Url),
#[allow(dead_code)]
Guest(String),
Guest(Url),
GetUsername(Url),
SetUserName(Url, AccessToken, String),
GetThreePID(Url, AccessToken),
GetTokenEmail(Url, AccessToken, String, String, String),
GetTokenPhone(Url, AccessToken, String, String, String),
GetTokenEmail(Url, AccessToken, Url, String, String),
GetTokenPhone(Url, AccessToken, Url, String, String),
SubmitPhoneToken(Url, String, String, String),
AddThreePID(Url, AccessToken, String, String, String),
AddThreePID(Url, AccessToken, Url, String, String),
DeleteThreePID(Url, AccessToken, Medium, String),
ChangePassword(Url, AccessToken, String, String, String),
AccountDestruction(Url, AccessToken, String, String),
......@@ -56,7 +56,7 @@ pub enum BKCommand {
Option<String>,
Sender<(Vec<Message>, String)>,
),
GetFileAsync(String, Sender<String>),
GetFileAsync(Url, Sender<String>),
GetAvatarAsync(Url, Option<Member>, Sender<String>),
GetMedia(Url, String),
GetMediaUrl(Url, String, Sender<String>),
......
......@@ -152,13 +152,13 @@ pub fn get_threepid(
pub fn get_email_token(
base: Url,
access_token: AccessToken,
identity: String,
identity: Url,
email: String,
client_secret: String,
) -> Result<(String, String), Error> {
let params = EmailTokenParameters { access_token };
let body = EmailTokenBody {
id_server: Url::parse(&identity)?.try_into()?,
id_server: identity.try_into()?,
client_secret: client_secret.clone(),
email,
send_attempt: 1,
......@@ -190,13 +190,13 @@ pub fn get_email_token(
pub fn get_phone_token(
base: Url,
access_token: AccessToken,
identity: String,
identity: Url,
phone: String,
client_secret: String,
) -> Result<(String, String), Error> {
let params = PhoneTokenParameters { access_token };
let body = PhoneTokenBody {
id_server: Url::parse(&identity)?.try_into()?,
id_server: identity.try_into()?,
client_secret: client_secret.clone(),
phone_number: phone,
country: String::new(),
......@@ -229,14 +229,14 @@ pub fn get_phone_token(
pub fn add_threepid(
base: Url,
access_token: AccessToken,
identity: String,
identity: Url,
client_secret: String,
sid: String,
) -> Result<(), Error> {
let params = AddThreePIDParameters { access_token };
let body = AddThreePIDBody {
three_pid_creds: ThreePIDCredentials {
id_server: Url::parse(&identity)?.try_into()?,
id_server: identity.try_into()?,
sid: sid.clone(),
client_secret,
},
......
......@@ -201,7 +201,7 @@ pub fn get_prev_batch_from(
let path = format!("rooms/{}/context/{}", roomid, evid);
let url = client_url(baseu, &path, params)?;
let r = json_q("get", &url, &json!(null))?;
let r = json_q("get", url, &json!(null))?;
let prev_batch = r["start"].to_string().trim_matches('"').to_string();
Ok(prev_batch)
......@@ -263,10 +263,10 @@ pub fn dw_media(
Some(d) => String::from(d),
};
download_file(url.as_str(), fname, dest)
download_file(url, fname, dest)
}
pub fn download_file(url: &str, fname: String, dest: Option<&str>) -> Result<String, Error> {
pub fn download_file(url: Url, fname: String, dest: Option<&str>) -> Result<String, Error> {
let fpath = Path::new(&fname);
// If the file is already cached and recent enough, don't download it
......@@ -287,12 +287,12 @@ pub fn download_file(url: &str, fname: String, dest: Option<&str>) -> Result<Str
}
}
pub fn json_q(method: &str, url: &Url, attrs: &JsonValue) -> Result<JsonValue, Error> {
pub fn json_q(method: &str, url: Url, attrs: &JsonValue) -> Result<JsonValue, Error> {
let mut conn = match method {
"post" => HTTP_CLIENT.get_client()?.post(url.as_str()),
"put" => HTTP_CLIENT.get_client()?.put(url.as_str()),
"delete" => HTTP_CLIENT.get_client()?.delete(url.as_str()),
_ => HTTP_CLIENT.get_client()?.get(url.as_str()),
"post" => HTTP_CLIENT.get_client()?.post(url),
"put" => HTTP_CLIENT.get_client()?.put(url),
"delete" => HTTP_CLIENT.get_client()?.delete(url),
_ => HTTP_CLIENT.get_client()?.get(url),
};
if !attrs.is_null() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment