-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.js
1239 lines (1192 loc) · 39.5 KB
/
client.js
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
//===============================================
// CLEAR GUN DATABASE
localStorage.clear();
//(function() {
//===============================================
// INIT GUN DATABASE
let gunurl = window.location.origin+'/gun';
//console.log(gunurl);
var gun = Gun(gunurl);
gun.on('hi', peer => {//peer connect
console.log('connect peer to',peer);
//console.log('peer connect!');
});
gun.on('bye', (peer)=>{// peer disconnect
console.log('disconnected from', peer);
//console.log('disconnected from peer!');
});
gun.get('mark').put({
name: "Mark",
email: "[email protected]",
});
let doc = document.getElementById('guntext');
gun.get('mark').on(function(data, key){
//console.log("update:", data);
doc.innerText = data.name;
});
//gun.get('~@test').map(function(data,key){//user
//console.log("data",data);
//});
const PERMISSIONS = [
{ name: "clipboard-read" },
{ name: "clipboard-write" }
];
/** Watch for pastes */
navigator.clipboard.addEventListener('clipboardchange', e => {
navigator.clipboard.getText().then( text => {
log('Updated clipboard contents: '+text)
})
});
//===============================================
// TESTING LOGIN / DO NOT USED PRODUCTION!
var users=[];
users.push({index:0,value:"beta",passphrase:"test"});
users.push({index:1,value:"alpha",passphrase:"test"});
users.push({index:1,value:"delta",passphrase:"test"});
users.push({index:2,value:"bbb",passphrase:"test"});
users.push({index:3,value:"test",passphrase:"test"});
$("#users").change(function(){
//console.log("selected");
let idx=$(this).val();
//console.log(idx);
if(users[idx]!=null){
$('#alias').val(users[idx].value);
$('#passphrase').val(users[idx].passphrase);
}
});
function addusers(index, data) {
//console.log("index",index);console.log("value",data);
$('#users').append($('<option/>', {
value: index,
text : data.value
}));
}
$.each(users,addusers);
//===============================================
// TEST GUN / USER
$("#btngun").click(async function(){
//console.dir(Gun);
//console.log(gun);
var list = gun.get('clist');
//list.set({name:"test1",x:0,y:0,z:0});
//list.set({name:"test3",x:0,y:0,z:0});
//list.get('123').put({name:"test1",x:1,y:0,z:0});
//list.get('223').put({name:"test2",x:2,y:0,z:0});
//list.get('323').put({name:"test3",x:3,y:0,z:0});
//list.get('423').put({name:"test4",x:3,y:0,z:0});
//list.get('523').put({name:"test5",x:3,y:0,z:0});
//console.log(list);
console.log(list._.map);
console.log(list._.next);
if(list._.next !=null){
//console.log(list._.next.length);
let i = 0;
for(var o in list._.next){
i++;
console.log(o);
}
console.log(i)
}
//list.on(function(data,key){
//console.log('data',data);
//console.log('key',key);
//});
//list.once().map().once(function(data, key){
//console.log("data > ", data);
//console.log("key > ", key);
//});
console.log(list.map())
list.map().once(function(data, key){
console.log("data > ", data);
//console.log("key > ", key);
});
//setTimeout(function(){
//console.log("init gun...");
//}, 1000);
//gun.get('~@test').once(ack=>{
//console.log(ack);
//});
});
$("#btnuser").click(function(){
let user = gun.user();
console.log(user);
//let user = gun.user();
//let sec = await SEA.work("foo", "bar");
//let mix = await SEA.encrypt("bar", sec);
//mix = JSON.stringify(mix)
//console.log(mix);
//gun.get('any'+user.is.pub+'graph').get('foo').put(mix);
//gun.get(user.is.pub).get('foo').put(mix);
//console.log(user.is.pub);
//gun.get('any'+user.is.pub+'graph').get('foo').once(ack=>{
//console.log(ack);
//});
//gun.get(user.is.pub).get('foo').once((data,key)=>{
//console.log(data);
//});
});
function setClipboard(value) {
var tempInput = document.createElement("input");
tempInput.style = "position: absolute; left: -1000px; top: -1000px";
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
navigator.clipboard.writeText(value)
.then(() => {
// Success!
console.log("COPY IT?")
})
.catch(err => {
console.log('Something went wrong', err);
});
}
$("#aliaskeycopy").click(function(){
let user = gun.user();
if(!user.is)return;
//console.log(user.is.pub);
setClipboard(user.is.pub);
});
//===============================================
// LOGIN
//===============================================
$("#btnlogin").click(function(){
//console.log("LOGIN......");
let user = gun.user();
//console.log($('#alias').val());
//console.log($('#passphrase').val());
user.auth($('#alias').val(), $('#passphrase').val(),(ack)=>{//user login username and password
if(ack.err){
console.log(ack.err);
//modalmessage(ack.err);
}else{
//console.log(ack);
//modalmessage(ack);
$("#login").hide();
$("#profile").show();
selectactive("btnprofile");
//$("#messages").show();
//$("#publicchat").show();
//$("#privatechat").show();
$('#username').text($('#alias').val());
$('#aliaskeycopy').text("Alias:"+$('#alias').val()+" (Key Copy)");
user.get('profile').get('alias').decryptonce(ack=>{//get user profile alias key for value
//console.log(ack);
$('#inputalias').val(ack);
});
$('#aliaspublickey').val(ack.sea.pub);
updateContacts();
$("#navmenu").show();
}
});
});
$("#btnforgot").click(function(){
$('#login').hide();
$('#forgot').show();
});
//===============================================
// REGISTER
$("#btnregister").click(function(){
let user = gun.user();
user.create($('#alias').val(), $('#passphrase').val(),(ack)=>{//create user and password
if(ack.err){
console.log(ack.err);//if user exist or error
}else{
console.log(ack);//pass if created
modalmessage("Created " + $('#alias').val() + "!");
}
});
});
//===============================================
// FORGOT
$("#btnforgothint").click(async function(){
//let user = gun.user();
let alias = $('#falias').val();
alias = await gun.get('~@'+alias).then();//reused variable
if(!alias){//check user exist if not return false.
modalmessage('Not Found Alias!');
return;
}
let publickey;
for(let obj in alias){//object
//console.log(obj);
publickey = obj;//property name for public key
}
publickey = SEA.opt.pub(publickey);//check and convert to key or null?
//console.log(publickey);
let q1 = ($('#fquestion1').val() || '').trim(); //get id fquestion1 input
let q2 = ($('#fquestion2').val() || '').trim(); //get id fquestion2 input
if((!q1)||(!q2)){
//console.log('Q Empty!');
modalmessage('"Question (1 || 2) Empty!"');
return;
}
let to = gun.user(publickey);//get user alias graph
let hint = await to.get('hint').then();//get encrypt hint key graph
let dec = await Gun.SEA.work(q1,q2);//get fquestion1 and fquestion2 string to mix key
hint = await Gun.SEA.decrypt(hint,dec);//get hint and key decrypt message
//console.log(hint);
if(hint !=null){//check if hint is string or null
$('#fhint').val(hint);
}else{
modalmessage("Fail Decrypt!");
}
});
$("#btnbacklogin").click(function(){
$('#login').show();
$('#forgot').hide();
});
//===============================================
// PROFILE
$('#copypublickey').click(function(){//select input text and copy command to clipboard
$('#aliaspublickey').select();
document.execCommand('copy');
navigator.clipboard.writeText($('#aliaspublickey').val())
.then(() => {
// Success!
console.log("COPY IT?")
})
.catch(err => {
console.log('Something went wrong', err);
});
});
$("#inputalias").keyup(function() {
let aliasval = $("#inputalias").val();
//console.log(aliasval);
let user = gun.user();
user.get('profile').get('alias').encryptput($("#inputalias").val());
});
$("#getalias").click(function(){
let user = gun.user();
//user.get('profile').get('alias').decryptonce(ack=>{
//console.log(ack);
//});
user.get('profile').get('alias').once(ack=>{
console.log(ack);
});
});
$("#grantkey").click(async function(){
let user = gun.user();
let key = $('#accesskey').val();
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
//console.log(who);
if(who != null){
console.log("PASS");
modalmessage("Grant access:" + who);
user.get('profile').get('alias').grantkey(to);//grant key
}else{
console.log("FAIL");
modalmessage("Grant access fail!");
}
});
//USER REVOKE KEY
$("#revokekey").click(async function(){
let user = gun.user();
let key = $('#accesskey').val();
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
//console.log(who);
if(who != null){
console.log("PASS");
user.get('profile').get('alias').revokekey(to);//revoke key
modalmessage("Revoke access:" + who);
}else{
console.log("FAIL");
modalmessage("Revoke access fail!");
}
});
//USER GENERATE KEY
$("#btnmainsharedatagenkey").click(async function(){
let user = gun.user();
user.get('sharedata').get('access').get('key').trustgenkey();
});
// USER GET KEY LATEST
$("#btnmainsharedatalatestkey").click(async function(){
let user = gun.user();
user.get('sharedata').get('access').get('key').trustgetkey((ack)=>{
console.log("////==========");
console.log(ack);
console.log("////==========");
});
});
//
$("#putvalue").click(async function(){
let key = $('#inputsearchpublickey').val(); //public key
let keyvalue = $('#dataalias').val();// input text
keyvalue="helloworld";
console.log(keyvalue);
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
//console.log(who);
if(who != null){
console.log("PASS");
to.get('profile').get('alias').encryptput(keyvalue);// encrypt value | data
}else{
console.log("FAIL");
}
});
//https://github.com/amark/gun/blob/master/lib/mix.js
//USER TRUST PUBLIC KEY
$("#btnmainsharedatrust").click(async function(){
let user = gun.user();
let key = $('#accesskey').val();
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
//console.log(who);
if(who != null){
console.log("PASS");
user.get('sharedata').get('access').get('key').trustkey(to);
}else{
console.log("FAIL");
}
});
//USER DISTRUST PUBLIC KEY
$("#btnmainsharedadistrust").click(async function(){
let user = gun.user();
let key = $('#accesskey').val();
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
//console.log(who);
if(who != null){
console.log("PASS");
user.get('sharedata').get('access').get('key').distrustkey(to);
}else{
console.log("FAIL");
}
});
// USER WRITE DATA
$("#mainsharedatawrite").click(async function(){
//let key = $('#inputsearchpublickey').val(); //public key
let keyvalue = $('#mainsharedatainput').val();// input text
if(!keyvalue){
console.log("empty!");
return;
}
let user = gun.user();
var msg = "test";
msg = keyvalue;
user.get('sharedata').get('access').get('key').trustput(msg);
});
// USER READ DATA
$("#mainsharedataread").click(async function(){
let user = gun.user();
user.get('sharedata').get('access').get('key').trustget((ack)=>{
$("#mainsharedatainput").val(ack);
});
});
// GUN SHARE WRITE
$("#btnsubsharedatawrite").click(async function(){
let key = $('#inputsearchpublickey').val(); //public key
let keyvalue = $('#sharewrite').val(); //public key
if(!keyvalue){
console.log("empty!");
return;
}
let to = gun.user(key);
let who = await to.get('alias').then();
//let user = gun.user();
if((who != null)){
//console.log("found!", who);
//let pub = await to.get('pub').then();
//console.log(pub);
to.get('sharedata').get('access').get('key').trustput(keyvalue);
}else{
console.log("Not found!");
}
});
// GUN SHARE READ
$("#btnsubsharedataread").click(async function(){
let key = $('#inputsearchpublickey').val(); //public key
let user = gun.user();
let to = gun.user(key);
let who = await to.get('alias').then();
if((who != null)){
//console.log("found!", who);
to.get('sharedata').get('access').get('key').trustget((ack)=>{
console.log(ack);
$("#sharewrite").val(ack);
});
}else{
console.log("Not found!");
}
});
// GUN SHARE GENERATE KEY
$("#btnsubsharedatagenkey").click(async function(){
let key = $('#inputsearchpublickey').val(); //public key
let user = gun.user();
let to = gun.user(key);
let who = await to.get('alias').then();
if((who != null)){
console.log("found!", who);
//let pub = await to.get('pub').then();
to.get('sharedata').get('access').get('key').trustgenkey();
}else{
console.log("Not found!");
}
});
// GUN SHARE GET KEY LATEST GRAPH
$("#btnsubsharedalatestkey").click(async function(){
let key = $('#inputsearchpublickey').val(); //public key
let user = gun.user();
let to = gun.user(key);
let who = await to.get('alias').then();
if((who != null)){
console.log("found!", who);
let pub = await to.get('pub').then();
to.get('sharedata').get('access').get('key').trustgetkey((ack)=>{
console.log(ack);
});
}else{
console.log("Not found!");
}
});
//https://gist.github.com/Lightnet/836b4d29b8104e06c2dd558e4d591b28#file-clientprototype-js-L475-L569
// CLIPBOARD PASTE
$("#searchpublickeypaste").click(async function(){
$('#inputsearchpublickey').focus();
document.execCommand("paste");
navigator.permissions.query({name: "clipboard-write"}).then(result => {
console.log(result);
if (result.state == "granted" || result.state == "prompt") {
/* write to the clipboard now */
console.log("READ?");
navigator.clipboard.readText()
.then(text => {
//my code to handle paste
console.log(text);
$('#inputsearchpublickey').val(text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
});
});
$("#accesskey").keyup(async function() {
let key = $('#accesskey').val();
if(key.length == 0){console.log("EMPTY!");return;}
let to = gun.user(key);
let who = await to.get('alias').then();
if(who != null){
$('#lookalias').text(who);
}
});
//===============================================
// SEARCH
$("#inputsearchpublickey").keyup(async function() {
let publickey = $("#inputsearchpublickey").val();
let to = gun.user(publickey);
if(publickey.length==0){console.log("NONE");return;}
let who = await to.get('alias').then();
if(!who){
who = "null";
}
$('#searchalias').text(' Alias: '+who);
to.get('profile').get('alias').decryptonce(ack=>{
console.log(ack)
$('#dataalias').val(ack);
},{sharetype:"user",sharekeytype:"path"})
});
//===============================================
// BUTTON NAV MENU
function hidediv(){
$("#profile").hide();
$("#changepassphrase").hide();
$("#passphrasehint").hide();
$("#messages").hide();
$("#publicchat").hide();
$("#privatechat").hide();
}
$('#btnprofile').click(function(){
hidediv();
$("#profile").show();
selectactive("btnprofile");
});
$('#btnchangepassphrase').click(function(){
hidediv();
$("#changepassphrase").show();
selectactive("btnchangepassphrase");
});
$('#btnpassphrase').click(function(){
hidediv();
$("#passphrasehint").show();
selectactive("btnpassphrase");
});
$('#btnmessage').click(function(){
hidediv();
$("#messages").show();
selectactive("btnmessage");
});
$('#btnpublicchat').click(function(){
hidediv();
InitChat();
$("#publicchat").show();
selectactive("btnpublicchat");
});
$('#btnprivatechat').click(function(){
hidediv();
$("#privatechat").show();
//initPrivateChat();
updateprivatechatlist();
selectactive("btnprivatechat");
});
var tabs=[]
tabs.push({id:"btnprofile"});
tabs.push({id:"btnchangepassphrase"});
tabs.push({id:"btnpassphrase"});
tabs.push({id:"btnmessage"});
tabs.push({id:"btnpublicchat"});
tabs.push({id:"btnprivatechat"});
function selectactive(tab){
for(let idx in tabs){
console.log(tab);
//$('#'+tabs[idx].id).removeClass("active");
if($('#'+tabs[idx].id).hasClass('active')){
$('#'+tabs[idx].id).removeClass("active");
break;
}
}
$('#'+tab).addClass("active");
}
//===============================================
// CHANGE PASSPHRASE
$('#btnchangepassphraseapply').click(function(){
let user = gun.user();
//console.log($('#oldpassphrase').val());console.log($('#newpassphrase').val());console.log("btnchangepassphraseapply");
user.auth(user.is.alias, $('#oldpassphrase').val(), (ack) => {//user auth call
//console.log(ack);
let status = ack.err || "Saved!";//check if there error else saved message.
console.log(status);
modalmessage(status);
}, {change: $('#newpassphrase').val()});//set config to change password
});
//===============================================
// PASSPHRASE HINT
$('#btnapplypassphrasehint').click(async function(){
//console.log($('#question1').val());console.log($('#question2').val());console.log($('#hint').val());console.log("btnapplypassphrase");
let user = gun.user();
let q1 = $('#question1').val(); //get input id question 1
let q2 = $('#question2').val(); //get input id question 2
let hint = $('#hint').val(); //get input id hint
let sec = await Gun.SEA.secret(user.is.epub, user._.sea);//mix key to decrypt
let enc_q1 = await Gun.SEA.encrypt(q1, sec);//encrypt q1
user.get('forgot').get('q1').put(enc_q1);//set hash q1 to user data store
let enc_q2 = await Gun.SEA.encrypt(q2, sec);//encrypt q1
user.get('forgot').get('q2').put(enc_q2); //set hash q2 to user data store
sec = await Gun.SEA.work(q1,q2);//encrypt key
//console.log(sec);
let enc = await Gun.SEA.encrypt(hint, sec);//encrypt hint
//console.log(enc);
user.get('hint').put(enc,ack=>{//set hash hint
//console.log(ack);
if(ack.err){
//console.log("Error!");
modalmessage(ack.err);
return;
}
if(ack.ok){
//console.log('Hint Apply!');
modalmessage('Hint Apply!');
}
});
});
$('#btngetpassphrasehint').click(async function(){
let user = gun.user();
let question1,question2,hint;
let sec = await Gun.SEA.secret(user.is.epub, user._.sea);//mix key to decrypt
question1 = await user.get('forgot').get('q1').then();
question1 = await Gun.SEA.decrypt(question1, sec);//decrypt question1
question2 = await user.get('forgot').get('q2').then();
question2 = await Gun.SEA.decrypt(question2, sec);//decrypt question2
$('#question1').val(question1);//set input text
$('#question2').val(question2);//set input text
sec = await Gun.SEA.work(question1,question2);//encrypt key
//console.log(sec);
hint = await user.get('hint').then();//get encrypt hint
hint = await Gun.SEA.decrypt(hint, sec);//decrypt hint
//console.log(hint);
$('#hint').val(hint);
});
//===============================================
// MESSAGES
$('#btnadduser').click(async function(){
let publickey = ($('#mpublickey').val() || '').trim();
if(!publickey){console.log("Public Key EMPTY!");return;}
let user = gun.user();
let to = gun.user(publickey);//get alias
let who = await to.then() || {};//get alias data
if(!who.alias){console.log("No Alias!");return;}
user.get("contacts").get(publickey).put({alias:who.alias});
updateContacts();
});
$('#btnremoveuser').click(async function(){
let publickey = ($('#mpublickey').val() || '').trim();
if(!publickey){console.log("Public Key EMPTY!");return;}
let user = gun.user();
let to = gun.user(publickey);//get alias
let who = await to.then() || {};//get alias data
if(!who.alias){console.log("No Alias!");return;}
user.get("contacts").get(publickey).put(null);
updateContacts();
});
function updateContacts(){
$('#usercontacts').empty();
$('#usercontacts').append($('<option selected disabled>-- Select User --</option>'));
let user = gun.user();
user.get("contacts").once().map().once(function(data,key){
//console.log("data",data);
//console.log("key",key);
if($("#" + key).length){
}else{
if(data !=null){
addusercontact(key, data);
}
}
});
console.log("update contacts");
}
function addusercontact(index, data) {
//console.log("index",index);console.log("value",data);
//console.log($("#" + index).length)
let bfound=false;
$("#usercontacts option").each(function(idx) {//loop option
if($(this).val() == index){//if key value exist
bfound=true;
return;
}
//$(this).siblings('[value="'+ val +'"]').remove();
});
if(!bfound){//if not found add option for user contacts
if($("#" + index).length){
console.log("NONE?")
}else{
$('#usercontacts').append($('<option/>', {
//id: index,
value: index,
text : data.alias
}));
}
}
}
$("#usercontacts").change(function(){
//console.log("selected");
let idx=$(this).val();
//console.log(idx);
$('#mpublickey').val(idx);
viewprivatemessages();
});
var messages=[];
var UIdec;
function CleanMessages(){
$('#messagelist').empty();
}
async function sendprivatemessage(){
let msg = ($('#inputmessagechat').val() || '').trim();
let publickey = ($('#mpublickey').val() || '').trim();
if(!msg){console.log("Message EMPTY!");return;}
if(!publickey){console.log("Public Key EMPTY!");return;}
let user = gun.user();
let to = gun.user(publickey);//get alias
let who = await to.then() || {};//get alias data
if(!who.alias){console.log("No Alias!");return;}
let sec = await Gun.SEA.secret(who.epub, user._.sea); // Diffie-Hellman
let enc = await Gun.SEA.encrypt(msg, sec); //encrypt message
user.get('messages').get(publickey).set(enc);
console.log("finish...");
}
async function viewprivatemessages(){
let user = gun.user();
if(!user.is){ return }//check if user exist
//messages = [];
CleanMessages();
let pub = ($('#mpublickey').val() || '').trim();
if(!pub) return;//check if not id empty
let to = gun.user(pub);//get alias
let who = await to.then() || {};//get alias data
if(!who.alias){
console.log("No Alias!");
$('#mwho').text("who?");
return;
}
$('#mwho').text(who.alias);
UIdec = await Gun.SEA.secret(who.epub, user._.sea); // Diffie-Hellman
user.get('messages').get(pub).map().once((data,id)=>{
UI(data,id,user.is.alias)
});
to.get('messages').get(user._.sea.pub).map().once((data,id)=>{
UI(data,id,who.alias)
});
}
async function UI(say, id, alias){
say = await Gun.SEA.decrypt(say, UIdec);
//messages.push({id:id,alias:alias,message:say});
if($("#" + id).length){
//console.log("found!?");
}else{
$('#messagelist').append($('<div/>', {
id: id,
text : alias + ": " + say
}));
}
let element = document.getElementById("messagelist");
element.scrollTop = element.scrollHeight;
}
$("#mpublickey").keyup(async function(e) {
viewprivatemessages();
})
$("#inputmessagechat").keyup(async function(e) {
//console.log(e);
//console.log($('#inputmessagechat').val());
if(e.key == "Enter"){
//console.log("Enter");
sendprivatemessage();
}
});
function MessagesResize(){
let height = $(window).height(); - $('#messages').offset().top;
//$('#messages').height(height);
$('#messages').css('height', height - 50);
//console.log(height);
//console.log($('#messages').offset().top);
height = $('#messages').height();
//console.log(height);
$('#messagelist').css('height', height - 44);
}
$(window).resize(function() {
MessagesResize();
});
MessagesResize();
//===============================================
// PUBLIC CHAT
//===============================================
var gunchat;
function timestamp(){
let currentDate = new Date();
//console.log(currentDate);
let year = currentDate.getFullYear();
let month = ("0" + (currentDate.getMonth() + 1 ) ).slice(-2);
let date = ("0" +currentDate.getDate()).slice(-2);
let hour = ("0" +currentDate.getHours()).slice(-2);
let minute = ("0" +currentDate.getMinutes()).slice(-2);
let second = ("0" +currentDate.getSeconds()).slice(-2);
let millisecond = currentDate.getMilliseconds();
return year + "/" + (month) + "/" + date + ":" + hour+ ":" + minute+ ":" + second+ ":" + millisecond;
}
function scrollPublicMessage(){
let element = document.getElementById("publicchatlist");
element.scrollTop = element.scrollHeight;
}
$("#inputpublicchat").keyup(async function(e) {
if(e.key == "Enter"){
//console.log("Enter");
let user = gun.user();
if(!user.is){ return }//check if user exist
let msg = ($('#inputpublicchat').val() || '').trim();
if(!msg) return;//check if not id empty
let encmsg = await SEA.work("public","chat");//encrypttion key default?
//console.log(encmsg);
let enc = await SEA.encrypt(msg,encmsg);
//console.log(enc);
let who = await user.get('alias').then();
//console.log(who);
//console.log(typeof enc)
enc = window.btoa(enc);
gun.get('chat').get(timestamp()).put({
alias:who,
message:enc
});
console.log("send message...");
}
});
//https://gun.eco/docs/RAD
async function InitChat(){
console.log("Init Chat...")
$('#publicchatlist').empty();
let encmsg = await SEA.work("public","chat"); //encrypttion key default?
async function qcallback(data,key){
console.log('incoming messages...')
//console.log("key",key);
console.log("data",data);
if(data == null)return;
if(data.message != null){
let message = window.atob(data.message);
//console.log(message);
let dec = await SEA.decrypt(message,encmsg);
//console.log(dec)
if(dec!=null){
$('#publicchatlist').append($('<div/>', {
id: key,
text : data.alias + ": " + dec
}));
scrollPublicMessage();
}
}
}
let currentDate = new Date();
let year = currentDate.getFullYear();
let month = ("0" + (currentDate.getMonth() + 1 ) ).slice(-2);
let date = ("0" +currentDate.getDate()).slice(-2);
let timestring = year + "/" + month + "/" + date + ":";
console.log(timestring);
if(gunchat !=null){
gunchat.off()
}
gunchat = gun.get('chat');
//gunchat.get({'.': {'*': '2019/08/'}}).map().once(qcallback);
//gunchat.get({'.': {'*': timestring}}).map().once(qcallback);
gunchat.get({'.': {'*': timestring},'%': 50000}).map().once(qcallback);
}
function PublicChatResize(){
let height = $(window).height(); - $('#publicchat').offset().top;
$('#publicchat').css('height', height - 50);
height = $('#publicchat').height();
$('#publicchatlist').css('height', height - 44);
}
$(window).resize(function() {
PublicChatResize();
});
PublicChatResize();
//===============================================
// PRIVATE CHAT
var privatechatkey="";
var gunprivatechat;
var privatesharekey="";
function CleanPrivateChatMessages(){
$('#privatechatlist').empty();
}
function scrollPrivateMessage(){
let element = document.getElementById("privatechatlist");
element.scrollTop = element.scrollHeight;
}
function PrivateChatResize(){
let height = $(window).height(); - $('#privatechat').offset().top;
$('#privatechat').css('height', height - 50);
height = $('#privatechat').height();
$('#privatechatlist').css('height', height - 44);
}
$(window).resize(function() {
PrivateChatResize();
});
PrivateChatResize();
$("#inputprivatechat").keyup(async function(e) {
if(e.key == "Enter"){
//console.log("Enter");
let user = gun.user();
if(!user.is){ return }//check if user exist
let msg = ($('#inputprivatechat').val() || '').trim();
if(!msg) return;//check if not id empty
let who = await user.get('alias').then();
if(gunprivatechat !=null){
let enc = await SEA.encrypt(msg, privatesharekey);
enc = window.btoa(enc);//gun graph need to be string not SEA{} that will reject that is not soul of user
gunprivatechat.get('message').get(timestamp()).put({
alias:who,
message:enc
});
}
console.log("send private chat...");
}
});
async function initPrivateChat(){
//updateprivatechatlist();
CleanPrivateChatMessages();
let privatekey = ($('#privatechatkey').val() || "").trim();
if(!privatekey)return;
console.log("init chat...");
//Need to fail checks!
console.log(privatekey);
privatechatkey = privatekey;
let user = gun.user();
let pair = user._.sea;
//GET ENC SHARE KEY
let pub = await gun.get(privatechatkey).get('info').get('pub').then();
let title = await gun.get(privatechatkey).get('info').get('name').then();
if(pub == user.is.pub){
$('#ppublickey').show();
$('#btnprivatechatgrant').show();
$('#btnprivatechatrevoke').show();
}else{
$('#ppublickey').hide();
$('#btnprivatechatgrant').hide();
$('#btnprivatechatrevoke').hide();
}
$('#btnprivatechatcreate').hide();
$('#privatechatroom').hide();
$('#privatechatkey').hide();
$('#btnprivatechatjoin').hide();
$('#btnprivatechatleave').show();
$('#btnprivatechatadd').hide();
$('#btnprivatechatremove').hide();
$('#btnprivatechatname').text(title);
let to = gun.user(pub);
let epub =await to.get('epub').then();
let encsharekey = await to.get('privatechatroom').get(privatechatkey).get('pub').get(pair.pub).then();
console.log(encsharekey);
//let dh = await SEA.secret(pair.epub, pair);
let dh = await SEA.secret(epub, pair);
let dec = await SEA.decrypt(encsharekey, dh);
console.log(dec);
if(dec==null){
console.log("NULL SHARE KEY!");
return;
}
privatesharekey = dec;
if(gunprivatechat !=null){
gunprivatechat.off();
}
gunprivatechat = gun.get(privatekey);
let currentDate = new Date();
let year = currentDate.getFullYear();
let month = ("0" + (currentDate.getMonth() + 1 ) ).slice(-2);
let date = ("0" +currentDate.getDate()).slice(-2);
let timestring = year + "/" + month + "/" + date + ":";
async function qcallback(data,key){
console.log('incoming messages...')
//console.log("key",key);
//console.log("data",data);
if(data == null)return;
if(data.message != null){
let message = window.atob(data.message);
let decmsg = await SEA.decrypt(message,privatesharekey);
if(decmsg!=null){
$('#privatechatlist').append($('<div/>', {
id: key,
text : data.alias + ": " + decmsg
}));
scrollPrivateMessage();
}
}
}
gunprivatechat.get('message').get({'.': {'*': timestring},'%': 50000}).map().once(qcallback);
}
function leavePrivateChatRoom(){
$('#btnprivatechatjoin').show(); //Show Enter Room
$('#btnprivatechatleave').hide(); //Hide Leave Room
$('#ppublickey').hide(); //public key