discret 0.6.2

A backend to create peer to peer (P2P) applications, using a GraphQL inspired syntax
Documentation
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
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
#![allow(dead_code)]
use std::collections::HashSet;

use rusqlite::{params_from_iter, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, oneshot};

use crate::{
    base64_decode, base64_encode,
    database::VEC_OVERHEAD,
    security::{uid_decode, uid_encode, Ed25519SigningKey, MeetingToken, Uid},
    Parameters, ParametersAdd,
};

use super::{
    edge::Edge,
    graph_database::GraphDatabaseService,
    node::{extract_json, Node},
    sqlite_database::{Database, Writeable},
    Error, ResultParser,
};

pub fn create_table(conn: &Connection) -> Result<(), rusqlite::Error> {
    conn.execute(
        "
        CREATE TABLE _configuration (
            key TEXT NOT NULL,
            value TEXT,
            PRIMARY KEY(key)
        ) WITHOUT ROWID, STRICT",
        [],
    )?;
    Ok(())
}

pub const SYSTEM_NAMESPACE: &str = "sys";
//name of the system entities
pub const ROOM_ENT: &str = "sys.Room";
pub const ROOM_ENT_SHORT: &str = "0.0";

pub const AUTHORISATION_ENT: &str = "sys.Authorisation";
pub const AUTHORISATION_ENT_SHORT: &str = "0.1";

pub const USER_AUTH_ENT: &str = "sys.UserAuth";
pub const USER_AUTH_ENT_SHORT: &str = "0.2";

pub const ENTITY_RIGHT_ENT: &str = "sys.EntityRight";
pub const ENTITY_RIGHT_ENT_SHORT: &str = "0.3";

pub const PEER_ENT: &str = "sys.Peer";
pub const PEER_ENT_SHORT: &str = "0.4";

//pub const ALLOWED_PEER_ENT: &str = "sys.AllowedPeer";
pub const ALLOWED_PEER_ENT_SHORT: &str = "0.5";

//pub const ALLOWED_HARDWARE_ENT: &str = "sys.AllowedHardware";
pub const ALLOWED_HARDWARE_ENT_SHORT: &str = "0.6";

//name of the system fields
pub const ID_FIELD: &str = "id";
pub const ROOM_ID_FIELD: &str = "room_id";
pub const CREATION_DATE_FIELD: &str = "cdate";
pub const MODIFICATION_DATE_FIELD: &str = "mdate";
pub const PEER_FIELD: &str = "sys_peer";
pub const ROOM_FIELD: &str = "sys_room";
pub const ENTITY_FIELD: &str = "_entity";
pub const JSON_FIELD: &str = "_json";
pub const BINARY_FIELD: &str = "_binary";
pub const VERIFYING_KEY_FIELD: &str = "verifying_key";
pub const SIGNATURE_FIELD: &str = "_signature";

//names of some authentication fields used during auth validation
pub const ROOM_ADMIN_FIELD: &str = "admin";
pub const ROOM_ADMIN_FIELD_SHORT: &str = "32";
pub const ROOM_AUTHORISATION_FIELD: &str = "authorisations";
pub const ROOM_AUTHORISATION_FIELD_SHORT: &str = "33";

//names of some authentication fields used during auth validation
pub const AUTH_RIGHTS_FIELD: &str = "rights";
pub const AUTH_RIGHTS_FIELD_SHORT: &str = "33";
pub const AUTH_USER_FIELD: &str = "users";
pub const AUTH_USER_FIELD_SHORT: &str = "34";
pub const AUTH_USER_ADMIN_FIELD: &str = "user_admin";
pub const AUTH_USER_ADMIN_FIELD_SHORT: &str = "35";

pub const USER_VERIFYING_KEY_SHORT: &str = "32";
pub const USER_ENABLED_SHORT: &str = "33";

pub const RIGHT_ENTITY_SHORT: &str = "32";
pub const RIGHT_MUTATE_SELF_SHORT: &str = "33";
pub const RIGHT_MUTATE_ALL_SHORT: &str = "34";

pub const PEER_PUB_KEY_SHORT: &str = "32";
pub const PEER_NAME_SHORT: &str = "33";

pub const ALLOWED_PEER_PEER_SHORT: &str = "32";
pub const ALLOWED_PEER_TOKEN_SHORT: &str = "33";
pub const ALLOWED_PEER_STATUS_SHORT: &str = "35";

pub const ALLOWED_HARDWARE_NAME_SHORT: &str = "32";
pub const ALLOWED_HARDWARE_STATUS_SHORT: &str = "33";

