Skip to content

Commit

Permalink
Run cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
exul committed Jun 24, 2017
1 parent 4bedb75 commit e829ab4
Show file tree
Hide file tree
Showing 29 changed files with 1,309 additions and 960 deletions.
8 changes: 5 additions & 3 deletions src/bin/matrix-rocketchat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ fn build_logger(log_file_path: &str) -> slog::Logger {
let file = OpenOptions::new().create(true).write(true).truncate(true).open(path).expect("Log file creation failed");
let file_drain = slog_stream::stream(file, slog_json::new().add_default_keys().build());
let term_drain = slog_term::streamer().stderr().full().build();
slog::Logger::root(slog::duplicate(term_drain, file_drain).fuse(),
o!("version" => env!("CARGO_PKG_VERSION"),
"place" => file_line_logger_format))
slog::Logger::root(
slog::duplicate(term_drain, file_drain).fuse(),
o!("version" => env!("CARGO_PKG_VERSION"),
"place" => file_line_logger_format),
)
}

fn file_line_logger_format(info: &Record) -> String {
Expand Down
25 changes: 14 additions & 11 deletions src/matrix-rocketchat/api/matrix/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ pub trait MatrixApiClone {
}

impl<T> MatrixApiClone for T
where T: 'static + MatrixApi + Clone
where
T: 'static + MatrixApi + Clone,
{
fn clone_box(&self) -> Box<MatrixApi> {
Box::new(self.clone())
Expand All @@ -75,21 +76,23 @@ impl MatrixApi {
debug!(logger, format!("Querying homeserver {} for API versions", url));
let (body, status_code) = RestApi::call_matrix(GetSupportedVersionsEndpoint::method(), &url, "", &params)?;
if !status_code.is_success() {
let matrix_error_resp: MatrixErrorResponse = serde_json::from_str(&body)
.chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize error response from Matrix supported versions \
let matrix_error_resp: MatrixErrorResponse = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!(
"Could not deserialize error response from Matrix supported versions \
API endpoint: `{}` ",
body))
})?;
body
))
})?;
return Err(Error::from(ErrorKind::MatrixError(matrix_error_resp.error)));
}

let supported_versions: GetSupportedVersionsResponse = serde_json::from_str(&body)
.chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix supported versions API \
let supported_versions: GetSupportedVersionsResponse = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!(
"Could not deserialize response from Matrix supported versions API \
endpoint: `{}`",
body))
})?;
body
))
})?;
debug!(logger, format!("Homeserver supports versions {:?}", supported_versions.versions));
MatrixApi::get_max_supported_version_api(supported_versions.versions, config, logger)
}
Expand Down
85 changes: 47 additions & 38 deletions src/matrix-rocketchat/api/matrix/r0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,12 @@ impl MatrixApi {
}

impl super::MatrixApi for MatrixApi {
fn create_room(&self,
room_name: Option<String>,
room_alias_name: Option<String>,
room_creator_id: &UserId)
-> Result<RoomId> {
fn create_room(
&self,
room_name: Option<String>,
room_alias_name: Option<String>,
room_creator_id: &UserId,
) -> Result<RoomId> {
let endpoint = self.base_url.clone() + &CreateRoomEndpoint::request_path(());
let body_params = create_room::BodyParams {
creation_content: None,
Expand All @@ -71,8 +72,9 @@ impl super::MatrixApi for MatrixApi {
topic: None,
visibility: Some("private".to_string()),
};
let payload = serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize create_room body params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize create_room body params".to_string())
})?;
let user_id = room_creator_id.to_string();
let mut params = self.params_hash();
params.insert("user_id", &user_id);
Expand All @@ -82,12 +84,13 @@ impl super::MatrixApi for MatrixApi {
return Err(build_error(&endpoint, &body, &status_code));
}

let create_room_response: create_room::Response = serde_json::from_str(&body)
.chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix create_room API endpoint: \
let create_room_response: create_room::Response = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!(
"Could not deserialize response from Matrix create_room API endpoint: \
`{}`",
body))
})?;
body
))
})?;

