OXYGENHUB
◆ v0.9.19 oxygenhub / crates / hub / src / db / push.rs
1.6 KiB · Rust · last changed Phone alerts: a phone registers its Cloud Messaging token and key (PUT /api/v1/user/push), and each notification its account is told goes to it sealed to that key, sent keyless as the VM's service account; pins OxygenFlow main (refs oxygenhub-android#16) 8 days ago source blame history raw
1
//! Phones that take alerts (oxygenhub-android#16).
2
3
use super::{now_ms, Pool};
4
use sqlx::FromRow;
5
6
#[derive(Clone, Debug, FromRow)]
7
pub struct Device {
8
    pub token_id: i64,
9
    pub account_id: i64,
10
    pub fcm_token: String,
11
    pub public_key: String,
12
}
13
14
/// Register (or refresh) the phone signed in with token `token_id`.
15
pub async fn register(pool: &Pool, token_id: i64, account_id: i64, fcm_token: &str, public_key: &str) -> sqlx::Result<()> {
16
    let now = now_ms();
17
    sqlx::query(
18
        "INSERT INTO push_devices (token_id, account_id, fcm_token, public_key, created_ms, updated_ms) VALUES ($1, $2, $3, $4, $5, $5) \
19
         ON CONFLICT (token_id) DO UPDATE SET fcm_token = excluded.fcm_token, public_key = excluded.public_key, updated_ms = excluded.updated_ms",
20
    )
21
    .bind(token_id)
22
    .bind(account_id)
23
    .bind(fcm_token)
24
    .bind(public_key)
25
    .bind(now)
26
    .execute(pool)
27
    .await?;
28
    Ok(())
29
}
30
31
pub async fn forget(pool: &Pool, token_id: i64) -> sqlx::Result<bool> {
32
    Ok(sqlx::query("DELETE FROM push_devices WHERE token_id = $1").bind(token_id).execute(pool).await?.rows_affected() > 0)
33
}
34
35
/// Forget a registration Cloud Messaging says is gone.
36
pub async fn forget_fcm(pool: &Pool, fcm_token: &str) -> sqlx::Result<()> {
37
    sqlx::query("DELETE FROM push_devices WHERE fcm_token = $1").bind(fcm_token).execute(pool).await?;
38
    Ok(())
39
}
40
41
pub async fn of_account(pool: &Pool, account_id: i64) -> sqlx::Result<Vec<Device>> {
42
    sqlx::query_as("SELECT token_id, account_id, fcm_token, public_key FROM push_devices WHERE account_id = $1")
43
        .bind(account_id)
44
        .fetch_all(pool)
45
        .await
46
}