pub const SYSTEM_DATA_MODEL: &str = r#"
sys{
    // Entities for the authorisation model
    Room {
        admin: [sys.UserAuth],
        authorisations:[sys.Authorisation]
    }
    
    Authorisation( no_full_text_index) {
        name: String,
        rights:[sys.EntityRight] ,
        users:[sys.UserAuth],
        user_admin: [sys.UserAuth],
    }
    
    UserAuth{
        verif_key: Base64,
        enabled: Boolean default true,
    }
    
    EntityRight {
        entity: String,
        mutate_self: Boolean,
        mutate_all: Boolean,
    }

    Peer{
        pub_key: Base64 ,
        name: String default "anonymous"
    }

    AllowedPeer(no_full_text_index){
        peer: sys.Peer,
        meeting_token: Base64,
        last_connection: Integer default 0,
        status: String,
    }

    AllowedHardware{
        name: String,
        status: String default "enabled", //enabled, disabled, pending
    }

    OwnedInvite{
        room: Base64 nullable,
        authorisation: Base64 nullable,
    }

    Invite{
        invite_id: Base64,
        application : String,
        invite_sign: Base64,
    }

}"#;

#[derive(Deserialize, Clone)]
pub struct Peer {
    pub id: String,
    pub verifying_key: String,
}
impl Peer {
    pub fn create(id: Uid, meeting_pub_key: String) -> Node {
        let json = format!(
            r#"{{
                "{}": "{}", 
                "{}": "" 
            }}"#,
            PEER_PUB_KEY_SHORT, meeting_pub_key, PEER_NAME_SHORT
        );

        Node {
            id,
            room_id: None,
            cdate: 0,
            mdate: 0,
            _entity: PEER_ENT_SHORT.to_string(),
            _json: Some(json),
            ..Default::default()
        }
    }

    pub fn validate(peer: &Node) -> Result<(), Error> {
        if peer.room_id.is_some() {
            return Err(Error::InvalidPeerNode("room not empty".to_string()));
        }

        if !peer._entity.eq(PEER_ENT_SHORT) {
            return Err(Error::InvalidPeerNode("Invalid Entity".to_string()));
        }
        if peer.verify().is_err() {
            return Err(Error::InvalidPeerNode("Invalid Signature".to_string()));
        }
        Self::pub_key(peer)?;
        Ok(())
    }

    pub fn pub_key(peer: &Node) -> Result<Vec<u8>, Error> {
        if peer._json.is_none() {
            return Err(Error::InvalidPeerNode("empty json".to_string()));
        }
        let json = peer._json.as_ref().unwrap();
        let json: serde_json::Value = serde_json::from_str(json)?;
        let map = json
            .as_object()
            .ok_or(Error::InvalidJsonObject("Peer json".to_string()))?;

        let pub_key = map
            .get(PEER_PUB_KEY_SHORT)
            .ok_or(Error::InvalidJsonObject("Peer pub_key".to_string()))?;

        let pub_key = pub_key.as_str().ok_or(Error::InvalidJsonObject(
            "Peer pub_key is not a string".to_string(),
        ))?;

        let key = base64_decode(pub_key.as_bytes())?;

        Ok(key)
    }

    pub fn get_missing(
        keys: HashSet<Vec<u8>>,
        conn: &Connection,
    ) -> Result<HashSet<Vec<u8>>, Error> {
        let it = &mut keys.iter().peekable();
        let mut result = HashSet::with_capacity(keys.len());

        //limit the IN clause to a reasonable size, avoiding the 32766 parameter limit in sqlite
        let row_per_query = 500;
        let mut query_list = Vec::new();
        let mut row_num = 0;
        struct QueryParams<'a> {
            in_clause: String,
            ids: Vec<&'a Vec<u8>>,
        }
        let mut current_query = QueryParams {
            in_clause: String::new(),
            ids: Vec::new(),
        };

        while let Some(nid) = it.next() {
            current_query.in_clause.push('?');
            current_query.ids.push(nid);

            row_num += 1;
            if row_num < row_per_query {
                if it.peek().is_some() {
                    current_query.in_clause.push(',');
                }
            } else {
                query_list.push(current_query);
                row_num = 0;
                current_query = QueryParams {
                    in_clause: String::new(),
                    ids: Vec::new(),
                };
            }
            result.insert(nid.clone());
        }
        if !current_query.ids.is_empty() {
            query_list.push(current_query);
        }
        for current_query in &query_list {
            let ids = &current_query.ids;
            let in_clause = &current_query.in_clause;

            let query = format!(
                "SELECT verifying_key 
                FROM _node 
                WHERE _entity='{}' 
                AND verifying_key IN ({})
                AND room_id IS NULL",
                PEER_ENT_SHORT, in_clause
            );
            let mut stmt = conn.prepare(&query)?;
            let mut rows = stmt.query(params_from_iter(ids.iter()))?;
            while let Some(row) = rows.next()? {
                let veri: Vec<u8> = row.get(0)?;
                result.remove(&veri);
            }
        }
        Ok(result)
    }

    pub fn get_peers(
        keys: HashSet<Vec<u8>>,
        batch_size: usize,
        sender: &mpsc::Sender<Result<Vec<Node>, super::Error>>,
        conn: &Connection,
    ) -> Result<(), Error> {
        let it = &mut keys.iter().peekable();

        //limit the IN clause to a reasonable size, avoiding the 32766 parameter limit in sqlite
        let row_per_query = 500;
        let mut query_list = Vec::new();
        let mut row_num = 0;
        struct QueryParams<'a> {
            in_clause: String,
            ids: Vec<&'a Vec<u8>>,
        }
        let mut current_query = QueryParams {
            in_clause: String::new(),
            ids: Vec::new(),
        };

        while let Some(nid) = it.next() {
            current_query.in_clause.push('?');
            current_query.ids.push(nid);

            row_num += 1;
            if row_num < row_per_query {
                if it.peek().is_some() {
                    current_query.in_clause.push(',');
                }
            } else {
                query_list.push(current_query);
                row_num = 0;
                current_query = QueryParams {
                    in_clause: String::new(),
                    ids: Vec::new(),
                };
            }
        }
        if !current_query.ids.is_empty() {
            query_list.push(current_query);
        }
        let mut res = Vec::new();
        let mut len = 0;

        for current_query in &query_list {
            let ids = &current_query.ids;
            let in_clause = &current_query.in_clause;

            let query = format!(
                "SELECT id, room_id, cdate, mdate, _entity,_json, _binary, verifying_key, _signature  
                FROM _node 
                WHERE _entity='{}' 
                AND verifying_key IN ({})
                AND room_id IS NULL",
                PEER_ENT_SHORT, in_clause
            );
            let mut stmt = conn.prepare(&query)?;
            let mut rows = stmt.query(params_from_iter(ids.iter()))?;
            while let Some(row) = rows.next()? {
                let node = Node {
                    id: row.get(0)?,
                    room_id: row.get(1)?,
                    cdate: row.get(2)?,
                    mdate: row.get(3)?,
                    _entity: row.get(4)?,
                    _json: row.get(5)?,
                    _binary: row.get(6)?,
                    verifying_key: row.get(7)?,
                    _signature: row.get(8)?,
                    _local_id: None,
                };
                let size = bincode::serialized_size(&node)?;
                let insert_len = len + size + VEC_OVERHEAD;
                if insert_len > batch_size as u64 {
                    let ready = res;
                    res = Vec::new();
                    len = 0;
                    let s = sender.blocking_send(Ok(ready));
                    if s.is_err() {
                        break;
                    }
                } else {
                    len = insert_len;
                }

                res.push(node)
            }
        }
        if !res.is_empty() {
            let _ = sender.blocking_send(Ok(res));
        }
        Ok(())
    }

    pub fn get_node(
        verifying_key: Vec<u8>,
        conn: &Connection,
    ) -> Result<Option<Node>, rusqlite::Error> {
        let mut exists_stmt = conn.prepare_cached(
            "SELECT id, room_id, cdate, mdate, _entity,_json, _binary, verifying_key, _signature  
            FROM _node 
            WHERE _entity=? 
            AND verifying_key =?
            AND room_id IS NULL",
        )?;
        let peer: Option<Node> = exists_stmt
            .query_row((PEER_ENT_SHORT, &verifying_key), |row| {
                Ok(Node {
                    id: row.get(0)?,
                    room_id: row.get(1)?,
                    cdate: row.get(2)?,
                    mdate: row.get(3)?,
                    _entity: row.get(4)?,
                    _json: row.get(5)?,
                    _binary: row.get(6)?,
                    verifying_key: row.get(7)?,
                    _signature: row.get(8)?,
                    _local_id: None,
                })
            })
            .optional()?;
        Ok(peer)
    }
}

