push-messaging 0.1.1

Push Messaging package
Documentation
use std::{error::Error, fmt, str::FromStr};

use chrono::{Duration, DateTime, FixedOffset};
use serde::{Serialize, Deserialize, Serializer, Deserializer};
use serde_with::skip_serializing_none;

use crate::client::error::ClientError;


/// Fatal errors. Referred from [Firebase
/// documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#table9)
#[derive(PartialEq, Debug, Clone, Eq, Serialize, Deserialize)]
pub enum FcmError {
    /// The sender account used to send a message couldn't be authenticated. Possible causes are:
    ///
    /// Authorization header missing or with invalid syntax in HTTP request.
    ///
    /// * The Firebase project that the specified server key belongs to is
    ///   incorrect.
    /// * Legacy server keys only—the request originated from a server not
    ///   whitelisted in the Server key IPs.
    ///
    /// Check that the token you're sending inside the Authentication header is
    /// the correct Server key associated with your project. See Checking the
    /// validity of a Server key for details. If you are using a legacy server
    /// key, you're recommended to upgrade to a new key that has no IP
    /// restrictions.
    Unauthorized,

    /// Check that the JSON message is properly formatted and contains valid
    /// fields (for instance, making sure the right data type is passed in).
    InvalidMessage(String),

    /// The server couldn't process the request. Retry the same request, but you must:
    ///
    /// * Honor the [RetryAfter](enum.RetryAfter.html) value if included.
    /// * Implement exponential back-off in your retry mechanism. (e.g. if you
    ///   waited one second before the first retry, wait at least two second
    ///   before the next one, then 4 seconds and so on). If you're sending
    ///   multiple messages, delay each one independently by an additional random
    ///   amount to avoid issuing a new request for all messages at the same time.
    ///
    /// Senders that cause problems risk being blacklisted.
    ServerError(Option<RetryAfter>),
}

impl From<FcmError> for crate::client::error::ClientError{
    fn from(e: FcmError) -> Self {
        match e {
            FcmError::Unauthorized => Self::Unauthorized,
            FcmError::InvalidMessage(s) => Self::InvalidMessage(s),
            FcmError::ServerError(s) => Self::ServerError(format!("{:?}", s)),
        }
    }
}

impl Error for FcmError {}

impl fmt::Display for FcmError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FcmError::Unauthorized => write!(
                f,
                "authorization header missing or with invalid syntax in HTTP request"
            ),
            FcmError::InvalidMessage(ref s) => write!(f, "invalid message {}", s),
            FcmError::ServerError(_) => write!(f, "the server couldn't process the request"),
        }
    }
}

impl From<reqwest::Error> for FcmError {
    fn from(_: reqwest::Error) -> Self {
        Self::ServerError(None)
    }
}

#[serde_with::serde_as]
#[derive(PartialEq, Debug, Clone, Eq)]
pub enum RetryAfter {
    /// Amount of time to wait until retrying the message is allowed.
    Delay(Duration),

    /// A point in time until retrying the message is allowed.
    DateTime(DateTime<FixedOffset>),
}

#[serde_with::serde_as]
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RetryAfterSerializer {
    #[serde_as(as = "Option<serde_with::DurationSeconds<i64>>")]
    pub delay: Option<Duration>,
    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
    pub date_time: Option<DateTime<FixedOffset>>,
}

impl From<RetryAfter> for RetryAfterSerializer {
    fn from(r: RetryAfter) -> Self {
        match r {
            RetryAfter::Delay(d) => Self {
                delay: Some(d),
                date_time: None,
            },
            RetryAfter::DateTime(d) => Self {
                delay: None,
                date_time: Some(d),
            },
        }
    }
}

impl Serialize for RetryAfter {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        RetryAfterSerializer::from(self.clone()).serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for RetryAfter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'a>,
    {
        let r = RetryAfterSerializer::deserialize(deserializer)?;
        match (r.delay, r.date_time) {
            (Some(d), None) => Ok(RetryAfter::Delay(d)),
            (None, Some(d)) => Ok(RetryAfter::DateTime(d)),
            _ => Err(serde::de::Error::custom("invalid RetryAfter")),
        }
    }
}

impl FromStr for RetryAfter {
    type Err = FcmError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<i64>()
            .map(Duration::seconds)
            .map(RetryAfter::Delay)
            .or_else(|_| DateTime::parse_from_rfc2822(s).map(RetryAfter::DateTime))
            .map_err(|e| FcmError::InvalidMessage(format!("{}", e)))
    }
}



