Skip to content

Commit

Permalink
Run rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
jutuon committed May 26, 2024
1 parent dc15c89 commit 4501d9b
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 136 deletions.
6 changes: 2 additions & 4 deletions examples/simple_sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::path::PathBuf;

use clap::Parser;
use fcm::{
FcmClient,
message::{Message, Notification, Target},
FcmClient,
};
use serde_json::json;

Expand All @@ -30,9 +30,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
builder
};

let client = builder.build()
.await
.unwrap();
let client = builder.build().await.unwrap();

let message = Message {
data: Some(json!({
Expand Down
3 changes: 1 addition & 2 deletions src/android/android_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use serde::Serialize;
use serde_json::Value;

use super::{
android_fcm_options::AndroidFcmOptions,
android_message_priority::AndroidMessagePriority,
android_fcm_options::AndroidFcmOptions, android_message_priority::AndroidMessagePriority,
android_notification::AndroidNotification,
};

Expand Down
6 changes: 1 addition & 5 deletions src/android/android_notification.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
use serde::Serialize;

use super::{
light_settings::LightSettings,
notification_priority::NotificationPriority,
visibility::Visibility,
};
use super::{light_settings::LightSettings, notification_priority::NotificationPriority, visibility::Visibility};

#[derive(Debug, Default, Serialize)]
/// <https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages?authuser=0#androidnotification>
Expand Down
61 changes: 24 additions & 37 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ use reqwest::header::RETRY_AFTER;
use crate::client::response::FcmResponse;
use crate::message::{Message, MessageWrapper};

use self::{
oauth::OauthClient,
response::RetryAfter,
};
use self::{oauth::OauthClient, response::RetryAfter};

pub use self::oauth::OauthError;

Expand All @@ -28,19 +25,15 @@ pub enum FcmClientError {
#[error("Retry-After HTTP header value is not valid string")]
RetryAfterHttpHeaderIsNotString,
#[error("Retry-After HTTP header value is not valid, error: {error}, value: {value}")]
RetryAfterHttpHeaderInvalid {
error: chrono::ParseError,
value: String,
},
RetryAfterHttpHeaderInvalid { error: chrono::ParseError, value: String },
}

impl FcmClientError {
/// If this is `true` then most likely current service account
/// key is invalid.
pub fn is_access_token_missing_even_if_server_requests_completed(&self) -> bool {
match self {
FcmClientError::Oauth(error) =>
error.is_access_token_missing_even_if_server_requests_completed(),
FcmClientError::Oauth(error) => error.is_access_token_missing_even_if_server_requests_completed(),
_ => false,
}
}
Expand Down Expand Up @@ -109,9 +102,7 @@ impl FcmClient {
FcmClientBuilder::new()
}

async fn new_from_builder(
fcm_builder: FcmClientBuilder,
) -> Result<Self, FcmClientError> {
async fn new_from_builder(fcm_builder: FcmClientBuilder) -> Result<Self, FcmClientError> {
let builder = reqwest::ClientBuilder::new();
let builder = if let Some(timeout) = fcm_builder.fcm_request_timeout {
builder.timeout(timeout)
Expand All @@ -121,10 +112,7 @@ impl FcmClient {
let http_client = builder.build()?;

let oauth_client = if let Some(key_json) = fcm_builder.service_account_key_json_string {
OauthClient::create_with_string_key(
key_json,
fcm_builder.token_cache_json_path,
)
OauthClient::create_with_string_key(key_json, fcm_builder.token_cache_json_path)
.await
.map_err(FcmClientError::Oauth)?
} else {
Expand All @@ -134,10 +122,7 @@ impl FcmClient {
dotenvy::var("GOOGLE_APPLICATION_CREDENTIALS")?.into()
};

OauthClient::create_with_key_file(
service_account_key_path,
fcm_builder.token_cache_json_path,
)
OauthClient::create_with_key_file(service_account_key_path, fcm_builder.token_cache_json_path)
.await
.map_err(FcmClientError::Oauth)?
};
Expand All @@ -149,12 +134,17 @@ impl FcmClient {
}

pub async fn send(&self, message: impl AsRef<Message>) -> Result<FcmResponse, FcmClientError> {
let access_token = self.oauth_client.get_access_token()
let access_token = self
.oauth_client
.get_access_token()
.await
.map_err(FcmClientError::Oauth)?;

// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send
let url = format!("https://fcm.googleapis.com/v1/projects/{}/messages:send", self.oauth_client.get_project_id());
let url = format!(
"https://fcm.googleapis.com/v1/projects/{}/messages:send",
self.oauth_client.get_project_id()
);

let request = self
.http_client
Expand All @@ -164,17 +154,18 @@ impl FcmClient {
.build()?;

let response = self.http_client.execute(request).await?;
let retry_after = response
.headers()
.get(RETRY_AFTER);
let retry_after = response.headers().get(RETRY_AFTER);
let retry_after = if let Some(header_value) = retry_after {
let header_str = header_value.to_str()
let header_str = header_value
.to_str()
.map_err(|_| FcmClientError::RetryAfterHttpHeaderIsNotString)?;
let value = header_str.parse::<RetryAfter>()
.map_err(|error| FcmClientError::RetryAfterHttpHeaderInvalid {
error,
value: header_str.to_string(),
})?;
let value =
header_str
.parse::<RetryAfter>()
.map_err(|error| FcmClientError::RetryAfterHttpHeaderInvalid {
error,
value: header_str.to_string(),
})?;
Some(value)
} else {
None
Expand All @@ -186,10 +177,6 @@ impl FcmClient {
.ok()
.unwrap_or_default();

Ok(FcmResponse::new(
http_status_code,
response_json_object,
retry_after,
))
Ok(FcmResponse::new(http_status_code, response_json_object, retry_after))
}
}
23 changes: 8 additions & 15 deletions src/client/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,8 @@ impl OauthError {
pub(crate) fn is_access_token_missing_even_if_server_requests_completed(&self) -> bool {
matches!(
self,
OauthError::AccessTokenIsMissing |
OauthError::Oauth(
yup_oauth2::Error::MissingAccessToken |
yup_oauth2::Error::AuthError(_)
)
OauthError::AccessTokenIsMissing
| OauthError::Oauth(yup_oauth2::Error::MissingAccessToken | yup_oauth2::Error::AuthError(_))
)
}
}
Expand All @@ -46,7 +43,8 @@ impl OauthClient {
service_account_key_path: PathBuf,
token_cache_json_path: Option<PathBuf>,
) -> Result<Self, OauthError> {
let file = tokio::fs::read_to_string(&service_account_key_path).await
let file = tokio::fs::read_to_string(&service_account_key_path)
.await
.map_err(OauthError::ServiceAccountKeyReadingFailed)?;
Self::create_with_string_key(file, token_cache_json_path).await
}
Expand All @@ -57,20 +55,16 @@ impl OauthClient {
) -> Result<Self, OauthError> {
let key = yup_oauth2::parse_service_account_key(service_account_key_json_string)
.map_err(OauthError::ServiceAccountKeyReadingFailed)?;
let oauth_client = DefaultHyperClient.build_hyper_client()
.map_err(OauthError::Oauth)?;
let oauth_client = DefaultHyperClient.build_hyper_client().map_err(OauthError::Oauth)?;
let builder = ServiceAccountAuthenticator::with_client(key.clone(), oauth_client);
let builder = if let Some(path) = token_cache_json_path {
builder.persist_tokens_to_disk(path)
} else {
builder
};
let authenticator = builder.build()
.await
.map_err(OauthError::AuthenticatorCreatingFailed)?;
let authenticator = builder.build().await.map_err(OauthError::AuthenticatorCreatingFailed)?;

let project_id = key.project_id
.ok_or(OauthError::ProjectIdIsMissing)?;
let project_id = key.project_id.ok_or(OauthError::ProjectIdIsMissing)?;

Ok(OauthClient {
authenticator,
Expand All @@ -81,8 +75,7 @@ impl OauthClient {
pub async fn get_access_token(&self) -> Result<String, OauthError> {
let scopes = [FIREBASE_OAUTH_SCOPE];
let access_token = self.authenticator.token(&scopes).await?;
let access_token = access_token.token()
.ok_or(OauthError::AccessTokenIsMissing)?;
let access_token = access_token.token().ok_or(OauthError::AccessTokenIsMissing)?;

Ok(access_token.to_string())
}
Expand Down
Loading

0 comments on commit 4501d9b

Please sign in to comment.