pub struct PeerNodes {
    pub nodes: Vec<Node>,
}
impl Writeable for PeerNodes {
    fn write(&mut self, conn: &Connection) -> std::result::Result<(), rusqlite::Error> {
        for node in &self.nodes {
            let mut exists_stmt =
                conn.prepare_cached("SELECT 1 FROM _node WHERE id = ? AND _entity = ?")?;
            let exists: Option<i64> = exists_stmt
                .query_row((node.id, &node._entity), |row| row.get(0))
                .optional()?;
            if exists.is_none() {
                let mut insert_stmt = conn.prepare_cached(
                    "INSERT INTO _node ( 
                        id,
                        room_id,
                        cdate,
                        mdate,
                        _entity,
                        _json,
                        _binary,
                        verifying_key,
                        _signature
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?
                    )",
                )?;
                insert_stmt.insert((
                    &node.id,
                    &node.room_id,
                    &node.cdate,
                    &node.mdate,
                    &node._entity,
                    &node._json,
                    &node._binary,
                    &node.verifying_key,
                    &node._signature,
                ))?;
            }
        }

        Ok(())
    }
}

pub enum Status {
    Enabled,
    Pending,
    // Disabled,
}
impl Status {
    pub fn value(&self) -> &str {
        match self {
            Status::Enabled => STATUS_ENABLED,
            Status::Pending => STATUS_PENDING,
            // Status::Disabled => STATUS_DISABLED,
        }
    }
}

pub const STATUS_ENABLED: &str = "enabled";
pub const STATUS_PENDING: &str = "pending";
//pub const STATUS_DISABLED: &str = "disabled";