#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ErrorReason {
    /// Check that the request contains a registration token (in the `to` or
    /// `registration_ids` field).
    MissingRegistration,

    /// Check the format of the registration token you pass to the server. Make
    /// sure it matches the registration token the client app receives from
    /// registering with Firebase Notifications. Do not truncate or add
    /// additional characters.
    InvalidRegistration,

    /// An existing registration token may cease to be valid in a number of
    /// scenarios, including:
    ///
    /// * If the client app unregisters with FCM.
    /// * If the client app is automatically unregistered, which can happen if
    ///   the user uninstalls the application. For example, on iOS, if the APNS
    ///   Feedback Service reported the APNS token as invalid.
    /// * If the registration token expires (for example, Google might decide to
    ///   refresh registration tokens, or the APNS token has expired for iOS
    ///   devices).
    /// * If the client app is updated but the new version is not configured to
    ///   receive messages.
    ///
    /// For all these cases, remove this registration token from the app server
    /// and stop using it to send messages.
    NotRegistered,

    /// Make sure the message was addressed to a registration token whose
    /// package name matches the value passed in the request.
    InvalidPackageName,

    /// A registration token is tied to a certain group of senders. When a
    /// client app registers for FCM, it must specify which senders are allowed
    /// to send messages. You should use one of those sender IDs when sending
    /// messages to the client app. If you switch to a different sender, the
    /// existing registration tokens won't work.
    MismatchSenderId,

    /// Check that the provided parameters have the right name and type.
    InvalidParameters,

    /// Check that the total size of the payload data included in a message does
    /// not exceed FCM limits: 4096 bytes for most messages, or 2048 bytes in
    /// the case of messages to topics. This includes both the keys and the
    /// values.
    MessageTooBig,

    /// Check that the custom payload data does not contain a key (such as
    /// `from`, or `gcm`, or any value prefixed by google) that is used
    /// internally by FCM. Note that some words (such as `collapse_key`) are
    /// also used by FCM but are allowed in the payload, in which case the
    /// payload value will be overridden by the FCM value.
    InvalidDataKey,

    /// Check that the value used in `time_to_live` is an integer representing a
    /// duration in seconds between 0 and 2,419,200 (4 weeks).
    InvalidTtl,

    /// In internal use only. Check
    /// [FcmError::ServerError](enum.FcmError.html#variant.ServerError).
    Unavailable,

    /// In internal use only. Check
    /// [FcmError::ServerError](enum.FcmError.html#variant.ServerError).
    InternalServerError,

    /// The rate of messages to a particular device is too high. If an iOS app
    /// sends messages at a rate exceeding APNs limits, it may receive this
    /// error message
    ///
    /// Reduce the number of messages sent to this device and use exponential
    /// backoff to retry sending.
    DeviceMessageRateExceeded,

    /// The rate of messages to subscribers to a particular topic is too high.
    /// Reduce the number of messages sent for this topic and use exponential
    /// backoff to retry sending.
    TopicsMessageRateExceeded,

    /// A message targeted to an iOS device could not be sent because the
    /// required APNs authentication key was not uploaded or has expired. Check
    /// the validity of your development and production credentials.
    InvalidApnsCredential,
}

impl From<ErrorReason> for ClientError{
    fn from(e: ErrorReason) -> Self {
        let reason: String = match e {
            ErrorReason::MissingRegistration => "missing registration".into(),
            ErrorReason::InvalidRegistration => "invalid registration".into(),
            ErrorReason::NotRegistered => "not registered".into(),
            ErrorReason::InvalidPackageName => "invalid package name".into(),
            ErrorReason::MismatchSenderId => "mismatch sender id".into(),
            ErrorReason::InvalidParameters => "invalid parameters".into(),
            ErrorReason::MessageTooBig => "message too big".into(),
            ErrorReason::InvalidDataKey => "invalid data key".into(),
            ErrorReason::InvalidTtl => "invalid ttl".into(),
            ErrorReason::Unavailable => "unavailable".into(),
            ErrorReason::InternalServerError => "internal server error".into(),
            ErrorReason::DeviceMessageRateExceeded => "device message rate exceeded".into(),
            ErrorReason::TopicsMessageRateExceeded => "topics message rate exceeded".into(),
            ErrorReason::InvalidApnsCredential => "invalid apns credential".into(),
        };
        ClientError::InvalidMessage(reason)
    }
}