Ok(create_room_response.room_id)
}
Expand Down Expand Up @@ -117,12 +120,13 @@ impl super::MatrixApi for MatrixApi {
return Err(build_error(&endpoint, &body, &status_code));
}

let room_create: Value = serde_json::from_str(&body)
.chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix get_state_events_for_empty_key \
let room_create: Value = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!(
"Could not deserialize response from Matrix get_state_events_for_empty_key \
API endpoint: `{}`",
body))
})?;
body
))
})?;

let room_creator = room_create["creator"].to_string().replace("\"", "");
let user_id = UserId::try_from(&room_creator).chain_err(|| ErrorKind::InvalidUserId(room_creator))?;
Expand All @@ -142,10 +146,9 @@ impl super::MatrixApi for MatrixApi {

debug!(self.logger, format!("List of room members for room {} successfully received", matrix_room_id));

let room_member_events: get_member_events::Response = serde_json::from_str(&body)
.chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix members API endpoint: `{}`", body))
})?;
let room_member_events: get_member_events::Response = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix members API endpoint: `{}`", body))
})?;
Ok(room_member_events.chunk)
}

Expand All @@ -154,8 +157,9 @@ impl super::MatrixApi for MatrixApi {
let endpoint = self.base_url.clone() + &InviteUserEndpoint::request_path(path_params);
let params = self.params_hash();
let body_params = invite_user::BodyParams { user_id: matrix_user_id.clone() };
let payload = serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize invite user params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize invite user params".to_string())
})?;

let (body, status_code) = RestApi::call_matrix(InviteUserEndpoint::method(), &endpoint, &payload, &params)?;
if !status_code.is_success() {
Expand Down Expand Up @@ -205,8 +209,9 @@ impl super::MatrixApi for MatrixApi {
initial_device_display_name: None,
auth: None,
};
let payload = serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize account body params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize account body params".to_string())
})?;