#[derive(Deserialize, Clone)]
pub struct AllowedPeer {
    pub peer: Peer,
    //  pub status: String,
    pub meeting_token: String,
}
impl AllowedPeer {
    pub fn create(
        id: Uid,
        private_room_id: Uid,
        token: String,
        peer_id: Uid,
        status: Status,
    ) -> (Node, Edge) {
        let json = format!(
            r#"{{ 
                "{}": "{}",
                "{}": "{}"
            }}"#,
            ALLOWED_PEER_TOKEN_SHORT,
            token,
            ALLOWED_PEER_STATUS_SHORT,
            status.value()
        );

        let node = Node {
            id,
            room_id: Some(private_room_id),
            cdate: 0,
            mdate: 0,
            _entity: ALLOWED_PEER_ENT_SHORT.to_string(),
            _json: Some(json),
            ..Default::default()
        };

        let edge = Edge {
            src: id,
            src_entity: ALLOWED_PEER_ENT_SHORT.to_string(),
            label: ALLOWED_PEER_PEER_SHORT.to_string(),
            dest: peer_id,
            cdate: 0,
            ..Default::default()
        };

        (node, edge)
    }

    pub async fn add(
        room_id: &str,
        verifying_key: &str,
        meeting_token: &str,
        status: Status,
        db: &GraphDatabaseService,
    ) -> Result<Self, crate::Error> {
        let query = "query {
            result: sys.Peer(verifying_key=$verifying_key){
                id
                verifying_key
            }
        }";

        let mut param = Parameters::new();
        param.add("verifying_key", verifying_key.to_string())?;

        let peer_str = db.query(query, Some(param)).await?;

        let mut query_result: ResultParser = ResultParser::new(&peer_str)?;
        let mut result: Vec<Peer> = query_result.take_array("result")?;

        if result.is_empty() {
            return Err(crate::Error::from(Error::UnknownPeer()));
        }

        let peer_obj = result.pop().unwrap();
        let peer_id = peer_obj.id.clone();

        let query = "query {
            result: sys.AllowedPeer(room_id=$room_id){
                meeting_token
                status
                peer(id=$peer_id){
                    id
                    verifying_key
                }
            }
        }";

        let mut param = Parameters::new();
        param.add("room_id", room_id.to_string())?;
        param.add("peer_id", peer_id.to_string())?;
        let peer_str = db.query(query, Some(param)).await?;
        let mut query_result: ResultParser = ResultParser::new(&peer_str)?;
        let mut result: Vec<AllowedPeer> = query_result.take_array("result")?;

        if !result.is_empty() {
            return Ok(result.pop().unwrap());
        }

        let mut param = Parameters::new();
        param.add("room_id", room_id.to_string())?;
        param.add("peer_id", peer_id.to_string())?;
        param.add("meeting_token", meeting_token.to_string())?;
        param.add("status", status.value().to_string())?;
        db.mutate(
            "mutate {
                result: sys.AllowedPeer{
                    room_id: $room_id
                    meeting_token: $meeting_token
                    status: $status
                    peer: {id:$peer_id}
                }
            }",
            Some(param),
        )
        .await?;

        Ok(Self {
            peer: peer_obj,
            // status: status.value().to_string(),
            meeting_token: meeting_token.to_string(),
        })
    }

    pub async fn get(
        room_id: String,
        status: Status,
        db: &GraphDatabaseService,
    ) -> Result<Vec<AllowedPeer>, crate::Error> {
        let query = "query {
            result: sys.AllowedPeer(room_id=$room_id, status=$status){
                meeting_token
                status
                peer {
                    id
                    verifying_key
                }
            }
        }";

        let mut param = Parameters::new();
        param.add("room_id", room_id)?;
        param.add("status", status.value().to_string())?;

        let peer_str = db.query(query, Some(param)).await?;
        let mut query_result: ResultParser = ResultParser::new(&peer_str)?;
        let result: Vec<AllowedPeer> = query_result.take_array("result")?;

        Ok(result)
    }
}

