# lib.rs - source
Source of the Rust file `db/db-sqlx-maria/src/lib.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
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    990
    991
    992
    993
    994
    995
    996
    997
    998
    999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404

    // Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
    // SPDX-FileCopyrightText: 2023 Aravinth Manivannan <realaravinth@batsense.net>
    //
    // SPDX-License-Identifier: AGPL-3.0-or-later

    use std::str::FromStr;

    use db_core::dev::*;

    use sqlx::mysql::MySqlPoolOptions;
    use sqlx::types::time::OffsetDateTime;
    use sqlx::ConnectOptions;
    use sqlx::MySqlPool;
    use uuid::Uuid;

    pub mod errors;
    #[cfg(test)]
    pub mod tests;

    #[derive(Clone)]
    pub struct Database {
        pub pool: MySqlPool,
    }

    /// Use an existing database pool
    pub struct Conn(pub MySqlPool);

    /// Connect to database
    pub enum ConnectionOptions {
        /// fresh connection
        Fresh(Fresh),
        /// existing connection
        Existing(Conn),
    }

    pub struct Fresh {
        pub pool_options: MySqlPoolOptions,
        pub disable_logging: bool,
        pub url: String,
    }

    pub mod dev {
        pub use super::errors::*;
        pub use super::Database;
        pub use db_core::dev::*;
        pub use sqlx::Error;
    }

    pub mod prelude {
        pub use super::*;
    }

    #[async_trait]
    impl Connect for ConnectionOptions {
        type Pool = Database;
        async fn connect(self) -> DBResult<Self::Pool> {
            let pool = match self {
                Self::Fresh(fresh) => {
                    let mut connect_options =
                        sqlx::mysql::MySqlConnectOptions::from_str(&fresh.url).unwrap();
                    if fresh.disable_logging {
                        connect_options = connect_options.disable_statement_logging();
                    }
                    fresh
                        .pool_options
                        .connect_with(connect_options)
                        .await
                        .map_err(|e| DBError::DBError(Box::new(e)))?
                }

                Self::Existing(conn) => conn.0,
            };
            Ok(Database { pool })
        }
    }

    use dev::*;

    #[async_trait]
    impl Migrate for Database {
        async fn migrate(&self) -> DBResult<()> {
            sqlx::migrate!("./migrations/")
                .run(&self.pool)
                .await
                .map_err(|e| DBError::DBError(Box::new(e)))?;
            Ok(())
        }
    }

    #[async_trait]
    impl MCDatabase for Database {
        /// ping DB
        async fn ping(&self) -> bool {
            use sqlx::Connection;

            if let Ok(mut con) = self.pool.acquire().await {
                con.ping().await.is_ok()
            } else {
                false
            }
        }

        /// register a new user
        async fn register(&self, p: &Register) -> DBResult<()> {
            let res = if let Some(email) = &p.email {
                sqlx::query!(
                    "insert into mcaptcha_users
            (name , password, email, secret) values (?, ?, ?, ?)",
                    &p.username,
                    &p.hash,
                    &email,
                    &p.secret,
                )
                .execute(&self.pool)
                .await
            } else {
                sqlx::query!(
                    "INSERT INTO mcaptcha_users
            (name , password,  secret) VALUES (?, ?, ?)",
                    &p.username,
                    &p.hash,
                    &p.secret,
                )
                .execute(&self.pool)
                .await
            };
            res.map_err(map_register_err)?;
            Ok(())
        }

        /// delete a user
        async fn delete_user(&self, username: &str) -> DBResult<()> {
            sqlx::query!("DELETE FROM mcaptcha_users WHERE name = (?)", username)
                .execute(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;
            Ok(())
        }

        /// check if username exists
        async fn username_exists(&self, username: &str) -> DBResult<bool> {
            match sqlx::query!("SELECT name from mcaptcha_users WHERE name = ?", username,)
                .fetch_one(&self.pool)
                .await
            {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// get user email
        async fn get_email(&self, username: &str) -> DBResult<Option<String>> {
            struct Email {
                email: Option<String>,
            }

            let res = sqlx::query_as!(
                Email,
                "SELECT email FROM mcaptcha_users WHERE name = ?",
                username
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;
            Ok(res.email)
        }

        /// check if email exists
        async fn email_exists(&self, email: &str) -> DBResult<bool> {
            match sqlx::query!("SELECT name from mcaptcha_users WHERE email = ?", email)
                .fetch_one(&self.pool)
                .await
            {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// update a user's email
        async fn update_email(&self, p: &UpdateEmail) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set email = ?
                WHERE name = ?",
                &p.new_email,
                &p.username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// get a user's password
        async fn get_password(&self, l: &Login) -> DBResult<NameHash> {
            struct Password {
                name: String,
                password: String,
            }

            let rec = match l {
                Login::Username(u) => sqlx::query_as!(
                    Password,
                    r#"SELECT name, password  FROM mcaptcha_users WHERE name = ?"#,
                    u,
                )
                .fetch_one(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?,

                Login::Email(e) => sqlx::query_as!(
                    Password,
                    r#"SELECT name, password  FROM mcaptcha_users WHERE email = ?"#,
                    e,
                )
                .fetch_one(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?,
            };

            let res = NameHash {
                hash: rec.password,
                username: rec.name,
            };

            Ok(res)
        }

        /// update user's password
        async fn update_password(&self, p: &NameHash) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set password = ?
                WHERE name = ?",
                &p.hash,
                &p.username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// update username
        async fn update_username(&self, current: &str, new: &str) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set name = ?
                WHERE name = ?",
                new,
                current,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// get a user's secret
        async fn get_secret(&self, username: &str) -> DBResult<Secret> {
            let secret = sqlx::query_as!(
                Secret,
                r#"SELECT secret  FROM mcaptcha_users WHERE name = ?"#,
                username,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(secret)
        }

        /// get a user's secret from a captcha key
        async fn get_secret_from_captcha(&self, key: &str) -> DBResult<Secret> {
            let secret = sqlx::query_as!(
                Secret,
                r#"SELECT secret  FROM mcaptcha_users WHERE ID = (
                        SELECT user_id FROM mcaptcha_config WHERE captcha_key = ?
                        )"#,
                key,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(secret)
        }

        /// update a user's secret
        async fn update_secret(&self, username: &str, secret: &str) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set secret = ?
            WHERE name = ?",
                &secret,
                &username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// create new captcha
        async fn create_captcha(&self, username: &str, p: &CreateCaptcha) -> DBResult<()> {
            sqlx::query!(
                "INSERT INTO mcaptcha_config
            (`captcha_key`, `user_id`, `duration`, `name`)
            VALUES (?, (SELECT ID FROM mcaptcha_users WHERE name = ?), ?, ?)",
                p.key,
                username,
                p.duration as i32,
                p.description,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// Get captcha config
        async fn get_captcha_config(&self, username: &str, key: &str) -> DBResult<Captcha> {
            let captcha = sqlx::query_as!(
                InternaleCaptchaConfig,
                "SELECT `config_id`, `duration`, `name`, `captcha_key` from mcaptcha_config WHERE
                            `captcha_key` = ? AND
                            user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?) ",
                &key,
                &username,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(captcha.into())
        }

        /// Get all captchas belonging to user
        async fn get_all_user_captchas(&self, username: &str) -> DBResult<Vec<Captcha>> {
            let mut res = sqlx::query_as!(
                InternaleCaptchaConfig,
                "SELECT captcha_key, name, config_id, duration FROM mcaptcha_config WHERE
                user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?) ",
                &username,
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            let mut captchas = Vec::with_capacity(res.len());

            res.drain(0..).for_each(|r| captchas.push(r.into()));

            Ok(captchas)
        }

        /// update captcha metadata; doesn't change captcha key
        async fn update_captcha_metadata(
            &self,
            username: &str,
            p: &CreateCaptcha,
        ) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_config SET name = ?, duration = ?
                WHERE user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                AND captcha_key = ?",
                p.description,
                p.duration,
                username,
                p.key,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// update captcha key; doesn't change metadata
        async fn update_captcha_key(
            &self,
            username: &str,
            old_key: &str,
            new_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_config SET captcha_key = ?
            WHERE captcha_key = ? AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                new_key,
                old_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Add levels to captcha
        async fn add_captcha_levels(
            &self,
            username: &str,
            captcha_key: &str,
            levels: &[Level],
        ) -> DBResult<()> {
            use futures::future::try_join_all;
            let mut futs = Vec::with_capacity(levels.len());

            for level in levels.iter() {
                let difficulty_factor = level.difficulty_factor as i32;
                let visitor_threshold = level.visitor_threshold as i32;
                let fut = sqlx::query!(
                    "INSERT INTO mcaptcha_levels (
                difficulty_factor,
                visitor_threshold,
                config_id) VALUES  (
                ?, ?, (
                    SELECT config_id FROM mcaptcha_config WHERE
                    captcha_key = (?) AND user_id = (
                    SELECT ID FROM mcaptcha_users WHERE name = ?
                        )));",
                    difficulty_factor,
                    visitor_threshold,
                    &captcha_key,
                    username,
                )
                .execute(&self.pool);
                futs.push(fut);
            }

            try_join_all(futs)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            let mut futs = Vec::with_capacity(levels.len());

            for level in levels.iter() {
                let difficulty_factor = level.difficulty_factor as i32;
                let visitor_threshold = level.visitor_threshold as i32;
                let fut = sqlx::query!(
                    "INSERT INTO
                        mcaptcha_track_nonce (level_id, nonce)
                    VALUES  ((
                        SELECT
                            level_id
                        FROM
                            mcaptcha_levels
                        WHERE
                            config_id = (SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?)
                        AND
                            difficulty_factor = ?
                        AND
                            visitor_threshold = ?
                        ), ?);",
                    &captcha_key,
                    difficulty_factor,
                    visitor_threshold,
                    0,
                )
                .execute(&self.pool);
                futs.push(fut);
            }

            try_join_all(futs)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// check if captcha exists
        async fn captcha_exists(
            &self,
            username: Option<&str>,
            captcha_key: &str,
        ) -> DBResult<bool> {
            //        let mut exists = false;

            #[allow(dead_code)]
            struct ConfigId {
                config_id: i32,
            }
            let res = match username {
                Some(username) => {
                    sqlx::query_as!(
                        ConfigId,
                        "SELECT config_id FROM mcaptcha_config
                            WHERE
                                captcha_key = ?
                            AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                        captcha_key,
                        username
                    )
                    .fetch_one(&self.pool)
                    .await
                    //                if let Some(x) = x.exists {
                    //                    exists = x;
                    //                };
                }

                None => {
                    sqlx::query_as!(
                        ConfigId,
                        "SELECT config_id from mcaptcha_config WHERE captcha_key = ?",
                        &captcha_key,
                    )
                    .fetch_one(&self.pool)
                    .await
                } //if let Some(x) = x.exists {
                  //    exists = x;
                  //};
            };
            match res {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// Delete all levels of a captcha
        async fn delete_captcha_levels(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_levels
            WHERE config_id = (
                SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                AND user_id = (
                SELECT ID from mcaptcha_users WHERE name = ?
                )
                )",
                captcha_key,
                username
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Delete captcha
        async fn delete_captcha(&self, username: &str, captcha_key: &str) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_config where captcha_key= (?)
                    AND
                user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                captcha_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Get captcha levels
        async fn get_captcha_levels(
            &self,
            username: Option<&str>,
            captcha_key: &str,
        ) -> DBResult<Vec<Level>> {
            struct I32Levels {
                difficulty_factor: i32,
                visitor_threshold: i32,
            }
            let levels = match username {
                None => sqlx::query_as!(
                    I32Levels,
                    "SELECT difficulty_factor, visitor_threshold FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                    ) ORDER BY difficulty_factor ASC;",
                    captcha_key,
                )
                .fetch_all(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?,

                Some(username) => sqlx::query_as!(
                    I32Levels,
                    "SELECT difficulty_factor, visitor_threshold FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                    AND user_id = (SELECT ID from mcaptcha_users WHERE name = ?)
                    )
                ORDER BY difficulty_factor ASC;",
                    captcha_key,
                    username
                )
                .fetch_all(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?,
            };

            let mut new_levels = Vec::with_capacity(levels.len());
            for l in levels.iter() {
                new_levels.push(Level {
                    difficulty_factor: l.difficulty_factor as u32,
                    visitor_threshold: l.visitor_threshold as u32,
                });
            }
            Ok(new_levels)
        }

        /// Get captcha's cooldown period
        async fn get_captcha_cooldown(&self, captcha_key: &str) -> DBResult<i32> {
            struct DurationResp {
                duration: i32,
            }

            let resp = sqlx::query_as!(
                DurationResp,
                "SELECT duration FROM mcaptcha_config
                where captcha_key= ?",
                captcha_key,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(resp.duration)
        }
        /// Add traffic configuration
        async fn add_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
            pattern: &TrafficPattern,
        ) -> DBResult<()> {
            sqlx::query!(
                "INSERT INTO mcaptcha_sitekey_user_provided_avg_traffic (
                config_id,
                avg_traffic,
                peak_sustainable_traffic,
                broke_my_site_traffic
                ) VALUES (
                 (SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                 AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                ), ?, ?, ?)",
                //payload.avg_traffic,
                captcha_key,
                username,
                pattern.avg_traffic as i32,
                pattern.peak_sustainable_traffic as i32,
                pattern.broke_my_site_traffic.as_ref().map(|v| *v as i32),
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// Get traffic configuration
        async fn get_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<TrafficPattern> {
            struct Traffic {
                peak_sustainable_traffic: i32,
                avg_traffic: i32,
                broke_my_site_traffic: Option<i32>,
            }
            let res = sqlx::query_as!(
                Traffic,
                "SELECT
              avg_traffic,
              peak_sustainable_traffic,
              broke_my_site_traffic
            FROM
              mcaptcha_sitekey_user_provided_avg_traffic
            WHERE
              config_id = (
                SELECT
                  config_id
                FROM
                  mcaptcha_config
                WHERE
                  captcha_key = ?
                  AND user_id = (
                    SELECT
                      id
                    FROM
                      mcaptcha_users
                    WHERE
                      NAME = ?
                  )
              )
            ",
                captcha_key,
                username
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::TrafficPatternNotFound))?;
            Ok(TrafficPattern {
                broke_my_site_traffic: res.broke_my_site_traffic.as_ref().map(|v| *v as u32),
                avg_traffic: res.avg_traffic as u32,
                peak_sustainable_traffic: res.peak_sustainable_traffic as u32,
            })
        }

        /// Delete traffic configuration
        async fn delete_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_sitekey_user_provided_avg_traffic
            WHERE config_id = (
                SELECT config_id
                FROM
                    mcaptcha_config
                WHERE
                    captcha_key = ?
                AND
                    user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                );",
                captcha_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::TrafficPatternNotFound))?;
            Ok(())
        }

        /// create new notification
        async fn create_notification(&self, p: &AddNotification) -> DBResult<()> {
            let now = now_unix_time_stamp();
            sqlx::query!(
                "INSERT INTO mcaptcha_notifications (
                  heading, message, tx, rx, received)
                  VALUES  (
                  ?, ?,
                      (SELECT ID FROM mcaptcha_users WHERE name = ?),
                      (SELECT ID FROM mcaptcha_users WHERE name = ?),
                      ?
                          );",
                p.heading,
                p.message,
                p.from,
                p.to,
                now
            )
            .execute(&self.pool)
            .await
            .map_err(map_register_err)?;

            Ok(())
        }

        /// get all unread notifications
        async fn get_all_unread_notifications(
            &self,
            username: &str,
        ) -> DBResult<Vec<Notification>> {
            let mut inner_notifications = sqlx::query_file_as!(
                InnerNotification,
                "./src/get_all_unread_notifications.sql",
                &username
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            let mut notifications = Vec::with_capacity(inner_notifications.len());

            inner_notifications
                .drain(0..)
                .for_each(|n| notifications.push(n.into()));

            Ok(notifications)
        }

        /// mark a notification read
        async fn mark_notification_read(&self, username: &str, id: i32) -> DBResult<()> {
            sqlx::query_file_as!(
                Notification,
                "./src/mark_notification_read.sql",
                id,
                &username
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::NotificationNotFound))?;

            Ok(())
        }

        /// record PoWConfig fetches
        async fn record_fetch(&self, key: &str) -> DBResult<()> {
            let now = now_unix_time_stamp();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_fetched_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now,
        )
        .execute(&self.pool)
        .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// record PoWConfig solves
        async fn record_solve(&self, key: &str) -> DBResult<()> {
            let now = OffsetDateTime::now_utc();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_solved_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now,
        )
        .execute(&self.pool)
        .await
        .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// record PoWConfig confirms
        async fn record_confirm(&self, key: &str) -> DBResult<()> {
            let now = now_unix_time_stamp();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_confirmed_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now
        )
        .execute(&self.pool)
        .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// fetch PoWConfig fetches
        async fn fetch_config_fetched(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_fetched_stats
                WHERE
                    config_id = (
                        SELECT
                            config_id FROM mcaptcha_config
                        WHERE
                            captcha_key = ?
                        AND
                            user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user,
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }

        /// fetch PoWConfig solves
        async fn fetch_solve(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_solved_stats
                WHERE config_id = (
                    SELECT config_id FROM mcaptcha_config
                    WHERE
                        captcha_key = ?
                    AND
                         user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }

        /// fetch PoWConfig confirms
        async fn fetch_confirm(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_confirmed_stats
                WHERE
                    config_id = (
                        SELECT config_id FROM mcaptcha_config
                    WHERE
                        captcha_key = ?
                    AND
                         user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }

        /// record PoW timing
        async fn analysis_save(
            &self,
            captcha_id: &str,
            d: &CreatePerformanceAnalytics,
        ) -> DBResult<()> {
            let _ = sqlx::query!(
                "INSERT INTO mcaptcha_pow_analytics
                (config_id, time, difficulty_factor, worker_type)
            VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?, ?, ?)",
                captcha_id,
                d.time as i32,
                d.difficulty_factor as i32,
                &d.worker_type,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// fetch PoW analytics
        async fn analytics_fetch(
            &self,
            captcha_id: &str,
            limit: usize,
            offset: usize,
        ) -> DBResult<Vec<PerformanceAnalytics>> {
            struct P {
                id: i32,
                time: i32,
                difficulty_factor: i32,
                worker_type: String,
            }

            impl From<P> for PerformanceAnalytics {
                fn from(v: P) -> Self {
                    Self {
                        id: v.id as usize,
                        time: v.time as u32,
                        difficulty_factor: v.difficulty_factor as u32,
                        worker_type: v.worker_type,
                    }
                }
            }

            let mut c = sqlx::query_as!(
                P,
                "SELECT
                    id, time, difficulty_factor, worker_type
                FROM
                    mcaptcha_pow_analytics
                WHERE
                    config_id = (
                        SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?
                    )
                ORDER BY ID
                LIMIT ? OFFSET ?",
                &captcha_id,
                limit as i64,
                offset as i64,
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            let mut res = Vec::with_capacity(c.len());
            for i in c.drain(0..) {
                res.push(i.into())
            }

            Ok(res)
        }

        /// Create psuedo ID against campaign ID to publish analytics
        async fn analytics_create_psuedo_id_if_not_exists(
            &self,
            captcha_id: &str,
        ) -> DBResult<()> {
            let id = Uuid::new_v4();
            sqlx::query!(
                "
                INSERT INTO
                    mcaptcha_psuedo_campaign_id (config_id, psuedo_id)
                VALUES (
                    (SELECT config_id FROM mcaptcha_config WHERE captcha_key = (?)),
                    ?
                );",
                captcha_id,
                &id.to_string(),
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Get psuedo ID from campaign ID
        async fn analytics_get_psuedo_id_from_capmaign_id(
            &self,
            captcha_id: &str,
        ) -> DBResult<String> {
            let res = sqlx::query_as!(
                PsuedoID,
                "SELECT psuedo_id FROM
                    mcaptcha_psuedo_campaign_id
                WHERE
                     config_id = (SELECT config_id FROM mcaptcha_config WHERE captcha_key = (?));
                ",
                captcha_id
            ).fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(res.psuedo_id)
        }

        /// Get campaign ID from psuedo ID
        async fn analytics_get_capmaign_id_from_psuedo_id(
            &self,
            psuedo_id: &str,
        ) -> DBResult<String> {
            struct ID {
                captcha_key: String,
            }

            let res = sqlx::query_as!(
                ID,
                "SELECT
                    captcha_key
                FROM
                    mcaptcha_config
                WHERE
                     config_id = (
                         SELECT
                             config_id
                         FROM
                             mcaptcha_psuedo_campaign_id
                         WHERE
                             psuedo_id = ?
                     );",
                psuedo_id
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(res.captcha_key)
        }

        async fn analytics_delete_all_records_for_campaign(
            &self,
            campaign_id: &str,
        ) -> DBResult<()> {
            let _ = sqlx::query!(
                "
            DELETE FROM
                mcaptcha_psuedo_campaign_id
            WHERE config_id = (
                SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?
            );",
                campaign_id
            )
            .execute(&self.pool)
            .await;

            let _ = sqlx::query!(
                "
                DELETE FROM
                    mcaptcha_pow_analytics
                WHERE
                    config_id = (
                        SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?
                ) ",
                campaign_id
            )
            .execute(&self.pool)
            .await;

            Ok(())
        }
        /// Get all psuedo IDs
        async fn analytics_get_all_psuedo_ids(&self, page: usize) -> DBResult<Vec<String>> {
            const LIMIT: usize = 50;
            let offset = LIMIT * page;

            let mut res = sqlx::query_as!(
                PsuedoID,
                "
                    SELECT
                        psuedo_id
                    FROM
                        mcaptcha_psuedo_campaign_id
                        ORDER BY ID ASC LIMIT ? OFFSET ?;",
                LIMIT as i64,
                offset as i64
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(res.drain(0..).map(|r| r.psuedo_id).collect())
        }

        /// Track maximum nonce received against captcha levels
        async fn update_max_nonce_for_level(
            &self,
            captcha_key: &str,
            difficulty_factor: u32,
            latest_nonce: u32,
        ) -> DBResult<()> {
            let latest_nonce = latest_nonce as i64;
            sqlx::query!(
                    "UPDATE mcaptcha_track_nonce SET nonce = ?
                    WHERE level_id =  (
                        SELECT
                            level_id
                        FROM
                            mcaptcha_levels
                        WHERE
                            config_id = (SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?)
                        AND
                            difficulty_factor = ?
                        )
                    AND nonce <= ?;",
                    latest_nonce,
                    &captcha_key,
                    difficulty_factor as i64,
                    latest_nonce
                )
                .execute(&self.pool).await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Get maximum nonce tracked so far for captcha levels
        async fn get_max_nonce_for_level(
            &self,
            captcha_key: &str,
            difficulty_factor: u32,
        ) -> DBResult<u32> {
            struct X {
                nonce: i32,
            }

            async fn inner_get_max_nonce(
                pool: &MySqlPool,
                captcha_key: &str,
                difficulty_factor: u32,
            ) -> DBResult<X> {
                sqlx::query_as!(
                    X,
                    "SELECT nonce FROM mcaptcha_track_nonce
                    WHERE level_id =  (
                        SELECT
                            level_id
                        FROM
                            mcaptcha_levels
                        WHERE
                            config_id = (SELECT config_id FROM mcaptcha_config WHERE captcha_key = ?)
                        AND
                            difficulty_factor = ?
                        );",
                    &captcha_key,
                    difficulty_factor as i32,
                )
                    .fetch_one(pool).await
                    .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))
            }

            let res = inner_get_max_nonce(&self.pool, captcha_key, difficulty_factor).await;
            if let Err(DBError::CaptchaNotFound) = res {
                sqlx::query!(
                    "INSERT INTO
                        mcaptcha_track_nonce (level_id, nonce)
                    VALUES  ((
                        SELECT
                            level_id
                        FROM
                            mcaptcha_levels
                        WHERE
                            config_id = (SELECT config_id FROM mcaptcha_config WHERE captcha_key =?)
                        AND
                            difficulty_factor = ?
                        ), ?);",
                    &captcha_key,
                    difficulty_factor as i32,
                    0,
                )
                .execute(&self.pool)
                .await
                    .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

                let res =
                    inner_get_max_nonce(&self.pool, captcha_key, difficulty_factor).await?;
                Ok(res.nonce as u32)
            } else {
                let res = res?;
                Ok(res.nonce as u32)
            }
        }

        /// Get number of analytics entries that are under a certain duration
        async fn stats_get_num_logs_under_time(&self, duration: u32) -> DBResult<usize> {
            struct Count {
                count: Option<i64>,
            }

            //"SELECT COUNT(*) FROM (SELECT difficulty_factor FROM mcaptcha_pow_analytics WHERE time <= ?) as count",
            let count = sqlx::query_as!(
                Count,
                "SELECT
                    COUNT(difficulty_factor) AS count
                FROM
                    mcaptcha_pow_analytics
                WHERE time <= ?;",
                duration as i32,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(count.count.unwrap_or_else(|| 0) as usize)
        }

        /// Get the entry at a location in the list of analytics entires under a certain time limited
        /// and sorted in ascending order
        async fn stats_get_entry_at_location_for_time_limit_asc(
            &self,
            duration: u32,
            location: u32,
        ) -> DBResult<Option<usize>> {
            struct Difficulty {
                difficulty_factor: Option<i32>,
            }

            match sqlx::query_as!(
                Difficulty,
                "SELECT
                difficulty_factor
            FROM
                mcaptcha_pow_analytics
            WHERE
                time <= ?
            ORDER BY difficulty_factor ASC LIMIT 1 OFFSET ?;",
                duration as i32,
                location as i64 - 1,
            )
            .fetch_one(&self.pool)
            .await
            {
                Ok(res) => Ok(Some(res.difficulty_factor.unwrap() as usize)),
                Err(sqlx::Error::RowNotFound) => Ok(None),
                Err(e) => Err(map_row_not_found_err(e, DBError::CaptchaNotFound)),
            }
        }

        /// Get all easy captcha configurations on instance
        async fn get_all_easy_captchas(
            &self,
            limit: usize,
            offset: usize,
        ) -> DBResult<Vec<EasyCaptcha>> {
            struct InnerEasyCaptcha {
                captcha_key: String,
                name: String,
                username: String,
                peak_sustainable_traffic: i32,
                avg_traffic: i32,
                broke_my_site_traffic: Option<i32>,
            }
            let mut inner_res = sqlx::query_as!(
                InnerEasyCaptcha,
                    "SELECT
                  mcaptcha_sitekey_user_provided_avg_traffic.avg_traffic,
                  mcaptcha_sitekey_user_provided_avg_traffic.peak_sustainable_traffic,
                  mcaptcha_sitekey_user_provided_avg_traffic.broke_my_site_traffic,
                  mcaptcha_config.name,
                  mcaptcha_users.name as username,
                  mcaptcha_config.captcha_key
                FROM
                  mcaptcha_sitekey_user_provided_avg_traffic
                INNER JOIN
                    mcaptcha_config
                ON
                    mcaptcha_config.config_id = mcaptcha_sitekey_user_provided_avg_traffic.config_id
                INNER JOIN
                    mcaptcha_users
                ON
                    mcaptcha_config.user_id = mcaptcha_users.ID
                ORDER BY mcaptcha_config.config_id
                LIMIT ? OFFSET ?",
                limit as i64,
                offset as i64
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::TrafficPatternNotFound))?;
            let mut res = Vec::with_capacity(inner_res.len());
            inner_res.drain(0..).for_each(|v| {
                res.push(EasyCaptcha {
                    key: v.captcha_key,
                    description: v.name,
                    username: v.username,
                    traffic_pattern: TrafficPattern {
                        broke_my_site_traffic: v
                            .broke_my_site_traffic
                            .as_ref()
                            .map(|v| *v as u32),
                        avg_traffic: v.avg_traffic as u32,
                        peak_sustainable_traffic: v.peak_sustainable_traffic as u32,
                    },
                })
            });
            Ok(res)
        }
    }

    #[derive(Clone)]
    struct Date {
        time: OffsetDateTime,
    }

    impl Date {
        fn dates_to_unix(mut d: Vec<Self>) -> Vec<i64> {
            let mut dates = Vec::with_capacity(d.len());
            d.drain(0..)
                .for_each(|x| dates.push(x.time.unix_timestamp()));
            dates
        }
    }

    fn now_unix_time_stamp() -> OffsetDateTime {
        OffsetDateTime::now_utc()
    }

    #[derive(Debug, Clone, PartialEq)]
    /// Represents notification
    pub struct InnerNotification {
        /// receiver name  of the notification
        pub name: String,
        /// heading of the notification
        pub heading: String,
        /// message of the notification
        pub message: String,
        /// when notification was received
        pub received: OffsetDateTime,
        /// db assigned ID of the notification
        pub id: i32,
    }

    impl From<InnerNotification> for Notification {
        fn from(n: InnerNotification) -> Self {
            Notification {
                name: Some(n.name),
                heading: Some(n.heading),
                message: Some(n.message),
                received: Some(n.received.unix_timestamp()),
                id: Some(n.id),
            }
        }
    }

    #[derive(Clone)]
    struct InternaleCaptchaConfig {
        config_id: i32,
        duration: i32,
        name: String,
        captcha_key: String,
    }

    impl From<InternaleCaptchaConfig> for Captcha {
        fn from(i: InternaleCaptchaConfig) -> Self {
            Self {
                config_id: i.config_id,
                duration: i.duration,
                description: i.name,
                key: i.captcha_key,
            }
        }
    }

    struct PsuedoID {
        psuedo_id: String,
    }