cas/graphql/types/
notification.rs

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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use crate::{
    errors::AppError,
    graphql::types::{
        alert::Alert,
        jwt::Authentication,
        position::{MovingActivity, Position},
        user::find_user,
    },
    state::AppState,
};
use async_graphql::{Context, Enum, FieldResult, InputObject, SimpleObject};
use serde::{Deserialize, Serialize};
use std::{error::Error, str::FromStr};
use tokio_postgres::types::{to_sql_checked, FromSql, IsNull, ToSql, Type};
use tokio_postgres::Client;

#[derive(Enum, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
/// Enumeration which refers to the level of alert
pub enum LevelAlert {
    // User in the AREA
    One,

    // User in the AREA OR < 1km distance
    Two,

    // User in the AREA OR < 2km distance
    Three,
}

impl FromStr for LevelAlert {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "One" => Ok(LevelAlert::One),
            "Two" => Ok(LevelAlert::Two),
            "Three" => Ok(LevelAlert::Three),
            _ => Err(String::from("Can't parse this value as Level")),
        }
    }
}

impl<'a> FromSql<'a> for LevelAlert {
    fn from_sql(_ty: &Type, raw: &'a [u8]) -> Result<LevelAlert, Box<dyn Error + Sync + Send>> {
        match std::str::from_utf8(raw)? {
            "One" => Ok(LevelAlert::One),
            "Two" => Ok(LevelAlert::Two),
            "Three" => Ok(LevelAlert::Three),
            other => Err(format!("Unknown variant: {}", other).into()),
        }
    }

    fn accepts(ty: &Type) -> bool {
        ty.name() == "level_alert"
    }
}

impl ToSql for LevelAlert {
    fn to_sql(
        &self,
        _ty: &Type,
        out: &mut bytes::BytesMut,
    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
        let value = match *self {
            LevelAlert::One => "One",
            LevelAlert::Two => "Two",
            LevelAlert::Three => "Three",
        };
        out.extend_from_slice(value.as_bytes());
        Ok(IsNull::No)
    }

    fn accepts(ty: &Type) -> bool {
        ty.name() == "level_alert"
    }

    to_sql_checked!();
}

#[derive(SimpleObject, Clone, Debug, Serialize, Deserialize)]
/// Notification struct
pub struct Notification {
    pub id: i32,
    pub alert: Option<Alert>,
    pub user_id: i32,
    pub latitude: f64,
    pub longitude: f64,
    pub moving_activity: MovingActivity,
    pub seen: bool,
    pub level: LevelAlert,
    pub created_at: i64,
}

#[derive(InputObject)]
/// Alert input struct
pub struct NotificationUpdateInput {
    pub id: i32,
    pub seen: bool,
}

impl Notification {
    /// Create a new notification into the database from an alert_id and a position.
    /// Returns the new ID.
    pub async fn insert_db(
        client: &Client,
        alert_id: i32,
        position: &Position,
        level: LevelAlert,
    ) -> Result<i32, AppError> {
        match client
            .query(
                "INSERT INTO notifications(alert_id, user_id, location, activity, level)
                VALUES($1, $2, ST_SetSRID(ST_MakePoint($3, $4), 4326), $5, $6)
                RETURNING id
                ",
                &[
                    &alert_id,
                    &position.user_id,
                    &position.longitude,
                    &position.latitude,
                    &position.moving_activity,
                    &level,
                ],
            )
            .await
        {
            Ok(rows) => {
                let row = rows[0].clone();
                Ok(row.get("id"))
            }
            Err(e) => Err(AppError::Database(e.to_string())),
        }
    }
}

pub mod query {
    use super::*;

    /// Get notifications from the database
    pub async fn get_notifications<'ctx>(
        ctx: &Context<'ctx>,

        // Filter for `seen` field
        seen: Option<bool>,

        // Optional filter by id
        id: Option<i32>,

        // Optional filter by alert id
        alert_id: Option<i32>,

        // Optional limit results
        limit: Option<i64>,