pub struct AllowedPeerWriter(pub Node, pub Edge);
impl Writeable for AllowedPeerWriter {
    fn write(&mut self, conn: &Connection) -> std::result::Result<(), rusqlite::Error> {
        self.0.write(conn, false, &None, &None)?;
        self.1.write(conn)?;
        Ok(())
    }
}
pub async fn init_allowed_peers(
    database: &Database,
    peer_uid: Uid,
    public_key: &[u8; 32],
    allowed_uid: Uid,
    private_room_id: Uid,
    token: MeetingToken,
    signing_key: &Ed25519SigningKey,
) -> Result<(), Error> {
    //init peer entity
    let (reply, receive) = oneshot::channel::<Result<bool, Error>>();
    database
        .reader
        .send_async(Box::new(move |conn| {
            let room_node = Node::exist(&peer_uid, PEER_ENT_SHORT, conn);
            let _ = reply.send(room_node);
        }))
        .await?;
    let exists = receive.await??;
    if !exists {
        let mut peer_node = Peer::create(peer_uid, base64_encode(public_key));
        peer_node.sign(signing_key)?;

        let mut index = String::new();
        let val = serde_json::from_str(&peer_node._json.clone().unwrap())?;
        extract_json(&val, &mut index)?;
        let peer_writer = PeerWriter {
            node: peer_node,
            index,
        };

        database.writer.write(Box::new(peer_writer)).await?;
    }

    //init allowed_peer entity
    let (reply, receive) = oneshot::channel::<Result<bool, Error>>();
    database
        .reader
        .send_async(Box::new(move |conn| {
            let room_node = Node::exist(&allowed_uid, ALLOWED_PEER_ENT_SHORT, conn);
            let _ = reply.send(room_node);
        }))
        .await?;
    let exists = receive.await??;

    if !exists {
        let (mut all_node, mut all_edge) = AllowedPeer::create(
            allowed_uid,
            private_room_id,
            base64_encode(&token),
            peer_uid,
            Status::Enabled,
        );
        all_node.sign(signing_key)?;
        all_edge.sign(signing_key)?;

        let writer = AllowedPeerWriter(all_node, all_edge);
        database.writer.write(Box::new(writer)).await?;
    }

    Ok(())
}

//Initialised Peers needs to be inserted with the ftse index, otherwise it is not possible to update their name without getting ans horrible:'database disk image is malformed' error
pub struct PeerWriter {
    pub node: Node,
    pub index: String,
}
impl Writeable for PeerWriter {
    fn write(&mut self, conn: &Connection) -> std::result::Result<(), rusqlite::Error> {
        let mut insert_stmt = conn.prepare_cached(
            "INSERT INTO _node ( 
                        id,
                        room_id,
                        cdate,
                        mdate,
                        _entity,
                        _json,
                        _binary,
                        verifying_key,
                        _signature
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?
                    )",
        )?;
        let rowid = insert_stmt.insert((
            &self.node.id,
            &self.node.room_id,
            &self.node.cdate,
            &self.node.mdate,
            &self.node._entity,
            &self.node._json,
            &self.node._binary,
            &self.node.verifying_key,
            &self.node._signature,
        ))?;
        static UPDATE_FTS_QUERY: &str = "INSERT INTO _node_fts (rowid, text) VALUES (?, ?)";

        if !self.index.is_empty() {
            let mut insert_fts_stmt = conn.prepare_cached(UPDATE_FTS_QUERY)?;
            insert_fts_stmt.execute((rowid, &self.index))?;
        }
        Ok(())
    }
}

#[derive(Deserialize)]
pub struct AllowedHardware {
    pub id: String,
    pub name: String,
    pub status: String,
}
impl AllowedHardware {
    pub async fn get(
        id: Uid,
        private_room_id: Uid,
        status: &str,
        db: &GraphDatabaseService,
    ) -> Result<Option<Self>, crate::Error> {
        let mut param = Parameters::new();
        param.add("room_id", uid_encode(&private_room_id))?;
        param.add("id", uid_encode(&id))?;
        param.add("status", status.to_string())?;

        let res = db
            .query(
                r#"query {
                result: sys.AllowedHardware(id=$id, room_id=$room_id, status=$status){
                        id
                        name
                        status
                    }
                }"#,
                Some(param),
            )
            .await?;
        let mut query_result: ResultParser = ResultParser::new(&res)?;
        let mut result: Vec<Self> = query_result.take_array("result")?;
        Ok(result.pop())
    }

    pub async fn put(
        id: Uid,
        private_room_id: Uid,
        name: &str,
        status: &str,
        db: &GraphDatabaseService,
    ) -> Result<(), Error> {
        let json = format!(
            r#"{{ 
                "{}": "{}",
                "{}": "{}"
            }}"#,
            ALLOWED_HARDWARE_NAME_SHORT, name, ALLOWED_HARDWARE_STATUS_SHORT, status
        );

        let (reply, receive) = oneshot::channel::<Result<Option<Box<Node>>, rusqlite::Error>>();
        db.db
            .reader
            .send_async(Box::new(move |conn| {
                let room_node =
                    Node::get_in_room(&id, &private_room_id, ALLOWED_HARDWARE_ENT_SHORT, conn);
                let _ = reply.send(room_node);
            }))
            .await?;
        let existing = receive.await??;

        let mut node = match existing {
            Some(node) => *node,
            None => Node {
                id,
                room_id: Some(private_room_id),
                cdate: 0,
                mdate: 0,
                _entity: ALLOWED_HARDWARE_ENT_SHORT.to_string(),
                _json: None,
                ..Default::default()
            },
        };
        node._json = Some(json);
        db.db.writer.write(Box::new(node)).await?;
        Ok(())
    }
}