let (body, status_code) = RestApi::call_matrix(RegisterEndpoint::method(), &endpoint, &payload, &params)?;
if !status_code.is_success() {
Expand All @@ -223,8 +228,8 @@ impl super::MatrixApi for MatrixApi {
message.insert("msgtype".to_string(), json!(MessageType::Text));
message.insert("format".to_string(), json!("org.matrix.custom.html"));

let payload = serde_json::to_string(&message)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize message".to_string()))?;
let payload =
serde_json::to_string(&message).chain_err(|| ErrorKind::InvalidJSON("Could not serialize message".to_string()))?;
let txn_id = EventId::new(&self.base_url).chain_err(|| ErrorKind::EventIdGenerationFailed)?;
let path_params = send_message_event::PathParams {
room_id: matrix_room_id.clone(),
Expand Down Expand Up @@ -263,8 +268,9 @@ impl super::MatrixApi for MatrixApi {
body_params.insert("users".to_string(), json!(users));
body_params.insert("events".to_string(), json!(serde_json::Map::new()));

let payload = serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize power levels body params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize power levels body params".to_string())
})?;

let (body, status_code) =
RestApi::call_matrix(SendStateEventForEmptyKeyEndpoint::method(), &endpoint, &payload, &params)?;
Expand All @@ -282,9 +288,9 @@ impl super::MatrixApi for MatrixApi {
params.insert("user_id", &user_id);
let body_params = set_display_name::BodyParams { displayname: Some(name) };

let payload =
serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize set display name body params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize set display name body params".to_string())
})?;

let (body, status_code) = RestApi::call_matrix(SetDisplayNameEndpoint::method(), &endpoint, &payload, &params)?;
if !status_code.is_success() {
Expand All @@ -303,8 +309,9 @@ impl super::MatrixApi for MatrixApi {
let mut body_params = serde_json::Map::new();
body_params.insert("name".to_string(), Value::String(name));

let payload = serde_json::to_string(&body_params)
.chain_err(|| ErrorKind::InvalidJSON("Could not serialize room name body params".to_string()))?;
let payload = serde_json::to_string(&body_params).chain_err(|| {
ErrorKind::InvalidJSON("Could not serialize room name body params".to_string())
})?;

let (body, status_code) =
RestApi::call_matrix(SendStateEventForEmptyKeyEndpoint::method(), &endpoint, &payload, &params)?;
Expand All @@ -316,10 +323,12 @@ impl super::MatrixApi for MatrixApi {
}

fn build_error(endpoint: &str, body: &str, status_code: &StatusCode) -> Error {
let json_error_msg = format!("Could not deserialize error from Matrix API endpoint {} with status code {}: `{}`",
endpoint,
status_code,
body);
let json_error_msg = format!(
"Could not deserialize error from Matrix API endpoint {} with status code {}: `{}`",
endpoint,
status_code,
body
);
let json_error = ErrorKind::InvalidJSON(json_error_msg);
let matrix_error_resp: MatrixErrorResponse =
match serde_json::from_str(body).chain_err(|| json_error).map_err(Error::from) {
Expand Down
24 changes: 13 additions & 11 deletions src/matrix-rocketchat/api/rest_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ pub struct RestApi {}

impl RestApi {
/// Call a matrix REST API endpoint
pub fn call_matrix<'a>(method: RumaHttpMethod,
url: &str,
payload: &str,
params: &HashMap<&str, &'a str>)
-> Result<(String, StatusCode)> {
pub fn call_matrix<'a>(
method: RumaHttpMethod,
url: &str,
payload: &str,
params: &HashMap<&str, &'a str>,
) -> Result<(String, StatusCode)> {
let method = match method {
RumaHttpMethod::Delete => Method::Delete,
RumaHttpMethod::Get => Method::Get,
Expand All @@ -34,12 +35,13 @@ impl RestApi {
}

/// Call a REST API endpoint
pub fn call<'a>(method: Method,
url: &str,
payload: &str,
params: &HashMap<&str, &'a str>,
headers: Option<Headers>)
-> Result<(String, StatusCode)> {
pub fn call<'a>(
method: Method,
url: &str,
payload: &str,
params: &HashMap<&str, &'a str>,
headers: Option<Headers>,
) -> Result<(String, StatusCode)> {
let client = Client::new().chain_err(|| ErrorKind::ApiCallFailed(url.to_string()))?;
let encoded_url = RestApi::encode_url(url.to_string(), params)?;

Expand Down
23 changes: 14 additions & 9 deletions src/matrix-rocketchat/api/rocketchat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,18 @@ impl RocketchatApi {
Ok((body, status_code)) => (body, status_code),
Err(err) => {
debug!(logger, err);
bail_error!(ErrorKind::RocketchatServerUnreachable(url.clone()),
t!(["errors", "rocketchat_server_unreachable"]).with_vars(vec![("rocketchat_url", url)]));
bail_error!(
ErrorKind::RocketchatServerUnreachable(url.clone()),
t!(["errors", "rocketchat_server_unreachable"]).with_vars(vec![("rocketchat_url", url)])
);
}
};

if !status_code.is_success() {
bail_error!(ErrorKind::NoRocketchatServer(url.clone()),
t!(["errors", "no_rocketchat_server"]).with_vars(vec![("rocketchat_url", url.clone())]));
bail_error!(
ErrorKind::NoRocketchatServer(url.clone()),
t!(["errors", "no_rocketchat_server"]).with_vars(vec![("rocketchat_url", url.clone())])
);
}

let rocketchat_info: GetInfoResponse =
Expand All @@ -139,11 +143,12 @@ impl RocketchatApi {

let min_version = "0.49".to_string();
Err(Error {
error_chain: ErrorKind::UnsupportedRocketchatApiVersion(min_version.clone(), version.clone()).into(),
user_message: Some(t!(["errors", "unsupported_rocketchat_api_version"]).with_vars(vec![("min_version",
min_version),
("version", version)])),
})
error_chain: ErrorKind::UnsupportedRocketchatApiVersion(min_version.clone(), version.clone()).into(),
user_message: Some(t!(["errors", "unsupported_rocketchat_api_version"]).with_vars(vec![
("min_version", min_version),
("version", version),
])),
})
}
}

Expand Down

0 comments on commit e829ab4

Please sign in to comment.