        // Optional offset results. It should be used with limit field.
        offset: Option<i64>,
    ) -> Result<Option<Vec<Notification>>, AppError> {
        let state = ctx.data::<AppState>().expect("Can't connect to db");
        let client = &*state.client;
        let auth: &Authentication = ctx.data()?;
        match auth {
            Authentication::NotLogged => Err(AppError::Unauthorized),
            Authentication::Logged(claims) => {
                let claim_user = find_user(client, claims.user_id)
                    .await
                    .expect("Should not be here");

                let limit = limit.unwrap_or(20);
                let offset = offset.unwrap_or(0);

                let base_query = "SELECT n.id,
                                n.alert_id,
                                n.seen,
                                n.level,
                                extract(epoch from n.created_at)::double precision as created_at,
                                ST_Y(n.location::geometry) AS latitude,
                                ST_X(n.location::geometry) AS longitude,
                                n.activity,
                                n.user_id,
                                a.id as alert_id,
                                a.user_id as alert_user_id,
                                extract(epoch from a.created_at)::double precision as alert_created_at,
                                ST_AsText(a.area) as alert_area,
                                ST_AsText(ST_Buffer(a.area::geography, 1000)) as alert_area_level2,
                                ST_AsText(ST_Buffer(a.area::geography, 2000)) as alert_area_level3,
                                a.text1 as alert_text1,
                                a.text2 as alert_text2,
                                a.text3 as alert_text3,
                                a.audio1 as alert_audio1,
                                a.audio2 as alert_audio2,
                                a.audio3 as alert_audio3,
                                a.reached_users as alert_reached_users
                        FROM notifications n
                        JOIN alerts a ON n.alert_id = a.id".to_string();

                let base_query = match id {
                    Some(idn) => format!("{} WHERE n.id = {}", base_query, idn),
                    None => format!("{} WHERE 1=1", base_query),
                };

                let base_query = match seen {
                    Some(seen_status) if seen_status => format!("{} AND seen = 't'", base_query),
                    Some(_) => format!("{} AND seen = 'f'", base_query),
                    None => base_query,
                };

                let rows = match alert_id {
                    Some (ida) =>
                        client
                        .query(&format!(
                            "{base_query} AND n.user_id = $1 AND n.alert_id = $2 ORDER BY n.id DESC LIMIT $3 OFFSET $4",
                        ), &[&claim_user.id, &ida, &limit, &offset])
                        .await?,
                    None =>
                        client.query(
                            &format!("{base_query} AND n.user_id = $1 ORDER BY n.id DESC LIMIT $2 OFFSET $3"),
                            &[&claim_user.id, &limit, &offset],
                        )
                        .await?,
                };

                let notifications: Vec<Notification> = rows
                    .iter()
                    .map(|row| Notification {
                        id: row.get("id"),
                        alert: Some(Alert {
                            id: row.get("alert_id"),
                            user_id: row.get("alert_user_id"),
                            created_at: row.get::<_, f64>("alert_created_at") as i64,
                            area: row.get("alert_area"),
                            area_level2: row.get("alert_area_level2"),
                            area_level3: row.get("alert_area_level3"),
                            text1: row.get("alert_text1"),
                            text2: row.get("alert_text2"),
                            text3: row.get("alert_text3"),
                            audio1: row.get("alert_audio1"),
                            audio2: row.get("alert_audio2"),
                            audio3: row.get("alert_audio3"),
                            reached_users: row.get("alert_reached_users"),
                            notifications: vec![],
                        }),
                        seen: row.get("seen"),
                        level: row.get("level"),
                        user_id: row.get("user_id"),
                        latitude: row.get("latitude"),
                        longitude: row.get("longitude"),
                        moving_activity: row.get("activity"),
                        created_at: row.get::<_, f64>("created_at") as i64,
                    })
                    .collect();

                Ok(Some(notifications))
            }
        }
    }
}

pub mod mutations {
    use super::*;

    pub async fn notification_update<'ctx>(
        ctx: &Context<'ctx>,
        input: NotificationUpdateInput,
    ) -> FieldResult<Notification> {
        let state = ctx.data::<AppState>().expect("Can't connect to db");
        let client = &*state.client;

        let auth: &Authentication = ctx.data()?;
        match auth {
            Authentication::NotLogged => Err(AppError::NotFound("Owner".to_string()).into()),
            Authentication::Logged(claims) => {
                let user = find_user(client, claims.user_id)
                    .await
                    .expect("Should not be here");

                let notification = client.query("SELECT n.id,
                                n.alert_id,
                                n.seen,
                                n.level,
                                extract(epoch from n.created_at)::double precision as created_at,
                                ST_Y(n.location::geometry) AS latitude,
                                ST_X(n.location::geometry) AS longitude,
                                n.activity,
                                n.user_id,
                                a.id as alert_id,
                                a.user_id as alert_user_id,
                                extract(epoch from a.created_at)::double precision as alert_created_at,
                                ST_AsText(a.area) as alert_area,
                                ST_AsText(ST_Buffer(a.area::geography, 1000)) as alert_area_level2,
                                ST_AsText(ST_Buffer(a.area::geography, 2000)) as alert_area_level3,
                                a.text1 as alert_text1,
                                a.text2 as alert_text2,
                                a.text3 as alert_text3,
                                a.audio1 as alert_audio1,
                                a.audio2 as alert_audio2,
                                a.audio3 as alert_audio3,
                                a.reached_users as alert_reached_users
                        FROM notifications n
                        JOIN alerts a ON n.alert_id = a.id
                        WHERE n.id = $1
                        ",
                       &[&input.id])
                    .await?
                    .iter()
                    .map(|row| Notification {
                        id: row.get("id"),
                        alert: Some(Alert {
                            id: row.get("alert_id"),
                            user_id: row.get("alert_user_id"),
                            created_at: row.get::<_, f64>("alert_created_at") as i64,
                            area: row.get("alert_area"),
                            area_level2: row.get("alert_area_level2"),
                            area_level3: row.get("alert_area_level3"),
                            text1: row.get("alert_text1"),
                            text2: row.get("alert_text2"),
                            text3: row.get("alert_text3"),
                            audio1: row.get("alert_audio1"),
                            audio2: row.get("alert_audio2"),
                            audio3: row.get("alert_audio3"),
                            reached_users: row.get("alert_reached_users"),
                            notifications: vec![],
                        }),
                        seen: row.get("seen"),
                        level: row.get("level"),
                        user_id: row.get("user_id"),
                        latitude: row.get("latitude"),
                        longitude: row.get("longitude"),
                        moving_activity: row.get("activity"),
                        created_at: row.get::<_, f64>("created_at") as i64,
                    })
                    .collect::<Vec<Notification>>()
                    .first()
                    .cloned()
                    .ok_or_else(|| AppError::NotFound("Notification".to_string()))?;

                if notification.user_id != user.id {
                    return Err(AppError::NotFound("Notification".to_string()).into());
                }

                client
                    .query(
                        "UPDATE notifications SET seen = $1 WHERE id = $2",
                        &[&input.seen, &input.id],
                    )
                    .await?;

                Ok(notification)
            }
        }
    }
}