#[derive(Clone)]
pub struct OwnedInvite {
    pub id: Uid,
    pub room: Option<Uid>,
    pub authorisation: Option<Uid>,
}
impl OwnedInvite {
    pub async fn delete(id: Uid, db: &GraphDatabaseService) -> Result<(), Error> {
        let mut param = Parameters::new();
        param.add("id", uid_encode(&id))?;
        db.delete(
            "delete { 
            sys.OwnedInvite{
                $id
            }
        }",
            Some(param),
        )
        .await?;
        Ok(())
    }

    pub async fn list_valid(
        room_id: String,
        db: &GraphDatabaseService,
    ) -> Result<Vec<Self>, crate::Error> {
        let mut param = Parameters::new();
        param.add("room_id", room_id)?;

        let result = db
            .query(
                "query{
            sys.OwnedInvite(room_id=$room_id, order_by(mdate desc)){
                id
                room
                authorisation
            }
        }",
                Some(param),
            )
            .await?;

        #[derive(Deserialize)]
        struct SerProdInvite {
            id: String,
            room: Option<String>,
            authorisation: Option<String>,
        }

        let mut list = Vec::new();
        let mut q = ResultParser::new(&result)?;
        let invites: Vec<SerProdInvite> = q.take_array("sys.OwnedInvite")?;
        for invite in invites {
            let id = uid_decode(&invite.id)?;
            let room = match invite.room {
                Some(v) => Some(uid_decode(&v)?),
                None => None,
            };
            let authorisation = match invite.authorisation {
                Some(v) => Some(uid_decode(&v)?),
                None => None,
            };

            list.push(Self {
                id,
                room,
                authorisation,
            })
        }
        Ok(list)
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub struct Invite {
    pub invite_id: Uid,
    pub application: String,
    pub invite_sign: Vec<u8>,
}
impl Invite {
    pub async fn create(
        room_id: String,
        default_room: Option<DefaultRoom>,
        application: String,
        db: &GraphDatabaseService,
    ) -> Result<(Self, OwnedInvite), Error> {
        let (default_room_id, default_auth_id) = match default_room.as_ref() {
            Some(r) => (
                Some(uid_decode(&r.room)?),
                Some(uid_decode(&r.authorisation)?),
            ),
            None => (None, None),
        };

        let (room, auth) = match default_room {
            Some(r) => (Some(r.room), Some(r.authorisation)),
            None => (None, None),
        };

        let mut param = Parameters::new();
        param.add("room_id", room_id)?;
        param.add("room", room)?;
        param.add("auth", auth)?;

        let res = db
            .mutate(
                "mutate {
            sys.OwnedInvite {
                room_id:$room_id
                room: $room
                authorisation: $auth 
            }
        }",
                Some(param),
            )
            .await?;
        #[derive(Deserialize)]
        struct Id {
            id: String,
        }
        let mut parser = ResultParser::new(&res).unwrap();
        let id: Id = parser.take_object("sys.OwnedInvite").unwrap();

        let invite_id = id.id;
        let invite_id = uid_decode(&invite_id)?;
        let hash_val = Self::hash_val(invite_id, &application);
        let (_key, invite_sign) = db.sign(hash_val).await;

        let invite = Self {
            invite_id,
            application,
            invite_sign,
        };

        let owned = OwnedInvite {
            id: invite_id,
            room: default_room_id,
            authorisation: default_auth_id,
        };

        Ok((invite, owned))
    }

    pub async fn delete(
        room_id: String,
        invite_id: Uid,
        db: &GraphDatabaseService,
    ) -> Result<(), crate::Error> {
        let mut param = Parameters::new();
        param.add("room_id", room_id.clone())?;
        param.add("invite_id", uid_encode(&invite_id))?;

        let result = db
            .query(
                "query{
        sys.Invite(room_id=$room_id, invite_id = $invite_id){
                id
            }
        }",
                Some(param),
            )
            .await?;

        #[derive(Deserialize)]
        struct InvId {
            id: String,
        }

        let mut q = ResultParser::new(&result)?;
        let ids: Vec<InvId> = q.take_array("sys.Invite")?;

        for id in ids {
            let mut param = Parameters::new();
            param.add("id", id.id)?;

            db.delete(
                "delete {
            sys.Invite{
                $id
            }
        }",
                Some(param),
            )
            .await?;
        }

        Ok(())
    }

    pub async fn insert(
        &self,
        room_id: String,
        db: &GraphDatabaseService,
    ) -> Result<(), crate::Error> {
        let mut param = Parameters::new();
        param.add("room_id", room_id.clone())?;
        param.add("invite_id", uid_encode(&self.invite_id))?;

        let result = db
            .query(
                "query{
            sys.Invite(room_id=$room_id,invite_id=$invite_id ){
                id
            }
        }",
                Some(param),
            )
            .await?;

        #[derive(Deserialize)]
        struct InvId {
            id: String,
        }
        let mut q = ResultParser::new(&result)?;
        let ids: Vec<InvId> = q.take_array("sys.Invite")?;

        if !ids.is_empty() {
            return Ok(());
        }

        let mut param = Parameters::new();
        param.add("room_id", room_id)?;
        param.add("invite_id", uid_encode(&self.invite_id))?;
        param.add("application", self.application.clone())?;
        param.add("invite_sign", base64_encode(&self.invite_sign))?;

        db.mutate(
            "mutate {
            sys.Invite {
                room_id: $room_id
                invite_id: $invite_id
                application: $application
                invite_sign: $invite_sign
            }
        }",
            Some(param),
        )
        .await?;
        Ok(())
    }

    pub async fn list(
        room_id: String,
        db: &GraphDatabaseService,
    ) -> Result<Vec<Self>, crate::Error> {
        let mut param = Parameters::new();
        param.add("room_id", room_id)?;

        let result = db
            .query(
                "query{
            sys.Invite(room_id=$room_id, order_by(mdate desc)){
                invite_id
                application
                invite_sign
            }
        }",
                Some(param),
            )
            .await?;

        #[derive(Deserialize)]
        struct SerInvite {
            invite_id: String,
            application: String,
            invite_sign: String,
        }

        let mut list = Vec::new();
        let mut q = ResultParser::new(&result)?;
        let invites: Vec<SerInvite> = q.take_array("sys.Invite")?;
        for invite in invites {
            let invite_id = uid_decode(&invite.invite_id)?;
            let application = invite.application;
            let invite_sign = base64_decode(invite.invite_sign.as_bytes())?;

            list.push(Self {
                invite_id,
                application,
                invite_sign,
            })
        }
        Ok(list)
    }

    pub fn hash(&self) -> Vec<u8> {
        Self::hash_val(self.invite_id, &self.application)
    }

    fn hash_val(invite_id: Uid, application: &String) -> Vec<u8> {
        let mut hasher = blake3::Hasher::new();
        hasher.update(&invite_id);
        hasher.update(application.as_bytes());
        let hash = hasher.finalize();
        hash.as_bytes().to_vec()
    }
}

