summaryrefslogtreecommitdiff
path: root/src/push/app.rs
blob: 2d6e15c6ba47490b4e3f78bd2afeb38ff994e51c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use sqlx::SqlitePool;
use web_push::{
    ContentEncoding, IsahcWebPushClient, PartialVapidSignatureBuilder, SubscriptionInfo,
    WebPushClient, WebPushMessageBuilder,
};

use super::{Id, repo::Provider as _};

use crate::{
    db::NotFound as _,
    user::{self, User},
};

pub struct Push<'a> {
    db: &'a SqlitePool,
    vapid_public_key: &'a str,
    vapid_signer: &'a PartialVapidSignatureBuilder,
}

impl<'a> Push<'a> {
    pub const fn new(
        db: &'a SqlitePool,
        vapid_public_key: &'a str,
        vapid_signer: &'a PartialVapidSignatureBuilder,
    ) -> Self {
        Self {
            db,
            vapid_public_key,
            vapid_signer,
        }
    }

    pub fn public_key(&self) -> &str {
        self.vapid_public_key
    }

    pub async fn register(
        &self,
        user: &User,
        subscription: &SubscriptionInfo,
    ) -> Result<Id, RegisterError> {
        let mut tx = self.db.begin().await?;
        let id = tx.subscriptions().create(user, subscription).await?;
        tx.commit().await?;

        Ok(id)
    }

    pub async fn echo(
        &self,
        user: &User,
        subscription: &Id,
        message: &str,
    ) -> Result<(), EchoError> {
        let mut tx = self.db.begin().await?;
        let subscription = tx
            .subscriptions()
            .by_id(subscription)
            .await
            .not_found(|| EchoError::NotFound(subscription.clone()))?;
        if subscription.user != user.id {
            return Err(EchoError::NotSubscriber(subscription.id, user.id.clone()));
        }

        tx.commit().await?;

        self.send(&subscription.info, message).await?;

        Ok(())
    }

    async fn send(&self, subscription: &SubscriptionInfo, message: &str) -> Result<(), EchoError> {
        let sig_builder = self
            .vapid_signer
            .clone()
            .add_sub_info(subscription)
            .build()?;

        let payload = message.as_bytes();

        let mut message_builder = WebPushMessageBuilder::new(subscription);
        message_builder.set_payload(ContentEncoding::Aes128Gcm, payload);
        message_builder.set_vapid_signature(sig_builder);
        let message = message_builder.build()?;

        let client = IsahcWebPushClient::new()?;
        client.send(message).await?;

        Ok(())
    }

    pub async fn unregister(&self, user: &User, subscription: &Id) -> Result<(), UnregisterError> {
        let mut tx = self.db.begin().await?;
        let subscription = tx
            .subscriptions()
            .by_id(subscription)
            .await
            .not_found(|| UnregisterError::NotFound(subscription.clone()))?;
        if subscription.user != user.id {
            return Err(UnregisterError::NotSubscriber(
                subscription.id,
                user.id.clone(),
            ));
        }
        tx.subscriptions().delete(&subscription).await?;
        tx.commit().await?;

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum RegisterError {
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

#[derive(Debug, thiserror::Error)]
pub enum EchoError {
    #[error("subscription {0} not found")]
    NotFound(Id),
    #[error("user {1} is not the subscriber for subscription {0}")]
    NotSubscriber(Id, user::Id),
    #[error(transparent)]
    WebPush(#[from] web_push::WebPushError),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

#[derive(Debug, thiserror::Error)]
pub enum UnregisterError {
    #[error("subscription {0} not found")]
    NotFound(Id),
    #[error("user {1} is not the subscriber for subscription {0}")]
    NotSubscriber(Id, user::Id),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}