///
/// When creating an invitation, you may specify a default room and authorisation.
/// A new peer using this invitation will be provided access to this room.
///
pub struct DefaultRoom {
    // The room identifier
    pub room: String,

    // An authorisation identifier that belongs to the room
    pub authorisation: String,
}

#[cfg(test)]
mod tests {
    use crate::security::{Ed25519SigningKey, HardwareFingerprint};
    use crate::Configuration;
    use crate::{event_service::EventService, security::random32};

    use crate::database::sqlite_database::prepare_connection;

    use super::*;

    use std::{fs, path::PathBuf};
    const DATA_PATH: &str = "test_data/database/system_entities/";
    fn init_database_path() {
        let path: PathBuf = DATA_PATH.into();
        fs::create_dir_all(&path).unwrap();
    }
    #[test]
    fn peer() {
        let conn1 = Connection::open_in_memory().unwrap();
        prepare_connection(&conn1).unwrap();

        let num_peer = 10;
        let mut peers = HashSet::with_capacity(num_peer);

        for _ in 0..num_peer {
            let keypair = Ed25519SigningKey::new();
            let mut node = Node {
                _entity: PEER_ENT_SHORT.to_string(),
                ..Default::default()
            };
            node.sign(&keypair).unwrap();
            assert!(node.verify().is_ok());
            peers.insert(node.verifying_key.clone());
            node.write(&conn1, false, &None, &None).unwrap();
        }

        let conn2 = Connection::open_in_memory().unwrap();
        prepare_connection(&conn2).unwrap();

        let missing_1 = Peer::get_missing(peers.clone(), &conn1).unwrap();
        assert_eq!(missing_1.len(), 0);

        let missing = Peer::get_missing(peers.clone(), &conn2).unwrap();
        assert_eq!(missing.len(), num_peer);

        let keys = missing.into_iter().collect();
        let (reply, mut receive) = mpsc::channel::<Result<Vec<Node>, Error>>(1);

        Peer::get_peers(keys, 400 * 1024, &reply, &conn1).unwrap();

        let nodes = receive.blocking_recv().unwrap().unwrap();
        assert_eq!(nodes.len(), num_peer);

        let mut pn = PeerNodes { nodes };

        pn.write(&conn2).unwrap();

        let missing = Peer::get_missing(peers, &conn2).unwrap();
        assert_eq!(missing.len(), 0);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn init_allowed_peer() {
        init_database_path();

        let path: PathBuf = DATA_PATH.into();
        let secret = random32();
        let pub_key = &random32();

        let base_result = {
            let (app, _verifying_key, _private_room) = GraphDatabaseService::start(
                "authorisation app",
                "",
                &secret,
                &pub_key,
                path.clone(),
                &Configuration::default(),
                EventService::new(),
            )
            .await
            .unwrap();

            let res = app
                .query(
                    "query {
                    sys.AllowedPeer{
                        meeting_token
                        status
                        peer {
                            id
                            mdate
                            cdate
                            verifying_key
                            pub_key
                        }
                    }
                }",
                    None,
                )
                .await
                .unwrap();

            assert!(res.len() > 240); //make sure that it contains stuff

            res
        };
        {
            let (app, _verifying_key, _private_room) = GraphDatabaseService::start(
                "authorisation app",
                "",
                &secret,
                &pub_key,
                path,
                &Configuration::default(),
                EventService::new(),
            )
            .await
            .unwrap();

            let res = app
                .query(
                    "query {
                    sys.AllowedPeer{
                        meeting_token
                        status
                        peer {
                            id
                            mdate
                            cdate
                            verifying_key
                            pub_key
                        }
                    }
                }",
                    None,
                )
                .await
                .unwrap();
            //ensure that we get the same result when reading the same database again
            assert_eq!(res, base_result);
        }

        let path: PathBuf = format!("{}/otherpaht", DATA_PATH).into();
        let (app, _verifying_key, _private_room) = GraphDatabaseService::start(
            "authorisation app",
            "",
            &secret,
            &pub_key,
            path,
            &Configuration::default(),
            EventService::new(),
        )
        .await
        .unwrap();

        let res = app
            .query(
                "query {
                sys.AllowedPeer{
                    meeting_token
                    status
                    peer {
                        id
                        mdate
                        cdate
                        verifying_key
                        pub_key
                    }
                }
            }",
                None,
            )
            .await
            .unwrap();
        //ensure that we get the same result when creating a database with the same credentials
        assert_eq!(res, base_result);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn get_allowed() {
        init_database_path();

        let path: PathBuf = DATA_PATH.into();
        let secret = random32();
        let pub_key = &random32();

        let (app, _verifying_key, private_room) = GraphDatabaseService::start(
            "authorisation app",
            "",
            &secret,
            &pub_key,
            path.clone(),
            &Configuration::default(),
            EventService::new(),
        )
        .await
        .unwrap();

        let list = app.get_allowed_peers(private_room).await.unwrap();

        assert_eq!(1, list.len());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hardware() {
        init_database_path();

        let path: PathBuf = DATA_PATH.into();
        let secret = random32();
        let pub_key = &random32();

        let (app, _verifying_key, private_room) = GraphDatabaseService::start(
            "authorisation app",
            "",
            &secret,
            &pub_key,
            path.clone(),
            &Configuration::default(),
            EventService::new(),
        )
        .await
        .unwrap();

        let mut finger_path = path.clone();
        finger_path.push("hardwarefingerprint.bin");
        let hardware = HardwareFingerprint::get(&finger_path).unwrap();

        let status = "allowed";

        AllowedHardware::put(hardware.id, private_room, &hardware.name, status, &app)
            .await
            .unwrap();

        let allowed = AllowedHardware::get(hardware.id, private_room, status, &app)
            .await
            .unwrap();

        assert!(allowed.is_some());
        let allowed = allowed.unwrap();
        assert_eq!(hardware.name, allowed.name);
        assert_eq!(status, allowed.status);

        let disabled = "disabled";
        AllowedHardware::put(hardware.id, private_room, &hardware.name, disabled, &app)
            .await
            .unwrap();

        let allowed = AllowedHardware::get(hardware.id, private_room, status, &app)
            .await
            .unwrap();

        assert!(allowed.is_none());

        let allowed = AllowedHardware::get(hardware.id, private_room, disabled, &app)
            .await
            .unwrap();

        assert!(allowed.is_some());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn invite() {
        init_database_path();

        let path: PathBuf = DATA_PATH.into();
        let secret = random32();
        let pub_key = &random32();

        let (db, _verifying_key, private_room) = GraphDatabaseService::start(
            "authorisation app",
            "",
            &secret,
            &pub_key,
            path.clone(),
            &Configuration::default(),
            EventService::new(),
        )
        .await
        .unwrap();

        let (invite, _) = Invite::create(
            uid_encode(&private_room),
            None,
            "authorisation app".to_string(),
            &db,
        )
        .await
        .unwrap();

        let prod_list = OwnedInvite::list_valid(uid_encode(&private_room), &db)
            .await
            .unwrap();

        assert_eq!(prod_list.len(), 1);

        for prod in prod_list {
            OwnedInvite::delete(prod.id, &db).await.unwrap();
        }

        invite.insert(uid_encode(&private_room), &db).await.unwrap();
        invite.insert(uid_encode(&private_room), &db).await.unwrap();
        invite.insert(uid_encode(&private_room), &db).await.unwrap();
        invite.insert(uid_encode(&private_room), &db).await.unwrap();

        let prod_list = OwnedInvite::list_valid(uid_encode(&private_room), &db)
            .await
            .unwrap();
        assert_eq!(prod_list.len(), 0);

        let ins_list = Invite::list(uid_encode(&private_room), &db).await.unwrap();
        assert_eq!(ins_list.len(), 1);
        Invite::delete(uid_encode(&private_room), invite.invite_id, &db)
            .await
            .unwrap();

        let ins_list = Invite::list(uid_encode(&private_room), &db).await.unwrap();
        assert_eq!(ins_list.len(), 0);

        let bin_invite = bincode::serialize(&invite).unwrap();
        println!("Invite: {}", base64_encode(&bin_invite));

        drop(db);
    }
}